id stringlengths 25 30 | content stringlengths 14 942k | max_stars_repo_path stringlengths 49 55 |
|---|---|---|
crossvul-cpp_data_good_596_0 | /*
+----------------------------------------------------------------------+
| HipHop for PHP |
+----------------------------------------------------------------------+
| Copyright (c) 2010-present Facebook, Inc. (http://www.facebook.com) |
| Copyright (c) 1997-2010 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. |
+----------------------------------------------------------------------+
*/
#include "hphp/runtime/ext/extension.h"
#include "hphp/runtime/base/builtin-functions.h"
#include "hphp/runtime/base/execution-context.h"
#include "hphp/runtime/vm/native-data.h"
#include "hphp/runtime/ext/memcached/libmemcached_portability.h"
#include "hphp/runtime/ext/sockets/ext_sockets.h"
#include "hphp/runtime/base/rds-local.h"
#include "hphp/runtime/base/ini-setting.h"
#include "hphp/runtime/base/zend-string.h"
#include <vector>
// MMC values must match pecl-memcache for compatibility
#define MMC_SERIALIZED 0x0001
#define MMC_COMPRESSED 0x0002
#define MMC_TYPE_STRING 0x0000
#define MMC_TYPE_BOOL 0x0100
#define MMC_TYPE_LONG 0x0300
#define MMC_TYPE_DOUBLE 0x0700
#define MMC_TYPE_MASK 0x0F00
namespace HPHP {
const int64_t k_MEMCACHE_COMPRESSED = MMC_COMPRESSED;
static bool ini_on_update_hash_strategy(const std::string& value);
static bool ini_on_update_hash_function(const std::string& value);
struct MEMCACHEGlobals final {
std::string hash_strategy;
std::string hash_function;
};
static __thread MEMCACHEGlobals* s_memcache_globals;
#define MEMCACHEG(name) s_memcache_globals->name
const StaticString s_MemcacheData("MemcacheData");
struct MemcacheData {
memcached_st m_memcache;
TYPE_SCAN_IGNORE_FIELD(m_memcache);
int m_compress_threshold;
double m_min_compress_savings;
MemcacheData(): m_memcache(), m_compress_threshold(0),
m_min_compress_savings(0.2) {
memcached_create(&m_memcache);
if (MEMCACHEG(hash_strategy) == "consistent") {
// need to hook up a global variable to set this
memcached_behavior_set(&m_memcache, MEMCACHED_BEHAVIOR_DISTRIBUTION,
MEMCACHED_DISTRIBUTION_CONSISTENT_KETAMA);
} else {
memcached_behavior_set(&m_memcache, MEMCACHED_BEHAVIOR_DISTRIBUTION,
MEMCACHED_DISTRIBUTION_MODULA);
}
if (MEMCACHEG(hash_function) == "fnv") {
memcached_behavior_set(&m_memcache, MEMCACHED_BEHAVIOR_HASH,
MEMCACHED_HASH_FNV1A_32);
} else {
memcached_behavior_set(&m_memcache, MEMCACHED_BEHAVIOR_HASH,
MEMCACHED_HASH_CRC);
}
};
~MemcacheData() {
memcached_free(&m_memcache);
};
};
static bool ini_on_update_hash_strategy(const std::string& value) {
if (!strncasecmp(value.data(), "standard", sizeof("standard"))) {
MEMCACHEG(hash_strategy) = "standard";
} else if (!strncasecmp(value.data(), "consistent", sizeof("consistent"))) {
MEMCACHEG(hash_strategy) = "consistent";
}
return false;
}
static bool ini_on_update_hash_function(const std::string& value) {
if (!strncasecmp(value.data(), "crc32", sizeof("crc32"))) {
MEMCACHEG(hash_function) = "crc32";
} else if (!strncasecmp(value.data(), "fnv", sizeof("fnv"))) {
MEMCACHEG(hash_function) = "fnv";
}
return false;
}
static bool hasAvailableServers(const MemcacheData* data) {
if (memcached_server_count(&data->m_memcache) == 0) {
raise_warning("Memcache: No servers added to memcache connection");
return false;
}
return true;
}
static bool isServerReachable(const String& host, int port /*= 0*/) {
auto hostInfo = HHVM_FN(getaddrinfo)(host, port);
if (hostInfo.isBoolean() && !hostInfo.toBoolean()) {
raise_warning("Memcache: Can't connect to %s:%d", host.c_str(), port);
return false;
}
return true;
}
///////////////////////////////////////////////////////////////////////////////
// methods
static bool HHVM_METHOD(Memcache, connect, const String& host, int port /*= 0*/,
int /*timeout*/ /*= 0*/, int /*timeoutms*/ /*= 0*/) {
auto data = Native::data<MemcacheData>(this_);
memcached_return_t ret;
if (!host.empty() &&
!strncmp(host.c_str(), "unix://", sizeof("unix://") - 1)) {
const char *socket_path = host.substr(sizeof("unix://") - 1).c_str();
ret = memcached_server_add_unix_socket(&data->m_memcache, socket_path);
} else {
if (!isServerReachable(host, port)) {
return false;
}
ret = memcached_server_add(&data->m_memcache, host.c_str(), port);
}
return (ret == MEMCACHED_SUCCESS);
}
static uint32_t memcache_get_flag_for_type(const Variant& var) {
switch (var.getType()) {
case KindOfBoolean:
return MMC_TYPE_BOOL;
case KindOfInt64:
return MMC_TYPE_LONG;
case KindOfDouble:
return MMC_TYPE_DOUBLE;
case KindOfUninit:
case KindOfNull:
case KindOfPersistentString:
case KindOfString:
case KindOfPersistentVec:
case KindOfVec:
case KindOfPersistentDict:
case KindOfDict:
case KindOfPersistentKeyset:
case KindOfKeyset:
case KindOfPersistentShape:
case KindOfShape:
case KindOfPersistentArray:
case KindOfArray:
case KindOfObject:
case KindOfResource:
case KindOfRef:
case KindOfFunc:
case KindOfClass:
return MMC_TYPE_STRING;
}
not_reached();
}
static void memcache_set_type_from_flag(Variant& var, uint32_t flags) {
switch (flags & MMC_TYPE_MASK) {
case MMC_TYPE_BOOL:
var = var.toBoolean();
break;
case MMC_TYPE_LONG:
var = var.toInt64();
break;
case MMC_TYPE_DOUBLE:
var = var.toDouble();
break;
}
}
static std::vector<char> memcache_prepare_for_storage(const MemcacheData* data,
const Variant& var,
int &flag) {
String v;
if (var.isString()) {
v = var.toString();
} else if (var.isNumeric() || var.isBoolean()) {
flag &= ~MMC_COMPRESSED;
v = var.toString();
} else {
flag |= MMC_SERIALIZED;
v = f_serialize(var);
}
std::vector<char> payload;
size_t value_len = v.length();
if (!var.isNumeric() && !var.isBoolean() &&
data->m_compress_threshold && value_len >= data->m_compress_threshold) {
flag |= MMC_COMPRESSED;
}
if (flag & MMC_COMPRESSED) {
size_t payload_len = compressBound(value_len);
payload.resize(payload_len);
if (compress((Bytef*)payload.data(), &payload_len,
(const Bytef*)v.data(), value_len) == Z_OK) {
payload.resize(payload_len);
if (payload_len >= value_len * (1 - data->m_min_compress_savings)) {
flag &= ~MMC_COMPRESSED;
}
} else {
flag &= ~MMC_COMPRESSED;
raise_warning("could not compress value");
}
}
if (!(flag & MMC_COMPRESSED)) {
payload.resize(0);
payload.insert(payload.end(), v.data(), v.data() + value_len);
}
flag |= memcache_get_flag_for_type(var);
return payload;
}
static String memcache_prepare_key(const String& var) {
String var_mutable(var, CopyString);
auto data = var_mutable.get()->mutableData();
for (int i = 0; i < var.length(); i++) {
// This is a stupid encoding since it causes collisions but it matches php5
if (data[i] <= ' ') {
data[i] = '_';
}
}
return data;
}
static Variant unserialize_if_serialized(const char *payload,
size_t payload_len,
uint32_t flags) {
Variant ret = uninit_null();
if (flags & MMC_SERIALIZED) {
ret = unserialize_from_buffer(
payload,
payload_len,
VariableUnserializer::Type::Serialize
);
} else {
if (payload_len == 0) {
ret = empty_string();
} else {
ret = String(payload, payload_len, CopyString);
}
}
return ret;
}
static Variant memcache_fetch_from_storage(const char *payload,
size_t payload_len,
uint32_t flags) {
Variant ret = uninit_null();
if (flags & MMC_COMPRESSED) {
bool done = false;
std::vector<char> buffer;
size_t buffer_len;
for (int factor = 1; !done && factor <= 16; ++factor) {
if (payload_len >=
std::numeric_limits<unsigned long>::max() / (1 << factor)) {
break;
}
buffer_len = payload_len * (1 << factor) + 1;
buffer.resize(buffer_len);
if (uncompress((Bytef*)buffer.data(), &buffer_len,
(const Bytef*)payload, (uLong)payload_len) == Z_OK) {
done = true;
}
}
if (!done) {
raise_warning("could not uncompress value");
return init_null();
}
ret = unserialize_if_serialized(buffer.data(), buffer_len, flags);
} else {
ret = unserialize_if_serialized(payload, payload_len, flags);
}
memcache_set_type_from_flag(ret, flags);
return ret;
}
static bool HHVM_METHOD(Memcache, add, const String& key, const Variant& var,
int flag /*= 0*/, int expire /*= 0*/) {
if (key.empty()) {
raise_warning("Key cannot be empty");
return false;
}
auto data = Native::data<MemcacheData>(this_);
if (!hasAvailableServers(data)) {
return false;
}
std::vector<char> serialized = memcache_prepare_for_storage(data, var, flag);
String serializedKey = memcache_prepare_key(key);
memcached_return_t ret = memcached_add(&data->m_memcache,
serializedKey.c_str(),
serializedKey.length(),
serialized.data(),
serialized.size(),
expire, flag);
return (ret == MEMCACHED_SUCCESS);
}
static bool HHVM_METHOD(Memcache, set, const String& key, const Variant& var,
int flag /*= 0*/, int expire /*= 0*/) {
if (key.empty()) {
raise_warning("Key cannot be empty");
return false;
}
auto data = Native::data<MemcacheData>(this_);
if (!hasAvailableServers(data)) {
return false;
}
String serializedKey = memcache_prepare_key(key);
std::vector<char> serializedVar =
memcache_prepare_for_storage(data, var, flag);
memcached_return_t ret = memcached_set(&data->m_memcache,
serializedKey.c_str(),
serializedKey.length(),
serializedVar.data(),
serializedVar.size(), expire, flag);
if (ret == MEMCACHED_SUCCESS) {
return true;
}
return false;
}
static bool HHVM_METHOD(Memcache, replace, const String& key,
const Variant& var, int flag /*= 0*/,
int expire /*= 0*/) {
if (key.empty()) {
raise_warning("Key cannot be empty");
return false;
}
auto data = Native::data<MemcacheData>(this_);
if (!hasAvailableServers(data)) {
return false;
}
String serializedKey = memcache_prepare_key(key);
std::vector<char> serialized = memcache_prepare_for_storage(data, var, flag);
memcached_return_t ret = memcached_replace(&data->m_memcache,
serializedKey.c_str(),
serializedKey.length(),
serialized.data(),
serialized.size(),
expire, flag);
return (ret == MEMCACHED_SUCCESS);
}
static Variant
HHVM_METHOD(Memcache, get, const Variant& key, VRefParam /*flags*/ /*= null*/) {
auto data = Native::data<MemcacheData>(this_);
if (!hasAvailableServers(data)) {
return false;
}
if (key.isArray()) {
std::vector<const char *> real_keys;
std::vector<size_t> key_len;
Array keyArr = key.toArray();
real_keys.reserve(keyArr.size());
key_len.reserve(keyArr.size());
for (ArrayIter iter(keyArr); iter; ++iter) {
auto key = iter.second().toString();
String serializedKey = memcache_prepare_key(key);
char *k = new char[serializedKey.length()+1];
memcpy(k, serializedKey.c_str(), serializedKey.length() + 1);
real_keys.push_back(k);
key_len.push_back(serializedKey.length());
}
if (!real_keys.empty()) {
const char *payload = nullptr;
size_t payload_len = 0;
uint32_t flags = 0;
const char *res_key = nullptr;
size_t res_key_len = 0;
memcached_result_st result;
memcached_return_t ret = memcached_mget(&data->m_memcache, &real_keys[0],
&key_len[0], real_keys.size());
memcached_result_create(&data->m_memcache, &result);
// To mimic PHP5 should return empty array at failure.
Array return_val = Array::Create();
while ((memcached_fetch_result(&data->m_memcache, &result, &ret))
!= nullptr) {
if (ret != MEMCACHED_SUCCESS) {
// should probably notify about errors
continue;
}
payload = memcached_result_value(&result);
payload_len = memcached_result_length(&result);
flags = memcached_result_flags(&result);
res_key = memcached_result_key_value(&result);
res_key_len = memcached_result_key_length(&result);
return_val.set(String(res_key, res_key_len, CopyString),
memcache_fetch_from_storage(payload,
payload_len, flags));
}
memcached_result_free(&result);
for ( size_t i = 0 ; i < real_keys.size() ; i++ ) {
delete [] real_keys[i];
}
return return_val;
}
} else {
char *payload = nullptr;
size_t payload_len = 0;
uint32_t flags = 0;
memcached_return_t ret;
String serializedKey = memcache_prepare_key(key.toString());
if (serializedKey.length() == 0) {
return false;
}
payload = memcached_get(&data->m_memcache, serializedKey.c_str(),
serializedKey.length(), &payload_len, &flags, &ret);
/* This is for historical reasons from libmemcached*/
if (ret == MEMCACHED_END) {
ret = MEMCACHED_NOTFOUND;
}
if (ret == MEMCACHED_NOTFOUND) {
return false;
}
if (ret != MEMCACHED_SUCCESS) {
return false;
}
Variant retval = memcache_fetch_from_storage(payload, payload_len, flags);
free(payload);
return retval;
}
return false;
}
static bool HHVM_METHOD(Memcache, delete, const String& key,
int expire /*= 0*/) {
if (key.empty()) {
raise_warning("Key cannot be empty");
return false;
}
auto data = Native::data<MemcacheData>(this_);
if (!hasAvailableServers(data)) {
return false;
}
String serializedKey = memcache_prepare_key(key);
memcached_return_t ret = memcached_delete(&data->m_memcache,
serializedKey.c_str(),
serializedKey.length(),
expire);
return (ret == MEMCACHED_SUCCESS);
}
static Variant HHVM_METHOD(Memcache, increment, const String& key,
int offset /*= 1*/) {
if (key.empty()) {
raise_warning("Key cannot be empty");
return false;
}
auto data = Native::data<MemcacheData>(this_);
if (!hasAvailableServers(data)) {
return false;
}
uint64_t value;
String serializedKey = memcache_prepare_key(key);
memcached_return_t ret = memcached_increment(&data->m_memcache,
serializedKey.c_str(),
serializedKey.length(), offset,
&value);
if (ret == MEMCACHED_SUCCESS) {
return (int64_t)value;
}
return false;
}
static Variant HHVM_METHOD(Memcache, decrement, const String& key,
int offset /*= 1*/) {
if (key.empty()) {
raise_warning("Key cannot be empty");
return false;
}
auto data = Native::data<MemcacheData>(this_);
if (!hasAvailableServers(data)) {
return false;
}
uint64_t value;
String serializedKey = memcache_prepare_key(key);
memcached_return_t ret = memcached_decrement(&data->m_memcache,
serializedKey.c_str(),
serializedKey.length(), offset,
&value);
if (ret == MEMCACHED_SUCCESS) {
return (int64_t)value;
}
return false;
}
static bool HHVM_METHOD(Memcache, close) {
auto data = Native::data<MemcacheData>(this_);
memcached_quit(&data->m_memcache);
return true;
}
static Variant HHVM_METHOD(Memcache, getversion) {
auto data = Native::data<MemcacheData>(this_);
int server_count = memcached_server_count(&data->m_memcache);
char version[16];
int version_len = 0;
if (memcached_version(&data->m_memcache) != MEMCACHED_SUCCESS) {
return false;
}
for (int x = 0; x < server_count; x++) {
LMCD_SERVER_POSITION_INSTANCE_TYPE instance =
memcached_server_instance_by_position(&data->m_memcache, x);
uint8_t majorVersion = LMCD_SERVER_MAJOR_VERSION(instance);
uint8_t minorVersion = LMCD_SERVER_MINOR_VERSION(instance);
uint8_t microVersion = LMCD_SERVER_MICRO_VERSION(instance);
if (!majorVersion) {
continue;
}
version_len = snprintf(version, sizeof(version),
"%" PRIu8 ".%" PRIu8 ".%" PRIu8,
majorVersion, minorVersion, microVersion);
return String(version, version_len, CopyString);
}
return false;
}
static bool HHVM_METHOD(Memcache, flush, int expire /*= 0*/) {
auto data = Native::data<MemcacheData>(this_);
return memcached_flush(&data->m_memcache, expire) == MEMCACHED_SUCCESS;
}
static bool HHVM_METHOD(Memcache, setcompressthreshold, int threshold,
double min_savings /* = 0.2 */) {
if (threshold < 0) {
raise_warning("threshold must be a positive integer");
return false;
}
if (min_savings < 0 || min_savings > 1) {
raise_warning("min_savings must be a float in the 0..1 range");
return false;
}
auto data = Native::data<MemcacheData>(this_);
data->m_compress_threshold = threshold;
data->m_min_compress_savings = min_savings;
return true;
}
static Array memcache_build_stats(const memcached_st *ptr,
memcached_stat_st *memc_stat,
memcached_return_t *ret) {
char **curr_key;
char **stat_keys = memcached_stat_get_keys(const_cast<memcached_st*>(ptr),
memc_stat, ret);
if (*ret != MEMCACHED_SUCCESS) {
if (stat_keys) {
free(stat_keys);
}
return Array();
}
Array return_val = Array::Create();
for (curr_key = stat_keys; *curr_key; curr_key++) {
char *mc_val;
mc_val = memcached_stat_get_value(ptr, memc_stat, *curr_key, ret);
if (*ret != MEMCACHED_SUCCESS) {
break;
}
return_val.set(String(*curr_key, CopyString),
String(mc_val, CopyString));
free(mc_val);
}
free(stat_keys);
return return_val;
}
static Array HHVM_METHOD(Memcache, getstats,
const String& type /* = null_string */,
int slabid /* = 0 */, int limit /* = 100 */) {
auto data = Native::data<MemcacheData>(this_);
if (!memcached_server_count(&data->m_memcache)) {
return Array();
}
char extra_args[30] = {0};
if (slabid) {
snprintf(extra_args, sizeof(extra_args), "%s %d %d", type.c_str(),
slabid, limit);
} else if (!type.empty()) {
snprintf(extra_args, sizeof(extra_args), "%s", type.c_str());
}
LMCD_SERVER_POSITION_INSTANCE_TYPE instance =
memcached_server_instance_by_position(&data->m_memcache, 0);
const char *hostname = LMCD_SERVER_HOSTNAME(instance);
in_port_t port = LMCD_SERVER_PORT(instance);
memcached_stat_st stats;
if (memcached_stat_servername(&stats, extra_args, hostname,
port) != MEMCACHED_SUCCESS) {
return Array();
}
memcached_return_t ret;
return memcache_build_stats(&data->m_memcache, &stats, &ret);
}
static Array HHVM_METHOD(Memcache, getextendedstats,
const String& /*type*/ /* = null_string */,
int /*slabid*/ /* = 0 */, int /*limit*/ /* = 100 */) {
auto data = Native::data<MemcacheData>(this_);
memcached_return_t ret;
memcached_stat_st *stats;
stats = memcached_stat(&data->m_memcache, nullptr, &ret);
if (ret != MEMCACHED_SUCCESS) {
return Array();
}
int server_count = memcached_server_count(&data->m_memcache);
Array return_val;
for (int server_id = 0; server_id < server_count; server_id++) {
memcached_stat_st *stat;
LMCD_SERVER_POSITION_INSTANCE_TYPE instance =
memcached_server_instance_by_position(&data->m_memcache, server_id);
const char *hostname = LMCD_SERVER_HOSTNAME(instance);
in_port_t port = LMCD_SERVER_PORT(instance);
stat = stats + server_id;
Array server_stats = memcache_build_stats(&data->m_memcache, stat, &ret);
if (ret != MEMCACHED_SUCCESS) {
continue;
}
auto const port_str = folly::to<std::string>(port);
auto const key_len = strlen(hostname) + 1 + port_str.length();
auto key = String(key_len, ReserveString);
key += hostname;
key += ":";
key += port_str;
return_val.set(key, server_stats);
}
free(stats);
return return_val;
}
static bool
HHVM_METHOD(Memcache, addserver, const String& host, int port /* = 11211 */,
bool /*persistent*/ /* = false */, int weight /* = 0 */,
int /*timeout*/ /* = 0 */, int /*retry_interval*/ /* = 0 */,
bool /*status*/ /* = true */,
const Variant& /*failure_callback*/ /* = uninit_variant */,
int /*timeoutms*/ /* = 0 */) {
auto data = Native::data<MemcacheData>(this_);
memcached_return_t ret;
if (!host.empty() &&
!strncmp(host.c_str(), "unix://", sizeof("unix://") - 1)) {
const char *socket_path = host.substr(sizeof("unix://") - 1).c_str();
ret = memcached_server_add_unix_socket_with_weight(&data->m_memcache,
socket_path, weight);
} else {
ret = memcached_server_add_with_weight(&data->m_memcache, host.c_str(),
port, weight);
}
if (ret == MEMCACHED_SUCCESS) {
return true;
}
return false;
}
///////////////////////////////////////////////////////////////////////////////
struct MemcacheExtension final : Extension {
MemcacheExtension() : Extension("memcache", "3.0.8") {};
void threadInit() override {
assertx(!s_memcache_globals);
s_memcache_globals = new MEMCACHEGlobals;
IniSetting::Bind(this, IniSetting::PHP_INI_ALL,
"memcache.hash_strategy", "standard",
IniSetting::SetAndGet<std::string>(
ini_on_update_hash_strategy,
nullptr
),
&MEMCACHEG(hash_strategy));
IniSetting::Bind(this, IniSetting::PHP_INI_ALL,
"memcache.hash_function", "crc32",
IniSetting::SetAndGet<std::string>(
ini_on_update_hash_function,
nullptr
),
&MEMCACHEG(hash_function));
}
void threadShutdown() override {
delete s_memcache_globals;
s_memcache_globals = nullptr;
}
void moduleInit() override {
HHVM_RC_INT(MEMCACHE_COMPRESSED, k_MEMCACHE_COMPRESSED);
HHVM_RC_BOOL(MEMCACHE_HAVE_SESSION, true);
HHVM_ME(Memcache, connect);
HHVM_ME(Memcache, add);
HHVM_ME(Memcache, set);
HHVM_ME(Memcache, replace);
HHVM_ME(Memcache, get);
HHVM_ME(Memcache, delete);
HHVM_ME(Memcache, increment);
HHVM_ME(Memcache, decrement);
HHVM_ME(Memcache, close);
HHVM_ME(Memcache, getversion);
HHVM_ME(Memcache, flush);
HHVM_ME(Memcache, setcompressthreshold);
HHVM_ME(Memcache, getstats);
HHVM_ME(Memcache, getextendedstats);
HHVM_ME(Memcache, addserver);
Native::registerNativeDataInfo<MemcacheData>(s_MemcacheData.get());
loadSystemlib();
}
} s_memcache_extension;;
}
| ./CrossVul/dataset_final_sorted/CWE-125/cpp/good_596_0 |
crossvul-cpp_data_bad_2813_1 | /*****************************************************************
|
| AP4 - hvcC Atoms
|
| Copyright 2002-2016 Axiomatic Systems, LLC
|
|
| This file is part of Bento4/AP4 (MP4 Atom Processing Library).
|
| Unless you have obtained Bento4 under a difference license,
| this version of Bento4 is Bento4|GPL.
| Bento4|GPL is free software; you can redistribute it and/or modify
| it under the terms of the GNU General Public License as published by
| the Free Software Foundation; either version 2, or (at your option)
| any later version.
|
| Bento4|GPL 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 Bento4|GPL; see the file COPYING. If not, write to the
| Free Software Foundation, 59 Temple Place - Suite 330, Boston, MA
| 02111-1307, USA.
|
****************************************************************/
/*----------------------------------------------------------------------
| includes
+---------------------------------------------------------------------*/
#include "Ap4HvccAtom.h"
#include "Ap4AtomFactory.h"
#include "Ap4Utils.h"
#include "Ap4Types.h"
#include "Ap4HevcParser.h"
/*----------------------------------------------------------------------
| dynamic cast support
+---------------------------------------------------------------------*/
AP4_DEFINE_DYNAMIC_CAST_ANCHOR(AP4_HvccAtom)
/*----------------------------------------------------------------------
| AP4_HvccAtom::GetProfileName
+---------------------------------------------------------------------*/
const char*
AP4_HvccAtom::GetProfileName(AP4_UI08 profile_space, AP4_UI08 profile)
{
if (profile_space != 0) {
return NULL;
}
switch (profile) {
case AP4_HEVC_PROFILE_MAIN: return "Main";
case AP4_HEVC_PROFILE_MAIN_10: return "Main 10";
case AP4_HEVC_PROFILE_MAIN_STILL_PICTURE: return "Main Still Picture";
case AP4_HEVC_PROFILE_REXT: return "Rext";
}
return NULL;
}
/*----------------------------------------------------------------------
| AP4_HvccAtom::GetChromaFormatName
+---------------------------------------------------------------------*/
const char*
AP4_HvccAtom::GetChromaFormatName(AP4_UI08 chroma_format)
{
switch (chroma_format) {
case AP4_HEVC_CHROMA_FORMAT_MONOCHROME: return "Monochrome";
case AP4_HEVC_CHROMA_FORMAT_420: return "4:2:0";
case AP4_HEVC_CHROMA_FORMAT_422: return "4:2:2";
case AP4_HEVC_CHROMA_FORMAT_444: return "4:4:4";
}
return NULL;
}
/*----------------------------------------------------------------------
| AP4_AvccAtom::Create
+---------------------------------------------------------------------*/
AP4_HvccAtom*
AP4_HvccAtom::Create(AP4_Size size, AP4_ByteStream& stream)
{
// read the raw bytes in a buffer
unsigned int payload_size = size-AP4_ATOM_HEADER_SIZE;
AP4_DataBuffer payload_data(payload_size);
AP4_Result result = stream.Read(payload_data.UseData(), payload_size);
if (AP4_FAILED(result)) return NULL;
return new AP4_HvccAtom(size, payload_data.GetData());
}
/*----------------------------------------------------------------------
| AP4_HvccAtom::AP4_HvccAtom
+---------------------------------------------------------------------*/
AP4_HvccAtom::AP4_HvccAtom() :
AP4_Atom(AP4_ATOM_TYPE_HVCC, AP4_ATOM_HEADER_SIZE),
m_ConfigurationVersion(1),
m_GeneralProfileSpace(0),
m_GeneralTierFlag(0),
m_GeneralProfile(0),
m_GeneralProfileCompatibilityFlags(0),
m_GeneralConstraintIndicatorFlags(0),
m_GeneralLevel(0),
m_Reserved1(0),
m_MinSpatialSegmentation(0),
m_Reserved2(0),
m_ParallelismType(0),
m_Reserved3(0),
m_ChromaFormat(0),
m_Reserved4(0),
m_LumaBitDepth(8),
m_Reserved5(0),
m_ChromaBitDepth(8),
m_AverageFrameRate(0),
m_ConstantFrameRate(0),
m_NumTemporalLayers(0),
m_TemporalIdNested(0),
m_NaluLengthSize(4)
{
UpdateRawBytes();
m_Size32 += m_RawBytes.GetDataSize();
}
/*----------------------------------------------------------------------
| AP4_HvccAtom::AP4_HvccAtom
+---------------------------------------------------------------------*/
AP4_HvccAtom::AP4_HvccAtom(const AP4_HvccAtom& other) :
AP4_Atom(AP4_ATOM_TYPE_HVCC, other.m_Size32),
m_ConfigurationVersion(other.m_ConfigurationVersion),
m_GeneralProfileSpace(other.m_GeneralProfileSpace),
m_GeneralTierFlag(other.m_GeneralTierFlag),
m_GeneralProfile(other.m_GeneralProfile),
m_GeneralProfileCompatibilityFlags(other.m_GeneralProfileCompatibilityFlags),
m_GeneralConstraintIndicatorFlags(other.m_GeneralConstraintIndicatorFlags),
m_GeneralLevel(other.m_GeneralLevel),
m_Reserved1(other.m_Reserved1),
m_MinSpatialSegmentation(other.m_MinSpatialSegmentation),
m_Reserved2(other.m_Reserved2),
m_ParallelismType(other.m_ParallelismType),
m_Reserved3(other.m_Reserved3),
m_ChromaFormat(other.m_ChromaFormat),
m_Reserved4(other.m_Reserved4),
m_LumaBitDepth(other.m_LumaBitDepth),
m_Reserved5(other.m_Reserved5),
m_ChromaBitDepth(other.m_ChromaBitDepth),
m_AverageFrameRate(other.m_AverageFrameRate),
m_ConstantFrameRate(other.m_ConstantFrameRate),
m_NumTemporalLayers(other.m_NumTemporalLayers),
m_TemporalIdNested(other.m_TemporalIdNested),
m_NaluLengthSize(other.m_NaluLengthSize),
m_RawBytes(other.m_RawBytes)
{
// deep copy of the parameters
unsigned int i = 0;
for (i=0; i<other.m_Sequences.ItemCount(); i++) {
m_Sequences.Append(other.m_Sequences[i]);
}
}
/*----------------------------------------------------------------------
| AP4_HvccAtom::AP4_HvccAtom
+---------------------------------------------------------------------*/
AP4_HvccAtom::AP4_HvccAtom(AP4_UI08 general_profile_space,
AP4_UI08 general_tier_flag,
AP4_UI08 general_profile,
AP4_UI32 general_profile_compatibility_flags,
AP4_UI64 general_constraint_indicator_flags,
AP4_UI08 general_level,
AP4_UI32 min_spatial_segmentation,
AP4_UI08 parallelism_type,
AP4_UI08 chroma_format,
AP4_UI08 luma_bit_depth,
AP4_UI08 chroma_bit_depth,
AP4_UI16 average_frame_rate,
AP4_UI08 constant_frame_rate,
AP4_UI08 num_temporal_layers,
AP4_UI08 temporal_id_nested,
AP4_UI08 nalu_length_size,
const AP4_Array<AP4_DataBuffer>& video_parameters,
const AP4_Array<AP4_DataBuffer>& sequence_parameters,
const AP4_Array<AP4_DataBuffer>& picture_parameters) :
AP4_Atom(AP4_ATOM_TYPE_HVCC, AP4_ATOM_HEADER_SIZE),
m_ConfigurationVersion(1),
m_GeneralProfileSpace(general_profile_space),
m_GeneralTierFlag(general_tier_flag),
m_GeneralProfile(general_profile),
m_GeneralProfileCompatibilityFlags(general_profile_compatibility_flags),
m_GeneralConstraintIndicatorFlags(general_constraint_indicator_flags),
m_GeneralLevel(general_level),
m_Reserved1(0),
m_MinSpatialSegmentation(min_spatial_segmentation),
m_Reserved2(0),
m_ParallelismType(parallelism_type),
m_Reserved3(0),
m_ChromaFormat(chroma_format),
m_Reserved4(0),
m_LumaBitDepth(luma_bit_depth),
m_Reserved5(0),
m_ChromaBitDepth(chroma_bit_depth),
m_AverageFrameRate(average_frame_rate),
m_ConstantFrameRate(constant_frame_rate),
m_NumTemporalLayers(num_temporal_layers),
m_TemporalIdNested(temporal_id_nested),
m_NaluLengthSize(nalu_length_size)
{
// deep copy of the parameters
AP4_HvccAtom::Sequence vps_sequence;
vps_sequence.m_NaluType = AP4_HEVC_NALU_TYPE_VPS_NUT;
vps_sequence.m_ArrayCompleteness = 0;
for (unsigned int i=0; i<video_parameters.ItemCount(); i++) {
vps_sequence.m_Nalus.Append(video_parameters[i]);
}
if (vps_sequence.m_Nalus.ItemCount()) {
m_Sequences.Append(vps_sequence);
}
AP4_HvccAtom::Sequence sps_sequence;
sps_sequence.m_NaluType = AP4_HEVC_NALU_TYPE_SPS_NUT;
sps_sequence.m_ArrayCompleteness = 0;
for (unsigned int i=0; i<sequence_parameters.ItemCount(); i++) {
sps_sequence.m_Nalus.Append(sequence_parameters[i]);
}
if (sps_sequence.m_Nalus.ItemCount()) {
m_Sequences.Append(sps_sequence);
}
AP4_HvccAtom::Sequence pps_sequence;
pps_sequence.m_NaluType = AP4_HEVC_NALU_TYPE_PPS_NUT;
pps_sequence.m_ArrayCompleteness = 0;
for (unsigned int i=0; i<picture_parameters.ItemCount(); i++) {
pps_sequence.m_Nalus.Append(picture_parameters[i]);
}
if (pps_sequence.m_Nalus.ItemCount()) {
m_Sequences.Append(pps_sequence);
}
UpdateRawBytes();
m_Size32 += m_RawBytes.GetDataSize();
}
/*----------------------------------------------------------------------
| AP4_HvccAtom::AP4_HvccAtom
+---------------------------------------------------------------------*/
AP4_HvccAtom::AP4_HvccAtom(AP4_UI32 size, const AP4_UI08* payload) :
AP4_Atom(AP4_ATOM_TYPE_HVCC, size)
{
// make a copy of our configuration bytes
unsigned int payload_size = size-AP4_ATOM_HEADER_SIZE;
m_RawBytes.SetData(payload, payload_size);
// parse the payload
m_ConfigurationVersion = payload[0];
m_GeneralProfileSpace = (payload[1]>>6) & 0x03;
m_GeneralTierFlag = (payload[1]>>5) & 0x01;
m_GeneralProfile = (payload[1] ) & 0x1F;
m_GeneralProfileCompatibilityFlags = AP4_BytesToUInt32BE(&payload[2]);
m_GeneralConstraintIndicatorFlags = (((AP4_UI64)AP4_BytesToUInt32BE(&payload[6]))<<16) | AP4_BytesToUInt16BE(&payload[10]);
m_GeneralLevel = payload[12];
m_Reserved1 = (payload[13]>>4) & 0x0F;
m_MinSpatialSegmentation = AP4_BytesToUInt16BE(&payload[13]) & 0x0FFF;
m_Reserved2 = (payload[15]>>2) & 0x3F;
m_ParallelismType = payload[15] & 0x03;
m_Reserved3 = (payload[16]>>2) & 0x3F;
m_ChromaFormat = payload[16] & 0x03;
m_Reserved4 = (payload[17]>>3) & 0x1F;
m_LumaBitDepth = 8+(payload[17] & 0x07);
m_Reserved5 = (payload[18]>>3) & 0x1F;
m_ChromaBitDepth = 8+(payload[18] & 0x07);
m_AverageFrameRate = AP4_BytesToUInt16BE(&payload[19]);
m_ConstantFrameRate = (payload[21]>>6) & 0x03;
m_NumTemporalLayers = (payload[21]>>3) & 0x07;
m_TemporalIdNested = (payload[21]>>2) & 0x01;
m_NaluLengthSize = 1+(payload[21] & 0x03);
AP4_UI08 num_seq = payload[22];
m_Sequences.SetItemCount(num_seq);
unsigned int cursor = 23;
for (unsigned int i=0; i<num_seq; i++) {
Sequence& seq = m_Sequences[i];
if (cursor+1 > payload_size) break;
seq.m_ArrayCompleteness = (payload[cursor] >> 7) & 0x01;
seq.m_Reserved = (payload[cursor] >> 6) & 0x01;
seq.m_NaluType = payload[cursor] & 0x3F;
cursor += 1;
if (cursor+2 > payload_size) break;
AP4_UI16 nalu_count = AP4_BytesToUInt16BE(&payload[cursor]);
seq.m_Nalus.SetItemCount(nalu_count);
cursor += 2;
for (unsigned int j=0; j<nalu_count; j++) {
if (cursor+2 > payload_size) break;
unsigned int nalu_length = AP4_BytesToUInt16BE(&payload[cursor]);
cursor += 2;
if (cursor + nalu_length > payload_size) break;
seq.m_Nalus[j].SetData(&payload[cursor], nalu_length);
cursor += nalu_length;
}
}
}
/*----------------------------------------------------------------------
| AP4_HvccAtom::UpdateRawBytes
+---------------------------------------------------------------------*/
void
AP4_HvccAtom::UpdateRawBytes()
{
AP4_BitWriter bits(23);
bits.Write(m_ConfigurationVersion, 8);
bits.Write(m_GeneralProfileSpace, 2);
bits.Write(m_GeneralTierFlag, 1);
bits.Write(m_GeneralProfile, 5);
bits.Write(m_GeneralProfileCompatibilityFlags, 32);
bits.Write((AP4_UI32)(m_GeneralConstraintIndicatorFlags>>32), 16);
bits.Write((AP4_UI32)(m_GeneralConstraintIndicatorFlags), 32);
bits.Write(m_GeneralLevel, 8);
bits.Write(0xFF, 4);
bits.Write(m_MinSpatialSegmentation, 12);
bits.Write(0xFF, 6);
bits.Write(m_ParallelismType, 2);
bits.Write(0xFF, 6);
bits.Write(m_ChromaFormat, 2);
bits.Write(0xFF, 5);
bits.Write(m_LumaBitDepth >= 8 ? m_LumaBitDepth - 8 : 0, 3);
bits.Write(0xFF, 5);
bits.Write(m_ChromaBitDepth >= 8 ? m_ChromaBitDepth - 8 : 0, 3);
bits.Write(m_AverageFrameRate, 16);
bits.Write(m_ConstantFrameRate, 2);
bits.Write(m_NumTemporalLayers, 3);
bits.Write(m_TemporalIdNested, 1);
bits.Write(m_NaluLengthSize > 0 ? m_NaluLengthSize - 1 : 0, 2);
bits.Write(m_Sequences.ItemCount(), 8);
m_RawBytes.SetData(bits.GetData(), 23);
for (unsigned int i=0; i<m_Sequences.ItemCount(); i++) {
AP4_UI08 bytes[3];
bytes[0] = (m_Sequences[i].m_ArrayCompleteness ? (1<<7) : 0) | m_Sequences[i].m_NaluType;
AP4_BytesFromUInt16BE(&bytes[1], m_Sequences[i].m_Nalus.ItemCount());
m_RawBytes.AppendData(bytes, 3);
for (unsigned int j=0; j<m_Sequences[i].m_Nalus.ItemCount(); j++) {
AP4_UI08 size[2];
AP4_BytesFromUInt16BE(&size[0], (AP4_UI16)m_Sequences[i].m_Nalus[j].GetDataSize());
m_RawBytes.AppendData(size, 2);
m_RawBytes.AppendData(m_Sequences[i].m_Nalus[j].GetData(), m_Sequences[i].m_Nalus[j].GetDataSize());
}
}
}
/*----------------------------------------------------------------------
| AP4_HvccAtom::WriteFields
+---------------------------------------------------------------------*/
AP4_Result
AP4_HvccAtom::WriteFields(AP4_ByteStream& stream)
{
return stream.Write(m_RawBytes.GetData(), m_RawBytes.GetDataSize());
}
/*----------------------------------------------------------------------
| AP4_HvccAtom::InspectFields
+---------------------------------------------------------------------*/
AP4_Result
AP4_HvccAtom::InspectFields(AP4_AtomInspector& inspector)
{
inspector.AddField("Configuration Version", m_ConfigurationVersion);
inspector.AddField("Profile Space", m_GeneralProfileSpace);
const char* profile_name = GetProfileName(m_GeneralProfileSpace, m_GeneralProfile);
if (profile_name) {
inspector.AddField("Profile", profile_name);
} else {
inspector.AddField("Profile", m_GeneralProfile);
}
inspector.AddField("Tier", m_GeneralTierFlag);
inspector.AddField("Profile Compatibility", m_GeneralProfileCompatibilityFlags, AP4_AtomInspector::HINT_HEX);
inspector.AddField("Constraint", m_GeneralConstraintIndicatorFlags, AP4_AtomInspector::HINT_HEX);
inspector.AddField("Level", m_GeneralLevel);
inspector.AddField("Min Spatial Segmentation", m_MinSpatialSegmentation);
inspector.AddField("Parallelism Type", m_ParallelismType);
inspector.AddField("Chroma Format", m_ChromaFormat);
inspector.AddField("Chroma Depth", m_ChromaBitDepth);
inspector.AddField("Luma Depth", m_LumaBitDepth);
inspector.AddField("Average Frame Rate", m_AverageFrameRate);
inspector.AddField("Constant Frame Rate", m_ConstantFrameRate);
inspector.AddField("Number Of Temporal Layers", m_NumTemporalLayers);
inspector.AddField("Temporal Id Nested", m_TemporalIdNested);
inspector.AddField("NALU Length Size", m_NaluLengthSize);
return AP4_SUCCESS;
}
| ./CrossVul/dataset_final_sorted/CWE-125/cpp/bad_2813_1 |
crossvul-cpp_data_good_138_0 | /**
* Simple engine for creating PDF files.
* It supports text, shapes, images etc...
* Capable of handling millions of objects without too much performance
* penalty.
* Public domain license - no warrenty implied; use at your own risk.
*/
/**
* PDF HINTS & TIPS
* The following sites have various bits & pieces about PDF document
* generation
* http://www.mactech.com/articles/mactech/Vol.15/15.09/PDFIntro/index.html
* http://gnupdf.org/Introduction_to_PDF
* http://www.planetpdf.com/mainpage.asp?WebPageID=63
* http://archive.vector.org.uk/art10008970
* http://www.adobe.com/devnet/acrobat/pdfs/pdf_reference_1-7.pdf
* https://blog.idrsolutions.com/2013/01/understanding-the-pdf-file-format-overview/
*
* To validate the PDF output, there are several online validators:
* http://www.validatepdfa.com/online.htm
* http://www.datalogics.com/products/callas/callaspdfA-onlinedemo.asp
* http://www.pdf-tools.com/pdf/validate-pdfa-online.aspx
*
* In addition the 'pdftk' server can be used to analyse the output:
* https://www.pdflabs.com/docs/pdftk-cli-examples/
*
* PDF page markup operators:
* b closepath, fill,and stroke path.
* B fill and stroke path.
* b* closepath, eofill,and stroke path.
* B* eofill and stroke path.
* BI begin image.
* BMC begin marked content.
* BT begin text object.
* BX begin section allowing undefined operators.
* c curveto.
* cm concat. Concatenates the matrix to the current transform.
* cs setcolorspace for fill.
* CS setcolorspace for stroke.
* d setdash.
* Do execute the named XObject.
* DP mark a place in the content stream, with a dictionary.
* EI end image.
* EMC end marked content.
* ET end text object.
* EX end section that allows undefined operators.
* f fill path.
* f* eofill Even/odd fill path.
* g setgray (fill).
* G setgray (stroke).
* gs set parameters in the extended graphics state.
* h closepath.
* i setflat.
* ID begin image data.
* j setlinejoin.
* J setlinecap.
* k setcmykcolor (fill).
* K setcmykcolor (stroke).
* l lineto.
* m moveto.
* M setmiterlimit.
* n end path without fill or stroke.
* q save graphics state.
* Q restore graphics state.
* re rectangle.
* rg setrgbcolor (fill).
* RG setrgbcolor (stroke).
* s closepath and stroke path.
* S stroke path.
* sc setcolor (fill).
* SC setcolor (stroke).
* sh shfill (shaded fill).
* Tc set character spacing.
* Td move text current point.
* TD move text current point and set leading.
* Tf set font name and size.
* Tj show text.
* TJ show text, allowing individual character positioning.
* TL set leading.
* Tm set text matrix.
* Tr set text rendering mode.
* Ts set super/subscripting text rise.
* Tw set word spacing.
* Tz set horizontal scaling.
* T* move to start of next line.
* v curveto.
* w setlinewidth.
* W clip.
* y curveto.
*/
#define _POSIX_SOURCE /* For localtime_r */
#include <sys/types.h>
#include <ctype.h>
#include <sys/stat.h>
#include <errno.h>
#include <limits.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
#include "pdfgen.h"
#define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0]))
#define PDF_RGB_R(c) ((((c) >> 16) & 0xff) / 255.0)
#define PDF_RGB_G(c) ((((c) >> 8) & 0xff) / 255.0)
#define PDF_RGB_B(c) ((((c) >> 0) & 0xff) / 255.0)
#if defined(_MSC_VER)
/*
* As stated here: http://stackoverflow.com/questions/70013/how-to-detect-if-im-compiling-code-with-visual-studio-2008
* Visual Studio 2015 has better support for C99
* We need to use __inline for older version.
*/
#if _MSC_VER < 1900
#define inline __inline
#endif
#endif // _MSC_VER
typedef struct pdf_object pdf_object;
enum {
OBJ_none, /* skipped */
OBJ_info,
OBJ_stream,
OBJ_font,
OBJ_page,
OBJ_bookmark,
OBJ_outline,
OBJ_catalog,
OBJ_pages,
OBJ_image,
OBJ_count,
};
struct flexarray {
void ***bins;
int item_count;
int bin_count;
};
struct pdf_object {
int type; /* See OBJ_xxxx */
int index; /* PDF output index */
int offset; /* Byte position within the output file */
struct pdf_object *prev; /* Previous of this type */
struct pdf_object *next; /* Next of this type */
union {
struct {
struct pdf_object *page;
char name[64];
struct pdf_object *parent;
struct flexarray children;
} bookmark;
struct {
char *text;
int len;
} stream;
struct {
int width;
int height;
struct flexarray children;
} page;
struct pdf_info info;
struct {
char name[64];
int index;
} font;
};
};
struct pdf_doc {
char errstr[128];
int errval;
struct flexarray objects;
int width;
int height;
struct pdf_object *current_font;
struct pdf_object *last_objects[OBJ_count];
struct pdf_object *first_objects[OBJ_count];
};
/**
* Simple flexible resizing array implementation
* The bins get larger in powers of two
* bin 0 = 1024 items
* 1 = 2048 items
* 2 = 4096 items
* etc...
*/
/* What is the first index that will be in the given bin? */
#define MIN_SHIFT 10
#define MIN_OFFSET ((1 << MIN_SHIFT) - 1)
static int bin_offset[] = {
(1 << (MIN_SHIFT + 0)) - 1 - MIN_OFFSET,
(1 << (MIN_SHIFT + 1)) - 1 - MIN_OFFSET,
(1 << (MIN_SHIFT + 2)) - 1 - MIN_OFFSET,
(1 << (MIN_SHIFT + 3)) - 1 - MIN_OFFSET,
(1 << (MIN_SHIFT + 4)) - 1 - MIN_OFFSET,
(1 << (MIN_SHIFT + 5)) - 1 - MIN_OFFSET,
(1 << (MIN_SHIFT + 6)) - 1 - MIN_OFFSET,
(1 << (MIN_SHIFT + 7)) - 1 - MIN_OFFSET,
(1 << (MIN_SHIFT + 8)) - 1 - MIN_OFFSET,
(1 << (MIN_SHIFT + 9)) - 1 - MIN_OFFSET,
(1 << (MIN_SHIFT + 10)) - 1 - MIN_OFFSET,
(1 << (MIN_SHIFT + 11)) - 1 - MIN_OFFSET,
(1 << (MIN_SHIFT + 12)) - 1 - MIN_OFFSET,
(1 << (MIN_SHIFT + 13)) - 1 - MIN_OFFSET,
(1 << (MIN_SHIFT + 14)) - 1 - MIN_OFFSET,
(1 << (MIN_SHIFT + 15)) - 1 - MIN_OFFSET,
};
static inline int flexarray_get_bin(struct flexarray *flex, int index)
{
int i;
(void)flex;
for (i = 0; i < ARRAY_SIZE(bin_offset); i++)
if (index < bin_offset[i])
return i - 1;
return -1;
}
static inline int flexarray_get_bin_size(struct flexarray *flex, int bin)
{
(void)flex;
if (bin >= ARRAY_SIZE(bin_offset))
return -1;
int next = bin_offset[bin + 1];
return next - bin_offset[bin];
}
static inline int flexarray_get_bin_offset(struct flexarray *flex, int bin, int index)
{
(void)flex;
return index - bin_offset[bin];
}
static void flexarray_clear(struct flexarray *flex)
{
int i;
for (i = 0; i < flex->bin_count; i++)
free(flex->bins[i]);
free(flex->bins);
flex->bin_count = 0;
flex->item_count = 0;
}
static inline int flexarray_size(struct flexarray *flex)
{
return flex->item_count;
}
static int flexarray_set(struct flexarray *flex, int index, void *data)
{
int bin = flexarray_get_bin(flex, index);
if (bin < 0)
return -EINVAL;
if (bin >= flex->bin_count) {
void *bins = realloc(flex->bins, (flex->bin_count + 1) *
sizeof(flex->bins));
if (!bins)
return -ENOMEM;
flex->bin_count++;
flex->bins = bins;
flex->bins[flex->bin_count - 1] =
calloc(flexarray_get_bin_size(flex, flex->bin_count - 1),
sizeof(void *));
if (!flex->bins[flex->bin_count - 1]) {
flex->bin_count--;
return -ENOMEM;
}
}
flex->item_count++;
flex->bins[bin][flexarray_get_bin_offset(flex, bin, index)] = data;
return flex->item_count - 1;
}
static inline int flexarray_append(struct flexarray *flex, void *data)
{
return flexarray_set(flex, flexarray_size(flex), data);
}
static inline void *flexarray_get(struct flexarray *flex, int index)
{
int bin;
if (index >= flex->item_count)
return NULL;
bin = flexarray_get_bin(flex, index);
if (bin < 0 || bin >= flex->bin_count)
return NULL;
return flex->bins[bin][flexarray_get_bin_offset(flex, bin, index)];
}
/**
* PDF Implementation
*/
static int pdf_set_err(struct pdf_doc *doc, int errval,
const char *buffer, ...)
__attribute__ ((format(printf, 3, 4)));
static int pdf_set_err(struct pdf_doc *doc, int errval,
const char *buffer, ...)
{
va_list ap;
int len;
va_start(ap, buffer);
len = vsnprintf(doc->errstr, sizeof(doc->errstr) - 2, buffer, ap);
va_end(ap);
/* Make sure we're properly terminated */
if (doc->errstr[len] != '\n')
doc->errstr[len] = '\n';
doc->errstr[len] = '\0';
doc->errval = errval;
return errval;
}
const char *pdf_get_err(struct pdf_doc *pdf, int *errval)
{
if (!pdf)
return NULL;
if (pdf->errstr[0] == '\0')
return NULL;
if (errval) *errval = pdf->errval;
return pdf->errstr;
}
void pdf_clear_err(struct pdf_doc *pdf)
{
if (!pdf)
return;
pdf->errstr[0] = '\0';
pdf->errval = 0;
}
static struct pdf_object *pdf_get_object(struct pdf_doc *pdf, int index)
{
return flexarray_get(&pdf->objects, index);
}
static int pdf_append_object(struct pdf_doc *pdf, struct pdf_object *obj)
{
int index = flexarray_append(&pdf->objects, obj);
if (index < 0)
return index;
obj->index = index;
if (pdf->last_objects[obj->type]) {
obj->prev = pdf->last_objects[obj->type];
pdf->last_objects[obj->type]->next = obj;
}
pdf->last_objects[obj->type] = obj;
if (!pdf->first_objects[obj->type])
pdf->first_objects[obj->type] = obj;
return 0;
}
static struct pdf_object *pdf_add_object(struct pdf_doc *pdf, int type)
{
struct pdf_object *obj;
obj = calloc(1, sizeof(struct pdf_object));
if (!obj) {
pdf_set_err(pdf, -errno, "Unable to allocate object %d: %s",
flexarray_size(&pdf->objects) + 1, strerror(errno));
return NULL;
}
obj->type = type;
if (pdf_append_object(pdf, obj) < 0) {
free(obj);
return NULL;
}
return obj;
}
struct pdf_doc *pdf_create(int width, int height, struct pdf_info *info)
{
struct pdf_doc *pdf;
struct pdf_object *obj;
pdf = calloc(1, sizeof(struct pdf_doc));
pdf->width = width;
pdf->height = height;
/* We don't want to use ID 0 */
pdf_add_object(pdf, OBJ_none);
/* Create the 'info' object */
obj = pdf_add_object(pdf, OBJ_info);
if (info)
obj->info = *info;
/* FIXME: Should be quoting PDF strings? */
if (!obj->info.date[0]) {
time_t now = time(NULL);
struct tm tm;
#ifdef _WIN32
struct tm *tmp;
tmp = localtime(&now);
tm = *tmp;
#else
localtime_r(&now, &tm);
#endif
strftime(obj->info.date, sizeof(obj->info.date),
"%Y%m%d%H%M%SZ", &tm);
}
if (!obj->info.creator[0])
strcpy(obj->info.creator, "pdfgen");
if (!obj->info.producer[0])
strcpy(obj->info.producer, "pdfgen");
if (!obj->info.title[0])
strcpy(obj->info.title, "pdfgen");
if (!obj->info.author[0])
strcpy(obj->info.author, "pdfgen");
if (!obj->info.subject[0])
strcpy(obj->info.subject, "pdfgen");
pdf_add_object(pdf, OBJ_pages);
pdf_add_object(pdf, OBJ_catalog);
pdf_set_font(pdf, "Times-Roman");
return pdf;
}
int pdf_width(struct pdf_doc *pdf)
{
return pdf->width;
}
int pdf_height(struct pdf_doc *pdf)
{
return pdf->height;
}
static void pdf_object_destroy(struct pdf_object *object)
{
switch (object->type) {
case OBJ_stream:
case OBJ_image:
free(object->stream.text);
break;
case OBJ_page:
flexarray_clear(&object->page.children);
break;
case OBJ_bookmark:
flexarray_clear(&object->bookmark.children);
break;
}
free(object);
}
void pdf_destroy(struct pdf_doc *pdf)
{
if (pdf) {
int i;
for (i = 0; i < flexarray_size(&pdf->objects); i++)
pdf_object_destroy(pdf_get_object(pdf, i));
flexarray_clear(&pdf->objects);
free(pdf);
}
}
static struct pdf_object *pdf_find_first_object(struct pdf_doc *pdf,
int type)
{
return pdf->first_objects[type];
}
static struct pdf_object *pdf_find_last_object(struct pdf_doc *pdf,
int type)
{
return pdf->last_objects[type];
}
int pdf_set_font(struct pdf_doc *pdf, const char *font)
{
struct pdf_object *obj;
int last_index = 0;
/* See if we've used this font before */
for (obj = pdf_find_first_object(pdf, OBJ_font); obj; obj = obj->next) {
if (strcmp(obj->font.name, font) == 0)
break;
last_index = obj->font.index;
}
/* Create a new font object if we need it */
if (!obj) {
obj = pdf_add_object(pdf, OBJ_font);
if (!obj)
return pdf->errval;
strncpy(obj->font.name, font, sizeof(obj->font.name));
obj->font.name[sizeof(obj->font.name) - 1] = '\0';
obj->font.index = last_index + 1;
}
pdf->current_font = obj;
return 0;
}
struct pdf_object *pdf_append_page(struct pdf_doc *pdf)
{
struct pdf_object *page;
page = pdf_add_object(pdf, OBJ_page);
if (!page)
return NULL;
page->page.width = pdf->width;
page->page.height = pdf->height;
return page;
}
int pdf_page_set_size(struct pdf_doc *pdf, struct pdf_object *page, int width, int height)
{
if (!page)
page = pdf_find_last_object(pdf, OBJ_page);
if (!page || page->type != OBJ_page)
return pdf_set_err(pdf, -EINVAL, "Invalid PDF page");
page->page.width = width;
page->page.height = height;
return 0;
}
static int pdf_save_object(struct pdf_doc *pdf, FILE *fp, int index)
{
struct pdf_object *object = pdf_get_object(pdf, index);
if (object->type == OBJ_none)
return -ENOENT;
object->offset = ftell(fp);
fprintf(fp, "%d 0 obj\r\n", index);
switch (object->type) {
case OBJ_stream:
case OBJ_image: {
int len = object->stream.len ? object->stream.len :
strlen(object->stream.text);
fwrite(object->stream.text, len, 1, fp);
break;
}
case OBJ_info: {
struct pdf_info *info = &object->info;
fprintf(fp, "<<\r\n"
" /Creator (%s)\r\n"
" /Producer (%s)\r\n"
" /Title (%s)\r\n"
" /Author (%s)\r\n"
" /Subject (%s)\r\n"
" /CreationDate (D:%s)\r\n"
">>\r\n",
info->creator, info->producer, info->title,
info->author, info->subject, info->date);
break;
}
case OBJ_page: {
int i;
struct pdf_object *font;
struct pdf_object *pages = pdf_find_first_object(pdf, OBJ_pages);
struct pdf_object *image = pdf_find_first_object(pdf, OBJ_image);
fprintf(fp, "<<\r\n"
"/Type /Page\r\n"
"/Parent %d 0 R\r\n", pages->index);
fprintf(fp, "/MediaBox [0 0 %d %d]\r\n",
object->page.width, object->page.height);
fprintf(fp, "/Resources <<\r\n");
fprintf(fp, " /Font <<\r\n");
for (font = pdf_find_first_object(pdf, OBJ_font); font; font = font->next)
fprintf(fp, " /F%d %d 0 R\r\n",
font->font.index, font->index);
fprintf(fp, " >>\r\n");
if (image) {
fprintf(fp, " /XObject <<");
for (; image; image = image->next)
fprintf(fp, "/Image%d %d 0 R ", image->index, image->index);
fprintf(fp, ">>\r\n");
}
fprintf(fp, ">>\r\n");
fprintf(fp, "/Contents [\r\n");
for (i = 0; i < flexarray_size(&object->page.children); i++) {
struct pdf_object *child = flexarray_get(&object->page.children, i);
fprintf(fp, "%d 0 R\r\n", child->index);
}
fprintf(fp, "]\r\n");
fprintf(fp, ">>\r\n");
break;
}
case OBJ_bookmark: {
struct pdf_object *parent, *other;
parent = object->bookmark.parent;
if (!parent)
parent = pdf_find_first_object(pdf, OBJ_outline);
if (!object->bookmark.page)
break;
fprintf(fp, "<<\r\n"
"/A << /Type /Action\r\n"
" /S /GoTo\r\n"
" /D [%d 0 R /XYZ 0 %d null]\r\n"
" >>\r\n"
"/Parent %d 0 R\r\n"
"/Title (%s)\r\n",
object->bookmark.page->index,
pdf->height,
parent->index,
object->bookmark.name);
int nchildren = flexarray_size(&object->bookmark.children);
if (nchildren > 0) {
struct pdf_object *f, *l;
f = flexarray_get(&object->bookmark.children, 0);
l = flexarray_get(&object->bookmark.children, nchildren - 1);
fprintf(fp, "/First %d 0 R\r\n", f->index);
fprintf(fp, "/Last %d 0 R\r\n", l->index);
}
// Find the previous bookmark with the same parent
for (other = object->prev;
other && other->bookmark.parent != object->bookmark.parent;
other = other->prev)
;
if (other)
fprintf(fp, "/Prev %d 0 R\r\n", other->index);
// Find the next bookmark with the same parent
for (other = object->next;
other && other->bookmark.parent != object->bookmark.parent;
other = other->next)
;
if (other)
fprintf(fp, "/Next %d 0 R\r\n", other->index);
fprintf(fp, ">>\r\n");
break;
}
case OBJ_outline: {
struct pdf_object *first, *last, *cur;
first = pdf_find_first_object(pdf, OBJ_bookmark);
last = pdf_find_last_object(pdf, OBJ_bookmark);
if (first && last) {
int count = 0;
cur = first;
while (cur) {
if (!cur->bookmark.parent)
count++;
cur = cur->next;
}
/* Bookmark outline */
fprintf(fp, "<<\r\n"
"/Count %d\r\n"
"/Type /Outlines\r\n"
"/First %d 0 R\r\n"
"/Last %d 0 R\r\n"
">>\r\n",
count, first->index, last->index);
}
break;
}
case OBJ_font:
fprintf(fp, "<<\r\n"
" /Type /Font\r\n"
" /Subtype /Type1\r\n"
" /BaseFont /%s\r\n"
" /Encoding /WinAnsiEncoding\r\n"
">>\r\n", object->font.name);
break;
case OBJ_pages: {
struct pdf_object *page;
int npages = 0;
fprintf(fp, "<<\r\n"
"/Type /Pages\r\n"
"/Kids [ ");
for (page = pdf_find_first_object(pdf, OBJ_page);
page;
page = page->next) {
npages++;
fprintf(fp, "%d 0 R ", page->index);
}
fprintf(fp, "]\r\n");
fprintf(fp, "/Count %d\r\n", npages);
fprintf(fp, ">>\r\n");
break;
}
case OBJ_catalog: {
struct pdf_object *outline = pdf_find_first_object(pdf, OBJ_outline);
struct pdf_object *pages = pdf_find_first_object(pdf, OBJ_pages);
fprintf(fp, "<<\r\n"
"/Type /Catalog\r\n");
if (outline)
fprintf(fp,
"/Outlines %d 0 R\r\n"
"/PageMode /UseOutlines\r\n", outline->index);
fprintf(fp, "/Pages %d 0 R\r\n"
">>\r\n",
pages->index);
break;
}
default:
return pdf_set_err(pdf, -EINVAL, "Invalid PDF object type %d",
object->type);
}
fprintf(fp, "endobj\r\n");
return 0;
}
int pdf_save(struct pdf_doc *pdf, const char *filename)
{
FILE *fp;
int i;
struct pdf_object *obj;
int xref_offset;
int xref_count = 0;
if (filename == NULL)
fp = stdout;
else if ((fp = fopen(filename, "wb")) == NULL)
return pdf_set_err(pdf, -errno, "Unable to open '%s': %s",
filename, strerror(errno));
fprintf(fp, "%%PDF-1.2\r\n");
/* Hibit bytes */
fprintf(fp, "%c%c%c%c%c\r\n", 0x25, 0xc7, 0xec, 0x8f, 0xa2);
/* Dump all the objects & get their file offsets */
for (i = 0; i < flexarray_size(&pdf->objects); i++)
if (pdf_save_object(pdf, fp, i) >= 0)
xref_count++;
/* xref */
xref_offset = ftell(fp);
fprintf(fp, "xref\r\n");
fprintf(fp, "0 %d\r\n", xref_count + 1);
fprintf(fp, "0000000000 65535 f\r\n");
for (i = 0; i < flexarray_size(&pdf->objects); i++) {
obj = pdf_get_object(pdf, i);
if (obj->type != OBJ_none)
fprintf(fp, "%10.10d 00000 n\r\n",
obj->offset);
}
fprintf(fp, "trailer\r\n"
"<<\r\n"
"/Size %d\r\n", xref_count + 1);
obj = pdf_find_first_object(pdf, OBJ_catalog);
fprintf(fp, "/Root %d 0 R\r\n", obj->index);
obj = pdf_find_first_object(pdf, OBJ_info);
fprintf(fp, "/Info %d 0 R\r\n", obj->index);
/* FIXME: Not actually generating a unique ID */
fprintf(fp, "/ID [<%16.16x> <%16.16x>]\r\n", 0x123, 0x123);
fprintf(fp, ">>\r\n"
"startxref\r\n");
fprintf(fp, "%d\r\n", xref_offset);
fprintf(fp, "%%%%EOF\r\n");
fclose(fp);
return 0;
}
static int pdf_add_stream(struct pdf_doc *pdf, struct pdf_object *page,
char *buffer)
{
struct pdf_object *obj;
int len;
char prefix[128];
char suffix[128];
if (!page)
page = pdf_find_last_object(pdf, OBJ_page);
if (!page)
return pdf_set_err(pdf, -EINVAL, "Invalid pdf page");
len = strlen(buffer);
/* We don't want any trailing whitespace in the stream */
while (len >= 1 && (buffer[len - 1] == '\r' ||
buffer[len - 1] == '\n')) {
buffer[len - 1] = '\0';
len--;
}
sprintf(prefix, "<< /Length %d >>stream\r\n", len);
sprintf(suffix, "\r\nendstream\r\n");
len += strlen(prefix) + strlen(suffix);
obj = pdf_add_object(pdf, OBJ_stream);
if (!obj)
return pdf->errval;
obj->stream.text = malloc(len + 1);
if (!obj->stream.text) {
obj->type = OBJ_none;
return pdf_set_err(pdf, -ENOMEM, "Insufficient memory for text (%d bytes)",
len + 1);
}
obj->stream.text[0] = '\0';
strcat(obj->stream.text, prefix);
strcat(obj->stream.text, buffer);
strcat(obj->stream.text, suffix);
obj->stream.len = 0;
return flexarray_append(&page->page.children, obj);
}
int pdf_add_bookmark(struct pdf_doc *pdf, struct pdf_object *page,
int parent, const char *name)
{
struct pdf_object *obj;
if (!page)
page = pdf_find_last_object(pdf, OBJ_page);
if (!page)
return pdf_set_err(pdf, -EINVAL,
"Unable to add bookmark, no pages available");
if (!pdf_find_first_object(pdf, OBJ_outline))
if (!pdf_add_object(pdf, OBJ_outline))
return pdf->errval;
obj = pdf_add_object(pdf, OBJ_bookmark);
if (!obj)
return pdf->errval;
strncpy(obj->bookmark.name, name, sizeof(obj->bookmark.name));
obj->bookmark.name[sizeof(obj->bookmark.name) - 1] = '\0';
obj->bookmark.page = page;
if (parent >= 0) {
struct pdf_object *parent_obj = pdf_get_object(pdf, parent);
if (!parent_obj)
return pdf_set_err(pdf, -EINVAL,
"Invalid parent ID %d supplied", parent);
obj->bookmark.parent = parent_obj;
flexarray_append(&parent_obj->bookmark.children, obj);
}
return obj->index;
}
struct dstr {
char *data;
int alloc_len;
int used_len;
};
static int dstr_ensure(struct dstr *str, int len)
{
if (str->alloc_len < len) {
int new_len = len + 4096;
char *new_data = realloc(str->data, new_len);
if (!new_data)
return -ENOMEM;
str->data = new_data;
str->alloc_len = new_len;
}
return 0;
}
static int dstr_printf(struct dstr *str, const char *fmt, ...)
__attribute__((format(printf,2,3)));
static int dstr_printf(struct dstr *str, const char *fmt, ...)
{
va_list ap, aq;
int len;
va_start(ap, fmt);
va_copy(aq, ap);
len = vsnprintf(NULL, 0, fmt, ap);
if (dstr_ensure(str, str->used_len + len + 1) < 0) {
va_end(ap);
va_end(aq);
return -ENOMEM;
}
vsprintf(&str->data[str->used_len], fmt, aq);
str->used_len += len;
va_end(ap);
va_end(aq);
return len;
}
static int dstr_append(struct dstr *str, const char *extend)
{
int len = strlen(extend);
if (dstr_ensure(str, str->used_len + len + 1) < 0)
return -ENOMEM;
strcpy(&str->data[str->used_len], extend);
str->used_len += len;
return len;
}
static void dstr_free(struct dstr *str)
{
free(str->data);
}
static int utf8_to_utf32(const char *utf8, int len, uint32_t *utf32)
{
uint32_t ch = *utf8;
int i;
uint8_t mask;
if ((ch & 0x80) == 0) {
len = 1;
mask = 0x7f;
} else if ((ch & 0xe0) == 0xc0 && len >= 2) {
len = 2;
mask = 0x1f;
} else if ((ch & 0xf0) == 0xe0 && len >= 3) {
len = 3;
mask = 0xf;
} else if ((ch & 0xf8) == 0xf0 && len >= 4) {
len = 4;
mask = 0x7;
} else
return -EINVAL;
ch = 0;
for (i = 0; i < len; i++) {
int shift = (len - i - 1) * 6;
if (i == 0)
ch |= ((uint32_t)(*utf8++) & mask) << shift;
else
ch |= ((uint32_t)(*utf8++) & 0x3f) << shift;
}
*utf32 = ch;
return len;
}
int pdf_add_text(struct pdf_doc *pdf, struct pdf_object *page,
const char *text, int size, int xoff, int yoff,
uint32_t colour)
{
int i, ret;
int len = text ? strlen(text) : 0;
struct dstr str = {0, 0, 0};
/* Don't bother adding empty/null strings */
if (!len)
return 0;
dstr_append(&str, "BT ");
dstr_printf(&str, "%d %d TD ", xoff, yoff);
dstr_printf(&str, "/F%d %d Tf ",
pdf->current_font->font.index, size);
dstr_printf(&str, "%f %f %f rg ",
PDF_RGB_R(colour), PDF_RGB_G(colour), PDF_RGB_B(colour));
dstr_append(&str, "(");
/* Escape magic characters properly */
for (i = 0; i < len; ) {
uint32_t code;
int code_len;
code_len = utf8_to_utf32(&text[i], len - i, &code);
if (code_len < 0) {
dstr_free(&str);
return pdf_set_err(pdf, -EINVAL, "Invalid UTF-8 encoding");
}
if (code > 255) {
/* We support *some* minimal UTF-8 characters */
char buf[5] = {0};
switch (code) {
case 0x160:
buf[0] = (char)0x8a;
break;
case 0x161:
buf[0] = (char)0x9a;
break;
case 0x17d:
buf[0] = (char)0x8e;
break;
case 0x17e:
buf[0] = (char)0x9e;
break;
case 0x20ac:
strcpy(buf, "\\200");
break;
default:
dstr_free(&str);
return pdf_set_err(pdf, -EINVAL, "Unsupported UTF-8 character: 0x%x 0o%o", code, code);
}
dstr_append(&str, buf);
} else if (strchr("()\\", code)) {
char buf[3];
/* Escape some characters */
buf[0] = '\\';
buf[1] = code;
buf[2] = '\0';
dstr_append(&str, buf);
} else if (strrchr("\n\r\t\b\f", code)) {
/* Skip over these characters */
;
} else {
char buf[2];
buf[0] = code;
buf[1] = '\0';
dstr_append(&str, buf);
}
i += code_len;
}
dstr_append(&str, ") Tj ");
dstr_append(&str, "ET");
ret = pdf_add_stream(pdf, page, str.data);
dstr_free(&str);
return ret;
}
/* How wide is each character, in points, at size 14 */
static const uint16_t helvetica_widths[256] = {
278, 278, 278, 278, 278, 278, 278, 278,
278, 278, 278, 278, 278, 278, 278, 278,
278, 278, 278, 278, 278, 278, 278, 278,
278, 278, 278, 278, 278, 278, 278, 278,
278, 278, 355, 556, 556, 889, 667, 191,
333, 333, 389, 584, 278, 333, 278, 278,
556, 556, 556, 556, 556, 556, 556, 556,
556, 556, 278, 278, 584, 584, 584, 556,
1015, 667, 667, 722, 722, 667, 611, 778,
722, 278, 500, 667, 556, 833, 722, 778,
667, 778, 722, 667, 611, 722, 667, 944,
667, 667, 611, 278, 278, 278, 469, 556,
333, 556, 556, 500, 556, 556, 278, 556,
556, 222, 222, 500, 222, 833, 556, 556,
556, 556, 333, 500, 278, 556, 500, 722,
500, 500, 500, 334, 260, 334, 584, 350,
556, 350, 222, 556, 333, 1000, 556, 556,
333, 1000, 667, 333, 1000, 350, 611, 350,
350, 222, 222, 333, 333, 350, 556, 1000,
333, 1000, 500, 333, 944, 350, 500, 667,
278, 333, 556, 556, 556, 556, 260, 556,
333, 737, 370, 556, 584, 333, 737, 333,
400, 584, 333, 333, 333, 556, 537, 278,
333, 333, 365, 556, 834, 834, 834, 611,
667, 667, 667, 667, 667, 667, 1000, 722,
667, 667, 667, 667, 278, 278, 278, 278,
722, 722, 778, 778, 778, 778, 778, 584,
778, 722, 722, 722, 722, 667, 667, 611,
556, 556, 556, 556, 556, 556, 889, 500,
556, 556, 556, 556, 278, 278, 278, 278,
556, 556, 556, 556, 556, 556, 556, 584,
611, 556, 556, 556, 556, 500, 556, 500
};
static const uint16_t helvetica_bold_widths[256] = {
278, 278, 278, 278, 278, 278, 278, 278,
278, 278, 278, 278, 278, 278, 278, 278,
278, 278, 278, 278, 278, 278, 278, 278,
278, 278, 278, 278, 278, 278, 278, 278,
278, 333, 474, 556, 556, 889, 722, 238,
333, 333, 389, 584, 278, 333, 278, 278,
556, 556, 556, 556, 556, 556, 556, 556,
556, 556, 333, 333, 584, 584, 584, 611,
975, 722, 722, 722, 722, 667, 611, 778,
722, 278, 556, 722, 611, 833, 722, 778,
667, 778, 722, 667, 611, 722, 667, 944,
667, 667, 611, 333, 278, 333, 584, 556,
333, 556, 611, 556, 611, 556, 333, 611,
611, 278, 278, 556, 278, 889, 611, 611,
611, 611, 389, 556, 333, 611, 556, 778,
556, 556, 500, 389, 280, 389, 584, 350,
556, 350, 278, 556, 500, 1000, 556, 556,
333, 1000, 667, 333, 1000, 350, 611, 350,
350, 278, 278, 500, 500, 350, 556, 1000,
333, 1000, 556, 333, 944, 350, 500, 667,
278, 333, 556, 556, 556, 556, 280, 556,
333, 737, 370, 556, 584, 333, 737, 333,
400, 584, 333, 333, 333, 611, 556, 278,
333, 333, 365, 556, 834, 834, 834, 611,
722, 722, 722, 722, 722, 722, 1000, 722,
667, 667, 667, 667, 278, 278, 278, 278,
722, 722, 778, 778, 778, 778, 778, 584,
778, 722, 722, 722, 722, 667, 667, 611,
556, 556, 556, 556, 556, 556, 889, 556,
556, 556, 556, 556, 278, 278, 278, 278,
611, 611, 611, 611, 611, 611, 611, 584,
611, 611, 611, 611, 611, 556, 611, 556
};
static uint16_t helvetica_bold_oblique_widths[256] = {
278, 278, 278, 278, 278, 278, 278, 278,
278, 278, 278, 278, 278, 278, 278, 278,
278, 278, 278, 278, 278, 278, 278, 278,
278, 278, 278, 278, 278, 278, 278, 278,
278, 333, 474, 556, 556, 889, 722, 238,
333, 333, 389, 584, 278, 333, 278, 278,
556, 556, 556, 556, 556, 556, 556, 556,
556, 556, 333, 333, 584, 584, 584, 611,
975, 722, 722, 722, 722, 667, 611, 778,
722, 278, 556, 722, 611, 833, 722, 778,
667, 778, 722, 667, 611, 722, 667, 944,
667, 667, 611, 333, 278, 333, 584, 556,
333, 556, 611, 556, 611, 556, 333, 611,
611, 278, 278, 556, 278, 889, 611, 611,
611, 611, 389, 556, 333, 611, 556, 778,
556, 556, 500, 389, 280, 389, 584, 350,
556, 350, 278, 556, 500, 1000, 556, 556,
333, 1000, 667, 333, 1000, 350, 611, 350,
350, 278, 278, 500, 500, 350, 556, 1000,
333, 1000, 556, 333, 944, 350, 500, 667,
278, 333, 556, 556, 556, 556, 280, 556,
333, 737, 370, 556, 584, 333, 737, 333,
400, 584, 333, 333, 333, 611, 556, 278,
333, 333, 365, 556, 834, 834, 834, 611,
722, 722, 722, 722, 722, 722, 1000, 722,
667, 667, 667, 667, 278, 278, 278, 278,
722, 722, 778, 778, 778, 778, 778, 584,
778, 722, 722, 722, 722, 667, 667, 611,
556, 556, 556, 556, 556, 556, 889, 556,
556, 556, 556, 556, 278, 278, 278, 278,
611, 611, 611, 611, 611, 611, 611, 584,
611, 611, 611, 611, 611, 556, 611, 556
};
static uint16_t helvetica_oblique_widths[256] = {
278, 278, 278, 278, 278, 278, 278, 278,
278, 278, 278, 278, 278, 278, 278, 278,
278, 278, 278, 278, 278, 278, 278, 278,
278, 278, 278, 278, 278, 278, 278, 278,
278, 278, 355, 556, 556, 889, 667, 191,
333, 333, 389, 584, 278, 333, 278, 278,
556, 556, 556, 556, 556, 556, 556, 556,
556, 556, 278, 278, 584, 584, 584, 556,
1015, 667, 667, 722, 722, 667, 611, 778,
722, 278, 500, 667, 556, 833, 722, 778,
667, 778, 722, 667, 611, 722, 667, 944,
667, 667, 611, 278, 278, 278, 469, 556,
333, 556, 556, 500, 556, 556, 278, 556,
556, 222, 222, 500, 222, 833, 556, 556,
556, 556, 333, 500, 278, 556, 500, 722,
500, 500, 500, 334, 260, 334, 584, 350,
556, 350, 222, 556, 333, 1000, 556, 556,
333, 1000, 667, 333, 1000, 350, 611, 350,
350, 222, 222, 333, 333, 350, 556, 1000,
333, 1000, 500, 333, 944, 350, 500, 667,
278, 333, 556, 556, 556, 556, 260, 556,
333, 737, 370, 556, 584, 333, 737, 333,
400, 584, 333, 333, 333, 556, 537, 278,
333, 333, 365, 556, 834, 834, 834, 611,
667, 667, 667, 667, 667, 667, 1000, 722,
667, 667, 667, 667, 278, 278, 278, 278,
722, 722, 778, 778, 778, 778, 778, 584,
778, 722, 722, 722, 722, 667, 667, 611,
556, 556, 556, 556, 556, 556, 889, 500,
556, 556, 556, 556, 278, 278, 278, 278,
556, 556, 556, 556, 556, 556, 556, 584,
611, 556, 556, 556, 556, 500, 556, 500
};
static uint16_t symbol_widths[256] = {
250, 250, 250, 250, 250, 250, 250, 250,
250, 250, 250, 250, 250, 250, 250, 250,
250, 250, 250, 250, 250, 250, 250, 250,
250, 250, 250, 250, 250, 250, 250, 250,
250, 333, 713, 500, 549, 833, 778, 439,
333, 333, 500, 549, 250, 549, 250, 278,
500, 500, 500, 500, 500, 500, 500, 500,
500, 500, 278, 278, 549, 549, 549, 444,
549, 722, 667, 722, 612, 611, 763, 603,
722, 333, 631, 722, 686, 889, 722, 722,
768, 741, 556, 592, 611, 690, 439, 768,
645, 795, 611, 333, 863, 333, 658, 500,
500, 631, 549, 549, 494, 439, 521, 411,
603, 329, 603, 549, 549, 576, 521, 549,
549, 521, 549, 603, 439, 576, 713, 686,
493, 686, 494, 480, 200, 480, 549, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
750, 620, 247, 549, 167, 713, 500, 753,
753, 753, 753, 1042, 987, 603, 987, 603,
400, 549, 411, 549, 549, 713, 494, 460,
549, 549, 549, 549, 1000, 603, 1000, 658,
823, 686, 795, 987, 768, 768, 823, 768,
768, 713, 713, 713, 713, 713, 713, 713,
768, 713, 790, 790, 890, 823, 549, 250,
713, 603, 603, 1042, 987, 603, 987, 603,
494, 329, 790, 790, 786, 713, 384, 384,
384, 384, 384, 384, 494, 494, 494, 494,
0, 329, 274, 686, 686, 686, 384, 384,
384, 384, 384, 384, 494, 494, 494, 0
};
static uint16_t times_widths[256] = {
250, 250, 250, 250, 250, 250, 250, 250,
250, 250, 250, 250, 250, 250, 250, 250,
250, 250, 250, 250, 250, 250, 250, 250,
250, 250, 250, 250, 250, 250, 250, 250,
250, 333, 408, 500, 500, 833, 778, 180,
333, 333, 500, 564, 250, 333, 250, 278,
500, 500, 500, 500, 500, 500, 500, 500,
500, 500, 278, 278, 564, 564, 564, 444,
921, 722, 667, 667, 722, 611, 556, 722,
722, 333, 389, 722, 611, 889, 722, 722,
556, 722, 667, 556, 611, 722, 722, 944,
722, 722, 611, 333, 278, 333, 469, 500,
333, 444, 500, 444, 500, 444, 333, 500,
500, 278, 278, 500, 278, 778, 500, 500,
500, 500, 333, 389, 278, 500, 500, 722,
500, 500, 444, 480, 200, 480, 541, 350,
500, 350, 333, 500, 444, 1000, 500, 500,
333, 1000, 556, 333, 889, 350, 611, 350,
350, 333, 333, 444, 444, 350, 500, 1000,
333, 980, 389, 333, 722, 350, 444, 722,
250, 333, 500, 500, 500, 500, 200, 500,
333, 760, 276, 500, 564, 333, 760, 333,
400, 564, 300, 300, 333, 500, 453, 250,
333, 300, 310, 500, 750, 750, 750, 444,
722, 722, 722, 722, 722, 722, 889, 667,
611, 611, 611, 611, 333, 333, 333, 333,
722, 722, 722, 722, 722, 722, 722, 564,
722, 722, 722, 722, 722, 722, 556, 500,
444, 444, 444, 444, 444, 444, 667, 444,
444, 444, 444, 444, 278, 278, 278, 278,
500, 500, 500, 500, 500, 500, 500, 564,
500, 500, 500, 500, 500, 500, 500, 500
};
static uint16_t times_bold_widths[256] = {
250, 250, 250, 250, 250, 250, 250, 250,
250, 250, 250, 250, 250, 250, 250, 250,
250, 250, 250, 250, 250, 250, 250, 250,
250, 250, 250, 250, 250, 250, 250, 250,
250, 333, 555, 500, 500, 1000, 833, 278,
333, 333, 500, 570, 250, 333, 250, 278,
500, 500, 500, 500, 500, 500, 500, 500,
500, 500, 333, 333, 570, 570, 570, 500,
930, 722, 667, 722, 722, 667, 611, 778,
778, 389, 500, 778, 667, 944, 722, 778,
611, 778, 722, 556, 667, 722, 722, 1000,
722, 722, 667, 333, 278, 333, 581, 500,
333, 500, 556, 444, 556, 444, 333, 500,
556, 278, 333, 556, 278, 833, 556, 500,
556, 556, 444, 389, 333, 556, 500, 722,
500, 500, 444, 394, 220, 394, 520, 350,
500, 350, 333, 500, 500, 1000, 500, 500,
333, 1000, 556, 333, 1000, 350, 667, 350,
350, 333, 333, 500, 500, 350, 500, 1000,
333, 1000, 389, 333, 722, 350, 444, 722,
250, 333, 500, 500, 500, 500, 220, 500,
333, 747, 300, 500, 570, 333, 747, 333,
400, 570, 300, 300, 333, 556, 540, 250,
333, 300, 330, 500, 750, 750, 750, 500,
722, 722, 722, 722, 722, 722, 1000, 722,
667, 667, 667, 667, 389, 389, 389, 389,
722, 722, 778, 778, 778, 778, 778, 570,
778, 722, 722, 722, 722, 722, 611, 556,
500, 500, 500, 500, 500, 500, 722, 444,
444, 444, 444, 444, 278, 278, 278, 278,
500, 556, 500, 500, 500, 500, 500, 570,
500, 556, 556, 556, 556, 500, 556, 500
} ;
static uint16_t times_bold_italic_widths[256] = {
250, 250, 250, 250, 250, 250, 250, 250,
250, 250, 250, 250, 250, 250, 250, 250,
250, 250, 250, 250, 250, 250, 250, 250,
250, 250, 250, 250, 250, 250, 250, 250,
250, 389, 555, 500, 500, 833, 778, 278,
333, 333, 500, 570, 250, 333, 250, 278,
500, 500, 500, 500, 500, 500, 500, 500,
500, 500, 333, 333, 570, 570, 570, 500,
832, 667, 667, 667, 722, 667, 667, 722,
778, 389, 500, 667, 611, 889, 722, 722,
611, 722, 667, 556, 611, 722, 667, 889,
667, 611, 611, 333, 278, 333, 570, 500,
333, 500, 500, 444, 500, 444, 333, 500,
556, 278, 278, 500, 278, 778, 556, 500,
500, 500, 389, 389, 278, 556, 444, 667,
500, 444, 389, 348, 220, 348, 570, 350,
500, 350, 333, 500, 500, 1000, 500, 500,
333, 1000, 556, 333, 944, 350, 611, 350,
350, 333, 333, 500, 500, 350, 500, 1000,
333, 1000, 389, 333, 722, 350, 389, 611,
250, 389, 500, 500, 500, 500, 220, 500,
333, 747, 266, 500, 606, 333, 747, 333,
400, 570, 300, 300, 333, 576, 500, 250,
333, 300, 300, 500, 750, 750, 750, 500,
667, 667, 667, 667, 667, 667, 944, 667,
667, 667, 667, 667, 389, 389, 389, 389,
722, 722, 722, 722, 722, 722, 722, 570,
722, 722, 722, 722, 722, 611, 611, 500,
500, 500, 500, 500, 500, 500, 722, 444,
444, 444, 444, 444, 278, 278, 278, 278,
500, 556, 500, 500, 500, 500, 500, 570,
500, 556, 556, 556, 556, 444, 500, 444
};
static uint16_t times_italic_widths[256] = {
250, 250, 250, 250, 250, 250, 250, 250,
250, 250, 250, 250, 250, 250, 250, 250,
250, 250, 250, 250, 250, 250, 250, 250,
250, 250, 250, 250, 250, 250, 250, 250,
250, 333, 420, 500, 500, 833, 778, 214,
333, 333, 500, 675, 250, 333, 250, 278,
500, 500, 500, 500, 500, 500, 500, 500,
500, 500, 333, 333, 675, 675, 675, 500,
920, 611, 611, 667, 722, 611, 611, 722,
722, 333, 444, 667, 556, 833, 667, 722,
611, 722, 611, 500, 556, 722, 611, 833,
611, 556, 556, 389, 278, 389, 422, 500,
333, 500, 500, 444, 500, 444, 278, 500,
500, 278, 278, 444, 278, 722, 500, 500,
500, 500, 389, 389, 278, 500, 444, 667,
444, 444, 389, 400, 275, 400, 541, 350,
500, 350, 333, 500, 556, 889, 500, 500,
333, 1000, 500, 333, 944, 350, 556, 350,
350, 333, 333, 556, 556, 350, 500, 889,
333, 980, 389, 333, 667, 350, 389, 556,
250, 389, 500, 500, 500, 500, 275, 500,
333, 760, 276, 500, 675, 333, 760, 333,
400, 675, 300, 300, 333, 500, 523, 250,
333, 300, 310, 500, 750, 750, 750, 500,
611, 611, 611, 611, 611, 611, 889, 667,
611, 611, 611, 611, 333, 333, 333, 333,
722, 667, 722, 722, 722, 722, 722, 675,
722, 722, 722, 722, 722, 556, 611, 500,
500, 500, 500, 500, 500, 500, 667, 444,
444, 444, 444, 444, 278, 278, 278, 278,
500, 500, 500, 500, 500, 500, 500, 675,
500, 500, 500, 500, 500, 444, 500, 444
};
static uint16_t zapfdingbats_widths[256] = {
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
278, 974, 961, 974, 980, 719, 789, 790,
791, 690, 960, 939, 549, 855, 911, 933,
911, 945, 974, 755, 846, 762, 761, 571,
677, 763, 760, 759, 754, 494, 552, 537,
577, 692, 786, 788, 788, 790, 793, 794,
816, 823, 789, 841, 823, 833, 816, 831,
923, 744, 723, 749, 790, 792, 695, 776,
768, 792, 759, 707, 708, 682, 701, 826,
815, 789, 789, 707, 687, 696, 689, 786,
787, 713, 791, 785, 791, 873, 761, 762,
762, 759, 759, 892, 892, 788, 784, 438,
138, 277, 415, 392, 392, 668, 668, 0,
390, 390, 317, 317, 276, 276, 509, 509,
410, 410, 234, 234, 334, 334, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 732, 544, 544, 910, 667, 760, 760,
776, 595, 694, 626, 788, 788, 788, 788,
788, 788, 788, 788, 788, 788, 788, 788,
788, 788, 788, 788, 788, 788, 788, 788,
788, 788, 788, 788, 788, 788, 788, 788,
788, 788, 788, 788, 788, 788, 788, 788,
788, 788, 788, 788, 894, 838, 1016, 458,
748, 924, 748, 918, 927, 928, 928, 834,
873, 828, 924, 924, 917, 930, 931, 463,
883, 836, 836, 867, 867, 696, 696, 874,
0, 874, 760, 946, 771, 865, 771, 888,
967, 888, 831, 873, 927, 970, 918, 0
};
static uint16_t courier_widths[256] = {
600, 600, 600, 600, 600, 600, 600, 600,
600, 600, 600, 600, 600, 600, 600, 600,
600, 600, 600, 600, 600, 600, 600, 600,
600, 600, 600, 600, 600, 600, 600, 600,
600, 600, 600, 600, 600, 600, 600, 600,
600, 600, 600, 600, 600, 600, 600, 600,
600, 600, 600, 600, 600, 600, 600, 600,
600, 600, 600, 600, 600, 600, 600, 600,
600, 600, 600, 600, 600, 600, 600, 600,
600, 600, 600, 600, 600, 600, 600, 600,
600, 600, 600, 600, 600, 600, 600, 600,
600, 600, 600, 600, 600, 600, 600, 600,
600, 600, 600, 600, 600, 600, 600, 600,
600, 600, 600, 600, 600, 600, 600, 600,
600, 600, 600, 600, 600, 600, 600, 600,
600, 600, 600, 600, 600, 600, 600, 600,
600, 600, 600, 600, 600, 600, 600, 600,
600, 600, 600, 600, 600, 600, 600, 600,
600, 600, 600, 600, 600, 600, 600, 600,
600, 600, 600, 600, 600, 600, 600, 600,
600, 600, 600, 600, 600, 600, 600, 600,
600, 600, 600, 600, 600, 600, 600, 600,
600, 600, 600, 600, 600, 600, 600, 600,
600, 600, 600, 600, 600, 600, 600, 600,
600, 600, 600, 600, 600, 600, 600, 600,
600, 600, 600, 600, 600, 600, 600, 600,
600, 600, 600, 600, 600, 600, 600, 600,
600, 600, 600, 600, 600, 600, 600, 600,
600, 600, 600, 600, 600, 600, 600, 600,
600, 600, 600, 600, 600, 600, 600, 600,
600, 600, 600, 600, 600, 600, 600, 600,
600, 600, 600, 600, 600, 600, 600, 600,
};
static int pdf_text_pixel_width(const char *text, int text_len, int size,
const uint16_t *widths)
{
int i;
int len = 0;
if (text_len < 0)
text_len = strlen(text);
for (i = 0; i < text_len; i++)
len += widths[(uint8_t)text[i]];
/* Our widths arrays are for 14pt fonts */
return len * size / (14 * 72);
}
static const uint16_t *find_font_widths(const char *font_name)
{
if (strcmp(font_name, "Helvetica") == 0)
return helvetica_widths;
if (strcmp(font_name, "Helvetica-Bold") == 0)
return helvetica_bold_widths;
if (strcmp(font_name, "Helvetica-BoldOblique") == 0)
return helvetica_bold_oblique_widths;
if (strcmp(font_name, "Helvetica-Oblique") == 0)
return helvetica_oblique_widths;
if (strcmp(font_name, "Courier") == 0 ||
strcmp(font_name, "Courier-Bold") == 0 ||
strcmp(font_name, "Courier-BoldOblique") == 0 ||
strcmp(font_name, "Courier-Oblique") == 0)
return courier_widths;
if (strcmp(font_name, "Times-Roman") == 0)
return times_widths;
if (strcmp(font_name, "Times-Bold") == 0)
return times_bold_widths;
if (strcmp(font_name, "Times-Italic") == 0)
return times_italic_widths;
if (strcmp(font_name, "Times-BoldItalic") == 0)
return times_bold_italic_widths;
if (strcmp(font_name, "Symbol") == 0)
return symbol_widths;
if (strcmp(font_name, "ZapfDingbats") == 0)
return zapfdingbats_widths;
return NULL;
}
int pdf_get_font_text_width(struct pdf_doc *pdf, const char *font_name,
const char *text, int size)
{
const uint16_t *widths = find_font_widths(font_name);
if (!widths)
return pdf_set_err(pdf, -EINVAL, "Unable to determine width for font '%s'",
pdf->current_font->font.name);
return pdf_text_pixel_width(text, -1, size, widths);
}
static const char *find_word_break(const char *string)
{
/* Skip over the actual word */
while (string && *string && !isspace(*string))
string++;
return string;
}
int pdf_add_text_wrap(struct pdf_doc *pdf, struct pdf_object *page,
const char *text, int size, int xoff, int yoff,
uint32_t colour, int wrap_width)
{
/* Move through the text string, stopping at word boundaries,
* trying to find the longest text string we can fit in the given width
*/
const char *start = text;
const char *last_best = text;
const char *end = text;
char line[512];
const uint16_t *widths;
int orig_yoff = yoff;
widths = find_font_widths(pdf->current_font->font.name);
if (!widths)
return pdf_set_err(pdf, -EINVAL, "Unable to determine width for font '%s'",
pdf->current_font->font.name);
while (start && *start) {
const char *new_end = find_word_break(end + 1);
int line_width;
int output = 0;
end = new_end;
line_width = pdf_text_pixel_width(start, end - start, size, widths);
if (line_width >= wrap_width) {
if (last_best == start) {
/* There is a single word that is too long for the line */
int i;
/* Find the best character to chop it at */
for (i = end - start - 1; i > 0; i--)
if (pdf_text_pixel_width(start, i, size, widths) < wrap_width)
break;
end = start + i;
} else
end = last_best;
output = 1;
}
if (*end == '\0')
output = 1;
if (*end == '\n' || *end == '\r')
output = 1;
if (output) {
int len = end - start;
strncpy(line, start, len);
line[len] = '\0';
pdf_add_text(pdf, page, line, size, xoff, yoff, colour);
if (*end == ' ')
end++;
start = last_best = end;
yoff -= size;
} else
last_best = end;
}
return orig_yoff - yoff;
}
int pdf_add_line(struct pdf_doc *pdf, struct pdf_object *page,
int x1, int y1, int x2, int y2, int width, uint32_t colour)
{
int ret;
struct dstr str = {0, 0, 0};
dstr_append(&str, "BT\r\n");
dstr_printf(&str, "%d w\r\n", width);
dstr_printf(&str, "%d %d m\r\n", x1, y1);
dstr_printf(&str, "/DeviceRGB CS\r\n");
dstr_printf(&str, "%f %f %f RG\r\n",
PDF_RGB_R(colour), PDF_RGB_G(colour), PDF_RGB_B(colour));
dstr_printf(&str, "%d %d l S\r\n", x2, y2);
dstr_append(&str, "ET");
ret = pdf_add_stream(pdf, page, str.data);
dstr_free(&str);
return ret;
}
int pdf_add_circle(struct pdf_doc *pdf, struct pdf_object *page,
int x, int y, int radius, int width, uint32_t colour, bool filled)
{
int ret;
struct dstr str = {0, 0, 0};
dstr_append(&str, "BT ");
if (filled)
dstr_printf(&str, "%f %f %f rg ",
PDF_RGB_R(colour), PDF_RGB_G(colour), PDF_RGB_B(colour));
else
dstr_printf(&str, "%f %f %f RG ",
PDF_RGB_R(colour), PDF_RGB_G(colour), PDF_RGB_B(colour));
dstr_printf(&str, "%d w ", width);
/* This is a bit of a rough approximation of a circle based on bezier curves.
* It's not exact
*/
dstr_printf(&str, "%d %d m ", x + radius, y);
dstr_printf(&str, "%d %d %d %d v ", x + radius, y + radius, x, y + radius);
dstr_printf(&str, "%d %d %d %d v ", x - radius, y + radius, x - radius, y);
dstr_printf(&str, "%d %d %d %d v ", x - radius, y - radius, x, y - radius);
dstr_printf(&str, "%d %d %d %d v ", x + radius, y - radius, x + radius, y);
if (filled)
dstr_append(&str, "f ");
else
dstr_append(&str, "S ");
dstr_append(&str, "ET");
ret = pdf_add_stream(pdf, page, str.data);
dstr_free(&str);
return ret;
}
int pdf_add_rectangle(struct pdf_doc *pdf, struct pdf_object *page,
int x, int y, int width, int height, int border_width,
uint32_t colour)
{
int ret;
struct dstr str = {0, 0, 0};
dstr_append(&str, "BT ");
dstr_printf(&str, "%f %f %f RG ",
PDF_RGB_R(colour), PDF_RGB_G(colour), PDF_RGB_B(colour));
dstr_printf(&str, "%d w ", border_width);
dstr_printf(&str, "%d %d %d %d re S ", x, y, width, height);
dstr_append(&str, "ET");
ret = pdf_add_stream(pdf, page, str.data);
dstr_free(&str);
return ret;
}
int pdf_add_filled_rectangle(struct pdf_doc *pdf, struct pdf_object *page,
int x, int y, int width, int height,
int border_width, uint32_t colour)
{
int ret;
struct dstr str = {0, 0, 0};
dstr_append(&str, "BT ");
dstr_printf(&str, "%f %f %f rg ",
PDF_RGB_R(colour), PDF_RGB_G(colour), PDF_RGB_B(colour));
dstr_printf(&str, "%d w ", border_width);
dstr_printf(&str, "%d %d %d %d re f ", x, y, width, height);
dstr_append(&str, "ET");
ret = pdf_add_stream(pdf, page, str.data);
dstr_free(&str);
return ret;
}
static const struct {
uint32_t code;
char ch;
} code_128a_encoding[] = {
{0x212222, ' '},
{0x222122, '!'},
{0x222221, '"'},
{0x121223, '#'},
{0x121322, '$'},
{0x131222, '%'},
{0x122213, '&'},
{0x122312, '\''},
{0x132212, '('},
{0x221213, ')'},
{0x221312, '*'},
{0x231212, '+'},
{0x112232, ','},
{0x122132, '-'},
{0x122231, '.'},
{0x113222, '/'},
{0x123122, '0'},
{0x123221, '1'},
{0x223211, '2'},
{0x221132, '3'},
{0x221231, '4'},
{0x213212, '5'},
{0x223112, '6'},
{0x312131, '7'},
{0x311222, '8'},
{0x321122, '9'},
{0x321221, ':'},
{0x312212, ';'},
{0x322112, '<'},
{0x322211, '='},
{0x212123, '>'},
{0x212321, '?'},
{0x232121, '@'},
{0x111323, 'A'},
{0x131123, 'B'},
{0x131321, 'C'},
{0x112313, 'D'},
{0x132113, 'E'},
{0x132311, 'F'},
{0x211313, 'G'},
{0x231113, 'H'},
{0x231311, 'I'},
{0x112133, 'J'},
{0x112331, 'K'},
{0x132131, 'L'},
{0x113123, 'M'},
{0x113321, 'N'},
{0x133121, 'O'},
{0x313121, 'P'},
{0x211331, 'Q'},
{0x231131, 'R'},
{0x213113, 'S'},
{0x213311, 'T'},
{0x213131, 'U'},
{0x311123, 'V'},
{0x311321, 'W'},
{0x331121, 'X'},
{0x312113, 'Y'},
{0x312311, 'Z'},
{0x332111, '['},
{0x314111, '\\'},
{0x221411, ']'},
{0x431111, '^'},
{0x111224, '_'},
{0x111422, '`'},
{0x121124, 'a'},
{0x121421, 'b'},
{0x141122, 'c'},
{0x141221, 'd'},
{0x112214, 'e'},
{0x112412, 'f'},
{0x122114, 'g'},
{0x122411, 'h'},
{0x142112, 'i'},
{0x142211, 'j'},
{0x241211, 'k'},
{0x221114, 'l'},
{0x413111, 'm'},
{0x241112, 'n'},
{0x134111, 'o'},
{0x111242, 'p'},
{0x121142, 'q'},
{0x121241, 'r'},
{0x114212, 's'},
{0x124112, 't'},
{0x124211, 'u'},
{0x411212, 'v'},
{0x421112, 'w'},
{0x421211, 'x'},
{0x212141, 'y'},
{0x214121, 'z'},
{0x412121, '{'},
{0x111143, '|'},
{0x111341, '}'},
{0x131141, '~'},
{0x114113, '\0'},
{0x114311, '\0'},
{0x411113, '\0'},
{0x411311, '\0'},
{0x113141, '\0'},
{0x114131, '\0'},
{0x311141, '\0'},
{0x411131, '\0'},
{0x211412, '\0'},
{0x211214, '\0'},
{0x211232, '\0'},
{0x2331112, '\0'},
};
static int find_128_encoding(char ch)
{
int i;
for (i = 0; i < ARRAY_SIZE(code_128a_encoding); i++) {
if (code_128a_encoding[i].ch == ch)
return i;
}
return -1;
}
static int pdf_barcode_128a_ch(struct pdf_doc *pdf, struct pdf_object *page,
int x, int y, int width, int height,
uint32_t colour, int index, int code_len)
{
uint32_t code = code_128a_encoding[index].code;
int i;
int line_width = width / 11;
for (i = 0; i < code_len; i++) {
uint8_t shift = (code_len - 1 - i) * 4;
uint8_t mask = (code >> shift) & 0xf;
if (!(i % 2)) {
int j;
for (j = 0; j < mask; j++) {
pdf_add_line(pdf, page, x, y, x, y + height, line_width, colour);
x += line_width;
}
} else
x += line_width * mask;
}
return x;
}
static int pdf_add_barcode_128a(struct pdf_doc *pdf, struct pdf_object *page,
int x, int y, int width, int height,
const char *string, uint32_t colour)
{
const char *s;
int len = strlen(string) + 3;
int char_width = width / len;
int checksum, i;
for (s = string; *s; s++)
if (find_128_encoding(*s) < 0)
return pdf_set_err(pdf, -EINVAL, "Invalid barcode character 0x%x", *s);
x = pdf_barcode_128a_ch(pdf, page, x, y, char_width, height, colour, 104,
6);
checksum = 104;
for (i = 1, s = string; *s; s++, i++) {
int index = find_128_encoding(*s);
x = pdf_barcode_128a_ch(pdf, page, x, y, char_width, height, colour, index,
6);
checksum += index * i;
}
x = pdf_barcode_128a_ch(pdf, page, x, y, char_width, height, colour,
checksum % 103, 6);
pdf_barcode_128a_ch(pdf, page, x, y, char_width, height, colour, 106,
7);
return 0;
}
/* Code 39 character encoding. Each 4-bit value indicates:
* 0 => wide bar
* 1 => narrow bar
* 2 => wide space
*/
static const struct {
uint32_t code;
char ch;
} code_39_encoding[] = {
{0x012110, '1'},
{0x102110, '2'},
{0x002111, '3'},
{0x112010, '4'},
{0x012011, '5'},
{0x102011, '6'},
{0x112100, '7'},
{0x012101, '8'},
{0x102101, '9'},
{0x112001, '0'},
{0x011210, 'A'},
{0x101210, 'B'},
{0x001211, 'C'},
{0x110210, 'D'},
{0x010211, 'E'},
{0x100211, 'F'},
{0x111200, 'G'},
{0x011201, 'H'},
{0x101201, 'I'},
{0x110201, 'J'},
{0x011120, 'K'},
{0x101120, 'L'},
{0x001121, 'M'},
{0x110120, 'N'},
{0x010121, 'O'},
{0x100121, 'P'},
{0x111020, 'Q'},
{0x011021, 'R'},
{0x101021, 'S'},
{0x110021, 'T'},
{0x021110, 'U'},
{0x120110, 'V'},
{0x020111, 'W'},
{0x121010, 'X'},
{0x021011, 'Y'},
{0x120011, 'Z'},
{0x121100, '-'},
{0x021101, '.'},
{0x120101, ' '},
{0x121001, '*'}, // 'stop' character
};
static int pdf_barcode_39_ch(struct pdf_doc *pdf, struct pdf_object *page, int x, int y, int char_width, int height, uint32_t colour, char ch)
{
int nw = char_width / 12;
int ww = char_width / 4;
int i;
uint32_t code;
if (nw <= 1 || ww <= 1)
return pdf_set_err(pdf, -EINVAL, "Insufficient width for each character");
for (i = 0; i < ARRAY_SIZE(code_39_encoding); i++) {
if (code_39_encoding[i].ch == ch) {
code = code_39_encoding[i].code;
break;
}
}
if (i == ARRAY_SIZE(code_39_encoding))
return pdf_set_err(pdf, -EINVAL, "Invalid Code 39 character %c 0x%x", ch, ch);
for (i = 5; i >= 0; i--) {
int pattern = (code >> i * 4) & 0xf;
if (pattern == 0) { // wide
if (pdf_add_filled_rectangle(pdf, page, x, y, ww - 1, height, 0, colour) < 0)
return pdf->errval;
x += ww;
}
if (pattern == 1) { // narrow
if (pdf_add_filled_rectangle(pdf, page, x, y, nw - 1, height, 0, colour) < 0)
return pdf->errval;
x += nw;
}
if (pattern == 2) { // space
x += nw;
}
}
return x;
}
static int pdf_add_barcode_39(struct pdf_doc *pdf, struct pdf_object *page,
int x, int y, int width, int height,
const char *string, uint32_t colour)
{
int len = strlen(string);
int char_width = width / (len + 2);
x = pdf_barcode_39_ch(pdf, page, x, y, char_width, height, colour, '*');
if (x < 0)
return x;
while (string && *string) {
x = pdf_barcode_39_ch(pdf, page, x, y, char_width, height, colour, *string);
if (x < 0)
return x;
string++;
};
x = pdf_barcode_39_ch(pdf, page, x, y, char_width, height, colour, '*');
if (x < 0)
return x;
return 0;
}
int pdf_add_barcode(struct pdf_doc *pdf, struct pdf_object *page,
int code, int x, int y, int width, int height,
const char *string, uint32_t colour)
{
if (!string || !*string)
return 0;
switch (code) {
case PDF_BARCODE_128A:
return pdf_add_barcode_128a(pdf, page, x, y,
width, height, string, colour);
case PDF_BARCODE_39:
return pdf_add_barcode_39(pdf, page, x, y, width, height, string, colour);
default:
return pdf_set_err(pdf, -EINVAL, "Invalid barcode code %d", code);
}
}
static pdf_object *pdf_add_raw_rgb24(struct pdf_doc *pdf,
uint8_t *data, int width, int height)
{
struct pdf_object *obj;
char line[1024];
int len;
uint8_t *final_data;
const char *endstream = ">\r\nendstream\r\n";
int i;
sprintf(line,
"<<\r\n/Type /XObject\r\n/Name /Image%d\r\n/Subtype /Image\r\n"
"/ColorSpace /DeviceRGB\r\n/Height %d\r\n/Width %d\r\n"
"/BitsPerComponent 8\r\n/Filter /ASCIIHexDecode\r\n"
"/Length %d\r\n>>stream\r\n",
flexarray_size(&pdf->objects), height, width, width * height * 3 * 2 + 1);
len = strlen(line) + width * height * 3 * 2 + strlen(endstream) + 1;
final_data = malloc(len);
if (!final_data) {
pdf_set_err(pdf, -ENOMEM, "Unable to allocate %d bytes memory for image",
len);
return NULL;
}
strcpy((char *)final_data, line);
uint8_t *pos = &final_data[strlen(line)];
for (i = 0; i < width * height * 3; i++) {
*pos++ = "0123456789ABCDEF"[(data[i] >> 4) & 0xf];
*pos++ = "0123456789ABCDEF"[data[i] & 0xf];
}
strcpy((char *)pos, endstream);
pos += strlen(endstream);
obj = pdf_add_object(pdf, OBJ_image);
if (!obj) {
free(final_data);
return NULL;
}
obj->stream.text = (char *)final_data;
obj->stream.len = pos - final_data;
return obj;
}
/* See http://www.64lines.com/jpeg-width-height for details */
static int jpeg_size(unsigned char* data, unsigned int data_size,
int *width, int *height)
{
int i = 0;
if (i + 3 < data_size && data[i] == 0xFF && data[i+1] == 0xD8 &&
data[i+2] == 0xFF && data[i+3] == 0xE0) {
i += 4;
if(i + 6 < data_size &&
data[i+2] == 'J' && data[i+3] == 'F' && data[i+4] == 'I' &&
data[i+5] == 'F' && data[i+6] == 0x00) {
unsigned short block_length = data[i] * 256 + data[i+1];
while(i<data_size) {
i+=block_length;
if((i + 1) >= data_size)
return -1;
if(data[i] != 0xFF)
return -1;
if(data[i+1] == 0xC0) {
*height = data[i+5]*256 + data[i+6];
*width = data[i+7]*256 + data[i+8];
return 0;
}
i+=2;
if (i + 1 < data_size)
block_length = data[i] * 256 + data[i+1];
}
}
}
return -1;
}
static pdf_object *pdf_add_raw_jpeg(struct pdf_doc *pdf,
const char *jpeg_file)
{
struct stat buf;
off_t len;
char *final_data;
uint8_t *jpeg_data;
int written = 0;
FILE *fp;
struct pdf_object *obj;
int width, height;
if (stat(jpeg_file, &buf) < 0) {
pdf_set_err(pdf, -errno, "Unable to access %s: %s", jpeg_file,
strerror(errno));
return NULL;
}
len = buf.st_size;
if ((fp = fopen(jpeg_file, "rb")) == NULL) {
pdf_set_err(pdf, -errno, "Unable to open %s: %s", jpeg_file,
strerror(errno));
return NULL;
}
jpeg_data = malloc(len);
if (!jpeg_data) {
pdf_set_err(pdf, -errno, "Unable to allocate: %zd", len);
fclose(fp);
return NULL;
}
if (fread(jpeg_data, len, 1, fp) != 1) {
pdf_set_err(pdf, -errno, "Unable to read full jpeg data");
free(jpeg_data);
fclose(fp);
return NULL;
}
fclose(fp);
if (jpeg_size(jpeg_data, len, &width, &height) < 0) {
free(jpeg_data);
pdf_set_err(pdf, -EINVAL, "Unable to determine jpeg width/height from %s",
jpeg_file);
return NULL;
}
final_data = malloc(len + 1024);
if (!final_data) {
pdf_set_err(pdf, -errno, "Unable to allocate jpeg data %zd", len + 1024);
free(jpeg_data);
return NULL;
}
written = sprintf(final_data,
"<<\r\n/Type /XObject\r\n/Name /Image%d\r\n"
"/Subtype /Image\r\n/ColorSpace /DeviceRGB\r\n"
"/Width %d\r\n/Height %d\r\n"
"/BitsPerComponent 8\r\n/Filter /DCTDecode\r\n"
"/Length %d\r\n>>stream\r\n",
flexarray_size(&pdf->objects), width, height, (int)len);
memcpy(&final_data[written], jpeg_data, len);
written += len;
written += sprintf(&final_data[written], "\r\nendstream\r\n");
free(jpeg_data);
obj = pdf_add_object(pdf, OBJ_image);
if (!obj) {
free(final_data);
return NULL;
}
obj->stream.text = final_data;
obj->stream.len = written;
return obj;
}
static int pdf_add_image(struct pdf_doc *pdf, struct pdf_object *page,
struct pdf_object *image, int x, int y, int width,
int height)
{
int ret;
struct dstr str = {0, 0, 0};
dstr_append(&str, "q ");
dstr_printf(&str, "%d 0 0 %d %d %d cm ", width, height, x, y);
dstr_printf(&str, "/Image%d Do ", image->index);
dstr_append(&str, "Q");
ret = pdf_add_stream(pdf, page, str.data);
dstr_free(&str);
return ret;
}
int pdf_add_ppm(struct pdf_doc *pdf, struct pdf_object *page,
int x, int y, int display_width, int display_height,
const char *ppm_file)
{
struct pdf_object *obj;
uint8_t *data;
FILE *fp;
char line[1024];
unsigned width, height, size;
/* Load the PPM file */
fp = fopen(ppm_file, "rb");
if (!fp)
return pdf_set_err(pdf, -errno, "Unable to open '%s'", ppm_file);
if (!fgets(line, sizeof(line) - 1, fp)) {
fclose(fp);
return pdf_set_err(pdf, -EINVAL, "Invalid PPM file");
}
/* We only support binary ppms */
if (strncmp(line, "P6", 2) != 0) {
fclose(fp);
return pdf_set_err(pdf, -EINVAL, "Only binary PPM files supported");
}
/* Find the width line */
do {
if (!fgets(line, sizeof(line) - 1, fp)) {
fclose(fp);
return pdf_set_err(pdf, -EINVAL, "Unable to find PPM size");
}
if (line[0] == '#')
continue;
if (sscanf(line, "%u %u\n", &width, &height) != 2) {
fclose(fp);
return pdf_set_err(pdf, -EINVAL, "Unable to find PPM size");
}
break;
} while (1);
/* Skip over the byte-size line */
if (!fgets(line, sizeof(line) - 1, fp)) {
fclose(fp);
return pdf_set_err(pdf, -EINVAL, "No byte-size line in PPM file");
}
if (width > INT_MAX || height > INT_MAX) {
fclose(fp);
return pdf_set_err(pdf, -EINVAL, "Invalid width/height in PPM file: %ux%u", width, height);
}
size = width * height * 3;
data = malloc(size);
if (!data) {
fclose(fp);
return pdf_set_err(pdf, -ENOMEM, "Unable to allocate memory for RGB data");
}
if (fread(data, 1, size, fp) != size) {
free(data);
fclose(fp);
return pdf_set_err(pdf, -EINVAL, "Insufficient RGB data available");
}
fclose(fp);
obj = pdf_add_raw_rgb24(pdf, data, width, height);
free(data);
if (!obj)
return pdf->errval;
return pdf_add_image(pdf, page, obj, x, y, display_width, display_height);
}
int pdf_add_jpeg(struct pdf_doc *pdf, struct pdf_object *page,
int x, int y, int display_width, int display_height,
const char *jpeg_file)
{
struct pdf_object *obj;
obj = pdf_add_raw_jpeg(pdf, jpeg_file);
if (!obj)
return pdf->errval;
return pdf_add_image(pdf, page, obj, x, y, display_width, display_height);
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/good_138_0 |
crossvul-cpp_data_good_3394_0 | /* Copyright 1998 by the Massachusetts Institute of Technology.
*
* 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.
* 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 <sys/types.h>
#include <stdlib.h>
#include <string.h>
#include "ares.h"
#include "ares_dns.h"
#include "ares_private.h"
#ifndef WIN32
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#ifndef __CYGWIN__
# include <arpa/nameser.h>
#endif
#include <netdb.h>
#endif
int ares_parse_a_reply(const unsigned char *abuf, int alen,
struct hostent **host)
{
unsigned int qdcount, ancount;
int status, i, rr_type, rr_class, rr_len, naddrs;
long int len;
int naliases;
const unsigned char *aptr;
char *hostname, *rr_name, *rr_data, **aliases;
struct in_addr *addrs;
struct hostent *hostent;
/* Set *host to NULL for all failure cases. */
*host = NULL;
/* Give up if abuf doesn't have room for a header. */
if (alen < HFIXEDSZ)
return ARES_EBADRESP;
/* Fetch the question and answer count from the header. */
qdcount = DNS_HEADER_QDCOUNT(abuf);
ancount = DNS_HEADER_ANCOUNT(abuf);
if (qdcount != 1)
return ARES_EBADRESP;
/* Expand the name from the question, and skip past the question. */
aptr = abuf + HFIXEDSZ;
status = ares_expand_name(aptr, abuf, alen, &hostname, &len);
if (status != ARES_SUCCESS)
return status;
if (aptr + len + QFIXEDSZ > abuf + alen)
{
free(hostname);
return ARES_EBADRESP;
}
aptr += len + QFIXEDSZ;
/* Allocate addresses and aliases; ancount gives an upper bound for both. */
addrs = malloc(ancount * sizeof(struct in_addr));
if (!addrs)
{
free(hostname);
return ARES_ENOMEM;
}
aliases = malloc((ancount + 1) * sizeof(char *));
if (!aliases)
{
free(hostname);
free(addrs);
return ARES_ENOMEM;
}
naddrs = 0;
naliases = 0;
/* Examine each answer resource record (RR) in turn. */
for (i = 0; i < (int)ancount; i++)
{
/* Decode the RR up to the data field. */
status = ares_expand_name(aptr, abuf, alen, &rr_name, &len);
if (status != ARES_SUCCESS)
break;
aptr += len;
if (aptr + RRFIXEDSZ > abuf + alen)
{
free(rr_name);
status = ARES_EBADRESP;
break;
}
rr_type = DNS_RR_TYPE(aptr);
rr_class = DNS_RR_CLASS(aptr);
rr_len = DNS_RR_LEN(aptr);
aptr += RRFIXEDSZ;
if (aptr + rr_len > abuf + alen)
{
free(rr_name);
status = ARES_EBADRESP;
break;
}
if (rr_class == C_IN && rr_type == T_A
&& rr_len == sizeof(struct in_addr)
&& strcasecmp(rr_name, hostname) == 0)
{
memcpy(&addrs[naddrs], aptr, sizeof(struct in_addr));
naddrs++;
status = ARES_SUCCESS;
}
if (rr_class == C_IN && rr_type == T_CNAME)
{
/* Record the RR name as an alias. */
aliases[naliases] = rr_name;
naliases++;
/* Decode the RR data and replace the hostname with it. */
status = ares_expand_name(aptr, abuf, alen, &rr_data, &len);
if (status != ARES_SUCCESS)
break;
free(hostname);
hostname = rr_data;
}
else
free(rr_name);
aptr += rr_len;
if (aptr > abuf + alen)
{
status = ARES_EBADRESP;
break;
}
}
if (status == ARES_SUCCESS && naddrs == 0)
status = ARES_ENODATA;
if (status == ARES_SUCCESS)
{
/* We got our answer. Allocate memory to build the host entry. */
aliases[naliases] = NULL;
hostent = malloc(sizeof(struct hostent));
if (hostent)
{
hostent->h_addr_list = malloc((naddrs + 1) * sizeof(char *));
if (hostent->h_addr_list)
{
/* Fill in the hostent and return successfully. */
hostent->h_name = hostname;
hostent->h_aliases = aliases;
hostent->h_addrtype = AF_INET;
hostent->h_length = sizeof(struct in_addr);
for (i = 0; i < naddrs; i++)
hostent->h_addr_list[i] = (char *) &addrs[i];
hostent->h_addr_list[naddrs] = NULL;
*host = hostent;
return ARES_SUCCESS;
}
free(hostent);
}
status = ARES_ENOMEM;
}
for (i = 0; i < naliases; i++)
free(aliases[i]);
free(aliases);
free(addrs);
free(hostname);
return status;
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/good_3394_0 |
crossvul-cpp_data_bad_1374_0 | /*
* GPAC - Multimedia Framework C SDK
*
* Authors: Jean Le Feuvre
* Copyright (c) Telecom ParisTech 2005-2012
*
* This file is part of GPAC / MPEG2-TS sub-project
*
* 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 <gpac/mpegts.h>
#ifndef GPAC_DISABLE_MPEG2TS
#include <string.h>
#include <gpac/constants.h>
#include <gpac/internal/media_dev.h>
#include <gpac/download.h>
#ifndef GPAC_DISABLE_STREAMING
#include <gpac/internal/ietf_dev.h>
#endif
#ifdef GPAC_CONFIG_LINUX
#include <unistd.h>
#endif
#ifdef GPAC_ENABLE_MPE
#include <gpac/dvb_mpe.h>
#endif
#ifdef GPAC_ENABLE_DSMCC
#include <gpac/ait.h>
#endif
#define DEBUG_TS_PACKET 0
GF_EXPORT
const char *gf_m2ts_get_stream_name(u32 streamType)
{
switch (streamType) {
case GF_M2TS_VIDEO_MPEG1:
return "MPEG-1 Video";
case GF_M2TS_VIDEO_MPEG2:
return "MPEG-2 Video";
case GF_M2TS_AUDIO_MPEG1:
return "MPEG-1 Audio";
case GF_M2TS_AUDIO_MPEG2:
return "MPEG-2 Audio";
case GF_M2TS_PRIVATE_SECTION:
return "Private Section";
case GF_M2TS_PRIVATE_DATA:
return "Private Data";
case GF_M2TS_AUDIO_AAC:
return "AAC Audio";
case GF_M2TS_VIDEO_MPEG4:
return "MPEG-4 Video";
case GF_M2TS_VIDEO_H264:
return "MPEG-4/H264 Video";
case GF_M2TS_VIDEO_SVC:
return "H264-SVC Video";
case GF_M2TS_VIDEO_HEVC:
return "HEVC Video";
case GF_M2TS_VIDEO_SHVC:
return "SHVC Video";
case GF_M2TS_VIDEO_SHVC_TEMPORAL:
return "SHVC Video Temporal Sublayer";
case GF_M2TS_VIDEO_MHVC:
return "MHVC Video";
case GF_M2TS_VIDEO_MHVC_TEMPORAL:
return "MHVC Video Temporal Sublayer";
case GF_M2TS_AUDIO_AC3:
return "Dolby AC3 Audio";
case GF_M2TS_AUDIO_DTS:
return "Dolby DTS Audio";
case GF_M2TS_SUBTITLE_DVB:
return "DVB Subtitle";
case GF_M2TS_SYSTEMS_MPEG4_PES:
return "MPEG-4 SL (PES)";
case GF_M2TS_SYSTEMS_MPEG4_SECTIONS:
return "MPEG-4 SL (Section)";
case GF_M2TS_MPE_SECTIONS:
return "MPE (Section)";
case GF_M2TS_METADATA_PES:
return "Metadata (PES)";
case GF_M2TS_METADATA_ID3_HLS:
return "ID3/HLS Metadata (PES)";
default:
return "Unknown";
}
}
static u32 gf_m2ts_reframe_default(GF_M2TS_Demuxer *ts, GF_M2TS_PES *pes, Bool same_pts, unsigned char *data, u32 data_len, GF_M2TS_PESHeader *pes_hdr)
{
GF_M2TS_PES_PCK pck;
pck.flags = 0;
if (pes->rap) pck.flags |= GF_M2TS_PES_PCK_RAP;
if (!same_pts) pck.flags |= GF_M2TS_PES_PCK_AU_START;
pck.DTS = pes->DTS;
pck.PTS = pes->PTS;
pck.data = (char *)data;
pck.data_len = data_len;
pck.stream = pes;
ts->on_event(ts, GF_M2TS_EVT_PES_PCK, &pck);
/*we consumed all data*/
return 0;
}
static u32 gf_m2ts_reframe_reset(GF_M2TS_Demuxer *ts, GF_M2TS_PES *pes, Bool same_pts, unsigned char *data, u32 data_len, GF_M2TS_PESHeader *pes_hdr)
{
if (pes->pck_data) {
gf_free(pes->pck_data);
pes->pck_data = NULL;
}
pes->pck_data_len = pes->pck_alloc_len = 0;
if (pes->prev_data) {
gf_free(pes->prev_data);
pes->prev_data = NULL;
}
pes->prev_data_len = 0;
pes->pes_len = 0;
pes->prev_PTS = 0;
pes->reframe = NULL;
pes->cc = -1;
pes->temi_tc_desc_len = 0;
return 0;
}
static void add_text(char **buffer, u32 *size, u32 *pos, char *msg, u32 msg_len)
{
if (!msg || !buffer) return;
if (*pos+msg_len>*size) {
*size = *pos+msg_len-*size+256;
*buffer = (char *)gf_realloc(*buffer, *size);
}
strncpy((*buffer)+(*pos), msg, msg_len);
*pos += msg_len;
}
static GF_Err id3_parse_tag(char *data, u32 length, char **output, u32 *output_size, u32 *output_pos)
{
GF_BitStream *bs;
u32 pos;
if ((data[0] != 'I') || (data[1] != 'D') || (data[2] != '3'))
return GF_NOT_SUPPORTED;
bs = gf_bs_new(data, length, GF_BITSTREAM_READ);
gf_bs_skip_bytes(bs, 3);
/*u8 major = */gf_bs_read_u8(bs);
/*u8 minor = */gf_bs_read_u8(bs);
/*u8 unsync = */gf_bs_read_int(bs, 1);
/*u8 ext_hdr = */ gf_bs_read_int(bs, 1);
gf_bs_read_int(bs, 6);
u32 size = gf_id3_read_size(bs);
pos = (u32) gf_bs_get_position(bs);
if (size != length-pos)
size = length-pos;
while (size && (gf_bs_available(bs)>=10) ) {
u32 ftag = gf_bs_read_u32(bs);
u32 fsize = gf_id3_read_size(bs);
/*u16 fflags = */gf_bs_read_u16(bs);
size -= 10;
//TODO, handle more ID3 tags ?
if (ftag==ID3V2_FRAME_TXXX) {
u32 pos = (u32) gf_bs_get_position(bs);
char *text = data+pos;
add_text(output, output_size, output_pos, text, fsize);
} else {
GF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, ("[MPEG-2 TS] ID3 tag not handled, patch welcome\n", gf_4cc_to_str(ftag) ) );
}
gf_bs_skip_bytes(bs, fsize);
}
gf_bs_del(bs);
return GF_OK;
}
static u32 gf_m2ts_reframe_id3_pes(GF_M2TS_Demuxer *ts, GF_M2TS_PES *pes, Bool same_pts, unsigned char *data, u32 data_len, GF_M2TS_PESHeader *pes_hdr)
{
char frame_header[256];
char *output_text = NULL;
u32 output_len = 0;
u32 pos = 0;
GF_M2TS_PES_PCK pck;
pck.flags = 0;
if (pes->rap) pck.flags |= GF_M2TS_PES_PCK_RAP;
if (!same_pts) pck.flags |= GF_M2TS_PES_PCK_AU_START;
pck.DTS = pes->DTS;
pck.PTS = pes->PTS;
sprintf(frame_header, LLU" --> NEXT\n", pes->PTS);
add_text(&output_text, &output_len, &pos, frame_header, (u32)strlen(frame_header));
id3_parse_tag((char *)data, data_len, &output_text, &output_len, &pos);
add_text(&output_text, &output_len, &pos, "\n\n", 2);
pck.data = (char *)output_text;
pck.data_len = pos;
pck.stream = pes;
ts->on_event(ts, GF_M2TS_EVT_PES_PCK, &pck);
gf_free(output_text);
/*we consumed all data*/
return 0;
}
static u32 gf_m2ts_sync(GF_M2TS_Demuxer *ts, char *data, u32 size, Bool simple_check)
{
u32 i=0;
/*if first byte is sync assume we're sync*/
if (simple_check && (data[i]==0x47)) return 0;
while (i < size) {
if (i+192 >= size) return size;
if ((data[i]==0x47) && (data[i+188]==0x47))
break;
if (i+192 >= size) return size;
if ((data[i]==0x47) && (data[i+192]==0x47)) {
ts->prefix_present = 1;
break;
}
i++;
}
if (i) {
GF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, ("[MPEG-2 TS] re-sync skipped %d bytes\n", i) );
}
return i;
}
GF_EXPORT
Bool gf_m2ts_crc32_check(u8 *data, u32 len)
{
u32 crc = gf_crc_32(data, len);
u32 crc_val = GF_4CC((u8) data[len], (u8) data[len+1], (u8) data[len+2], (u8) data[len+3]);
return (crc==crc_val) ? GF_TRUE : GF_FALSE;
}
static GF_M2TS_SectionFilter *gf_m2ts_section_filter_new(gf_m2ts_section_callback process_section_callback, Bool process_individual)
{
GF_M2TS_SectionFilter *sec;
GF_SAFEALLOC(sec, GF_M2TS_SectionFilter);
if (!sec) {
GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[MPEG-2 TS] gf_m2ts_section_filter_new : OUT OF MEMORY\n"));
return NULL;
}
sec->cc = -1;
sec->process_section = process_section_callback;
sec->process_individual = process_individual;
return sec;
}
static void gf_m2ts_reset_sections(GF_List *sections)
{
u32 count;
GF_M2TS_Section *section;
//GF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, ("[MPEG-2 TS] Deleting sections\n"));
count = gf_list_count(sections);
while (count) {
section = gf_list_get(sections, 0);
gf_list_rem(sections, 0);
if (section->data) gf_free(section->data);
gf_free(section);
count--;
}
}
static void gf_m2ts_section_filter_reset(GF_M2TS_SectionFilter *sf)
{
if (sf->section) {
gf_free(sf->section);
sf->section = NULL;
}
while (sf->table) {
GF_M2TS_Table *t = sf->table;
sf->table = t->next;
gf_m2ts_reset_sections(t->sections);
gf_list_del(t->sections);
gf_free(t);
}
sf->cc = -1;
sf->length = sf->received = 0;
sf->demux_restarted = 1;
}
static void gf_m2ts_section_filter_del(GF_M2TS_SectionFilter *sf)
{
gf_m2ts_section_filter_reset(sf);
gf_free(sf);
}
static void gf_m2ts_metadata_descriptor_del(GF_M2TS_MetadataDescriptor *metad)
{
if (metad) {
if (metad->service_id_record) gf_free(metad->service_id_record);
if (metad->decoder_config) gf_free(metad->decoder_config);
if (metad->decoder_config_id) gf_free(metad->decoder_config_id);
gf_free(metad);
}
}
GF_EXPORT
void gf_m2ts_es_del(GF_M2TS_ES *es, GF_M2TS_Demuxer *ts)
{
gf_list_del_item(es->program->streams, es);
if (es->flags & GF_M2TS_ES_IS_SECTION) {
GF_M2TS_SECTION_ES *ses = (GF_M2TS_SECTION_ES *)es;
if (ses->sec) gf_m2ts_section_filter_del(ses->sec);
#ifdef GPAC_ENABLE_MPE
if (es->flags & GF_M2TS_ES_IS_MPE)
gf_dvb_mpe_section_del(es);
#endif
} else if (es->pid!=es->program->pmt_pid) {
GF_M2TS_PES *pes = (GF_M2TS_PES *)es;
if ((pes->flags & GF_M2TS_INHERIT_PCR) && ts->ess[es->program->pcr_pid]==es)
ts->ess[es->program->pcr_pid] = NULL;
if (pes->pck_data) gf_free(pes->pck_data);
if (pes->prev_data) gf_free(pes->prev_data);
if (pes->buf) gf_free(pes->buf);
if (pes->reassemble_buf) gf_free(pes->reassemble_buf);
if (pes->temi_tc_desc) gf_free(pes->temi_tc_desc);
if (pes->metadata_descriptor) gf_m2ts_metadata_descriptor_del(pes->metadata_descriptor);
}
if (es->slcfg) gf_free(es->slcfg);
gf_free(es);
}
static void gf_m2ts_reset_sdt(GF_M2TS_Demuxer *ts)
{
while (gf_list_count(ts->SDTs)) {
GF_M2TS_SDT *sdt = (GF_M2TS_SDT *)gf_list_last(ts->SDTs);
gf_list_rem_last(ts->SDTs);
if (sdt->provider) gf_free(sdt->provider);
if (sdt->service) gf_free(sdt->service);
gf_free(sdt);
}
}
GF_EXPORT
GF_M2TS_SDT *gf_m2ts_get_sdt_info(GF_M2TS_Demuxer *ts, u32 program_id)
{
u32 i;
for (i=0; i<gf_list_count(ts->SDTs); i++) {
GF_M2TS_SDT *sdt = (GF_M2TS_SDT *)gf_list_get(ts->SDTs, i);
if (sdt->service_id==program_id) return sdt;
}
return NULL;
}
static void gf_m2ts_section_complete(GF_M2TS_Demuxer *ts, GF_M2TS_SectionFilter *sec, GF_M2TS_SECTION_ES *ses)
{
//seek mode, only process PAT and PMT
if (ts->seek_mode && (sec->section[0] != GF_M2TS_TABLE_ID_PAT) && (sec->section[0] != GF_M2TS_TABLE_ID_PMT)) {
/*clean-up (including broken sections)*/
if (sec->section) gf_free(sec->section);
sec->section = NULL;
sec->length = sec->received = 0;
return;
}
if (!sec->process_section) {
if ((ts->on_event && (sec->section[0]==GF_M2TS_TABLE_ID_AIT)) ) {
#ifdef GPAC_ENABLE_DSMCC
GF_M2TS_SL_PCK pck;
pck.data_len = sec->length;
pck.data = sec->section;
pck.stream = (GF_M2TS_ES *)ses;
//ts->on_event(ts, GF_M2TS_EVT_AIT_FOUND, &pck);
on_ait_section(ts, GF_M2TS_EVT_AIT_FOUND, &pck);
#endif
} else if ((ts->on_event && (sec->section[0]==GF_M2TS_TABLE_ID_DSM_CC_ENCAPSULATED_DATA || sec->section[0]==GF_M2TS_TABLE_ID_DSM_CC_UN_MESSAGE ||
sec->section[0]==GF_M2TS_TABLE_ID_DSM_CC_DOWNLOAD_DATA_MESSAGE || sec->section[0]==GF_M2TS_TABLE_ID_DSM_CC_STREAM_DESCRIPTION || sec->section[0]==GF_M2TS_TABLE_ID_DSM_CC_PRIVATE)) ) {
#ifdef GPAC_ENABLE_DSMCC
GF_M2TS_SL_PCK pck;
pck.data_len = sec->length;
pck.data = sec->section;
pck.stream = (GF_M2TS_ES *)ses;
on_dsmcc_section(ts,GF_M2TS_EVT_DSMCC_FOUND,&pck);
//ts->on_event(ts, GF_M2TS_EVT_DSMCC_FOUND, &pck);
#endif
}
#ifdef GPAC_ENABLE_MPE
else if (ts->on_mpe_event && ((ses && (ses->flags & GF_M2TS_EVT_DVB_MPE)) || (sec->section[0]==GF_M2TS_TABLE_ID_INT)) ) {
GF_M2TS_SL_PCK pck;
pck.data_len = sec->length;
pck.data = sec->section;
pck.stream = (GF_M2TS_ES *)ses;
ts->on_mpe_event(ts, GF_M2TS_EVT_DVB_MPE, &pck);
}
#endif
else if (ts->on_event) {
GF_M2TS_SL_PCK pck;
pck.data_len = sec->length;
pck.data = sec->section;
pck.stream = (GF_M2TS_ES *)ses;
ts->on_event(ts, GF_M2TS_EVT_DVB_GENERAL, &pck);
}
} else {
Bool has_syntax_indicator;
u8 table_id;
u16 extended_table_id;
u32 status, section_start, i;
GF_M2TS_Table *t, *prev_t;
unsigned char *data;
Bool section_valid = 0;
status = 0;
/*parse header*/
data = (u8 *)sec->section;
/*look for proper table*/
table_id = data[0];
if (ts->on_event) {
switch (table_id) {
case GF_M2TS_TABLE_ID_PAT:
case GF_M2TS_TABLE_ID_SDT_ACTUAL:
case GF_M2TS_TABLE_ID_PMT:
case GF_M2TS_TABLE_ID_NIT_ACTUAL:
case GF_M2TS_TABLE_ID_TDT:
case GF_M2TS_TABLE_ID_TOT:
{
GF_M2TS_SL_PCK pck;
pck.data_len = sec->length;
pck.data = sec->section;
pck.stream = (GF_M2TS_ES *)ses;
ts->on_event(ts, GF_M2TS_EVT_DVB_GENERAL, &pck);
}
}
}
has_syntax_indicator = (data[1] & 0x80) ? 1 : 0;
if (has_syntax_indicator) {
extended_table_id = (data[3]<<8) | data[4];
} else {
extended_table_id = 0;
}
prev_t = NULL;
t = sec->table;
while (t) {
if ((t->table_id==table_id) && (t->ex_table_id == extended_table_id)) break;
prev_t = t;
t = t->next;
}
/*create table*/
if (!t) {
GF_SAFEALLOC(t, GF_M2TS_Table);
if (!t) {
GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[MPEG-2 TS] Fail to alloc table %d %d\n", table_id, extended_table_id));
return;
}
GF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, ("[MPEG-2 TS] Creating table %d %d\n", table_id, extended_table_id));
t->table_id = table_id;
t->ex_table_id = extended_table_id;
t->last_version_number = 0xFF;
t->sections = gf_list_new();
if (prev_t) prev_t->next = t;
else sec->table = t;
}
if (has_syntax_indicator) {
if (sec->length < 4) {
GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[MPEG-2 TS] corrupted section length %d less than CRC \n", sec->length));
} else {
/*remove crc32*/
sec->length -= 4;
if (gf_m2ts_crc32_check((char *)data, sec->length)) {
s32 cur_sec_num;
t->version_number = (data[5] >> 1) & 0x1f;
if (t->last_section_number && t->section_number && (t->version_number != t->last_version_number)) {
GF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, ("[MPEG-2 TS] table transmission interrupted: previous table (v=%d) %d/%d sections - new table (v=%d) %d/%d sections\n", t->last_version_number, t->section_number, t->last_section_number, t->version_number, data[6] + 1, data[7] + 1) );
gf_m2ts_reset_sections(t->sections);
t->section_number = 0;
}
t->current_next_indicator = (data[5] & 0x1) ? 1 : 0;
/*add one to section numbers to detect if we missed or not the first section in the table*/
cur_sec_num = data[6] + 1;
t->last_section_number = data[7] + 1;
section_start = 8;
/*we missed something*/
if (!sec->process_individual && t->section_number + 1 != cur_sec_num) {
/* TODO - Check how to handle sections when the first complete section does
not have its sec num 0 */
section_valid = 0;
if (t->is_init) {
GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[MPEG-2 TS] corrupted table (lost section %d)\n", cur_sec_num ? cur_sec_num-1 : 31) );
}
} else {
section_valid = 1;
t->section_number = cur_sec_num;
}
} else {
GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[MPEG-2 TS] corrupted section (CRC32 failed)\n"));
}
}
} else {
section_valid = 1;
section_start = 3;
}
/*process section*/
if (section_valid) {
GF_M2TS_Section *section;
GF_SAFEALLOC(section, GF_M2TS_Section);
if (!section) {
GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[MPEG-2 TS] Fail to create section\n"));
return;
}
section->data_size = sec->length - section_start;
section->data = (unsigned char*)gf_malloc(sizeof(unsigned char)*section->data_size);
memcpy(section->data, sec->section + section_start, sizeof(unsigned char)*section->data_size);
gf_list_add(t->sections, section);
if (t->section_number == 1) {
status |= GF_M2TS_TABLE_START;
if (t->last_version_number == t->version_number) {
t->is_repeat = 1;
} else {
t->is_repeat = 0;
}
/*only update version number in the first section of the table*/
t->last_version_number = t->version_number;
}
if (t->is_init) {
if (t->is_repeat) {
status |= GF_M2TS_TABLE_REPEAT;
} else {
status |= GF_M2TS_TABLE_UPDATE;
}
} else {
status |= GF_M2TS_TABLE_FOUND;
}
if (t->last_section_number == t->section_number) {
u32 table_size;
status |= GF_M2TS_TABLE_END;
table_size = 0;
for (i=0; i<gf_list_count(t->sections); i++) {
GF_M2TS_Section *section = gf_list_get(t->sections, i);
table_size += section->data_size;
}
if (t->is_repeat) {
if (t->table_size != table_size) {
status |= GF_M2TS_TABLE_UPDATE;
GF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, ("[MPEG-2 TS] Repeated section found with different sizes (old table %d bytes, new table %d bytes)\n", t->table_size, table_size) );
t->table_size = table_size;
}
} else {
t->table_size = table_size;
}
t->is_init = 1;
/*reset section number*/
t->section_number = 0;
t->is_repeat = 0;
}
if (sec->process_individual) {
/*send each section of the table and not the aggregated table*/
if (sec->process_section)
sec->process_section(ts, ses, t->sections, t->table_id, t->ex_table_id, t->version_number, (u8) (t->last_section_number - 1), status);
gf_m2ts_reset_sections(t->sections);
} else {
if (status&GF_M2TS_TABLE_END) {
if (sec->process_section)
sec->process_section(ts, ses, t->sections, t->table_id, t->ex_table_id, t->version_number, (u8) (t->last_section_number - 1), status);
gf_m2ts_reset_sections(t->sections);
}
}
} else {
sec->cc = -1;
t->section_number = 0;
}
}
/*clean-up (including broken sections)*/
if (sec->section) gf_free(sec->section);
sec->section = NULL;
sec->length = sec->received = 0;
}
static Bool gf_m2ts_is_long_section(u8 table_id)
{
switch (table_id) {
case GF_M2TS_TABLE_ID_MPEG4_BIFS:
case GF_M2TS_TABLE_ID_MPEG4_OD:
case GF_M2TS_TABLE_ID_INT:
case GF_M2TS_TABLE_ID_EIT_ACTUAL_PF:
case GF_M2TS_TABLE_ID_EIT_OTHER_PF:
case GF_M2TS_TABLE_ID_ST:
case GF_M2TS_TABLE_ID_SIT:
case GF_M2TS_TABLE_ID_DSM_CC_PRIVATE:
case GF_M2TS_TABLE_ID_MPE_FEC:
case GF_M2TS_TABLE_ID_DSM_CC_DOWNLOAD_DATA_MESSAGE:
case GF_M2TS_TABLE_ID_DSM_CC_UN_MESSAGE:
return 1;
default:
if (table_id >= GF_M2TS_TABLE_ID_EIT_SCHEDULE_MIN && table_id <= GF_M2TS_TABLE_ID_EIT_SCHEDULE_MAX)
return 1;
else
return 0;
}
}
static u32 gf_m2ts_get_section_length(char byte0, char byte1, char byte2)
{
u32 length;
if (gf_m2ts_is_long_section(byte0)) {
length = 3 + ( ((((u32)byte1)<<8) | (byte2&0xff)) & 0xfff );
} else {
length = 3 + ( ((((u32)byte1)<<8) | (byte2&0xff)) & 0x3ff );
}
return length;
}
static void gf_m2ts_gather_section(GF_M2TS_Demuxer *ts, GF_M2TS_SectionFilter *sec, GF_M2TS_SECTION_ES *ses, GF_M2TS_Header *hdr, unsigned char *data, u32 data_size)
{
u32 payload_size = data_size;
u8 expect_cc = (sec->cc<0) ? hdr->continuity_counter : (sec->cc + 1) & 0xf;
Bool disc = (expect_cc == hdr->continuity_counter) ? 0 : 1;
sec->cc = expect_cc;
/*may happen if hdr->adaptation_field=2 no payload in TS packet*/
if (!data_size) return;
if (hdr->payload_start) {
u32 ptr_field;
ptr_field = data[0];
if (ptr_field+1>data_size) {
GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[MPEG-2 TS] Invalid section start (@ptr_field=%d, @data_size=%d)\n", ptr_field, data_size) );
return;
}
/*end of previous section*/
if (!sec->length && sec->received) {
/* the length of the section could not be determined from the previous TS packet because we had only 1 or 2 bytes */
if (sec->received == 1)
sec->length = gf_m2ts_get_section_length(sec->section[0], data[1], data[2]);
else /* (sec->received == 2) */
sec->length = gf_m2ts_get_section_length(sec->section[0], sec->section[1], data[1]);
sec->section = (char*)gf_realloc(sec->section, sizeof(char)*sec->length);
}
if (sec->length && sec->received + ptr_field >= sec->length) {
u32 len = sec->length - sec->received;
memcpy(sec->section + sec->received, data+1, sizeof(char)*len);
sec->received += len;
if (ptr_field > len)
GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[MPEG-2 TS] Invalid pointer field (@ptr_field=%d, @remaining=%d)\n", ptr_field, len) );
gf_m2ts_section_complete(ts, sec, ses);
}
data += ptr_field+1;
data_size -= ptr_field+1;
payload_size -= ptr_field+1;
aggregated_section:
if (sec->section) gf_free(sec->section);
sec->length = sec->received = 0;
sec->section = (char*)gf_malloc(sizeof(char)*data_size);
memcpy(sec->section, data, sizeof(char)*data_size);
sec->received = data_size;
} else if (disc) {
if (sec->section) gf_free(sec->section);
sec->section = NULL;
sec->received = sec->length = 0;
return;
} else if (!sec->section) {
return;
} else {
if (sec->length && sec->received+data_size > sec->length)
data_size = sec->length - sec->received;
if (sec->length) {
memcpy(sec->section + sec->received, data, sizeof(char)*data_size);
} else {
sec->section = (char*)gf_realloc(sec->section, sizeof(char)*(sec->received+data_size));
memcpy(sec->section + sec->received, data, sizeof(char)*data_size);
}
sec->received += data_size;
}
/*alloc final buffer*/
if (!sec->length && (sec->received >= 3)) {
sec->length = gf_m2ts_get_section_length(sec->section[0], sec->section[1], sec->section[2]);
sec->section = (char*)gf_realloc(sec->section, sizeof(char)*sec->length);
if (sec->received > sec->length) {
data_size -= sec->received - sec->length;
sec->received = sec->length;
}
}
if (!sec->length || sec->received < sec->length) return;
/*OK done*/
gf_m2ts_section_complete(ts, sec, ses);
if (payload_size > data_size) {
data += data_size;
/* detect padding after previous section */
if (data[0] != 0xFF) {
data_size = payload_size - data_size;
payload_size = data_size;
goto aggregated_section;
}
}
}
static void gf_m2ts_process_sdt(GF_M2TS_Demuxer *ts, GF_M2TS_SECTION_ES *ses, GF_List *sections, u8 table_id, u16 ex_table_id, u8 version_number, u8 last_section_number, u32 status)
{
u32 pos, evt_type;
u32 nb_sections;
u32 data_size;
unsigned char *data;
GF_M2TS_Section *section;
/*wait for the last section */
if (!(status&GF_M2TS_TABLE_END)) return;
/*skip if already received*/
if (status&GF_M2TS_TABLE_REPEAT) {
if (ts->on_event) ts->on_event(ts, GF_M2TS_EVT_SDT_REPEAT, NULL);
return;
}
if (table_id != GF_M2TS_TABLE_ID_SDT_ACTUAL) {
return;
}
gf_m2ts_reset_sdt(ts);
nb_sections = gf_list_count(sections);
if (nb_sections > 1) {
GF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, ("[MPEG-2 TS] SDT on multiple sections not supported\n"));
}
section = (GF_M2TS_Section *)gf_list_get(sections, 0);
data = section->data;
data_size = section->data_size;
//orig_net_id = (data[0] << 8) | data[1];
pos = 3;
while (pos < data_size) {
GF_M2TS_SDT *sdt;
u32 descs_size, d_pos, ulen;
GF_SAFEALLOC(sdt, GF_M2TS_SDT);
if (!sdt) {
GF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, ("[MPEG-2 TS] Fail to create SDT\n"));
return;
}
gf_list_add(ts->SDTs, sdt);
sdt->service_id = (data[pos]<<8) + data[pos+1];
sdt->EIT_schedule = (data[pos+2] & 0x2) ? 1 : 0;
sdt->EIT_present_following = (data[pos+2] & 0x1);
sdt->running_status = (data[pos+3]>>5) & 0x7;
sdt->free_CA_mode = (data[pos+3]>>4) & 0x1;
descs_size = ((data[pos+3]&0xf)<<8) | data[pos+4];
pos += 5;
d_pos = 0;
while (d_pos < descs_size) {
u8 d_tag = data[pos+d_pos];
u8 d_len = data[pos+d_pos+1];
switch (d_tag) {
case GF_M2TS_DVB_SERVICE_DESCRIPTOR:
if (sdt->provider) gf_free(sdt->provider);
sdt->provider = NULL;
if (sdt->service) gf_free(sdt->service);
sdt->service = NULL;
d_pos+=2;
sdt->service_type = data[pos+d_pos];
ulen = data[pos+d_pos+1];
d_pos += 2;
sdt->provider = (char*)gf_malloc(sizeof(char)*(ulen+1));
memcpy(sdt->provider, data+pos+d_pos, sizeof(char)*ulen);
sdt->provider[ulen] = 0;
d_pos += ulen;
ulen = data[pos+d_pos];
d_pos += 1;
sdt->service = (char*)gf_malloc(sizeof(char)*(ulen+1));
memcpy(sdt->service, data+pos+d_pos, sizeof(char)*ulen);
sdt->service[ulen] = 0;
d_pos += ulen;
break;
default:
GF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, ("[MPEG-2 TS] Skipping descriptor (0x%x) not supported\n", d_tag));
d_pos += d_len;
if (d_len == 0) d_pos = descs_size;
break;
}
}
pos += descs_size;
}
evt_type = GF_M2TS_EVT_SDT_FOUND;
if (ts->on_event) ts->on_event(ts, evt_type, NULL);
}
static void gf_m2ts_process_mpeg4section(GF_M2TS_Demuxer *ts, GF_M2TS_SECTION_ES *es, GF_List *sections, u8 table_id, u16 ex_table_id, u8 version_number, u8 last_section_number, u32 status)
{
GF_M2TS_SL_PCK sl_pck;
u32 nb_sections, i;
GF_M2TS_Section *section;
/*skip if already received*/
if (status & GF_M2TS_TABLE_REPEAT)
if (!(es->flags & GF_M2TS_ES_SEND_REPEATED_SECTIONS))
return;
GF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, ("[MPEG-2 TS] Sections for PID %d\n", es->pid) );
/*send all sections (eg SL-packets)*/
nb_sections = gf_list_count(sections);
for (i=0; i<nb_sections; i++) {
section = (GF_M2TS_Section *)gf_list_get(sections, i);
sl_pck.data = (char *)section->data;
sl_pck.data_len = section->data_size;
sl_pck.stream = (GF_M2TS_ES *)es;
sl_pck.version_number = version_number;
if (ts->on_event) ts->on_event(ts, GF_M2TS_EVT_SL_PCK, &sl_pck);
}
}
static void gf_m2ts_process_nit(GF_M2TS_Demuxer *ts, GF_M2TS_SECTION_ES *nit_es, GF_List *sections, u8 table_id, u16 ex_table_id, u8 version_number, u8 last_section_number, u32 status)
{
GF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, ("[MPEG-2 TS] NIT table processing (not yet implemented)"));
}
static void gf_m2ts_process_tdt_tot(GF_M2TS_Demuxer *ts, GF_M2TS_SECTION_ES *tdt_tot_es, GF_List *sections, u8 table_id, u16 ex_table_id, u8 version_number, u8 last_section_number, u32 status)
{
unsigned char *data;
u32 data_size, nb_sections;
u32 date, yp, mp, k;
GF_M2TS_Section *section;
GF_M2TS_TDT_TOT *time_table;
const char *table_name;
/*wait for the last section */
if ( !(status & GF_M2TS_TABLE_END) )
return;
switch (table_id) {
case GF_M2TS_TABLE_ID_TDT:
table_name = "TDT";
break;
case GF_M2TS_TABLE_ID_TOT:
table_name = "TOT";
break;
default:
GF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, ("[MPEG-2 TS] Unimplemented table_id %u for PID %u\n", table_id, GF_M2TS_PID_TDT_TOT_ST));
return;
}
nb_sections = gf_list_count(sections);
if (nb_sections > 1) {
GF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, ("[MPEG-2 TS] %s on multiple sections not supported\n", table_name));
}
section = (GF_M2TS_Section *)gf_list_get(sections, 0);
data = section->data;
data_size = section->data_size;
/*TOT only contains 40 bits of UTC_time; TDT add descriptors and a CRC*/
if ((table_id==GF_M2TS_TABLE_ID_TDT) && (data_size != 5)) {
GF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, ("[MPEG-2 TS] Corrupted TDT size\n", table_name));
}
GF_SAFEALLOC(time_table, GF_M2TS_TDT_TOT);
if (!time_table) {
GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[MPEG-2 TS] Fail to alloc DVB time table\n"));
return;
}
/*UTC_time - see annex C of DVB-SI ETSI EN 300468*/
/* decodes an Modified Julian Date (MJD) into a Co-ordinated Universal Time (UTC)
See annex C of DVB-SI ETSI EN 300468 */
date = data[0]*256 + data[1];
yp = (u32)((date - 15078.2)/365.25);
mp = (u32)((date - 14956.1 - (u32)(yp * 365.25))/30.6001);
time_table->day = (u32)(date - 14956 - (u32)(yp * 365.25) - (u32)(mp * 30.6001));
if (mp == 14 || mp == 15) k = 1;
else k = 0;
time_table->year = yp + k + 1900;
time_table->month = mp - 1 - k*12;
time_table->hour = 10*((data[2]&0xf0)>>4) + (data[2]&0x0f);
time_table->minute = 10*((data[3]&0xf0)>>4) + (data[3]&0x0f);
time_table->second = 10*((data[4]&0xf0)>>4) + (data[4]&0x0f);
assert(time_table->hour<24 && time_table->minute<60 && time_table->second<60);
GF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, ("[MPEG-2 TS] Stream UTC time is %u/%02u/%02u %02u:%02u:%02u\n", time_table->year, time_table->month, time_table->day, time_table->hour, time_table->minute, time_table->second));
switch (table_id) {
case GF_M2TS_TABLE_ID_TDT:
if (ts->TDT_time) gf_free(ts->TDT_time);
ts->TDT_time = time_table;
if (ts->on_event) ts->on_event(ts, GF_M2TS_EVT_TDT, time_table);
break;
case GF_M2TS_TABLE_ID_TOT:
#if 0
{
u32 pos, loop_len;
loop_len = ((data[5]&0x0f) << 8) | (data[6] & 0xff);
data += 7;
pos = 0;
while (pos < loop_len) {
u8 tag = data[pos];
pos += 2;
if (tag == GF_M2TS_DVB_LOCAL_TIME_OFFSET_DESCRIPTOR) {
char tmp_time[10];
u16 offset_hours, offset_minutes;
now->country_code[0] = data[pos];
now->country_code[1] = data[pos+1];
now->country_code[2] = data[pos+2];
now->country_region_id = data[pos+3]>>2;
sprintf(tmp_time, "%02x", data[pos+4]);
offset_hours = atoi(tmp_time);
sprintf(tmp_time, "%02x", data[pos+5]);
offset_minutes = atoi(tmp_time);
now->local_time_offset_seconds = (offset_hours * 60 + offset_minutes) * 60;
if (data[pos+3] & 1) now->local_time_offset_seconds *= -1;
dvb_decode_mjd_to_unix_time(data+pos+6, &now->unix_next_toc);
sprintf(tmp_time, "%02x", data[pos+11]);
offset_hours = atoi(tmp_time);
sprintf(tmp_time, "%02x", data[pos+12]);
offset_minutes = atoi(tmp_time);
now->next_time_offset_seconds = (offset_hours * 60 + offset_minutes) * 60;
if (data[pos+3] & 1) now->next_time_offset_seconds *= -1;
pos+= 13;
}
}
/*TODO: check lengths are ok*/
if (ts->on_event) ts->on_event(ts, GF_M2TS_EVT_TOT, time_table);
}
#endif
/*check CRC32*/
if (ts->tdt_tot->length<4) {
GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[MPEG-2 TS] corrupted %s table (less than 4 bytes but CRC32 should be present\n", table_name));
goto error_exit;
}
if (!gf_m2ts_crc32_check(ts->tdt_tot->section, ts->tdt_tot->length-4)) {
GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[MPEG-2 TS] corrupted %s table (CRC32 failed)\n", table_name));
goto error_exit;
}
if (ts->TDT_time) gf_free(ts->TDT_time);
ts->TDT_time = time_table;
if (ts->on_event) ts->on_event(ts, GF_M2TS_EVT_TOT, time_table);
break;
default:
assert(0);
goto error_exit;
}
return; /*success*/
error_exit:
gf_free(time_table);
return;
}
static GF_M2TS_MetadataPointerDescriptor *gf_m2ts_read_metadata_pointer_descriptor(GF_BitStream *bs, u32 length)
{
u32 size;
GF_M2TS_MetadataPointerDescriptor *d;
GF_SAFEALLOC(d, GF_M2TS_MetadataPointerDescriptor);
if (!d) return NULL;
d->application_format = gf_bs_read_u16(bs);
size = 2;
if (d->application_format == 0xFFFF) {
d->application_format_identifier = gf_bs_read_u32(bs);
size += 4;
}
d->format = gf_bs_read_u8(bs);
size += 1;
if (d->format == 0xFF) {
d->format_identifier = gf_bs_read_u32(bs);
size += 4;
}
d->service_id = gf_bs_read_u8(bs);
d->locator_record_flag = (gf_bs_read_int(bs, 1) ? GF_TRUE : GF_FALSE);
d->carriage_flag = (enum metadata_carriage)gf_bs_read_int(bs, 2);
gf_bs_read_int(bs, 5); /*reserved */
size += 2;
if (d->locator_record_flag) {
d->locator_length = gf_bs_read_u8(bs);
d->locator_data = (char *)gf_malloc(d->locator_length);
size += 1 + d->locator_length;
gf_bs_read_data(bs, d->locator_data, d->locator_length);
}
if (d->carriage_flag != 3) {
d->program_number = gf_bs_read_u16(bs);
size += 2;
}
if (d->carriage_flag == 1) {
d->ts_location = gf_bs_read_u16(bs);
d->ts_id = gf_bs_read_u16(bs);
size += 4;
}
if (length-size > 0) {
d->data_size = length-size;
d->data = (char *)gf_malloc(d->data_size);
gf_bs_read_data(bs, d->data, d->data_size);
}
return d;
}
static void gf_m2ts_metadata_pointer_descriptor_del(GF_M2TS_MetadataPointerDescriptor *metapd)
{
if (metapd) {
if (metapd->locator_data) gf_free(metapd->locator_data);
if (metapd->data) gf_free(metapd->data);
gf_free(metapd);
}
}
static GF_M2TS_MetadataDescriptor *gf_m2ts_read_metadata_descriptor(GF_BitStream *bs, u32 length)
{
u32 size;
GF_M2TS_MetadataDescriptor *d;
GF_SAFEALLOC(d, GF_M2TS_MetadataDescriptor);
if (!d) return NULL;
d->application_format = gf_bs_read_u16(bs);
size = 2;
if (d->application_format == 0xFFFF) {
d->application_format_identifier = gf_bs_read_u32(bs);
size += 4;
}
d->format = gf_bs_read_u8(bs);
size += 1;
if (d->format == 0xFF) {
d->format_identifier = gf_bs_read_u32(bs);
size += 4;
}
d->service_id = gf_bs_read_u8(bs);
d->decoder_config_flags = gf_bs_read_int(bs, 3);
d->dsmcc_flag = (gf_bs_read_int(bs, 1) ? GF_TRUE : GF_FALSE);
gf_bs_read_int(bs, 4); /* reserved */
size += 2;
if (d->dsmcc_flag) {
d->service_id_record_length = gf_bs_read_u8(bs);
d->service_id_record = (char *)gf_malloc(d->service_id_record_length);
size += 1 + d->service_id_record_length;
gf_bs_read_data(bs, d->service_id_record, d->service_id_record_length);
}
if (d->decoder_config_flags == 1) {
d->decoder_config_length = gf_bs_read_u8(bs);
d->decoder_config = (char *)gf_malloc(d->decoder_config_length);
size += 1 + d->decoder_config_length;
gf_bs_read_data(bs, d->decoder_config, d->decoder_config_length);
}
if (d->decoder_config_flags == 3) {
d->decoder_config_id_length = gf_bs_read_u8(bs);
d->decoder_config_id = (char *)gf_malloc(d->decoder_config_id_length);
size += 1 + d->decoder_config_id_length;
gf_bs_read_data(bs, d->decoder_config_id, d->decoder_config_id_length);
}
if (d->decoder_config_flags == 4) {
d->decoder_config_service_id = gf_bs_read_u8(bs);
size++;
}
return d;
}
static void gf_m2ts_process_pmt(GF_M2TS_Demuxer *ts, GF_M2TS_SECTION_ES *pmt, GF_List *sections, u8 table_id, u16 ex_table_id, u8 version_number, u8 last_section_number, u32 status)
{
u32 info_length, pos, desc_len, evt_type, nb_es,i;
u32 nb_sections;
u32 data_size;
u32 nb_hevc, nb_hevc_temp, nb_shvc, nb_shvc_temp, nb_mhvc, nb_mhvc_temp;
unsigned char *data;
GF_M2TS_Section *section;
GF_Err e = GF_OK;
/*wait for the last section */
if (!(status&GF_M2TS_TABLE_END)) return;
nb_es = 0;
/*skip if already received but no update detected (eg same data) */
if ((status&GF_M2TS_TABLE_REPEAT) && !(status&GF_M2TS_TABLE_UPDATE)) {
if (ts->on_event) ts->on_event(ts, GF_M2TS_EVT_PMT_REPEAT, pmt->program);
return;
}
if (pmt->sec->demux_restarted) {
pmt->sec->demux_restarted = 0;
return;
}
GF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, ("[MPEG-2 TS] PMT Found or updated\n"));
nb_sections = gf_list_count(sections);
if (nb_sections > 1) {
GF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, ("PMT on multiple sections not supported\n"));
}
section = (GF_M2TS_Section *)gf_list_get(sections, 0);
data = section->data;
data_size = section->data_size;
pmt->program->pcr_pid = ((data[0] & 0x1f) << 8) | data[1];
info_length = ((data[2]&0xf)<<8) | data[3];
if (info_length != 0) {
/* ...Read Descriptors ... */
u8 tag, len;
u32 first_loop_len = 0;
tag = data[4];
len = data[5];
while (info_length > first_loop_len) {
if (tag == GF_M2TS_MPEG4_IOD_DESCRIPTOR) {
u32 size;
GF_BitStream *iod_bs;
iod_bs = gf_bs_new((char *)data+8, len-2, GF_BITSTREAM_READ);
if (pmt->program->pmt_iod) gf_odf_desc_del((GF_Descriptor *)pmt->program->pmt_iod);
e = gf_odf_parse_descriptor(iod_bs , (GF_Descriptor **) &pmt->program->pmt_iod, &size);
gf_bs_del(iod_bs );
if (e==GF_OK) {
/*remember program number for service/program selection*/
if (pmt->program->pmt_iod) pmt->program->pmt_iod->ServiceID = pmt->program->number;
/*if empty IOD (freebox case), discard it and use dynamic declaration of object*/
if (!gf_list_count(pmt->program->pmt_iod->ESDescriptors)) {
gf_odf_desc_del((GF_Descriptor *)pmt->program->pmt_iod);
pmt->program->pmt_iod = NULL;
}
}
} else if (tag == GF_M2TS_METADATA_POINTER_DESCRIPTOR) {
GF_BitStream *metadatapd_bs;
GF_M2TS_MetadataPointerDescriptor *metapd;
metadatapd_bs = gf_bs_new((char *)data+6, len, GF_BITSTREAM_READ);
metapd = gf_m2ts_read_metadata_pointer_descriptor(metadatapd_bs, len);
gf_bs_del(metadatapd_bs);
if (metapd->application_format_identifier == GF_M2TS_META_ID3 &&
metapd->format_identifier == GF_M2TS_META_ID3 &&
metapd->carriage_flag == METADATA_CARRIAGE_SAME_TS) {
/*HLS ID3 Metadata */
pmt->program->metadata_pointer_descriptor = metapd;
} else {
/* don't know what to do with it for now, delete */
gf_m2ts_metadata_pointer_descriptor_del(metapd);
}
} else {
GF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, ("[MPEG-2 TS] Skipping descriptor (0x%x) and others not supported\n", tag));
}
first_loop_len += 2 + len;
}
}
if (data_size <= 4 + info_length) return;
data += 4 + info_length;
data_size -= 4 + info_length;
pos = 0;
/* count de number of program related PMT received */
for(i=0; i<gf_list_count(ts->programs); i++) {
GF_M2TS_Program *prog = (GF_M2TS_Program *)gf_list_get(ts->programs,i);
if(prog->pmt_pid == pmt->pid) {
break;
}
}
nb_hevc = nb_hevc_temp = nb_shvc = nb_shvc_temp = nb_mhvc = nb_mhvc_temp = 0;
while (pos<data_size) {
GF_M2TS_PES *pes = NULL;
GF_M2TS_SECTION_ES *ses = NULL;
GF_M2TS_ES *es = NULL;
Bool inherit_pcr = 0;
u32 pid, stream_type, reg_desc_format;
stream_type = data[0];
pid = ((data[1] & 0x1f) << 8) | data[2];
desc_len = ((data[3] & 0xf) << 8) | data[4];
GF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, ("stream_type :%d \n",stream_type));
switch (stream_type) {
/* PES */
case GF_M2TS_VIDEO_MPEG1:
case GF_M2TS_VIDEO_MPEG2:
case GF_M2TS_VIDEO_DCII:
case GF_M2TS_VIDEO_MPEG4:
case GF_M2TS_SYSTEMS_MPEG4_PES:
case GF_M2TS_VIDEO_H264:
case GF_M2TS_VIDEO_SVC:
case GF_M2TS_VIDEO_MVCD:
case GF_M2TS_VIDEO_HEVC:
case GF_M2TS_VIDEO_HEVC_MCTS:
case GF_M2TS_VIDEO_HEVC_TEMPORAL:
case GF_M2TS_VIDEO_SHVC:
case GF_M2TS_VIDEO_SHVC_TEMPORAL:
case GF_M2TS_VIDEO_MHVC:
case GF_M2TS_VIDEO_MHVC_TEMPORAL:
inherit_pcr = 1;
case GF_M2TS_AUDIO_MPEG1:
case GF_M2TS_AUDIO_MPEG2:
case GF_M2TS_AUDIO_AAC:
case GF_M2TS_AUDIO_LATM_AAC:
case GF_M2TS_AUDIO_AC3:
case GF_M2TS_AUDIO_DTS:
case GF_M2TS_MHAS_MAIN:
case GF_M2TS_MHAS_AUX:
case GF_M2TS_SUBTITLE_DVB:
case GF_M2TS_METADATA_PES:
GF_SAFEALLOC(pes, GF_M2TS_PES);
if (!pes) {
GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[MPEG2TS] Failed to allocate ES for pid %d\n", pid));
return;
}
pes->cc = -1;
pes->flags = GF_M2TS_ES_IS_PES;
if (inherit_pcr)
pes->flags |= GF_M2TS_INHERIT_PCR;
es = (GF_M2TS_ES *)pes;
break;
case GF_M2TS_PRIVATE_DATA:
GF_SAFEALLOC(pes, GF_M2TS_PES);
if (!pes) {
GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[MPEG2TS] Failed to allocate ES for pid %d\n", pid));
return;
}
pes->cc = -1;
pes->flags = GF_M2TS_ES_IS_PES;
es = (GF_M2TS_ES *)pes;
break;
/* Sections */
case GF_M2TS_SYSTEMS_MPEG4_SECTIONS:
GF_SAFEALLOC(ses, GF_M2TS_SECTION_ES);
if (!ses) {
GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[MPEG2TS] Failed to allocate ES for pid %d\n", pid));
return;
}
es = (GF_M2TS_ES *)ses;
es->flags |= GF_M2TS_ES_IS_SECTION;
/* carriage of ISO_IEC_14496 data in sections */
if (stream_type == GF_M2TS_SYSTEMS_MPEG4_SECTIONS) {
/*MPEG-4 sections need to be fully checked: if one section is lost, this means we lost
one SL packet in the AU so we must wait for the complete section again*/
ses->sec = gf_m2ts_section_filter_new(gf_m2ts_process_mpeg4section, 0);
/*create OD container*/
if (!pmt->program->additional_ods) {
pmt->program->additional_ods = gf_list_new();
ts->has_4on2 = 1;
}
}
break;
case GF_M2TS_13818_6_ANNEX_A:
case GF_M2TS_13818_6_ANNEX_B:
case GF_M2TS_13818_6_ANNEX_C:
case GF_M2TS_13818_6_ANNEX_D:
case GF_M2TS_PRIVATE_SECTION:
case GF_M2TS_QUALITY_SEC:
case GF_M2TS_MORE_SEC:
GF_SAFEALLOC(ses, GF_M2TS_SECTION_ES);
if (!ses) {
GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[MPEG2TS] Failed to allocate ES for pid %d\n", pid));
return;
}
es = (GF_M2TS_ES *)ses;
es->flags |= GF_M2TS_ES_IS_SECTION;
es->pid = pid;
es->service_id = pmt->program->number;
if (stream_type == GF_M2TS_PRIVATE_SECTION) {
GF_LOG(GF_LOG_INFO, GF_LOG_CONTAINER, ("AIT sections on pid %d\n", pid));
} else if (stream_type == GF_M2TS_QUALITY_SEC) {
GF_LOG(GF_LOG_INFO, GF_LOG_CONTAINER, ("Quality metadata sections on pid %d\n", pid));
} else if (stream_type == GF_M2TS_MORE_SEC) {
GF_LOG(GF_LOG_INFO, GF_LOG_CONTAINER, ("MORE sections on pid %d\n", pid));
} else {
GF_LOG(GF_LOG_INFO, GF_LOG_CONTAINER, ("stream type DSM CC user private sections on pid %d \n", pid));
}
/* NULL means: trigger the call to on_event with DVB_GENERAL type and the raw section as payload */
ses->sec = gf_m2ts_section_filter_new(NULL, 1);
//ses->sec->service_id = pmt->program->number;
break;
case GF_M2TS_MPE_SECTIONS:
if (! ts->prefix_present) {
GF_LOG(GF_LOG_INFO, GF_LOG_CONTAINER, ("stream type MPE found : pid = %d \n", pid));
#ifdef GPAC_ENABLE_MPE
es = gf_dvb_mpe_section_new();
if (es->flags & GF_M2TS_ES_IS_SECTION) {
/* NULL means: trigger the call to on_event with DVB_GENERAL type and the raw section as payload */
((GF_M2TS_SECTION_ES*)es)->sec = gf_m2ts_section_filter_new(NULL, 1);
}
#endif
break;
}
default:
GF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, ("[MPEG-2 TS] Stream type (0x%x) for PID %d not supported\n", stream_type, pid ) );
//GF_LOG(/*GF_LOG_WARNING*/GF_LOG_ERROR, GF_LOG_CONTAINER, ("[MPEG-2 TS] Stream type (0x%x) for PID %d not supported\n", stream_type, pid ) );
break;
}
if (es) {
es->stream_type = (stream_type==GF_M2TS_PRIVATE_DATA) ? 0 : stream_type;
es->program = pmt->program;
es->pid = pid;
es->component_tag = -1;
}
pos += 5;
data += 5;
while (desc_len) {
u8 tag = data[0];
u32 len = data[1];
if (es) {
switch (tag) {
case GF_M2TS_ISO_639_LANGUAGE_DESCRIPTOR:
if (pes)
pes->lang = GF_4CC(' ', data[2], data[3], data[4]);
break;
case GF_M2TS_MPEG4_SL_DESCRIPTOR:
es->mpeg4_es_id = ( (u32) data[2] & 0x1f) << 8 | data[3];
es->flags |= GF_M2TS_ES_IS_SL;
break;
case GF_M2TS_REGISTRATION_DESCRIPTOR:
reg_desc_format = GF_4CC(data[2], data[3], data[4], data[5]);
/*cf http://www.smpte-ra.org/mpegreg/mpegreg.html*/
switch (reg_desc_format) {
case GF_M2TS_RA_STREAM_AC3:
es->stream_type = GF_M2TS_AUDIO_AC3;
break;
case GF_M2TS_RA_STREAM_VC1:
es->stream_type = GF_M2TS_VIDEO_VC1;
break;
case GF_M2TS_RA_STREAM_GPAC:
if (len==8) {
es->stream_type = GF_4CC(data[6], data[7], data[8], data[9]);
es->flags |= GF_M2TS_GPAC_CODEC_ID;
break;
}
default:
GF_LOG(GF_LOG_INFO, GF_LOG_CONTAINER, ("Unknown registration descriptor %s\n", gf_4cc_to_str(reg_desc_format) ));
break;
}
break;
case GF_M2TS_DVB_EAC3_DESCRIPTOR:
es->stream_type = GF_M2TS_AUDIO_EC3;
break;
case GF_M2TS_DVB_DATA_BROADCAST_ID_DESCRIPTOR:
{
u32 id = data[2]<<8 | data[3];
if ((id == 0xB) && ses && !ses->sec) {
ses->sec = gf_m2ts_section_filter_new(NULL, 1);
}
}
break;
case GF_M2TS_DVB_SUBTITLING_DESCRIPTOR:
if (pes) {
pes->sub.language[0] = data[2];
pes->sub.language[1] = data[3];
pes->sub.language[2] = data[4];
pes->sub.type = data[5];
pes->sub.composition_page_id = (data[6]<<8) | data[7];
pes->sub.ancillary_page_id = (data[8]<<8) | data[9];
}
es->stream_type = GF_M2TS_DVB_SUBTITLE;
break;
case GF_M2TS_DVB_STREAM_IDENTIFIER_DESCRIPTOR:
{
es->component_tag = data[2];
GF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, ("Component Tag: %d on Program %d\n", es->component_tag, es->program->number));
}
break;
case GF_M2TS_DVB_TELETEXT_DESCRIPTOR:
es->stream_type = GF_M2TS_DVB_TELETEXT;
break;
case GF_M2TS_DVB_VBI_DATA_DESCRIPTOR:
es->stream_type = GF_M2TS_DVB_VBI;
break;
case GF_M2TS_HIERARCHY_DESCRIPTOR:
if (pes) {
u8 hierarchy_embedded_layer_index;
GF_BitStream *hbs = gf_bs_new((const char *)data, data_size, GF_BITSTREAM_READ);
/*u32 skip = */gf_bs_read_int(hbs, 16);
/*u8 res1 = */gf_bs_read_int(hbs, 1);
/*u8 temp_scal = */gf_bs_read_int(hbs, 1);
/*u8 spatial_scal = */gf_bs_read_int(hbs, 1);
/*u8 quality_scal = */gf_bs_read_int(hbs, 1);
/*u8 hierarchy_type = */gf_bs_read_int(hbs, 4);
/*u8 res2 = */gf_bs_read_int(hbs, 2);
/*u8 hierarchy_layer_index = */gf_bs_read_int(hbs, 6);
/*u8 tref_not_present = */gf_bs_read_int(hbs, 1);
/*u8 res3 = */gf_bs_read_int(hbs, 1);
hierarchy_embedded_layer_index = gf_bs_read_int(hbs, 6);
/*u8 res4 = */gf_bs_read_int(hbs, 2);
/*u8 hierarchy_channel = */gf_bs_read_int(hbs, 6);
gf_bs_del(hbs);
pes->depends_on_pid = 1+hierarchy_embedded_layer_index;
}
break;
case GF_M2TS_METADATA_DESCRIPTOR:
{
GF_BitStream *metadatad_bs;
GF_M2TS_MetadataDescriptor *metad;
metadatad_bs = gf_bs_new((char *)data+2, len, GF_BITSTREAM_READ);
metad = gf_m2ts_read_metadata_descriptor(metadatad_bs, len);
gf_bs_del(metadatad_bs);
if (metad->application_format_identifier == GF_M2TS_META_ID3 &&
metad->format_identifier == GF_M2TS_META_ID3) {
/*HLS ID3 Metadata */
if (pes) {
pes->metadata_descriptor = metad;
pes->stream_type = GF_M2TS_METADATA_ID3_HLS;
}
} else {
/* don't know what to do with it for now, delete */
gf_m2ts_metadata_descriptor_del(metad);
}
}
break;
default:
GF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, ("[MPEG-2 TS] skipping descriptor (0x%x) not supported\n", tag));
break;
}
}
data += len+2;
pos += len+2;
if (desc_len < len+2) {
GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[MPEG-2 TS] Invalid PMT es descriptor size for PID %d\n", pid ) );
break;
}
desc_len-=len+2;
}
if (es && !es->stream_type) {
gf_free(es);
es = NULL;
GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[MPEG-2 TS] Private Stream type (0x%x) for PID %d not supported\n", stream_type, pid ) );
}
if (!es) continue;
if (ts->ess[pid]) {
//this is component reuse across programs, overwrite the previously declared stream ...
if (status & GF_M2TS_TABLE_FOUND) {
GF_LOG(GF_LOG_INFO, GF_LOG_CONTAINER, ("[MPEG-2 TS] PID %d reused across programs %d and %d, not completely supported\n", pid, ts->ess[pid]->program->number, es->program->number ) );
//add stream to program but don't reassign the pid table until the stream is playing (>GF_M2TS_PES_FRAMING_SKIP)
gf_list_add(pmt->program->streams, es);
if (!(es->flags & GF_M2TS_ES_IS_SECTION) ) gf_m2ts_set_pes_framing(pes, GF_M2TS_PES_FRAMING_SKIP);
nb_es++;
//skip assignment below
es = NULL;
}
/*watchout for pmt update - FIXME this likely won't work in most cases*/
else {
GF_M2TS_ES *o_es = ts->ess[es->pid];
if ((o_es->stream_type == es->stream_type)
&& ((o_es->flags & GF_M2TS_ES_STATIC_FLAGS_MASK) == (es->flags & GF_M2TS_ES_STATIC_FLAGS_MASK))
&& (o_es->mpeg4_es_id == es->mpeg4_es_id)
&& ((o_es->flags & GF_M2TS_ES_IS_SECTION) || ((GF_M2TS_PES *)o_es)->lang == ((GF_M2TS_PES *)es)->lang)
) {
gf_free(es);
es = NULL;
} else {
gf_m2ts_es_del(o_es, ts);
ts->ess[es->pid] = NULL;
}
}
}
if (es) {
ts->ess[es->pid] = es;
gf_list_add(pmt->program->streams, es);
if (!(es->flags & GF_M2TS_ES_IS_SECTION) ) gf_m2ts_set_pes_framing(pes, GF_M2TS_PES_FRAMING_SKIP);
nb_es++;
}
if (es->stream_type == GF_M2TS_VIDEO_HEVC) nb_hevc++;
else if (es->stream_type == GF_M2TS_VIDEO_HEVC_TEMPORAL) nb_hevc_temp++;
else if (es->stream_type == GF_M2TS_VIDEO_SHVC) nb_shvc++;
else if (es->stream_type == GF_M2TS_VIDEO_SHVC_TEMPORAL) nb_shvc_temp++;
else if (es->stream_type == GF_M2TS_VIDEO_MHVC) nb_mhvc++;
else if (es->stream_type == GF_M2TS_VIDEO_MHVC_TEMPORAL) nb_mhvc_temp++;
}
//Table 2-139, implied hierarchy indexes
if (nb_hevc_temp + nb_shvc + nb_shvc_temp + nb_mhvc+ nb_mhvc_temp) {
for (i=0; i<gf_list_count(pmt->program->streams); i++) {
GF_M2TS_PES *es = (GF_M2TS_PES *)gf_list_get(pmt->program->streams, i);
if ( !(es->flags & GF_M2TS_ES_IS_PES)) continue;
if (es->depends_on_pid) continue;
switch (es->stream_type) {
case GF_M2TS_VIDEO_HEVC_TEMPORAL:
es->depends_on_pid = 1;
break;
case GF_M2TS_VIDEO_SHVC:
if (!nb_hevc_temp) es->depends_on_pid = 1;
else es->depends_on_pid = 2;
break;
case GF_M2TS_VIDEO_SHVC_TEMPORAL:
es->depends_on_pid = 3;
break;
case GF_M2TS_VIDEO_MHVC:
if (!nb_hevc_temp) es->depends_on_pid = 1;
else es->depends_on_pid = 2;
break;
case GF_M2TS_VIDEO_MHVC_TEMPORAL:
if (!nb_hevc_temp) es->depends_on_pid = 2;
else es->depends_on_pid = 3;
break;
}
}
}
if (nb_es) {
u32 i;
//translate hierarchy descriptors indexes into PIDs - check whether the PMT-index rules are the same for HEVC
for (i=0; i<gf_list_count(pmt->program->streams); i++) {
GF_M2TS_PES *an_es = NULL;
GF_M2TS_PES *es = (GF_M2TS_PES *)gf_list_get(pmt->program->streams, i);
if ( !(es->flags & GF_M2TS_ES_IS_PES)) continue;
if (!es->depends_on_pid) continue;
//fixeme we are not always assured that hierarchy_layer_index matches the stream index...
//+1 is because our first stream is the PMT
an_es = (GF_M2TS_PES *)gf_list_get(pmt->program->streams, es->depends_on_pid);
if (an_es) {
es->depends_on_pid = an_es->pid;
} else {
GF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, ("[M2TS] Wrong dependency index in hierarchy descriptor, assuming non-scalable stream\n"));
es->depends_on_pid = 0;
}
}
evt_type = (status&GF_M2TS_TABLE_FOUND) ? GF_M2TS_EVT_PMT_FOUND : GF_M2TS_EVT_PMT_UPDATE;
if (ts->on_event) ts->on_event(ts, evt_type, pmt->program);
} else {
/* if we found no new ES it's simply a repeat of the PMT */
if (ts->on_event) ts->on_event(ts, GF_M2TS_EVT_PMT_REPEAT, pmt->program);
}
}
static void gf_m2ts_process_pat(GF_M2TS_Demuxer *ts, GF_M2TS_SECTION_ES *ses, GF_List *sections, u8 table_id, u16 ex_table_id, u8 version_number, u8 last_section_number, u32 status)
{
GF_M2TS_Program *prog;
GF_M2TS_SECTION_ES *pmt;
u32 i, nb_progs, evt_type;
u32 nb_sections;
u32 data_size;
unsigned char *data;
GF_M2TS_Section *section;
/*wait for the last section */
if (!(status&GF_M2TS_TABLE_END)) return;
/*skip if already received*/
if (status&GF_M2TS_TABLE_REPEAT) {
if (ts->on_event) ts->on_event(ts, GF_M2TS_EVT_PAT_REPEAT, NULL);
return;
}
nb_sections = gf_list_count(sections);
if (nb_sections > 1) {
GF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, ("PAT on multiple sections not supported\n"));
}
section = (GF_M2TS_Section *)gf_list_get(sections, 0);
data = section->data;
data_size = section->data_size;
if (!(status&GF_M2TS_TABLE_UPDATE) && gf_list_count(ts->programs)) {
if (ts->pat->demux_restarted) {
ts->pat->demux_restarted = 0;
} else {
GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("Multiple different PAT on single TS found, ignoring new PAT declaration (table id %d - extended table id %d)\n", table_id, ex_table_id));
}
return;
}
nb_progs = data_size / 4;
for (i=0; i<nb_progs; i++) {
u16 number, pid;
number = (data[0]<<8) | data[1];
pid = (data[2]&0x1f)<<8 | data[3];
data += 4;
if (number==0) {
if (!ts->nit) {
ts->nit = gf_m2ts_section_filter_new(gf_m2ts_process_nit, 0);
}
} else {
GF_SAFEALLOC(prog, GF_M2TS_Program);
if (!prog) {
GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("Fail to allocate program for pid %d\n", pid));
return;
}
prog->streams = gf_list_new();
prog->pmt_pid = pid;
prog->number = number;
prog->ts = ts;
gf_list_add(ts->programs, prog);
GF_SAFEALLOC(pmt, GF_M2TS_SECTION_ES);
if (!pmt) {
GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("Fail to allocate pmt filter for pid %d\n", pid));
return;
}
pmt->flags = GF_M2TS_ES_IS_SECTION;
gf_list_add(prog->streams, pmt);
pmt->pid = prog->pmt_pid;
pmt->program = prog;
ts->ess[pmt->pid] = (GF_M2TS_ES *)pmt;
pmt->sec = gf_m2ts_section_filter_new(gf_m2ts_process_pmt, 0);
}
}
evt_type = (status&GF_M2TS_TABLE_UPDATE) ? GF_M2TS_EVT_PAT_UPDATE : GF_M2TS_EVT_PAT_FOUND;
if (ts->on_event) ts->on_event(ts, evt_type, NULL);
}
static void gf_m2ts_process_cat(GF_M2TS_Demuxer *ts, GF_M2TS_SECTION_ES *ses, GF_List *sections, u8 table_id, u16 ex_table_id, u8 version_number, u8 last_section_number, u32 status)
{
u32 evt_type;
/*
GF_M2TS_Program *prog;
GF_M2TS_SECTION_ES *pmt;
u32 i, nb_progs;
u32 nb_sections;
u32 data_size;
unsigned char *data;
GF_M2TS_Section *section;
*/
/*wait for the last section */
if (!(status&GF_M2TS_TABLE_END)) return;
/*skip if already received*/
if (status&GF_M2TS_TABLE_REPEAT) {
if (ts->on_event) ts->on_event(ts, GF_M2TS_EVT_CAT_REPEAT, NULL);
return;
}
/*
nb_sections = gf_list_count(sections);
if (nb_sections > 1) {
GF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, ("CAT on multiple sections not supported\n"));
}
section = (GF_M2TS_Section *)gf_list_get(sections, 0);
data = section->data;
data_size = section->data_size;
nb_progs = data_size / 4;
for (i=0; i<nb_progs; i++) {
u16 number, pid;
number = (data[0]<<8) | data[1];
pid = (data[2]&0x1f)<<8 | data[3];
data += 4;
if (number==0) {
if (!ts->nit) {
ts->nit = gf_m2ts_section_filter_new(gf_m2ts_process_nit, 0);
}
} else {
GF_SAFEALLOC(prog, GF_M2TS_Program);
prog->streams = gf_list_new();
prog->pmt_pid = pid;
prog->number = number;
gf_list_add(ts->programs, prog);
GF_SAFEALLOC(pmt, GF_M2TS_SECTION_ES);
pmt->flags = GF_M2TS_ES_IS_SECTION;
gf_list_add(prog->streams, pmt);
pmt->pid = prog->pmt_pid;
pmt->program = prog;
ts->ess[pmt->pid] = (GF_M2TS_ES *)pmt;
pmt->sec = gf_m2ts_section_filter_new(gf_m2ts_process_pmt, 0);
}
}
*/
evt_type = (status&GF_M2TS_TABLE_UPDATE) ? GF_M2TS_EVT_CAT_UPDATE : GF_M2TS_EVT_CAT_FOUND;
if (ts->on_event) ts->on_event(ts, evt_type, NULL);
}
u64 gf_m2ts_get_pts(unsigned char *data)
{
u64 pts;
u32 val;
pts = (u64)((data[0] >> 1) & 0x07) << 30;
val = (data[1] << 8) | data[2];
pts |= (u64)(val >> 1) << 15;
val = (data[3] << 8) | data[4];
pts |= (u64)(val >> 1);
return pts;
}
void gf_m2ts_pes_header(GF_M2TS_PES *pes, unsigned char *data, u32 data_size, GF_M2TS_PESHeader *pesh)
{
u32 has_pts, has_dts;
u32 len_check;
memset(pesh, 0, sizeof(GF_M2TS_PESHeader));
len_check = 0;
pesh->id = data[0];
pesh->pck_len = (data[1]<<8) | data[2];
/*
2bits
scrambling_control = gf_bs_read_int(bs,2);
priority = gf_bs_read_int(bs,1);
*/
pesh->data_alignment = (data[3] & 0x4) ? 1 : 0;
/*
copyright = gf_bs_read_int(bs,1);
original = gf_bs_read_int(bs,1);
*/
has_pts = (data[4]&0x80);
has_dts = has_pts ? (data[4]&0x40) : 0;
/*
ESCR_flag = gf_bs_read_int(bs,1);
ES_rate_flag = gf_bs_read_int(bs,1);
DSM_flag = gf_bs_read_int(bs,1);
additional_copy_flag = gf_bs_read_int(bs,1);
prev_crc_flag = gf_bs_read_int(bs,1);
extension_flag = gf_bs_read_int(bs,1);
*/
pesh->hdr_data_len = data[5];
data += 6;
if (has_pts) {
pesh->PTS = gf_m2ts_get_pts(data);
data+=5;
len_check += 5;
}
if (has_dts) {
pesh->DTS = gf_m2ts_get_pts(data);
//data+=5;
len_check += 5;
} else {
pesh->DTS = pesh->PTS;
}
if (len_check < pesh->hdr_data_len) {
GF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, ("[MPEG-2 TS] PID %d Skipping %d bytes in pes header\n", pes->pid, pesh->hdr_data_len - len_check));
} else if (len_check > pesh->hdr_data_len) {
GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[MPEG-2 TS] PID %d Wrong pes_header_data_length field %d bytes - read %d\n", pes->pid, pesh->hdr_data_len, len_check));
}
if ((pesh->PTS<90000) && ((s32)pesh->DTS<0)) {
GF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, ("[MPEG-2 TS] PID %d Wrong DTS %d negative for PTS %d - forcing to 0\n", pes->pid, pesh->DTS, pesh->PTS));
pesh->DTS=0;
}
}
static void gf_m2ts_store_temi(GF_M2TS_Demuxer *ts, GF_M2TS_PES *pes)
{
GF_BitStream *bs = gf_bs_new(pes->temi_tc_desc, pes->temi_tc_desc_len, GF_BITSTREAM_READ);
u32 has_timestamp = gf_bs_read_int(bs, 2);
Bool has_ntp = (Bool) gf_bs_read_int(bs, 1);
/*u32 has_ptp = */gf_bs_read_int(bs, 1);
/*u32 has_timecode = */gf_bs_read_int(bs, 2);
memset(&pes->temi_tc, 0, sizeof(GF_M2TS_TemiTimecodeDescriptor));
pes->temi_tc.force_reload = gf_bs_read_int(bs, 1);
pes->temi_tc.is_paused = gf_bs_read_int(bs, 1);
pes->temi_tc.is_discontinuity = gf_bs_read_int(bs, 1);
gf_bs_read_int(bs, 7);
pes->temi_tc.timeline_id = gf_bs_read_int(bs, 8);
if (has_timestamp) {
pes->temi_tc.media_timescale = gf_bs_read_u32(bs);
if (has_timestamp==2)
pes->temi_tc.media_timestamp = gf_bs_read_u64(bs);
else
pes->temi_tc.media_timestamp = gf_bs_read_u32(bs);
}
if (has_ntp) {
pes->temi_tc.ntp = gf_bs_read_u64(bs);
}
gf_bs_del(bs);
pes->temi_tc_desc_len = 0;
pes->temi_pending = 1;
}
void gf_m2ts_flush_pes(GF_M2TS_Demuxer *ts, GF_M2TS_PES *pes)
{
GF_M2TS_PESHeader pesh;
if (!ts) return;
/*we need at least a full, valid start code and PES header !!*/
if ((pes->pck_data_len >= 4) && !pes->pck_data[0] && !pes->pck_data[1] && (pes->pck_data[2] == 0x1)) {
u32 len;
Bool has_pes_header = GF_TRUE;
u32 stream_id = pes->pck_data[3];
Bool same_pts = GF_FALSE;
switch (stream_id) {
case GF_M2_STREAMID_PROGRAM_STREAM_MAP:
case GF_M2_STREAMID_PADDING:
case GF_M2_STREAMID_PRIVATE_2:
case GF_M2_STREAMID_ECM:
case GF_M2_STREAMID_EMM:
case GF_M2_STREAMID_PROGRAM_STREAM_DIRECTORY:
case GF_M2_STREAMID_DSMCC:
case GF_M2_STREAMID_H222_TYPE_E:
has_pes_header = GF_FALSE;
break;
}
if (has_pes_header) {
/*OK read header*/
gf_m2ts_pes_header(pes, pes->pck_data + 3, pes->pck_data_len - 3, &pesh);
/*send PES timing*/
if (ts->notify_pes_timing) {
GF_M2TS_PES_PCK pck;
memset(&pck, 0, sizeof(GF_M2TS_PES_PCK));
pck.PTS = pesh.PTS;
pck.DTS = pesh.DTS;
pck.stream = pes;
if (pes->rap) pck.flags |= GF_M2TS_PES_PCK_RAP;
pes->pes_end_packet_number = ts->pck_number;
if (ts->on_event) ts->on_event(ts, GF_M2TS_EVT_PES_TIMING, &pck);
}
GF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, ("[MPEG-2 TS] PID %d Got PES header DTS %d PTS %d\n", pes->pid, pesh.DTS, pesh.PTS));
if (pesh.PTS) {
if (pesh.PTS == pes->PTS) {
same_pts = GF_TRUE;
GF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, ("[MPEG-2 TS] PID %d - same PTS "LLU" for two consecutive PES packets \n", pes->pid, pes->PTS));
}
#ifndef GPAC_DISABLE_LOG
/*FIXME - this test should only be done for non bi-directionnally coded media
else if (pesh.PTS < pes->PTS) {
GF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, ("[MPEG-2 TS] PID %d - PTS "LLU" less than previous packet PTS "LLU"\n", pes->pid, pesh.PTS, pes->PTS) );
}
*/
#endif
pes->PTS = pesh.PTS;
#ifndef GPAC_DISABLE_LOG
{
if (pes->DTS && (pesh.DTS == pes->DTS)) {
GF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, ("[MPEG-2 TS] PID %d - same DTS "LLU" for two consecutive PES packets \n", pes->pid, pes->DTS));
}
if (pesh.DTS < pes->DTS) {
GF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, ("[MPEG-2 TS] PID %d - DTS "LLU" less than previous DTS "LLU"\n", pes->pid, pesh.DTS, pes->DTS));
}
}
#endif
pes->DTS = pesh.DTS;
}
/*no PTSs were coded, same time*/
else if (!pesh.hdr_data_len) {
same_pts = GF_TRUE;
}
/*3-byte start-code + 6 bytes header + hdr extensions*/
len = 9 + pesh.hdr_data_len;
} else {
/*3-byte start-code + 1 byte streamid*/
len = 4;
memset(&pesh, 0, sizeof(pesh));
}
if ((u8) pes->pck_data[3]==0xfa) {
GF_M2TS_SL_PCK sl_pck;
GF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, ("[MPEG-2 TS] SL Packet in PES for %d - ES ID %d\n", pes->pid, pes->mpeg4_es_id));
if (pes->pck_data_len > len) {
sl_pck.data = (char *)pes->pck_data + len;
sl_pck.data_len = pes->pck_data_len - len;
sl_pck.stream = (GF_M2TS_ES *)pes;
if (ts->on_event) ts->on_event(ts, GF_M2TS_EVT_SL_PCK, &sl_pck);
} else {
GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[MPEG-2 TS] Bad SL Packet size: (%d indicated < %d header)\n", pes->pid, pes->pck_data_len, len));
}
} else if (pes->reframe) {
u32 remain = 0;
u32 offset = len;
if (pesh.pck_len && (pesh.pck_len-3-pesh.hdr_data_len != pes->pck_data_len-len)) {
GF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, ("[MPEG-2 TS] PID %d PES payload size %d but received %d bytes\n", pes->pid, (u32) ( pesh.pck_len-3-pesh.hdr_data_len), pes->pck_data_len-len));
}
//copy over the remaining of previous PES payload before start of this PES payload
if (pes->prev_data_len) {
if (pes->prev_data_len < len) {
offset = len - pes->prev_data_len;
memcpy(pes->pck_data + offset, pes->prev_data, pes->prev_data_len);
} else {
GF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, ("[MPEG-2 TS] PID %d PES reassembly buffer overflow (%d bytes not processed from previous PES) - discarding prev data\n", pes->pid, pes->prev_data_len ));
}
}
if (!pes->temi_pending && pes->temi_tc_desc_len) {
gf_m2ts_store_temi(ts, pes);
}
if (pes->temi_pending) {
pes->temi_pending = 0;
pes->temi_tc.pes_pts = pes->PTS;
if (ts->on_event)
ts->on_event(ts, GF_M2TS_EVT_TEMI_TIMECODE, &pes->temi_tc);
}
if (! ts->seek_mode)
remain = pes->reframe(ts, pes, same_pts, pes->pck_data+offset, pes->pck_data_len-offset, &pesh);
//CLEANUP alloc stuff
if (pes->prev_data) gf_free(pes->prev_data);
pes->prev_data = NULL;
pes->prev_data_len = 0;
if (remain) {
pes->prev_data = gf_malloc(sizeof(char)*remain);
assert(pes->pck_data_len >= remain);
memcpy(pes->prev_data, pes->pck_data + pes->pck_data_len - remain, remain);
pes->prev_data_len = remain;
}
}
} else if (pes->pck_data_len) {
GF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, ("[MPEG-2 TS] PES %d: Bad PES Header, discarding packet (maybe stream is encrypted ?)\n", pes->pid));
}
pes->pck_data_len = 0;
pes->pes_len = 0;
pes->rap = 0;
}
static void gf_m2ts_process_pes(GF_M2TS_Demuxer *ts, GF_M2TS_PES *pes, GF_M2TS_Header *hdr, unsigned char *data, u32 data_size, GF_M2TS_AdaptationField *paf)
{
u8 expect_cc;
Bool disc=0;
Bool flush_pes = 0;
/*duplicated packet, NOT A DISCONTINUITY, we should discard the packet - however we may encounter this configuration in DASH at segment boundaries.
If payload start is set, ignore duplication*/
if (hdr->continuity_counter==pes->cc) {
if (!hdr->payload_start || (hdr->adaptation_field!=3) ) {
GF_LOG(GF_LOG_INFO, GF_LOG_CONTAINER, ("[MPEG-2 TS] PES %d: Duplicated Packet found (CC %d) - skipping\n", pes->pid, pes->cc));
return;
}
} else {
expect_cc = (pes->cc<0) ? hdr->continuity_counter : (pes->cc + 1) & 0xf;
if (expect_cc != hdr->continuity_counter)
disc = 1;
}
pes->cc = hdr->continuity_counter;
if (disc) {
if (pes->flags & GF_M2TS_ES_IGNORE_NEXT_DISCONTINUITY) {
pes->flags &= ~GF_M2TS_ES_IGNORE_NEXT_DISCONTINUITY;
disc = 0;
}
if (disc) {
if (hdr->payload_start) {
if (pes->pck_data_len) {
GF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, ("[MPEG-2 TS] PES %d: Packet discontinuity (%d expected - got %d) - may have lost end of previous PES\n", pes->pid, expect_cc, hdr->continuity_counter));
}
} else {
if (pes->pck_data_len) {
GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[MPEG-2 TS] PES %d: Packet discontinuity (%d expected - got %d) - trashing PES packet\n", pes->pid, expect_cc, hdr->continuity_counter));
}
pes->pck_data_len = 0;
pes->pes_len = 0;
pes->cc = -1;
return;
}
}
}
if (!pes->reframe) return;
if (hdr->payload_start) {
flush_pes = 1;
pes->pes_start_packet_number = ts->pck_number;
pes->before_last_pcr_value = pes->program->before_last_pcr_value;
pes->before_last_pcr_value_pck_number = pes->program->before_last_pcr_value_pck_number;
pes->last_pcr_value = pes->program->last_pcr_value;
pes->last_pcr_value_pck_number = pes->program->last_pcr_value_pck_number;
} else if (pes->pes_len && (pes->pck_data_len + data_size == pes->pes_len + 6)) {
/* 6 = startcode+stream_id+length*/
/*reassemble pes*/
if (pes->pck_data_len + data_size > pes->pck_alloc_len) {
pes->pck_alloc_len = pes->pck_data_len + data_size;
pes->pck_data = (u8*)gf_realloc(pes->pck_data, pes->pck_alloc_len);
}
memcpy(pes->pck_data+pes->pck_data_len, data, data_size);
pes->pck_data_len += data_size;
/*force discard*/
data_size = 0;
flush_pes = 1;
}
/*PES first fragment: flush previous packet*/
if (flush_pes && pes->pck_data_len) {
gf_m2ts_flush_pes(ts, pes);
if (!data_size) return;
}
/*we need to wait for first packet of PES*/
if (!pes->pck_data_len && !hdr->payload_start) {
GF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, ("[MPEG-2 TS] PID %d: Waiting for PES header, trashing data\n", hdr->pid));
return;
}
/*reassemble*/
if (pes->pck_data_len + data_size > pes->pck_alloc_len ) {
pes->pck_alloc_len = pes->pck_data_len + data_size;
pes->pck_data = (u8*)gf_realloc(pes->pck_data, pes->pck_alloc_len);
}
memcpy(pes->pck_data + pes->pck_data_len, data, data_size);
pes->pck_data_len += data_size;
if (paf && paf->random_access_indicator) pes->rap = 1;
if (hdr->payload_start && !pes->pes_len && (pes->pck_data_len>=6)) {
pes->pes_len = (pes->pck_data[4]<<8) | pes->pck_data[5];
GF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, ("[MPEG-2 TS] PID %d: Got PES packet len %d\n", pes->pid, pes->pes_len));
if (pes->pes_len + 6 == pes->pck_data_len) {
gf_m2ts_flush_pes(ts, pes);
}
}
}
static void gf_m2ts_get_adaptation_field(GF_M2TS_Demuxer *ts, GF_M2TS_AdaptationField *paf, unsigned char *data, u32 size, u32 pid)
{
unsigned char *af_extension;
paf->discontinuity_indicator = (data[0] & 0x80) ? 1 : 0;
paf->random_access_indicator = (data[0] & 0x40) ? 1 : 0;
paf->priority_indicator = (data[0] & 0x20) ? 1 : 0;
paf->PCR_flag = (data[0] & 0x10) ? 1 : 0;
paf->OPCR_flag = (data[0] & 0x8) ? 1 : 0;
paf->splicing_point_flag = (data[0] & 0x4) ? 1 : 0;
paf->transport_private_data_flag = (data[0] & 0x2) ? 1 : 0;
paf->adaptation_field_extension_flag = (data[0] & 0x1) ? 1 : 0;
af_extension = data + 1;
if (paf->PCR_flag == 1) {
u32 base = ((u32)data[1] << 24) | ((u32)data[2] << 16) | ((u32)data[3] << 8) | (u32)data[4];
u64 PCR = (u64) base;
paf->PCR_base = (PCR << 1) | (data[5] >> 7);
paf->PCR_ext = ((data[5] & 1) << 8) | data[6];
af_extension += 6;
}
if (paf->adaptation_field_extension_flag) {
u32 afext_bytes;
Bool ltw_flag, pwr_flag, seamless_flag, af_desc_not_present;
if (paf->OPCR_flag) {
af_extension += 6;
}
if (paf->splicing_point_flag) {
af_extension += 1;
}
if (paf->transport_private_data_flag) {
u32 priv_bytes = af_extension[0];
af_extension += 1 + priv_bytes;
}
afext_bytes = af_extension[0];
ltw_flag = af_extension[1] & 0x80 ? 1 : 0;
pwr_flag = af_extension[1] & 0x40 ? 1 : 0;
seamless_flag = af_extension[1] & 0x20 ? 1 : 0;
af_desc_not_present = af_extension[1] & 0x10 ? 1 : 0;
af_extension += 2;
if (!afext_bytes) {
GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[MPEG-2 TS] PID %d: Bad Adaptation Extension found\n", pid));
return;
}
afext_bytes-=1;
if (ltw_flag) {
af_extension += 2;
if (afext_bytes<2) {
GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[MPEG-2 TS] PID %d: Bad Adaptation Extension found\n", pid));
return;
}
afext_bytes-=2;
}
if (pwr_flag) {
af_extension += 3;
if (afext_bytes<3) {
GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[MPEG-2 TS] PID %d: Bad Adaptation Extension found\n", pid));
return;
}
afext_bytes-=3;
}
if (seamless_flag) {
af_extension += 3;
if (afext_bytes<3) {
GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[MPEG-2 TS] PID %d: Bad Adaptation Extension found\n", pid));
return;
}
afext_bytes-=3;
}
if (! af_desc_not_present) {
while (afext_bytes) {
GF_BitStream *bs;
char *desc;
u8 desc_tag = af_extension[0];
u8 desc_len = af_extension[1];
if (!desc_len || (u32) desc_len+2 > afext_bytes) {
GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[MPEG-2 TS] PID %d: Bad Adaptation Descriptor found (tag %d) size is %d but only %d bytes available\n", pid, desc_tag, desc_len, afext_bytes));
break;
}
desc = (char *) af_extension+2;
bs = gf_bs_new(desc, desc_len, GF_BITSTREAM_READ);
switch (desc_tag) {
case GF_M2TS_AFDESC_LOCATION_DESCRIPTOR:
{
Bool use_base_temi_url;
char URL[255];
GF_M2TS_TemiLocationDescriptor temi_loc;
memset(&temi_loc, 0, sizeof(GF_M2TS_TemiLocationDescriptor) );
temi_loc.reload_external = gf_bs_read_int(bs, 1);
temi_loc.is_announce = gf_bs_read_int(bs, 1);
temi_loc.is_splicing = gf_bs_read_int(bs, 1);
use_base_temi_url = gf_bs_read_int(bs, 1);
gf_bs_read_int(bs, 5); //reserved
temi_loc.timeline_id = gf_bs_read_int(bs, 7);
if (!use_base_temi_url) {
char *_url = URL;
u8 scheme = gf_bs_read_int(bs, 8);
u8 url_len = gf_bs_read_int(bs, 8);
switch (scheme) {
case 1:
strcpy(URL, "http://");
_url = URL+7;
break;
case 2:
strcpy(URL, "https://");
_url = URL+8;
break;
}
gf_bs_read_data(bs, _url, url_len);
_url[url_len] = 0;
}
temi_loc.external_URL = URL;
GF_LOG(GF_LOG_INFO, GF_LOG_CONTAINER, ("[MPEG-2 TS] PID %d AF Location descriptor found - URL %s\n", pid, URL));
if (ts->on_event) ts->on_event(ts, GF_M2TS_EVT_TEMI_LOCATION, &temi_loc);
}
break;
case GF_M2TS_AFDESC_TIMELINE_DESCRIPTOR:
if (ts->ess[pid] && (ts->ess[pid]->flags & GF_M2TS_ES_IS_PES)) {
GF_M2TS_PES *pes = (GF_M2TS_PES *) ts->ess[pid];
if (pes->temi_tc_desc_len)
gf_m2ts_store_temi(ts, pes);
if (pes->temi_tc_desc_alloc_size < desc_len) {
pes->temi_tc_desc = gf_realloc(pes->temi_tc_desc, desc_len);
pes->temi_tc_desc_alloc_size = desc_len;
}
memcpy(pes->temi_tc_desc, desc, desc_len);
pes->temi_tc_desc_len = desc_len;
GF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, ("[MPEG-2 TS] PID %d AF Timeline descriptor found\n", pid));
}
break;
}
gf_bs_del(bs);
af_extension += 2+desc_len;
afext_bytes -= 2+desc_len;
}
}
}
GF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, ("[MPEG-2 TS] PID %d: Adaptation Field found: Discontinuity %d - RAP %d - PCR: "LLD"\n", pid, paf->discontinuity_indicator, paf->random_access_indicator, paf->PCR_flag ? paf->PCR_base * 300 + paf->PCR_ext : 0));
}
static GF_Err gf_m2ts_process_packet(GF_M2TS_Demuxer *ts, unsigned char *data)
{
GF_M2TS_ES *es;
GF_M2TS_Header hdr;
GF_M2TS_AdaptationField af, *paf;
u32 payload_size, af_size;
u32 pos = 0;
ts->pck_number++;
/* read TS packet header*/
hdr.sync = data[0];
if (hdr.sync != 0x47) {
GF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, ("[MPEG-2 TS] TS Packet %d does not start with sync marker\n", ts->pck_number));
return GF_CORRUPTED_DATA;
}
hdr.error = (data[1] & 0x80) ? 1 : 0;
hdr.payload_start = (data[1] & 0x40) ? 1 : 0;
hdr.priority = (data[1] & 0x20) ? 1 : 0;
hdr.pid = ( (data[1]&0x1f) << 8) | data[2];
hdr.scrambling_ctrl = (data[3] >> 6) & 0x3;
hdr.adaptation_field = (data[3] >> 4) & 0x3;
hdr.continuity_counter = data[3] & 0xf;
if (hdr.error) {
GF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, ("[MPEG-2 TS] TS Packet %d has error (PID could be %d)\n", ts->pck_number, hdr.pid));
return GF_CORRUPTED_DATA;
}
//#if DEBUG_TS_PACKET
GF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, ("[MPEG-2 TS] TS Packet %d PID %d CC %d Encrypted %d\n", ts->pck_number, hdr.pid, hdr.continuity_counter, hdr.scrambling_ctrl));
//#endif
if (hdr.scrambling_ctrl) {
//TODO add decyphering
GF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, ("[MPEG-2 TS] TS Packet %d is scrambled - not supported\n", ts->pck_number, hdr.pid));
return GF_NOT_SUPPORTED;
}
paf = NULL;
payload_size = 184;
pos = 4;
switch (hdr.adaptation_field) {
/*adaptation+data*/
case 3:
af_size = data[4];
if (af_size>183) {
GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[MPEG-2 TS] TS Packet %d AF field larger than 183 !\n", ts->pck_number));
//error
return GF_CORRUPTED_DATA;
}
paf = ⁡
memset(paf, 0, sizeof(GF_M2TS_AdaptationField));
//this will stop you when processing invalid (yet existing) mpeg2ts streams in debug
assert( af_size<=183);
if (af_size>183)
GF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, ("[MPEG-2 TS] TS Packet %d Detected wrong adaption field size %u when control value is 3\n", ts->pck_number, af_size));
if (af_size) gf_m2ts_get_adaptation_field(ts, paf, data+5, af_size, hdr.pid);
pos += 1+af_size;
payload_size = 183 - af_size;
break;
/*adaptation only - still process in case of PCR*/
case 2:
af_size = data[4];
if (af_size != 183) {
GF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, ("[MPEG-2 TS] TS Packet %d AF size is %d when it must be 183 for AF type 2\n", ts->pck_number, af_size));
return GF_CORRUPTED_DATA;
}
paf = ⁡
memset(paf, 0, sizeof(GF_M2TS_AdaptationField));
gf_m2ts_get_adaptation_field(ts, paf, data+5, af_size, hdr.pid);
payload_size = 0;
/*no payload and no PCR, return*/
if (!paf->PCR_flag)
return GF_OK;
break;
/*reserved*/
case 0:
return GF_OK;
default:
break;
}
data += pos;
/*PAT*/
if (hdr.pid == GF_M2TS_PID_PAT) {
gf_m2ts_gather_section(ts, ts->pat, NULL, &hdr, data, payload_size);
return GF_OK;
} else if (hdr.pid == GF_M2TS_PID_CAT) {
gf_m2ts_gather_section(ts, ts->cat, NULL, &hdr, data, payload_size);
return GF_OK;
}
es = ts->ess[hdr.pid];
if (paf && paf->PCR_flag) {
if (!es) {
u32 i, j;
for(i=0; i<gf_list_count(ts->programs); i++) {
GF_M2TS_PES *first_pes = NULL;
GF_M2TS_Program *program = (GF_M2TS_Program *)gf_list_get(ts->programs,i);
if(program->pcr_pid != hdr.pid) continue;
for (j=0; j<gf_list_count(program->streams); j++) {
GF_M2TS_PES *pes = (GF_M2TS_PES *) gf_list_get(program->streams, j);
if (pes->flags & GF_M2TS_INHERIT_PCR) {
ts->ess[hdr.pid] = (GF_M2TS_ES *) pes;
pes->flags |= GF_M2TS_FAKE_PCR;
break;
}
if (pes->flags & GF_M2TS_ES_IS_PES) {
first_pes = pes;
}
}
//non found, use the first media stream as a PCR destination - Q: is it legal to have PCR only streams not declared in PMT ?
if (!es && first_pes) {
es = (GF_M2TS_ES *) first_pes;
first_pes->flags |= GF_M2TS_FAKE_PCR;
}
break;
}
if (!es)
es = ts->ess[hdr.pid];
}
if (es) {
GF_M2TS_PES_PCK pck;
s64 prev_diff_in_us;
Bool discontinuity;
s32 cc = -1;
if (es->flags & GF_M2TS_FAKE_PCR) {
cc = es->program->pcr_cc;
es->program->pcr_cc = hdr.continuity_counter;
}
else if (es->flags & GF_M2TS_ES_IS_PES) cc = ((GF_M2TS_PES*)es)->cc;
else if (((GF_M2TS_SECTION_ES*)es)->sec) cc = ((GF_M2TS_SECTION_ES*)es)->sec->cc;
discontinuity = paf->discontinuity_indicator;
if ((cc>=0) && es->program->before_last_pcr_value) {
//no increment of CC if AF only packet
if (hdr.adaptation_field == 2) {
if (hdr.continuity_counter != cc) {
discontinuity = GF_TRUE;
}
} else if (hdr.continuity_counter != ((cc + 1) & 0xF)) {
discontinuity = GF_TRUE;
}
}
memset(&pck, 0, sizeof(GF_M2TS_PES_PCK));
prev_diff_in_us = (s64) (es->program->last_pcr_value /27- es->program->before_last_pcr_value/27);
es->program->before_last_pcr_value = es->program->last_pcr_value;
es->program->before_last_pcr_value_pck_number = es->program->last_pcr_value_pck_number;
es->program->last_pcr_value_pck_number = ts->pck_number;
es->program->last_pcr_value = paf->PCR_base * 300 + paf->PCR_ext;
if (!es->program->last_pcr_value) es->program->last_pcr_value = 1;
GF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, ("[MPEG-2 TS] PID %d PCR found "LLU" ("LLU" at 90kHz) - PCR diff is %d us\n", hdr.pid, es->program->last_pcr_value, es->program->last_pcr_value/300, (s32) (es->program->last_pcr_value - es->program->before_last_pcr_value)/27 ));
pck.PTS = es->program->last_pcr_value;
pck.stream = (GF_M2TS_PES *)es;
//try to ignore all discontinuities that are less than 200 ms (seen in some HLS setup ...)
if (discontinuity) {
s64 diff_in_us = (s64) (es->program->last_pcr_value - es->program->before_last_pcr_value) / 27;
u64 diff = ABS(diff_in_us - prev_diff_in_us);
if ((diff_in_us<0) && (diff_in_us >= -200000)) {
GF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, ("[MPEG-2 TS] PID %d new PCR, with discontinuity signaled, is less than previously received PCR (diff %d us) but not too large, trying to ignore discontinuity\n", hdr.pid, diff_in_us));
}
//ignore PCR discontinuity indicator if PCR found is larger than previously received PCR and diffence between PCR before and after discontinuity indicator is smaller than 50ms
else if ((diff_in_us > 0) && (diff < 200000)) {
GF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, ("[MPEG-2 TS] PID %d PCR discontinuity signaled but diff is small (diff %d us - PCR diff %d vs prev PCR diff %d) - ignore it\n", hdr.pid, diff, diff_in_us, prev_diff_in_us));
} else if (paf->discontinuity_indicator) {
GF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, ("[MPEG-2 TS] PID %d PCR discontinuity signaled (diff %d us - PCR diff %d vs prev PCR diff %d)\n", hdr.pid, diff, diff_in_us, prev_diff_in_us));
pck.flags = GF_M2TS_PES_PCK_DISCONTINUITY;
} else {
GF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, ("[MPEG-2 TS] PID %d PCR discontinuity not signaled (diff %d us - PCR diff %d vs prev PCR diff %d)\n", hdr.pid, diff, diff_in_us, prev_diff_in_us));
pck.flags = GF_M2TS_PES_PCK_DISCONTINUITY;
}
}
else if ( (es->program->last_pcr_value < es->program->before_last_pcr_value) ) {
s64 diff_in_us = (s64) (es->program->last_pcr_value - es->program->before_last_pcr_value) / 27;
//if less than 200 ms before PCR loop at the last PCR, this is a PCR loop
if (GF_M2TS_MAX_PCR - es->program->before_last_pcr_value < 5400000 /*2*2700000*/) {
GF_LOG(GF_LOG_INFO, GF_LOG_CONTAINER, ("[MPEG-2 TS] PID %d PCR loop found from "LLU" to "LLU" \n", hdr.pid, es->program->before_last_pcr_value, es->program->last_pcr_value));
} else if ((diff_in_us<0) && (diff_in_us >= -200000)) {
GF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, ("[MPEG-2 TS] PID %d new PCR, without discontinuity signaled, is less than previously received PCR (diff %d us) but not too large, trying to ignore discontinuity\n", hdr.pid, diff_in_us));
} else {
GF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, ("[MPEG-2 TS] PID %d PCR found "LLU" is less than previously received PCR "LLU" (PCR diff %g sec) but no discontinuity signaled\n", hdr.pid, es->program->last_pcr_value, es->program->before_last_pcr_value, (GF_M2TS_MAX_PCR - es->program->before_last_pcr_value + es->program->last_pcr_value) / 27000000.0));
pck.flags = GF_M2TS_PES_PCK_DISCONTINUITY;
}
}
if (pck.flags & GF_M2TS_PES_PCK_DISCONTINUITY) {
gf_m2ts_reset_parsers_for_program(ts, es->program);
}
if (ts->on_event) {
ts->on_event(ts, GF_M2TS_EVT_PES_PCR, &pck);
}
}
}
/*check for DVB reserved PIDs*/
if (!es) {
if (hdr.pid == GF_M2TS_PID_SDT_BAT_ST) {
gf_m2ts_gather_section(ts, ts->sdt, NULL, &hdr, data, payload_size);
return GF_OK;
} else if (hdr.pid == GF_M2TS_PID_NIT_ST) {
/*ignore them, unused at application level*/
gf_m2ts_gather_section(ts, ts->nit, NULL, &hdr, data, payload_size);
return GF_OK;
} else if (hdr.pid == GF_M2TS_PID_EIT_ST_CIT) {
/* ignore EIT messages for the moment */
gf_m2ts_gather_section(ts, ts->eit, NULL, &hdr, data, payload_size);
return GF_OK;
} else if (hdr.pid == GF_M2TS_PID_TDT_TOT_ST) {
gf_m2ts_gather_section(ts, ts->tdt_tot, NULL, &hdr, data, payload_size);
} else {
/* ignore packet */
}
} else if (es->flags & GF_M2TS_ES_IS_SECTION) { /* The stream uses sections to carry its payload */
GF_M2TS_SECTION_ES *ses = (GF_M2TS_SECTION_ES *)es;
if (ses->sec) gf_m2ts_gather_section(ts, ses->sec, ses, &hdr, data, payload_size);
} else {
GF_M2TS_PES *pes = (GF_M2TS_PES *)es;
/* regular stream using PES packets */
if (pes->reframe && payload_size) gf_m2ts_process_pes(ts, pes, &hdr, data, payload_size, paf);
}
return GF_OK;
}
GF_EXPORT
GF_Err gf_m2ts_process_data(GF_M2TS_Demuxer *ts, u8 *data, u32 data_size)
{
GF_Err e=GF_OK;
u32 pos, pck_size;
Bool is_align = 1;
if (ts->buffer_size) {
//we are sync, copy remaining bytes
if ( (ts->buffer[0]==0x47) && (ts->buffer_size<200)) {
u32 pck_size = ts->prefix_present ? 192 : 188;
if (ts->alloc_size < 200) {
ts->alloc_size = 200;
ts->buffer = (char*)gf_realloc(ts->buffer, sizeof(char)*ts->alloc_size);
}
memcpy(ts->buffer + ts->buffer_size, data, pck_size - ts->buffer_size);
e |= gf_m2ts_process_packet(ts, (unsigned char *)ts->buffer);
data += (pck_size - ts->buffer_size);
data_size = data_size - (pck_size - ts->buffer_size);
}
//not sync, copy over the complete buffer
else {
if (ts->alloc_size < ts->buffer_size+data_size) {
ts->alloc_size = ts->buffer_size+data_size;
ts->buffer = (char*)gf_realloc(ts->buffer, sizeof(char)*ts->alloc_size);
}
memcpy(ts->buffer + ts->buffer_size, data, sizeof(char)*data_size);
ts->buffer_size += data_size;
is_align = 0;
data = ts->buffer;
data_size = ts->buffer_size;
}
}
/*sync input data*/
pos = gf_m2ts_sync(ts, data, data_size, is_align);
if (pos==data_size) {
if (is_align) {
if (ts->alloc_size<data_size) {
ts->buffer = (char*)gf_realloc(ts->buffer, sizeof(char)*data_size);
ts->alloc_size = data_size;
}
memcpy(ts->buffer, data, sizeof(char)*data_size);
ts->buffer_size = data_size;
}
return GF_OK;
}
pck_size = ts->prefix_present ? 192 : 188;
for (;;) {
/*wait for a complete packet*/
if (data_size < pos + pck_size) {
ts->buffer_size = data_size - pos;
data += pos;
if (!ts->buffer_size) {
return e;
}
assert(ts->buffer_size<pck_size);
if (is_align) {
u32 s = ts->buffer_size;
if (s<200) s = 200;
if (ts->alloc_size < s) {
ts->alloc_size = s;
ts->buffer = (char*)gf_realloc(ts->buffer, sizeof(char)*ts->alloc_size);
}
memcpy(ts->buffer, data, sizeof(char)*ts->buffer_size);
} else {
memmove(ts->buffer, data, sizeof(char)*ts->buffer_size);
}
return e;
}
/*process*/
e |= gf_m2ts_process_packet(ts, (unsigned char *)data + pos);
pos += pck_size;
}
return e;
}
//unused
#if 0
GF_ESD *gf_m2ts_get_esd(GF_M2TS_ES *es)
{
GF_ESD *esd;
u32 k, esd_count;
esd = NULL;
if (es->program->pmt_iod && es->program->pmt_iod->ESDescriptors) {
esd_count = gf_list_count(es->program->pmt_iod->ESDescriptors);
for (k = 0; k < esd_count; k++) {
GF_ESD *esd_tmp = (GF_ESD *)gf_list_get(es->program->pmt_iod->ESDescriptors, k);
if (esd_tmp->ESID != es->mpeg4_es_id) continue;
esd = esd_tmp;
break;
}
}
if (!esd && es->program->additional_ods) {
u32 od_count, od_index;
od_count = gf_list_count(es->program->additional_ods);
for (od_index = 0; od_index < od_count; od_index++) {
GF_ObjectDescriptor *od = (GF_ObjectDescriptor *)gf_list_get(es->program->additional_ods, od_index);
esd_count = gf_list_count(od->ESDescriptors);
for (k = 0; k < esd_count; k++) {
GF_ESD *esd_tmp = (GF_ESD *)gf_list_get(od->ESDescriptors, k);
if (esd_tmp->ESID != es->mpeg4_es_id) continue;
esd = esd_tmp;
break;
}
}
}
return esd;
}
void gf_m2ts_set_segment_switch(GF_M2TS_Demuxer *ts)
{
u32 i;
for (i=0; i<GF_M2TS_MAX_STREAMS; i++) {
GF_M2TS_ES *es = (GF_M2TS_ES *) ts->ess[i];
if (!es) continue;
es->flags |= GF_M2TS_ES_IGNORE_NEXT_DISCONTINUITY;
}
}
#endif
GF_EXPORT
void gf_m2ts_reset_parsers_for_program(GF_M2TS_Demuxer *ts, GF_M2TS_Program *prog)
{
u32 i;
for (i=0; i<GF_M2TS_MAX_STREAMS; i++) {
GF_M2TS_ES *es = (GF_M2TS_ES *) ts->ess[i];
if (!es) continue;
if (prog && (es->program != prog) ) continue;
if (es->flags & GF_M2TS_ES_IS_SECTION) {
GF_M2TS_SECTION_ES *ses = (GF_M2TS_SECTION_ES *)es;
gf_m2ts_section_filter_reset(ses->sec);
} else {
GF_M2TS_PES *pes = (GF_M2TS_PES *)es;
if (!pes || (pes->pid==pes->program->pmt_pid)) continue;
pes->cc = -1;
pes->frame_state = 0;
pes->pck_data_len = 0;
if (pes->prev_data) gf_free(pes->prev_data);
pes->prev_data = NULL;
pes->prev_data_len = 0;
pes->PTS = pes->DTS = 0;
// pes->prev_PTS = 0;
// pes->first_dts = 0;
pes->pes_len = pes->pes_end_packet_number = pes->pes_start_packet_number = 0;
if (pes->buf) gf_free(pes->buf);
pes->buf = NULL;
if (pes->temi_tc_desc) gf_free(pes->temi_tc_desc);
pes->temi_tc_desc = NULL;
pes->temi_tc_desc_len = pes->temi_tc_desc_alloc_size = 0;
pes->before_last_pcr_value = pes->before_last_pcr_value_pck_number = 0;
pes->last_pcr_value = pes->last_pcr_value_pck_number = 0;
if (pes->program->pcr_pid==pes->pid) {
pes->program->last_pcr_value = pes->program->last_pcr_value_pck_number = 0;
pes->program->before_last_pcr_value = pes->program->before_last_pcr_value_pck_number = 0;
}
}
}
}
GF_EXPORT
void gf_m2ts_reset_parsers(GF_M2TS_Demuxer *ts)
{
gf_m2ts_reset_parsers_for_program(ts, NULL);
ts->pck_number = 0;
gf_m2ts_section_filter_reset(ts->cat);
gf_m2ts_section_filter_reset(ts->pat);
gf_m2ts_section_filter_reset(ts->sdt);
gf_m2ts_section_filter_reset(ts->nit);
gf_m2ts_section_filter_reset(ts->eit);
gf_m2ts_section_filter_reset(ts->tdt_tot);
}
#if 0 //unused
u32 gf_m2ts_pes_get_framing_mode(GF_M2TS_PES *pes)
{
if (pes->flags & GF_M2TS_ES_IS_SECTION) {
if (pes->flags & GF_M2TS_ES_IS_SL) {
if ( ((GF_M2TS_SECTION_ES *)pes)->sec->process_section == NULL)
return GF_M2TS_PES_FRAMING_DEFAULT;
}
return GF_M2TS_PES_FRAMING_SKIP_NO_RESET;
}
if (!pes->reframe ) return GF_M2TS_PES_FRAMING_SKIP_NO_RESET;
if (pes->reframe == gf_m2ts_reframe_default) return GF_M2TS_PES_FRAMING_RAW;
if (pes->reframe == gf_m2ts_reframe_reset) return GF_M2TS_PES_FRAMING_SKIP;
return GF_M2TS_PES_FRAMING_DEFAULT;
}
#endif
GF_EXPORT
GF_Err gf_m2ts_set_pes_framing(GF_M2TS_PES *pes, u32 mode)
{
if (!pes) return GF_BAD_PARAM;
GF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, ("[MPEG-2 TS] Setting pes framing mode of PID %d to %d\n", pes->pid, mode) );
/*ignore request for section PIDs*/
if (pes->flags & GF_M2TS_ES_IS_SECTION) {
if (pes->flags & GF_M2TS_ES_IS_SL) {
if (mode==GF_M2TS_PES_FRAMING_DEFAULT) {
((GF_M2TS_SECTION_ES *)pes)->sec->process_section = gf_m2ts_process_mpeg4section;
} else {
((GF_M2TS_SECTION_ES *)pes)->sec->process_section = NULL;
}
}
return GF_OK;
}
if (pes->pid==pes->program->pmt_pid) return GF_BAD_PARAM;
//if component reuse, disable previous pes
if ((mode > GF_M2TS_PES_FRAMING_SKIP) && (pes->program->ts->ess[pes->pid] != (GF_M2TS_ES *) pes)) {
GF_M2TS_PES *o_pes = (GF_M2TS_PES *) pes->program->ts->ess[pes->pid];
if (o_pes->flags & GF_M2TS_ES_IS_PES)
gf_m2ts_set_pes_framing(o_pes, GF_M2TS_PES_FRAMING_SKIP);
GF_LOG(GF_LOG_INFO, GF_LOG_CONTAINER, ("[MPEG-2 TS] Reassinging PID %d from program %d to program %d\n", pes->pid, o_pes->program->number, pes->program->number) );
pes->program->ts->ess[pes->pid] = (GF_M2TS_ES *) pes;
}
switch (mode) {
case GF_M2TS_PES_FRAMING_RAW:
pes->reframe = gf_m2ts_reframe_default;
break;
case GF_M2TS_PES_FRAMING_SKIP:
pes->reframe = gf_m2ts_reframe_reset;
break;
case GF_M2TS_PES_FRAMING_SKIP_NO_RESET:
pes->reframe = NULL;
break;
case GF_M2TS_PES_FRAMING_DEFAULT:
default:
switch (pes->stream_type) {
case GF_M2TS_VIDEO_MPEG1:
case GF_M2TS_VIDEO_MPEG2:
case GF_M2TS_VIDEO_H264:
case GF_M2TS_VIDEO_SVC:
case GF_M2TS_VIDEO_HEVC:
case GF_M2TS_VIDEO_HEVC_TEMPORAL:
case GF_M2TS_VIDEO_HEVC_MCTS:
case GF_M2TS_VIDEO_SHVC:
case GF_M2TS_VIDEO_SHVC_TEMPORAL:
case GF_M2TS_VIDEO_MHVC:
case GF_M2TS_VIDEO_MHVC_TEMPORAL:
case GF_M2TS_AUDIO_MPEG1:
case GF_M2TS_AUDIO_MPEG2:
case GF_M2TS_AUDIO_AAC:
case GF_M2TS_AUDIO_LATM_AAC:
case GF_M2TS_AUDIO_AC3:
case GF_M2TS_AUDIO_EC3:
//for all our supported codec types, use a reframer filter
pes->reframe = gf_m2ts_reframe_default;
break;
case GF_M2TS_PRIVATE_DATA:
/* TODO: handle DVB subtitle streams */
break;
case GF_M2TS_METADATA_ID3_HLS:
//TODO
pes->reframe = gf_m2ts_reframe_id3_pes;
break;
default:
pes->reframe = gf_m2ts_reframe_default;
break;
}
break;
}
return GF_OK;
}
GF_EXPORT
GF_M2TS_Demuxer *gf_m2ts_demux_new()
{
GF_M2TS_Demuxer *ts;
GF_SAFEALLOC(ts, GF_M2TS_Demuxer);
if (!ts) return NULL;
ts->programs = gf_list_new();
ts->SDTs = gf_list_new();
ts->pat = gf_m2ts_section_filter_new(gf_m2ts_process_pat, 0);
ts->cat = gf_m2ts_section_filter_new(gf_m2ts_process_cat, 0);
ts->sdt = gf_m2ts_section_filter_new(gf_m2ts_process_sdt, 1);
ts->nit = gf_m2ts_section_filter_new(gf_m2ts_process_nit, 0);
ts->eit = gf_m2ts_section_filter_new(NULL/*gf_m2ts_process_eit*/, 1);
ts->tdt_tot = gf_m2ts_section_filter_new(gf_m2ts_process_tdt_tot, 1);
#ifdef GPAC_ENABLE_MPE
gf_dvb_mpe_init(ts);
#endif
ts->nb_prog_pmt_received = 0;
ts->ChannelAppList = gf_list_new();
return ts;
}
GF_EXPORT
void gf_m2ts_demux_dmscc_init(GF_M2TS_Demuxer *ts) {
char temp_dir[GF_MAX_PATH];
u32 length;
GF_Err e;
ts->dsmcc_controler = gf_list_new();
ts->process_dmscc = 1;
strcpy(temp_dir, gf_get_default_cache_directory() );
length = (u32) strlen(temp_dir);
if(temp_dir[length-1] == GF_PATH_SEPARATOR) {
temp_dir[length-1] = 0;
}
ts->dsmcc_root_dir = (char*)gf_calloc(strlen(temp_dir)+strlen("CarouselData")+2,sizeof(char));
sprintf(ts->dsmcc_root_dir,"%s%cCarouselData",temp_dir,GF_PATH_SEPARATOR);
e = gf_mkdir(ts->dsmcc_root_dir);
if(e) {
GF_LOG(GF_LOG_INFO, GF_LOG_CONTAINER, ("[Process DSMCC] Error during the creation of the directory %s \n",ts->dsmcc_root_dir));
}
}
GF_EXPORT
void gf_m2ts_demux_del(GF_M2TS_Demuxer *ts)
{
u32 i;
if (ts->pat) gf_m2ts_section_filter_del(ts->pat);
if (ts->cat) gf_m2ts_section_filter_del(ts->cat);
if (ts->sdt) gf_m2ts_section_filter_del(ts->sdt);
if (ts->nit) gf_m2ts_section_filter_del(ts->nit);
if (ts->eit) gf_m2ts_section_filter_del(ts->eit);
if (ts->tdt_tot) gf_m2ts_section_filter_del(ts->tdt_tot);
for (i=0; i<GF_M2TS_MAX_STREAMS; i++) {
//bacause of pure PCR streams, en ES might be reassigned on 2 PIDs, one for the ES and one for the PCR
if (ts->ess[i] && (ts->ess[i]->pid==i)) gf_m2ts_es_del(ts->ess[i], ts);
}
if (ts->buffer) gf_free(ts->buffer);
while (gf_list_count(ts->programs)) {
GF_M2TS_Program *p = (GF_M2TS_Program *)gf_list_last(ts->programs);
gf_list_rem_last(ts->programs);
gf_list_del(p->streams);
/*reset OD list*/
if (p->additional_ods) {
gf_odf_desc_list_del(p->additional_ods);
gf_list_del(p->additional_ods);
}
if (p->pmt_iod) gf_odf_desc_del((GF_Descriptor *)p->pmt_iod);
if (p->metadata_pointer_descriptor) gf_m2ts_metadata_pointer_descriptor_del(p->metadata_pointer_descriptor);
gf_free(p);
}
gf_list_del(ts->programs);
if (ts->TDT_time) gf_free(ts->TDT_time);
gf_m2ts_reset_sdt(ts);
if (ts->tdt_tot)
gf_list_del(ts->SDTs);
#ifdef GPAC_ENABLE_MPE
gf_dvb_mpe_shutdown(ts);
#endif
if (ts->dsmcc_controler) {
if (gf_list_count(ts->dsmcc_controler)) {
#ifdef GPAC_ENABLE_DSMCC
GF_M2TS_DSMCC_OVERLORD* dsmcc_overlord = (GF_M2TS_DSMCC_OVERLORD*)gf_list_get(ts->dsmcc_controler,0);
gf_cleanup_dir(dsmcc_overlord->root_dir);
gf_rmdir(dsmcc_overlord->root_dir);
gf_m2ts_delete_dsmcc_overlord(dsmcc_overlord);
if(ts->dsmcc_root_dir) {
gf_free(ts->dsmcc_root_dir);
}
#endif
}
gf_list_del(ts->dsmcc_controler);
}
while(gf_list_count(ts->ChannelAppList)) {
#ifdef GPAC_ENABLE_DSMCC
GF_M2TS_CHANNEL_APPLICATION_INFO* ChanAppInfo = (GF_M2TS_CHANNEL_APPLICATION_INFO*)gf_list_get(ts->ChannelAppList,0);
gf_m2ts_delete_channel_application_info(ChanAppInfo);
gf_list_rem(ts->ChannelAppList,0);
#endif
}
gf_list_del(ts->ChannelAppList);
if (ts->dsmcc_root_dir) gf_free(ts->dsmcc_root_dir);
gf_free(ts);
}
#if 0//unused
void gf_m2ts_print_info(GF_M2TS_Demuxer *ts)
{
#ifdef GPAC_ENABLE_MPE
gf_m2ts_print_mpe_info(ts);
#endif
}
#endif
#define M2TS_PROBE_SIZE 188000
static Bool gf_m2ts_probe_buffer(char *buf, u32 size)
{
GF_Err e;
GF_M2TS_Demuxer *ts;
u32 lt;
lt = gf_log_get_tool_level(GF_LOG_CONTAINER);
gf_log_set_tool_level(GF_LOG_CONTAINER, GF_LOG_QUIET);
ts = gf_m2ts_demux_new();
e = gf_m2ts_process_data(ts, buf, size);
if (!ts->pck_number) e = GF_BAD_PARAM;
gf_m2ts_demux_del(ts);
gf_log_set_tool_level(GF_LOG_CONTAINER, lt);
if (e) return GF_FALSE;
return GF_TRUE;
}
GF_EXPORT
Bool gf_m2ts_probe_file(const char *fileName)
{
char buf[M2TS_PROBE_SIZE];
u32 size;
FILE *t;
if (!strncmp(fileName, "gmem://", 7)) {
u8 *mem_address;
if (gf_blob_get_data(fileName, &mem_address, &size) != GF_OK) {
return GF_FALSE;
}
if (size>M2TS_PROBE_SIZE) size = M2TS_PROBE_SIZE;
memcpy(buf, mem_address, size);
} else {
t = gf_fopen(fileName, "rb");
if (!t) return 0;
size = (u32) fread(buf, 1, M2TS_PROBE_SIZE, t);
gf_fclose(t);
if ((s32) size <= 0) return 0;
}
return gf_m2ts_probe_buffer(buf, size);
}
GF_EXPORT
Bool gf_m2ts_probe_data(const u8 *data, u32 size)
{
size /= 188;
size *= 188;
return gf_m2ts_probe_buffer((char *) data, size);
}
static void rewrite_pts_dts(unsigned char *ptr, u64 TS)
{
ptr[0] &= 0xf1;
ptr[0] |= (unsigned char)((TS&0x1c0000000ULL)>>29);
ptr[1] = (unsigned char)((TS&0x03fc00000ULL)>>22);
ptr[2] &= 0x1;
ptr[2] |= (unsigned char)((TS&0x0003f8000ULL)>>14);
ptr[3] = (unsigned char)((TS&0x000007f80ULL)>>7);
ptr[4] &= 0x1;
ptr[4] |= (unsigned char)((TS&0x00000007fULL)<<1);
assert(((u64)(ptr[0]&0xe)<<29) + ((u64)ptr[1]<<22) + ((u64)(ptr[2]&0xfe)<<14) + ((u64)ptr[3]<<7) + ((ptr[4]&0xfe)>>1) == TS);
}
#define ADJUST_TIMESTAMP(_TS) \
if (_TS < (u64) -ts_shift) _TS = pcr_mod + _TS + ts_shift; \
else _TS = _TS + ts_shift; \
while (_TS > pcr_mod) _TS -= pcr_mod; \
GF_EXPORT
GF_Err gf_m2ts_restamp(u8 *buffer, u32 size, s64 ts_shift, u8 *is_pes)
{
u32 done = 0;
u64 pcr_mod;
// if (!ts_shift) return GF_OK;
pcr_mod = 0x80000000;
pcr_mod*=4;
while (done + 188 <= size) {
u8 *pesh;
u8 *pck;
u64 pcr_base=0, pcr_ext=0;
u16 pid;
u8 adaptation_field, adaptation_field_length;
pck = (u8*) buffer+done;
if (pck[0]!=0x47) {
GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[M2TS Restamp] Invalid sync byte %X\n", pck[0]));
return GF_NON_COMPLIANT_BITSTREAM;
}
pid = ((pck[1] & 0x1f) <<8 ) + pck[2];
adaptation_field_length = 0;
adaptation_field = (pck[3] >> 4) & 0x3;
if ((adaptation_field==2) || (adaptation_field==3)) {
adaptation_field_length = pck[4];
if ( pck[5]&0x10 /*PCR_flag*/) {
pcr_base = (((u64)pck[6])<<25) + (pck[7]<<17) + (pck[8]<<9) + (pck[9]<<1) + (pck[10]>>7);
pcr_ext = ((pck[10]&1)<<8) + pck[11];
ADJUST_TIMESTAMP(pcr_base);
pck[6] = (unsigned char)(0xff&(pcr_base>>25));
pck[7] = (unsigned char)(0xff&(pcr_base>>17));
pck[8] = (unsigned char)(0xff&(pcr_base>>9));
pck[9] = (unsigned char)(0xff&(pcr_base>>1));
pck[10] = (unsigned char)(((0x1&pcr_base)<<7) | 0x7e | ((0x100&pcr_ext)>>8));
if (pcr_ext != ((pck[10]&1)<<8) + pck[11]) {
GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[M2TS Restamp] Sanity check failed for PCR restamping\n"));
return GF_IO_ERR;
}
pck[11] = (unsigned char)(0xff&pcr_ext);
}
/*add adaptation_field_length field*/
adaptation_field_length++;
}
if (!is_pes[pid] || !(pck[1]&0x40)) {
done+=188;
continue;
}
pesh = &pck[4+adaptation_field_length];
if ((pesh[0]==0x00) && (pesh[1]==0x00) && (pesh[2]==0x01)) {
Bool has_pts, has_dts;
if ((pesh[6]&0xc0)!=0x80) {
done+=188;
continue;
}
has_pts = (pesh[7]&0x80);
has_dts = has_pts ? (pesh[7]&0x40) : 0;
if (has_pts) {
u64 PTS;
if (((pesh[9]&0xe0)>>4)!=0x2) {
GF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, ("[M2TS Restamp] PID %4d: Wrong PES header, PTS decoding: '0010' expected\n", pid));
done+=188;
continue;
}
PTS = gf_m2ts_get_pts(pesh + 9);
ADJUST_TIMESTAMP(PTS);
rewrite_pts_dts(pesh+9, PTS);
}
if (has_dts) {
u64 DTS = gf_m2ts_get_pts(pesh + 14);
ADJUST_TIMESTAMP(DTS);
rewrite_pts_dts(pesh+14, DTS);
}
} else {
GF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, ("[M2TS Restamp] PID %4d: Wrong PES not beginning with start code\n", pid));
}
done+=188;
}
return GF_OK;
}
#endif /*GPAC_DISABLE_MPEG2TS*/
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_1374_0 |
crossvul-cpp_data_good_950_0 | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% AAA N N N N OOO TTTTT AAA TTTTT EEEEE %
% A A NN N NN N O O T A A T E %
% AAAAA N N N N N N O O T AAAAA T EEE %
% A A N NN N NN O O T A A T E %
% A A N N N N OOO T A A T EEEEE %
% %
% %
% MagickCore Image Annotation Methods %
% %
% Software Design %
% Cristy %
% July 1992 %
% %
% %
% Copyright 1999-2019 ImageMagick Studio LLC, a non-profit organization %
% dedicated to making software imaging solutions freely available. %
% %
% You may not use this file except in compliance with the License. You may %
% obtain a copy of the License at %
% %
% https://imagemagick.org/script/license.php %
% %
% Unless required by applicable law or agreed to in writing, software %
% distributed under the License is distributed on an "AS IS" BASIS, %
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %
% See the License for the specific language governing permissions and %
% limitations under the License. %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Digital Applications (www.digapp.com) contributed the stroked text algorithm.
% It was written by Leonard Rosenthol.
%
%
*/
/*
Include declarations.
*/
#include "magick/studio.h"
#include "magick/annotate.h"
#include "magick/attribute.h"
#include "magick/cache-private.h"
#include "magick/cache-view.h"
#include "magick/channel.h"
#include "magick/client.h"
#include "magick/color.h"
#include "magick/color-private.h"
#include "magick/colorspace-private.h"
#include "magick/composite.h"
#include "magick/composite-private.h"
#include "magick/constitute.h"
#include "magick/draw.h"
#include "magick/draw-private.h"
#include "magick/exception.h"
#include "magick/exception-private.h"
#include "magick/gem.h"
#include "magick/geometry.h"
#include "magick/image-private.h"
#include "magick/log.h"
#include "magick/quantum.h"
#include "magick/quantum-private.h"
#include "magick/pixel-accessor.h"
#include "magick/property.h"
#include "magick/resource_.h"
#include "magick/semaphore.h"
#include "magick/statistic.h"
#include "magick/string_.h"
#include "magick/token.h"
#include "magick/token-private.h"
#include "magick/transform.h"
#include "magick/type.h"
#include "magick/utility.h"
#include "magick/xwindow-private.h"
#if defined(MAGICKCORE_FREETYPE_DELEGATE)
#if defined(__MINGW32__)
# undef interface
#endif
#include <ft2build.h>
#if defined(FT_FREETYPE_H)
# include FT_FREETYPE_H
#else
# include <freetype/freetype.h>
#endif
#if defined(FT_GLYPH_H)
# include FT_GLYPH_H
#else
# include <freetype/ftglyph.h>
#endif
#if defined(FT_OUTLINE_H)
# include FT_OUTLINE_H
#else
# include <freetype/ftoutln.h>
#endif
#if defined(FT_BBOX_H)
# include FT_BBOX_H
#else
# include <freetype/ftbbox.h>
#endif /* defined(FT_BBOX_H) */
#endif
#if defined(MAGICKCORE_RAQM_DELEGATE)
#include <raqm.h>
#endif
typedef struct _GraphemeInfo
{
ssize_t
index,
x_offset,
x_advance,
y_offset;
size_t
cluster;
} GraphemeInfo;
/*
Annotate semaphores.
*/
static SemaphoreInfo
*annotate_semaphore = (SemaphoreInfo *) NULL;
/*
Forward declarations.
*/
static MagickBooleanType
RenderType(Image *,const DrawInfo *,const PointInfo *,TypeMetric *),
RenderPostscript(Image *,const DrawInfo *,const PointInfo *,TypeMetric *),
RenderFreetype(Image *,const DrawInfo *,const char *,const PointInfo *,
TypeMetric *),
RenderX11(Image *,const DrawInfo *,const PointInfo *,TypeMetric *);
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ A n n o t a t e C o m p o n e n t G e n e s i s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% AnnotateComponentGenesis() instantiates the annotate component.
%
% The format of the AnnotateComponentGenesis method is:
%
% MagickBooleanType AnnotateComponentGenesis(void)
%
*/
MagickExport MagickBooleanType AnnotateComponentGenesis(void)
{
if (annotate_semaphore == (SemaphoreInfo *) NULL)
annotate_semaphore=AllocateSemaphoreInfo();
return(MagickTrue);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ A n n o t a t e C o m p o n e n t T e r m i n u s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% AnnotateComponentTerminus() destroys the annotate component.
%
% The format of the AnnotateComponentTerminus method is:
%
% AnnotateComponentTerminus(void)
%
*/
MagickExport void AnnotateComponentTerminus(void)
{
if (annotate_semaphore == (SemaphoreInfo *) NULL)
ActivateSemaphoreInfo(&annotate_semaphore);
DestroySemaphoreInfo(&annotate_semaphore);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% A n n o t a t e I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% AnnotateImage() annotates an image with text.
%
% The format of the AnnotateImage method is:
%
% MagickBooleanType AnnotateImage(Image *image,DrawInfo *draw_info)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o draw_info: the draw info.
%
*/
MagickExport MagickBooleanType AnnotateImage(Image *image,
const DrawInfo *draw_info)
{
char
*p,
primitive[MaxTextExtent],
*text,
**textlist;
DrawInfo
*annotate,
*annotate_info;
GeometryInfo
geometry_info;
MagickBooleanType
status;
PointInfo
offset;
RectangleInfo
geometry;
register ssize_t
i;
TypeMetric
metrics;
size_t
height,
number_lines;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(draw_info != (DrawInfo *) NULL);
assert(draw_info->signature == MagickCoreSignature);
if (draw_info->text == (char *) NULL)
return(MagickFalse);
if (*draw_info->text == '\0')
return(MagickTrue);
annotate=CloneDrawInfo((ImageInfo *) NULL,draw_info);
text=annotate->text;
annotate->text=(char *) NULL;
annotate_info=CloneDrawInfo((ImageInfo *) NULL,draw_info);
number_lines=1;
for (p=text; *p != '\0'; p++)
if (*p == '\n')
number_lines++;
textlist=AcquireQuantumMemory(number_lines+1,sizeof(*textlist));
if (textlist == (char **) NULL)
{
annotate_info=DestroyDrawInfo(annotate_info);
annotate=DestroyDrawInfo(annotate);
text=DestroyString(text);
return(MagickFalse);
}
p=text;
for (i=0; i < number_lines; i++)
{
char
*q;
textlist[i]=p;
for (q=p; *q != '\0'; q++)
if ((*q == '\r') || (*q == '\n'))
break;
if (*q == '\r')
{
*q='\0';
q++;
}
*q='\0';
p=q+1;
}
textlist[i]=(char *) NULL;
SetGeometry(image,&geometry);
SetGeometryInfo(&geometry_info);
if (annotate_info->geometry != (char *) NULL)
{
(void) ParsePageGeometry(image,annotate_info->geometry,&geometry,
&image->exception);
(void) ParseGeometry(annotate_info->geometry,&geometry_info);
}
if (SetImageStorageClass(image,DirectClass) == MagickFalse)
{
annotate_info=DestroyDrawInfo(annotate_info);
annotate=DestroyDrawInfo(annotate);
textlist=(char **) RelinquishMagickMemory(textlist);
text=DestroyString(text);
return(MagickFalse);
}
if (IsGrayColorspace(image->colorspace) != MagickFalse)
(void) SetImageColorspace(image,sRGBColorspace);
status=MagickTrue;
(void) memset(&metrics,0,sizeof(metrics));
for (i=0; textlist[i] != (char *) NULL; i++)
{
if (*textlist[i] == '\0')
continue;
/*
Position text relative to image.
*/
annotate_info->affine.tx=geometry_info.xi-image->page.x;
annotate_info->affine.ty=geometry_info.psi-image->page.y;
(void) CloneString(&annotate->text,textlist[i]);
if ((metrics.width == 0) || (annotate->gravity != NorthWestGravity))
(void) GetTypeMetrics(image,annotate,&metrics);
height=(ssize_t) (metrics.ascent-metrics.descent+
draw_info->interline_spacing+0.5);
switch (annotate->gravity)
{
case UndefinedGravity:
default:
{
offset.x=annotate_info->affine.tx+i*annotate_info->affine.ry*height;
offset.y=annotate_info->affine.ty+i*annotate_info->affine.sy*height;
break;
}
case NorthWestGravity:
{
offset.x=(geometry.width == 0 ? -1.0 : 1.0)*annotate_info->affine.tx+i*
annotate_info->affine.ry*height+annotate_info->affine.ry*
(metrics.ascent+metrics.descent);
offset.y=(geometry.height == 0 ? -1.0 : 1.0)*annotate_info->affine.ty+i*
annotate_info->affine.sy*height+annotate_info->affine.sy*
metrics.ascent;
break;
}
case NorthGravity:
{
offset.x=(geometry.width == 0 ? -1.0 : 1.0)*annotate_info->affine.tx+
geometry.width/2.0+i*annotate_info->affine.ry*height-
annotate_info->affine.sx*metrics.width/2.0+annotate_info->affine.ry*
(metrics.ascent+metrics.descent);
offset.y=(geometry.height == 0 ? -1.0 : 1.0)*annotate_info->affine.ty+i*
annotate_info->affine.sy*height+annotate_info->affine.sy*
metrics.ascent-annotate_info->affine.rx*metrics.width/2.0;
break;
}
case NorthEastGravity:
{
offset.x=(geometry.width == 0 ? 1.0 : -1.0)*annotate_info->affine.tx+
geometry.width+i*annotate_info->affine.ry*height-
annotate_info->affine.sx*metrics.width+annotate_info->affine.ry*
(metrics.ascent+metrics.descent)-1.0;
offset.y=(geometry.height == 0 ? -1.0 : 1.0)*annotate_info->affine.ty+i*
annotate_info->affine.sy*height+annotate_info->affine.sy*
metrics.ascent-annotate_info->affine.rx*metrics.width;
break;
}
case WestGravity:
{
offset.x=(geometry.width == 0 ? -1.0 : 1.0)*annotate_info->affine.tx+i*
annotate_info->affine.ry*height+annotate_info->affine.ry*
(metrics.ascent+metrics.descent-(number_lines-1.0)*height)/2.0;
offset.y=(geometry.height == 0 ? -1.0 : 1.0)*annotate_info->affine.ty+
geometry.height/2.0+i*annotate_info->affine.sy*height+
annotate_info->affine.sy*(metrics.ascent+metrics.descent-
(number_lines-1.0)*height)/2.0;
break;
}
case StaticGravity:
case CenterGravity:
{
offset.x=(geometry.width == 0 ? -1.0 : 1.0)*annotate_info->affine.tx+
geometry.width/2.0+i*annotate_info->affine.ry*height-
annotate_info->affine.sx*metrics.width/2.0+annotate_info->affine.ry*
(metrics.ascent+metrics.descent-(number_lines-1)*height)/2.0;
offset.y=(geometry.height == 0 ? -1.0 : 1.0)*annotate_info->affine.ty+
geometry.height/2.0+i*annotate_info->affine.sy*height-
annotate_info->affine.rx*metrics.width/2.0+annotate_info->affine.sy*
(metrics.ascent+metrics.descent-(number_lines-1.0)*height)/2.0;
break;
}
case EastGravity:
{
offset.x=(geometry.width == 0 ? 1.0 : -1.0)*annotate_info->affine.tx+
geometry.width+i*annotate_info->affine.ry*height-
annotate_info->affine.sx*metrics.width+annotate_info->affine.ry*
(metrics.ascent+metrics.descent-(number_lines-1.0)*height)/2.0-1.0;
offset.y=(geometry.height == 0 ? -1.0 : 1.0)*annotate_info->affine.ty+
geometry.height/2.0+i*annotate_info->affine.sy*height-
annotate_info->affine.rx*metrics.width+annotate_info->affine.sy*
(metrics.ascent+metrics.descent-(number_lines-1.0)*height)/2.0;
break;
}
case SouthWestGravity:
{
offset.x=(geometry.width == 0 ? -1.0 : 1.0)*annotate_info->affine.tx+i*
annotate_info->affine.ry*height-annotate_info->affine.ry*
(number_lines-1.0)*height;
offset.y=(geometry.height == 0 ? 1.0 : -1.0)*annotate_info->affine.ty+
geometry.height+i*annotate_info->affine.sy*height-
annotate_info->affine.sy*(number_lines-1.0)*height+metrics.descent;
break;
}
case SouthGravity:
{
offset.x=(geometry.width == 0 ? -1.0 : 1.0)*annotate_info->affine.tx+
geometry.width/2.0+i*annotate_info->affine.ry*height-
annotate_info->affine.sx*metrics.width/2.0-annotate_info->affine.ry*
(number_lines-1.0)*height/2.0;
offset.y=(geometry.height == 0 ? 1.0 : -1.0)*annotate_info->affine.ty+
geometry.height+i*annotate_info->affine.sy*height-
annotate_info->affine.rx*metrics.width/2.0-annotate_info->affine.sy*
(number_lines-1.0)*height+metrics.descent;
break;
}
case SouthEastGravity:
{
offset.x=(geometry.width == 0 ? 1.0 : -1.0)*annotate_info->affine.tx+
geometry.width+i*annotate_info->affine.ry*height-
annotate_info->affine.sx*metrics.width-annotate_info->affine.ry*
(number_lines-1.0)*height-1.0;
offset.y=(geometry.height == 0 ? 1.0 : -1.0)*annotate_info->affine.ty+
geometry.height+i*annotate_info->affine.sy*height-
annotate_info->affine.rx*metrics.width-annotate_info->affine.sy*
(number_lines-1.0)*height+metrics.descent;
break;
}
}
switch (annotate->align)
{
case LeftAlign:
{
offset.x=annotate_info->affine.tx+i*annotate_info->affine.ry*height;
offset.y=annotate_info->affine.ty+i*annotate_info->affine.sy*height;
break;
}
case CenterAlign:
{
offset.x=annotate_info->affine.tx+i*annotate_info->affine.ry*height-
annotate_info->affine.sx*metrics.width/2.0;
offset.y=annotate_info->affine.ty+i*annotate_info->affine.sy*height-
annotate_info->affine.rx*metrics.width/2.0;
break;
}
case RightAlign:
{
offset.x=annotate_info->affine.tx+i*annotate_info->affine.ry*height-
annotate_info->affine.sx*metrics.width;
offset.y=annotate_info->affine.ty+i*annotate_info->affine.sy*height-
annotate_info->affine.rx*metrics.width;
break;
}
default:
break;
}
if (draw_info->undercolor.opacity != TransparentOpacity)
{
DrawInfo
*undercolor_info;
/*
Text box.
*/
undercolor_info=CloneDrawInfo((ImageInfo *) NULL,(DrawInfo *) NULL);
undercolor_info->fill=draw_info->undercolor;
undercolor_info->affine=draw_info->affine;
undercolor_info->affine.tx=offset.x-draw_info->affine.ry*metrics.ascent;
undercolor_info->affine.ty=offset.y-draw_info->affine.sy*metrics.ascent;
(void) FormatLocaleString(primitive,MaxTextExtent,
"rectangle 0.0,0.0 %g,%g",metrics.origin.x,(double) height);
(void) CloneString(&undercolor_info->primitive,primitive);
(void) DrawImage(image,undercolor_info);
(void) DestroyDrawInfo(undercolor_info);
}
annotate_info->affine.tx=offset.x;
annotate_info->affine.ty=offset.y;
(void) FormatLocaleString(primitive,MaxTextExtent,"stroke-width %g "
"line 0,0 %g,0",metrics.underline_thickness,metrics.width);
if (annotate->decorate == OverlineDecoration)
{
annotate_info->affine.ty-=(draw_info->affine.sy*(metrics.ascent+
metrics.descent-metrics.underline_position));
(void) CloneString(&annotate_info->primitive,primitive);
(void) DrawImage(image,annotate_info);
}
else
if (annotate->decorate == UnderlineDecoration)
{
annotate_info->affine.ty-=(draw_info->affine.sy*
metrics.underline_position);
(void) CloneString(&annotate_info->primitive,primitive);
(void) DrawImage(image,annotate_info);
}
/*
Annotate image with text.
*/
status=RenderType(image,annotate,&offset,&metrics);
if (status == MagickFalse)
break;
if (annotate->decorate == LineThroughDecoration)
{
annotate_info->affine.ty-=(draw_info->affine.sy*(height+
metrics.underline_position+metrics.descent)/2.0);
(void) CloneString(&annotate_info->primitive,primitive);
(void) DrawImage(image,annotate_info);
}
}
/*
Relinquish resources.
*/
annotate_info=DestroyDrawInfo(annotate_info);
annotate=DestroyDrawInfo(annotate);
textlist=(char **) RelinquishMagickMemory(textlist);
text=DestroyString(text);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% F o r m a t M a g i c k C a p t i o n %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% FormatMagickCaption() formats a caption so that it fits within the image
% width. It returns the number of lines in the formatted caption.
%
% The format of the FormatMagickCaption method is:
%
% ssize_t FormatMagickCaption(Image *image,DrawInfo *draw_info,
% const MagickBooleanType split,TypeMetric *metrics,char **caption)
%
% A description of each parameter follows.
%
% o image: The image.
%
% o draw_info: the draw info.
%
% o split: when no convenient line breaks-- insert newline.
%
% o metrics: Return the font metrics in this structure.
%
% o caption: the caption.
%
*/
MagickExport ssize_t FormatMagickCaption(Image *image,DrawInfo *draw_info,
const MagickBooleanType split,TypeMetric *metrics,char **caption)
{
MagickBooleanType
status;
register char
*p,
*q,
*s;
register ssize_t
i;
size_t
width;
ssize_t
n;
q=draw_info->text;
s=(char *) NULL;
for (p=(*caption); GetUTFCode(p) != 0; p+=GetUTFOctets(p))
{
if (IsUTFSpace(GetUTFCode(p)) != MagickFalse)
s=p;
if (GetUTFCode(p) == '\n')
{
q=draw_info->text;
continue;
}
for (i=0; i < (ssize_t) GetUTFOctets(p); i++)
*q++=(*(p+i));
*q='\0';
status=GetTypeMetrics(image,draw_info,metrics);
if (status == MagickFalse)
break;
width=(size_t) floor(metrics->width+draw_info->stroke_width+0.5);
if (width <= image->columns)
continue;
if (s != (char *) NULL)
{
*s='\n';
p=s;
}
else
if (split != MagickFalse)
{
/*
No convenient line breaks-- insert newline.
*/
n=p-(*caption);
if ((n > 0) && ((*caption)[n-1] != '\n'))
{
char
*target;
target=AcquireString(*caption);
CopyMagickString(target,*caption,n+1);
ConcatenateMagickString(target,"\n",strlen(*caption)+1);
ConcatenateMagickString(target,p,strlen(*caption)+2);
(void) DestroyString(*caption);
*caption=target;
p=(*caption)+n;
}
}
q=draw_info->text;
s=(char *) NULL;
}
n=0;
for (p=(*caption); GetUTFCode(p) != 0; p+=GetUTFOctets(p))
if (GetUTFCode(p) == '\n')
n++;
return(n);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% G e t M u l t i l i n e T y p e M e t r i c s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetMultilineTypeMetrics() returns the following information for the
% specified font and text:
%
% character width
% character height
% ascender
% descender
% text width
% text height
% maximum horizontal advance
% bounds: x1
% bounds: y1
% bounds: x2
% bounds: y2
% origin: x
% origin: y
% underline position
% underline thickness
%
% This method is like GetTypeMetrics() but it returns the maximum text width
% and height for multiple lines of text.
%
% The format of the GetMultilineTypeMetrics method is:
%
% MagickBooleanType GetMultilineTypeMetrics(Image *image,
% const DrawInfo *draw_info,TypeMetric *metrics)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o draw_info: the draw info.
%
% o metrics: Return the font metrics in this structure.
%
*/
MagickExport MagickBooleanType GetMultilineTypeMetrics(Image *image,
const DrawInfo *draw_info,TypeMetric *metrics)
{
char
**textlist;
DrawInfo
*annotate_info;
MagickBooleanType
status;
register ssize_t
i;
TypeMetric
extent;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(draw_info != (DrawInfo *) NULL);
assert(draw_info->text != (char *) NULL);
assert(draw_info->signature == MagickCoreSignature);
if (*draw_info->text == '\0')
return(MagickFalse);
annotate_info=CloneDrawInfo((ImageInfo *) NULL,draw_info);
annotate_info->text=DestroyString(annotate_info->text);
/*
Convert newlines to multiple lines of text.
*/
textlist=StringToList(draw_info->text);
if (textlist == (char **) NULL)
return(MagickFalse);
annotate_info->render=MagickFalse;
annotate_info->direction=UndefinedDirection;
(void) memset(metrics,0,sizeof(*metrics));
(void) memset(&extent,0,sizeof(extent));
/*
Find the widest of the text lines.
*/
annotate_info->text=textlist[0];
status=GetTypeMetrics(image,annotate_info,&extent);
*metrics=extent;
for (i=1; textlist[i] != (char *) NULL; i++)
{
annotate_info->text=textlist[i];
status=GetTypeMetrics(image,annotate_info,&extent);
if (extent.width > metrics->width)
*metrics=extent;
}
metrics->height=(double) (i*(size_t) (metrics->ascent-metrics->descent+0.5)+
(i-1)*draw_info->interline_spacing);
/*
Relinquish resources.
*/
annotate_info->text=(char *) NULL;
annotate_info=DestroyDrawInfo(annotate_info);
for (i=0; textlist[i] != (char *) NULL; i++)
textlist[i]=DestroyString(textlist[i]);
textlist=(char **) RelinquishMagickMemory(textlist);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% G e t T y p e M e t r i c s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetTypeMetrics() returns the following information for the specified font
% and text:
%
% character width
% character height
% ascender
% descender
% text width
% text height
% maximum horizontal advance
% bounds: x1
% bounds: y1
% bounds: x2
% bounds: y2
% origin: x
% origin: y
% underline position
% underline thickness
%
% The format of the GetTypeMetrics method is:
%
% MagickBooleanType GetTypeMetrics(Image *image,const DrawInfo *draw_info,
% TypeMetric *metrics)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o draw_info: the draw info.
%
% o metrics: Return the font metrics in this structure.
%
*/
MagickExport MagickBooleanType GetTypeMetrics(Image *image,
const DrawInfo *draw_info,TypeMetric *metrics)
{
DrawInfo
*annotate_info;
MagickBooleanType
status;
PointInfo
offset;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(draw_info != (DrawInfo *) NULL);
assert(draw_info->text != (char *) NULL);
assert(draw_info->signature == MagickCoreSignature);
annotate_info=CloneDrawInfo((ImageInfo *) NULL,draw_info);
annotate_info->render=MagickFalse;
annotate_info->direction=UndefinedDirection;
(void) memset(metrics,0,sizeof(*metrics));
offset.x=0.0;
offset.y=0.0;
status=RenderType(image,annotate_info,&offset,metrics);
if (image->debug != MagickFalse)
(void) LogMagickEvent(AnnotateEvent,GetMagickModule(),"Metrics: text: %s; "
"width: %g; height: %g; ascent: %g; descent: %g; max advance: %g; "
"bounds: %g,%g %g,%g; origin: %g,%g; pixels per em: %g,%g; "
"underline position: %g; underline thickness: %g",annotate_info->text,
metrics->width,metrics->height,metrics->ascent,metrics->descent,
metrics->max_advance,metrics->bounds.x1,metrics->bounds.y1,
metrics->bounds.x2,metrics->bounds.y2,metrics->origin.x,metrics->origin.y,
metrics->pixels_per_em.x,metrics->pixels_per_em.y,
metrics->underline_position,metrics->underline_thickness);
annotate_info=DestroyDrawInfo(annotate_info);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ R e n d e r T y p e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% RenderType() renders text on the image. It also returns the bounding box of
% the text relative to the image.
%
% The format of the RenderType method is:
%
% MagickBooleanType RenderType(Image *image,DrawInfo *draw_info,
% const PointInfo *offset,TypeMetric *metrics)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o draw_info: the draw info.
%
% o offset: (x,y) location of text relative to image.
%
% o metrics: bounding box of text.
%
*/
static MagickBooleanType RenderType(Image *image,const DrawInfo *draw_info,
const PointInfo *offset,TypeMetric *metrics)
{
const TypeInfo
*type_info;
DrawInfo
*annotate_info;
MagickBooleanType
status;
type_info=(const TypeInfo *) NULL;
if (draw_info->font != (char *) NULL)
{
if (*draw_info->font == '@')
{
status=RenderFreetype(image,draw_info,draw_info->encoding,offset,
metrics);
return(status);
}
if (*draw_info->font == '-')
return(RenderX11(image,draw_info,offset,metrics));
if (*draw_info->font == '^')
return(RenderPostscript(image,draw_info,offset,metrics));
if (IsPathAccessible(draw_info->font) != MagickFalse)
{
status=RenderFreetype(image,draw_info,draw_info->encoding,offset,
metrics);
return(status);
}
type_info=GetTypeInfo(draw_info->font,&image->exception);
if (type_info == (const TypeInfo *) NULL)
(void) ThrowMagickException(&image->exception,GetMagickModule(),
TypeWarning,"UnableToReadFont","`%s'",draw_info->font);
}
if ((type_info == (const TypeInfo *) NULL) &&
(draw_info->family != (const char *) NULL))
{
type_info=GetTypeInfoByFamily(draw_info->family,draw_info->style,
draw_info->stretch,draw_info->weight,&image->exception);
if (type_info == (const TypeInfo *) NULL)
{
char
**family;
int
number_families;
register ssize_t
i;
/*
Parse font family list.
*/
family=StringToArgv(draw_info->family,&number_families);
for (i=1; i < (ssize_t) number_families; i++)
{
type_info=GetTypeInfoByFamily(family[i],draw_info->style,
draw_info->stretch,draw_info->weight,&image->exception);
if (type_info != (const TypeInfo *) NULL)
break;
}
for (i=0; i < (ssize_t) number_families; i++)
family[i]=DestroyString(family[i]);
family=(char **) RelinquishMagickMemory(family);
if (type_info == (const TypeInfo *) NULL)
(void) ThrowMagickException(&image->exception,GetMagickModule(),
TypeWarning,"UnableToReadFont","`%s'",draw_info->family);
}
}
if (type_info == (const TypeInfo *) NULL)
type_info=GetTypeInfoByFamily("Arial",draw_info->style,
draw_info->stretch,draw_info->weight,&image->exception);
if (type_info == (const TypeInfo *) NULL)
type_info=GetTypeInfoByFamily("Helvetica",draw_info->style,
draw_info->stretch,draw_info->weight,&image->exception);
if (type_info == (const TypeInfo *) NULL)
type_info=GetTypeInfoByFamily("Century Schoolbook",draw_info->style,
draw_info->stretch,draw_info->weight,&image->exception);
if (type_info == (const TypeInfo *) NULL)
type_info=GetTypeInfoByFamily("Sans",draw_info->style,
draw_info->stretch,draw_info->weight,&image->exception);
if (type_info == (const TypeInfo *) NULL)
type_info=GetTypeInfoByFamily((const char *) NULL,draw_info->style,
draw_info->stretch,draw_info->weight,&image->exception);
if (type_info == (const TypeInfo *) NULL)
type_info=GetTypeInfo("*",&image->exception);
if (type_info == (const TypeInfo *) NULL)
{
status=RenderFreetype(image,draw_info,draw_info->encoding,offset,metrics);
return(status);
}
annotate_info=CloneDrawInfo((ImageInfo *) NULL,draw_info);
annotate_info->face=type_info->face;
if (type_info->metrics != (char *) NULL)
(void) CloneString(&annotate_info->metrics,type_info->metrics);
if (type_info->glyphs != (char *) NULL)
(void) CloneString(&annotate_info->font,type_info->glyphs);
status=RenderFreetype(image,annotate_info,type_info->encoding,offset,metrics);
annotate_info=DestroyDrawInfo(annotate_info);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ R e n d e r F r e e t y p e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% RenderFreetype() renders text on the image with a Truetype font. It also
% returns the bounding box of the text relative to the image.
%
% The format of the RenderFreetype method is:
%
% MagickBooleanType RenderFreetype(Image *image,DrawInfo *draw_info,
% const char *encoding,const PointInfo *offset,TypeMetric *metrics)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o draw_info: the draw info.
%
% o encoding: the font encoding.
%
% o offset: (x,y) location of text relative to image.
%
% o metrics: bounding box of text.
%
*/
#if defined(MAGICKCORE_FREETYPE_DELEGATE)
static size_t ComplexTextLayout(const Image *image,const DrawInfo *draw_info,
const char *text,const size_t length,const FT_Face face,const FT_Int32 flags,
GraphemeInfo **grapheme)
{
#if defined(MAGICKCORE_RAQM_DELEGATE)
const char
*features;
raqm_t
*rq;
raqm_glyph_t
*glyphs;
register ssize_t
i;
size_t
extent;
extent=0;
rq=raqm_create();
if (rq == (raqm_t *) NULL)
goto cleanup;
if (raqm_set_text_utf8(rq,text,length) == 0)
goto cleanup;
if (raqm_set_par_direction(rq,(raqm_direction_t) draw_info->direction) == 0)
goto cleanup;
if (raqm_set_freetype_face(rq,face) == 0)
goto cleanup;
features=GetImageProperty(image,"type:features");
if (features != (const char *) NULL)
{
char
breaker,
quote,
*token;
int
next,
status_token;
TokenInfo
*token_info;
next=0;
token_info=AcquireTokenInfo();
token=AcquireString("");
status_token=Tokenizer(token_info,0,token,50,features,"",",","",'\0',
&breaker,&next,"e);
while (status_token == 0)
{
raqm_add_font_feature(rq,token,strlen(token));
status_token=Tokenizer(token_info,0,token,50,features,"",",","",'\0',
&breaker,&next,"e);
}
token_info=DestroyTokenInfo(token_info);
token=DestroyString(token);
}
if (raqm_layout(rq) == 0)
goto cleanup;
glyphs=raqm_get_glyphs(rq,&extent);
if (glyphs == (raqm_glyph_t *) NULL)
{
extent=0;
goto cleanup;
}
*grapheme=(GraphemeInfo *) AcquireQuantumMemory(extent,sizeof(**grapheme));
if (*grapheme == (GraphemeInfo *) NULL)
{
extent=0;
goto cleanup;
}
for (i=0; i < (ssize_t) extent; i++)
{
(*grapheme)[i].index=glyphs[i].index;
(*grapheme)[i].x_offset=glyphs[i].x_offset;
(*grapheme)[i].x_advance=glyphs[i].x_advance;
(*grapheme)[i].y_offset=glyphs[i].y_offset;
(*grapheme)[i].cluster=glyphs[i].cluster;
}
cleanup:
raqm_destroy(rq);
return(extent);
#else
const char
*p;
FT_Error
ft_status;
register ssize_t
i;
ssize_t
last_glyph;
/*
Simple layout for bi-directional text (right-to-left or left-to-right).
*/
magick_unreferenced(image);
*grapheme=(GraphemeInfo *) AcquireQuantumMemory(length+1,sizeof(**grapheme));
if (*grapheme == (GraphemeInfo *) NULL)
return(0);
last_glyph=0;
p=text;
for (i=0; GetUTFCode(p) != 0; p+=GetUTFOctets(p), i++)
{
(*grapheme)[i].index=FT_Get_Char_Index(face,GetUTFCode(p));
(*grapheme)[i].x_offset=0;
(*grapheme)[i].y_offset=0;
if (((*grapheme)[i].index != 0) && (last_glyph != 0))
{
if (FT_HAS_KERNING(face))
{
FT_Vector
kerning;
ft_status=FT_Get_Kerning(face,(FT_UInt) last_glyph,(FT_UInt)
(*grapheme)[i].index,ft_kerning_default,&kerning);
if (ft_status == 0)
(*grapheme)[i-1].x_advance+=(FT_Pos) ((draw_info->direction ==
RightToLeftDirection ? -1.0 : 1.0)*kerning.x);
}
}
ft_status=FT_Load_Glyph(face,(*grapheme)[i].index,flags);
(*grapheme)[i].x_advance=face->glyph->advance.x;
(*grapheme)[i].cluster=p-text;
last_glyph=(*grapheme)[i].index;
}
return((size_t) i);
#endif
}
static int TraceCubicBezier(FT_Vector *p,FT_Vector *q,FT_Vector *to,
DrawInfo *draw_info)
{
AffineMatrix
affine;
char
path[MaxTextExtent];
affine=draw_info->affine;
(void) FormatLocaleString(path,MaxTextExtent,"C%g,%g %g,%g %g,%g",affine.tx+
p->x/64.0,affine.ty-p->y/64.0,affine.tx+q->x/64.0,affine.ty-q->y/64.0,
affine.tx+to->x/64.0,affine.ty-to->y/64.0);
(void) ConcatenateString(&draw_info->primitive,path);
return(0);
}
static int TraceLineTo(FT_Vector *to,DrawInfo *draw_info)
{
AffineMatrix
affine;
char
path[MaxTextExtent];
affine=draw_info->affine;
(void) FormatLocaleString(path,MaxTextExtent,"L%g,%g",affine.tx+to->x/64.0,
affine.ty-to->y/64.0);
(void) ConcatenateString(&draw_info->primitive,path);
return(0);
}
static int TraceMoveTo(FT_Vector *to,DrawInfo *draw_info)
{
AffineMatrix
affine;
char
path[MaxTextExtent];
affine=draw_info->affine;
(void) FormatLocaleString(path,MaxTextExtent,"M%g,%g",affine.tx+to->x/64.0,
affine.ty-to->y/64.0);
(void) ConcatenateString(&draw_info->primitive,path);
return(0);
}
static int TraceQuadraticBezier(FT_Vector *control,FT_Vector *to,
DrawInfo *draw_info)
{
AffineMatrix
affine;
char
path[MaxTextExtent];
affine=draw_info->affine;
(void) FormatLocaleString(path,MaxTextExtent,"Q%g,%g %g,%g",affine.tx+
control->x/64.0,affine.ty-control->y/64.0,affine.tx+to->x/64.0,affine.ty-
to->y/64.0);
(void) ConcatenateString(&draw_info->primitive,path);
return(0);
}
static MagickBooleanType RenderFreetype(Image *image,const DrawInfo *draw_info,
const char *encoding,const PointInfo *offset,TypeMetric *metrics)
{
#if !defined(FT_OPEN_PATHNAME)
#define FT_OPEN_PATHNAME ft_open_pathname
#endif
typedef struct _GlyphInfo
{
FT_UInt
id;
FT_Vector
origin;
FT_Glyph
image;
} GlyphInfo;
const char
*value;
DrawInfo
*annotate_info;
ExceptionInfo
*exception;
FT_BBox
bounds;
FT_BitmapGlyph
bitmap;
FT_Encoding
encoding_type;
FT_Error
ft_status;
FT_Face
face;
FT_Int32
flags;
FT_Library
library;
FT_Matrix
affine;
FT_Open_Args
args;
FT_Vector
origin;
GlyphInfo
glyph,
last_glyph;
GraphemeInfo
*grapheme;
MagickBooleanType
status;
PointInfo
point,
resolution;
register char
*p;
register ssize_t
i;
size_t
length;
ssize_t
code,
y;
static FT_Outline_Funcs
OutlineMethods =
{
(FT_Outline_MoveTo_Func) TraceMoveTo,
(FT_Outline_LineTo_Func) TraceLineTo,
(FT_Outline_ConicTo_Func) TraceQuadraticBezier,
(FT_Outline_CubicTo_Func) TraceCubicBezier,
0, 0
};
unsigned char
*utf8;
/*
Initialize Truetype library.
*/
exception=(&image->exception);
ft_status=FT_Init_FreeType(&library);
if (ft_status != 0)
ThrowBinaryException(TypeError,"UnableToInitializeFreetypeLibrary",
image->filename);
args.flags=FT_OPEN_PATHNAME;
if (draw_info->font == (char *) NULL)
args.pathname=ConstantString("helvetica");
else
if (*draw_info->font != '@')
args.pathname=ConstantString(draw_info->font);
else
args.pathname=ConstantString(draw_info->font+1);
face=(FT_Face) NULL;
ft_status=FT_Open_Face(library,&args,(long) draw_info->face,&face);
if (ft_status != 0)
{
(void) FT_Done_FreeType(library);
(void) ThrowMagickException(exception,GetMagickModule(),TypeError,
"UnableToReadFont","`%s'",args.pathname);
args.pathname=DestroyString(args.pathname);
return(MagickFalse);
}
args.pathname=DestroyString(args.pathname);
if ((draw_info->metrics != (char *) NULL) &&
(IsPathAccessible(draw_info->metrics) != MagickFalse))
(void) FT_Attach_File(face,draw_info->metrics);
encoding_type=FT_ENCODING_UNICODE;
ft_status=FT_Select_Charmap(face,encoding_type);
if ((ft_status != 0) && (face->num_charmaps != 0))
ft_status=FT_Set_Charmap(face,face->charmaps[0]);
if (encoding != (const char *) NULL)
{
if (LocaleCompare(encoding,"AdobeCustom") == 0)
encoding_type=FT_ENCODING_ADOBE_CUSTOM;
if (LocaleCompare(encoding,"AdobeExpert") == 0)
encoding_type=FT_ENCODING_ADOBE_EXPERT;
if (LocaleCompare(encoding,"AdobeStandard") == 0)
encoding_type=FT_ENCODING_ADOBE_STANDARD;
if (LocaleCompare(encoding,"AppleRoman") == 0)
encoding_type=FT_ENCODING_APPLE_ROMAN;
if (LocaleCompare(encoding,"BIG5") == 0)
encoding_type=FT_ENCODING_BIG5;
#if defined(FT_ENCODING_PRC)
if (LocaleCompare(encoding,"GB2312") == 0)
encoding_type=FT_ENCODING_PRC;
#endif
#if defined(FT_ENCODING_JOHAB)
if (LocaleCompare(encoding,"Johab") == 0)
encoding_type=FT_ENCODING_JOHAB;
#endif
#if defined(FT_ENCODING_ADOBE_LATIN_1)
if (LocaleCompare(encoding,"Latin-1") == 0)
encoding_type=FT_ENCODING_ADOBE_LATIN_1;
#endif
#if defined(FT_ENCODING_ADOBE_LATIN_2)
if (LocaleCompare(encoding,"Latin-2") == 0)
encoding_type=FT_ENCODING_OLD_LATIN_2;
#endif
if (LocaleCompare(encoding,"None") == 0)
encoding_type=FT_ENCODING_NONE;
if (LocaleCompare(encoding,"SJIScode") == 0)
encoding_type=FT_ENCODING_SJIS;
if (LocaleCompare(encoding,"Symbol") == 0)
encoding_type=FT_ENCODING_MS_SYMBOL;
if (LocaleCompare(encoding,"Unicode") == 0)
encoding_type=FT_ENCODING_UNICODE;
if (LocaleCompare(encoding,"Wansung") == 0)
encoding_type=FT_ENCODING_WANSUNG;
ft_status=FT_Select_Charmap(face,encoding_type);
if (ft_status != 0)
{
(void) FT_Done_Face(face);
(void) FT_Done_FreeType(library);
ThrowBinaryException(TypeError,"UnrecognizedFontEncoding",encoding);
}
}
/*
Set text size.
*/
resolution.x=DefaultResolution;
resolution.y=DefaultResolution;
if (draw_info->density != (char *) NULL)
{
GeometryInfo
geometry_info;
MagickStatusType
flags;
flags=ParseGeometry(draw_info->density,&geometry_info);
resolution.x=geometry_info.rho;
resolution.y=geometry_info.sigma;
if ((flags & SigmaValue) == 0)
resolution.y=resolution.x;
}
ft_status=FT_Set_Char_Size(face,(FT_F26Dot6) (64.0*draw_info->pointsize),
(FT_F26Dot6) (64.0*draw_info->pointsize),(FT_UInt) resolution.x,
(FT_UInt) resolution.y);
if (ft_status != 0)
{
(void) FT_Done_Face(face);
(void) FT_Done_FreeType(library);
ThrowBinaryException(TypeError,"UnableToReadFont",draw_info->font);
}
metrics->pixels_per_em.x=face->size->metrics.x_ppem;
metrics->pixels_per_em.y=face->size->metrics.y_ppem;
metrics->ascent=(double) face->size->metrics.ascender/64.0;
metrics->descent=(double) face->size->metrics.descender/64.0;
metrics->width=0;
metrics->origin.x=0;
metrics->origin.y=0;
metrics->height=(double) face->size->metrics.height/64.0;
metrics->max_advance=0.0;
if (face->size->metrics.max_advance > MagickEpsilon)
metrics->max_advance=(double) face->size->metrics.max_advance/64.0;
metrics->bounds.x1=0.0;
metrics->bounds.y1=metrics->descent;
metrics->bounds.x2=metrics->ascent+metrics->descent;
metrics->bounds.y2=metrics->ascent+metrics->descent;
metrics->underline_position=face->underline_position/64.0;
metrics->underline_thickness=face->underline_thickness/64.0;
if ((draw_info->text == (char *) NULL) || (*draw_info->text == '\0'))
{
(void) FT_Done_Face(face);
(void) FT_Done_FreeType(library);
return(MagickTrue);
}
/*
Compute bounding box.
*/
if (image->debug != MagickFalse)
(void) LogMagickEvent(AnnotateEvent,GetMagickModule(),"Font %s; "
"font-encoding %s; text-encoding %s; pointsize %g",
draw_info->font != (char *) NULL ? draw_info->font : "none",
encoding != (char *) NULL ? encoding : "none",
draw_info->encoding != (char *) NULL ? draw_info->encoding : "none",
draw_info->pointsize);
flags=FT_LOAD_DEFAULT;
if (draw_info->render == MagickFalse)
flags=FT_LOAD_NO_BITMAP;
if (draw_info->text_antialias == MagickFalse)
flags|=FT_LOAD_TARGET_MONO;
else
{
#if defined(FT_LOAD_TARGET_LIGHT)
flags|=FT_LOAD_TARGET_LIGHT;
#elif defined(FT_LOAD_TARGET_LCD)
flags|=FT_LOAD_TARGET_LCD;
#endif
}
value=GetImageProperty(image,"type:hinting");
if ((value != (const char *) NULL) && (LocaleCompare(value,"off") == 0))
flags|=FT_LOAD_NO_HINTING;
glyph.id=0;
glyph.image=NULL;
last_glyph.id=0;
last_glyph.image=NULL;
origin.x=0;
origin.y=0;
affine.xx=65536L;
affine.yx=0L;
affine.xy=0L;
affine.yy=65536L;
if (draw_info->render != MagickFalse)
{
affine.xx=(FT_Fixed) (65536L*draw_info->affine.sx+0.5);
affine.yx=(FT_Fixed) (-65536L*draw_info->affine.rx+0.5);
affine.xy=(FT_Fixed) (-65536L*draw_info->affine.ry+0.5);
affine.yy=(FT_Fixed) (65536L*draw_info->affine.sy+0.5);
}
annotate_info=CloneDrawInfo((ImageInfo *) NULL,draw_info);
if (annotate_info->dash_pattern != (double *) NULL)
annotate_info->dash_pattern[0]=0.0;
(void) CloneString(&annotate_info->primitive,"path '");
status=MagickTrue;
if (draw_info->render != MagickFalse)
{
if (image->storage_class != DirectClass)
(void) SetImageStorageClass(image,DirectClass);
if (image->matte == MagickFalse)
(void) SetImageAlphaChannel(image,OpaqueAlphaChannel);
}
point.x=0.0;
point.y=0.0;
for (p=draw_info->text; GetUTFCode(p) != 0; p+=GetUTFOctets(p))
if (GetUTFCode(p) < 0)
break;
utf8=(unsigned char *) NULL;
if (GetUTFCode(p) == 0)
p=draw_info->text;
else
{
utf8=ConvertLatin1ToUTF8((unsigned char *) draw_info->text);
if (utf8 != (unsigned char *) NULL)
p=(char *) utf8;
}
grapheme=(GraphemeInfo *) NULL;
length=ComplexTextLayout(image,draw_info,p,strlen(p),face,flags,&grapheme);
code=0;
for (i=0; i < (ssize_t) length; i++)
{
FT_Outline
outline;
/*
Render UTF-8 sequence.
*/
glyph.id=grapheme[i].index;
if (glyph.id == 0)
glyph.id=FT_Get_Char_Index(face,' ');
if ((glyph.id != 0) && (last_glyph.id != 0))
origin.x+=(FT_Pos) (64.0*draw_info->kerning);
glyph.origin=origin;
glyph.origin.x+=grapheme[i].x_offset;
glyph.origin.y+=grapheme[i].y_offset;
glyph.image=0;
ft_status=FT_Load_Glyph(face,glyph.id,flags);
if (ft_status != 0)
continue;
ft_status=FT_Get_Glyph(face->glyph,&glyph.image);
if (ft_status != 0)
continue;
outline=((FT_OutlineGlyph) glyph.image)->outline;
ft_status=FT_Outline_Get_BBox(&outline,&bounds);
if (ft_status != 0)
continue;
if ((p == draw_info->text) || (bounds.xMin < metrics->bounds.x1))
if (bounds.xMin != 0)
metrics->bounds.x1=(double) bounds.xMin;
if ((p == draw_info->text) || (bounds.yMin < metrics->bounds.y1))
if (bounds.yMin != 0)
metrics->bounds.y1=(double) bounds.yMin;
if ((p == draw_info->text) || (bounds.xMax > metrics->bounds.x2))
if (bounds.xMax != 0)
metrics->bounds.x2=(double) bounds.xMax;
if ((p == draw_info->text) || (bounds.yMax > metrics->bounds.y2))
if (bounds.yMax != 0)
metrics->bounds.y2=(double) bounds.yMax;
if (((draw_info->stroke.opacity != TransparentOpacity) ||
(draw_info->stroke_pattern != (Image *) NULL)) &&
((status != MagickFalse) && (draw_info->render != MagickFalse)))
{
/*
Trace the glyph.
*/
annotate_info->affine.tx=glyph.origin.x/64.0;
annotate_info->affine.ty=(-glyph.origin.y/64.0);
if ((outline.n_contours > 0) && (outline.n_points > 0))
ft_status=FT_Outline_Decompose(&outline,&OutlineMethods,
annotate_info);
}
FT_Vector_Transform(&glyph.origin,&affine);
(void) FT_Glyph_Transform(glyph.image,&affine,&glyph.origin);
ft_status=FT_Glyph_To_Bitmap(&glyph.image,ft_render_mode_normal,
(FT_Vector *) NULL,MagickTrue);
if (ft_status != 0)
continue;
bitmap=(FT_BitmapGlyph) glyph.image;
point.x=offset->x+bitmap->left;
if (bitmap->bitmap.pixel_mode == ft_pixel_mode_mono)
point.x=offset->x+(origin.x >> 6);
point.y=offset->y-bitmap->top;
if (draw_info->render != MagickFalse)
{
CacheView
*image_view;
register unsigned char
*p;
MagickBooleanType
transparent_fill;
/*
Rasterize the glyph.
*/
transparent_fill=((draw_info->fill.opacity == TransparentOpacity) &&
(draw_info->fill_pattern == (Image *) NULL) &&
(draw_info->stroke.opacity == TransparentOpacity) &&
(draw_info->stroke_pattern == (Image *) NULL)) ? MagickTrue :
MagickFalse;
p=bitmap->bitmap.buffer;
image_view=AcquireAuthenticCacheView(image,exception);
for (y=0; y < (ssize_t) bitmap->bitmap.rows; y++)
{
MagickBooleanType
active,
sync;
MagickRealType
fill_opacity;
PixelPacket
fill_color;
register PixelPacket
*magick_restrict q;
register ssize_t
x;
ssize_t
n,
x_offset,
y_offset;
if (status == MagickFalse)
continue;
x_offset=(ssize_t) ceil(point.x-0.5);
y_offset=(ssize_t) ceil(point.y+y-0.5);
if ((y_offset < 0) || (y_offset >= (ssize_t) image->rows))
continue;
q=(PixelPacket *) NULL;
if ((x_offset < 0) || (x_offset >= (ssize_t) image->columns))
active=MagickFalse;
else
{
q=GetCacheViewAuthenticPixels(image_view,x_offset,y_offset,
bitmap->bitmap.width,1,exception);
active=q != (PixelPacket *) NULL ? MagickTrue : MagickFalse;
}
n=y*bitmap->bitmap.pitch-1;
for (x=0; x < (ssize_t) bitmap->bitmap.width; x++)
{
n++;
x_offset++;
if ((x_offset < 0) || (x_offset >= (ssize_t) image->columns))
{
if (q != (PixelPacket *) NULL)
q++;
continue;
}
if (bitmap->bitmap.pixel_mode != ft_pixel_mode_mono)
fill_opacity=(MagickRealType) (p[n])/(bitmap->bitmap.num_grays-1);
else
fill_opacity=((p[(x >> 3)+y*bitmap->bitmap.pitch] &
(1 << (~x & 0x07)))) == 0 ? 0.0 : 1.0;
if (draw_info->text_antialias == MagickFalse)
fill_opacity=fill_opacity >= 0.5 ? 1.0 : 0.0;
if (active == MagickFalse)
q=GetCacheViewAuthenticPixels(image_view,x_offset,y_offset,1,1,
exception);
if (q == (PixelPacket *) NULL)
continue;
if (transparent_fill == MagickFalse)
{
(void) GetFillColor(draw_info,x_offset,y_offset,&fill_color);
fill_opacity=QuantumRange-fill_opacity*(QuantumRange-
fill_color.opacity);
MagickCompositeOver(&fill_color,fill_opacity,q,q->opacity,q);
}
else
{
double
Sa,
Da;
Da=1.0-(QuantumScale*(QuantumRange-q->opacity));
Sa=fill_opacity;
fill_opacity=(1.0-RoundToUnity(Sa+Da-Sa*Da))*QuantumRange;
SetPixelAlpha(q,fill_opacity);
}
if (active == MagickFalse)
{
sync=SyncCacheViewAuthenticPixels(image_view,exception);
if (sync == MagickFalse)
status=MagickFalse;
}
q++;
}
sync=SyncCacheViewAuthenticPixels(image_view,exception);
if (sync == MagickFalse)
status=MagickFalse;
}
image_view=DestroyCacheView(image_view);
if (((draw_info->stroke.opacity != TransparentOpacity) ||
(draw_info->stroke_pattern != (Image *) NULL)) &&
(status != MagickFalse))
{
/*
Draw text stroke.
*/
annotate_info->linejoin=RoundJoin;
annotate_info->affine.tx=offset->x;
annotate_info->affine.ty=offset->y;
(void) ConcatenateString(&annotate_info->primitive,"'");
if (strlen(annotate_info->primitive) > 7)
(void) DrawImage(image,annotate_info);
(void) CloneString(&annotate_info->primitive,"path '");
}
}
if ((fabs(draw_info->interword_spacing) >= MagickEpsilon) &&
(IsUTFSpace(GetUTFCode(p+grapheme[i].cluster)) != MagickFalse) &&
(IsUTFSpace(code) == MagickFalse))
origin.x+=(FT_Pos) (64.0*draw_info->interword_spacing);
else
origin.x+=(FT_Pos) grapheme[i].x_advance;
metrics->origin.x=(double) origin.x;
metrics->origin.y=(double) origin.y;
if (metrics->origin.x > metrics->width)
metrics->width=metrics->origin.x;
if (last_glyph.image != 0)
{
FT_Done_Glyph(last_glyph.image);
last_glyph.image=0;
}
last_glyph=glyph;
code=GetUTFCode(p+grapheme[i].cluster);
}
if (grapheme != (GraphemeInfo *) NULL)
grapheme=(GraphemeInfo *) RelinquishMagickMemory(grapheme);
if (utf8 != (unsigned char *) NULL)
utf8=(unsigned char *) RelinquishMagickMemory(utf8);
if (glyph.image != 0)
{
FT_Done_Glyph(glyph.image);
glyph.image=0;
}
/*
Determine font metrics.
*/
metrics->bounds.x1/=64.0;
metrics->bounds.y1/=64.0;
metrics->bounds.x2/=64.0;
metrics->bounds.y2/=64.0;
metrics->origin.x/=64.0;
metrics->origin.y/=64.0;
metrics->width/=64.0;
/*
Relinquish resources.
*/
annotate_info=DestroyDrawInfo(annotate_info);
(void) FT_Done_Face(face);
(void) FT_Done_FreeType(library);
return(status);
}
#else
static MagickBooleanType RenderFreetype(Image *image,const DrawInfo *draw_info,
const char *magick_unused(encoding),const PointInfo *offset,
TypeMetric *metrics)
{
(void) ThrowMagickException(&image->exception,GetMagickModule(),
MissingDelegateWarning,"DelegateLibrarySupportNotBuiltIn","`%s' (Freetype)",
draw_info->font != (char *) NULL ? draw_info->font : "none");
return(RenderPostscript(image,draw_info,offset,metrics));
}
#endif
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ R e n d e r P o s t s c r i p t %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% RenderPostscript() renders text on the image with a Postscript font. It
% also returns the bounding box of the text relative to the image.
%
% The format of the RenderPostscript method is:
%
% MagickBooleanType RenderPostscript(Image *image,DrawInfo *draw_info,
% const PointInfo *offset,TypeMetric *metrics)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o draw_info: the draw info.
%
% o offset: (x,y) location of text relative to image.
%
% o metrics: bounding box of text.
%
*/
static char *EscapeParenthesis(const char *source)
{
char
*destination;
register char
*q;
register const char
*p;
size_t
length;
assert(source != (const char *) NULL);
length=0;
for (p=source; *p != '\0'; p++)
{
if ((*p == '\\') || (*p == '(') || (*p == ')'))
{
if (~length < 1)
ThrowFatalException(ResourceLimitFatalError,"UnableToEscapeString");
length++;
}
length++;
}
destination=(char *) NULL;
if (~length >= (MaxTextExtent-1))
destination=(char *) AcquireQuantumMemory(length+MaxTextExtent,
sizeof(*destination));
if (destination == (char *) NULL)
ThrowFatalException(ResourceLimitFatalError,"UnableToEscapeString");
*destination='\0';
q=destination;
for (p=source; *p != '\0'; p++)
{
if ((*p == '\\') || (*p == '(') || (*p == ')'))
*q++='\\';
*q++=(*p);
}
*q='\0';
return(destination);
}
static MagickBooleanType RenderPostscript(Image *image,
const DrawInfo *draw_info,const PointInfo *offset,TypeMetric *metrics)
{
char
filename[MaxTextExtent],
geometry[MaxTextExtent],
*text;
FILE
*file;
Image
*annotate_image;
ImageInfo
*annotate_info;
int
unique_file;
MagickBooleanType
identity;
PointInfo
extent,
point,
resolution;
register ssize_t
i;
size_t
length;
ssize_t
y;
/*
Render label with a Postscript font.
*/
if (image->debug != MagickFalse)
(void) LogMagickEvent(AnnotateEvent,GetMagickModule(),
"Font %s; pointsize %g",draw_info->font != (char *) NULL ?
draw_info->font : "none",draw_info->pointsize);
file=(FILE *) NULL;
unique_file=AcquireUniqueFileResource(filename);
if (unique_file != -1)
file=fdopen(unique_file,"wb");
if ((unique_file == -1) || (file == (FILE *) NULL))
{
ThrowFileException(&image->exception,FileOpenError,"UnableToOpenFile",
filename);
return(MagickFalse);
}
(void) FormatLocaleFile(file,"%%!PS-Adobe-3.0\n");
(void) FormatLocaleFile(file,"/ReencodeType\n");
(void) FormatLocaleFile(file,"{\n");
(void) FormatLocaleFile(file," findfont dup length\n");
(void) FormatLocaleFile(file,
" dict begin { 1 index /FID ne {def} {pop pop} ifelse } forall\n");
(void) FormatLocaleFile(file,
" /Encoding ISOLatin1Encoding def currentdict end definefont pop\n");
(void) FormatLocaleFile(file,"} bind def\n");
/*
Sample to compute bounding box.
*/
identity=(fabs(draw_info->affine.sx-draw_info->affine.sy) < MagickEpsilon) &&
(fabs(draw_info->affine.rx) < MagickEpsilon) &&
(fabs(draw_info->affine.ry) < MagickEpsilon) ? MagickTrue : MagickFalse;
extent.x=0.0;
extent.y=0.0;
length=strlen(draw_info->text);
for (i=0; i <= (ssize_t) (length+2); i++)
{
point.x=fabs(draw_info->affine.sx*i*draw_info->pointsize+
draw_info->affine.ry*2.0*draw_info->pointsize);
point.y=fabs(draw_info->affine.rx*i*draw_info->pointsize+
draw_info->affine.sy*2.0*draw_info->pointsize);
if (point.x > extent.x)
extent.x=point.x;
if (point.y > extent.y)
extent.y=point.y;
}
(void) FormatLocaleFile(file,"%g %g moveto\n",identity != MagickFalse ? 0.0 :
extent.x/2.0,extent.y/2.0);
(void) FormatLocaleFile(file,"%g %g scale\n",draw_info->pointsize,
draw_info->pointsize);
if ((draw_info->font == (char *) NULL) || (*draw_info->font == '\0') ||
(strchr(draw_info->font,'/') != (char *) NULL))
(void) FormatLocaleFile(file,
"/Times-Roman-ISO dup /Times-Roman ReencodeType findfont setfont\n");
else
(void) FormatLocaleFile(file,
"/%s-ISO dup /%s ReencodeType findfont setfont\n",draw_info->font,
draw_info->font);
(void) FormatLocaleFile(file,"[%g %g %g %g 0 0] concat\n",
draw_info->affine.sx,-draw_info->affine.rx,-draw_info->affine.ry,
draw_info->affine.sy);
text=EscapeParenthesis(draw_info->text);
if (identity == MagickFalse)
(void) FormatLocaleFile(file,"(%s) stringwidth pop -0.5 mul -0.5 rmoveto\n",
text);
(void) FormatLocaleFile(file,"(%s) show\n",text);
text=DestroyString(text);
(void) FormatLocaleFile(file,"showpage\n");
(void) fclose(file);
(void) FormatLocaleString(geometry,MaxTextExtent,"%.20gx%.20g+0+0!",
floor(extent.x+0.5),floor(extent.y+0.5));
annotate_info=AcquireImageInfo();
(void) FormatLocaleString(annotate_info->filename,MaxTextExtent,"ps:%s",
filename);
(void) CloneString(&annotate_info->page,geometry);
if (draw_info->density != (char *) NULL)
(void) CloneString(&annotate_info->density,draw_info->density);
annotate_info->antialias=draw_info->text_antialias;
annotate_image=ReadImage(annotate_info,&image->exception);
CatchException(&image->exception);
annotate_info=DestroyImageInfo(annotate_info);
(void) RelinquishUniqueFileResource(filename);
if (annotate_image == (Image *) NULL)
return(MagickFalse);
resolution.x=DefaultResolution;
resolution.y=DefaultResolution;
if (draw_info->density != (char *) NULL)
{
GeometryInfo
geometry_info;
MagickStatusType
flags;
flags=ParseGeometry(draw_info->density,&geometry_info);
resolution.x=geometry_info.rho;
resolution.y=geometry_info.sigma;
if ((flags & SigmaValue) == 0)
resolution.y=resolution.x;
}
if (identity == MagickFalse)
(void) TransformImage(&annotate_image,"0x0",(char *) NULL);
else
{
RectangleInfo
crop_info;
crop_info=GetImageBoundingBox(annotate_image,&annotate_image->exception);
crop_info.height=(size_t) ((resolution.y/DefaultResolution)*
ExpandAffine(&draw_info->affine)*draw_info->pointsize+0.5);
crop_info.y=(ssize_t) ceil((resolution.y/DefaultResolution)*extent.y/8.0-
0.5);
(void) FormatLocaleString(geometry,MaxTextExtent,
"%.20gx%.20g%+.20g%+.20g",(double) crop_info.width,(double)
crop_info.height,(double) crop_info.x,(double) crop_info.y);
(void) TransformImage(&annotate_image,geometry,(char *) NULL);
}
metrics->pixels_per_em.x=(resolution.y/DefaultResolution)*
ExpandAffine(&draw_info->affine)*draw_info->pointsize;
metrics->pixels_per_em.y=metrics->pixels_per_em.x;
metrics->ascent=metrics->pixels_per_em.x;
metrics->descent=metrics->pixels_per_em.y/-5.0;
metrics->width=(double) annotate_image->columns/
ExpandAffine(&draw_info->affine);
metrics->height=1.152*metrics->pixels_per_em.x;
metrics->max_advance=metrics->pixels_per_em.x;
metrics->bounds.x1=0.0;
metrics->bounds.y1=metrics->descent;
metrics->bounds.x2=metrics->ascent+metrics->descent;
metrics->bounds.y2=metrics->ascent+metrics->descent;
metrics->underline_position=(-2.0);
metrics->underline_thickness=1.0;
if (draw_info->render == MagickFalse)
{
annotate_image=DestroyImage(annotate_image);
return(MagickTrue);
}
if (draw_info->fill.opacity != TransparentOpacity)
{
ExceptionInfo
*exception;
MagickBooleanType
sync;
PixelPacket
fill_color;
CacheView
*annotate_view;
/*
Render fill color.
*/
if (image->matte == MagickFalse)
(void) SetImageAlphaChannel(image,OpaqueAlphaChannel);
if (annotate_image->matte == MagickFalse)
(void) SetImageAlphaChannel(annotate_image,OpaqueAlphaChannel);
fill_color=draw_info->fill;
exception=(&image->exception);
annotate_view=AcquireAuthenticCacheView(annotate_image,exception);
for (y=0; y < (ssize_t) annotate_image->rows; y++)
{
register ssize_t
x;
register PixelPacket
*magick_restrict q;
q=GetCacheViewAuthenticPixels(annotate_view,0,y,annotate_image->columns,
1,exception);
if (q == (PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) annotate_image->columns; x++)
{
(void) GetFillColor(draw_info,x,y,&fill_color);
SetPixelAlpha(q,ClampToQuantum((((QuantumRange-GetPixelIntensity(
annotate_image,q))*(QuantumRange-fill_color.opacity))/
QuantumRange)));
SetPixelRed(q,fill_color.red);
SetPixelGreen(q,fill_color.green);
SetPixelBlue(q,fill_color.blue);
q++;
}
sync=SyncCacheViewAuthenticPixels(annotate_view,exception);
if (sync == MagickFalse)
break;
}
annotate_view=DestroyCacheView(annotate_view);
(void) CompositeImage(image,OverCompositeOp,annotate_image,
(ssize_t) ceil(offset->x-0.5),(ssize_t) ceil(offset->y-(metrics->ascent+
metrics->descent)-0.5));
}
annotate_image=DestroyImage(annotate_image);
return(MagickTrue);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ R e n d e r X 1 1 %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% RenderX11() renders text on the image with an X11 font. It also returns the
% bounding box of the text relative to the image.
%
% The format of the RenderX11 method is:
%
% MagickBooleanType RenderX11(Image *image,DrawInfo *draw_info,
% const PointInfo *offset,TypeMetric *metrics)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o draw_info: the draw info.
%
% o offset: (x,y) location of text relative to image.
%
% o metrics: bounding box of text.
%
*/
static MagickBooleanType RenderX11(Image *image,const DrawInfo *draw_info,
const PointInfo *offset,TypeMetric *metrics)
{
MagickBooleanType
status;
if (annotate_semaphore == (SemaphoreInfo *) NULL)
ActivateSemaphoreInfo(&annotate_semaphore);
LockSemaphoreInfo(annotate_semaphore);
status=XRenderImage(image,draw_info,offset,metrics);
UnlockSemaphoreInfo(annotate_semaphore);
return(status);
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/good_950_0 |
crossvul-cpp_data_good_2910_0 | /*
* (Tentative) USB Audio Driver for ALSA
*
* Copyright (c) 2002 by Takashi Iwai <tiwai@suse.de>
*
* Many codes borrowed from audio.c by
* Alan Cox (alan@lxorguk.ukuu.org.uk)
* Thomas Sailer (sailer@ife.ee.ethz.ch)
*
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*
* NOTES:
*
* - the linked URBs would be preferred but not used so far because of
* the instability of unlinking.
* - type II is not supported properly. there is no device which supports
* this type *correctly*. SB extigy looks as if it supports, but it's
* indeed an AC3 stream packed in SPDIF frames (i.e. no real AC3 stream).
*/
#include <linux/bitops.h>
#include <linux/init.h>
#include <linux/list.h>
#include <linux/slab.h>
#include <linux/string.h>
#include <linux/ctype.h>
#include <linux/usb.h>
#include <linux/moduleparam.h>
#include <linux/mutex.h>
#include <linux/usb/audio.h>
#include <linux/usb/audio-v2.h>
#include <linux/module.h>
#include <sound/control.h>
#include <sound/core.h>
#include <sound/info.h>
#include <sound/pcm.h>
#include <sound/pcm_params.h>
#include <sound/initval.h>
#include "usbaudio.h"
#include "card.h"
#include "midi.h"
#include "mixer.h"
#include "proc.h"
#include "quirks.h"
#include "endpoint.h"
#include "helper.h"
#include "debug.h"
#include "pcm.h"
#include "format.h"
#include "power.h"
#include "stream.h"
MODULE_AUTHOR("Takashi Iwai <tiwai@suse.de>");
MODULE_DESCRIPTION("USB Audio");
MODULE_LICENSE("GPL");
MODULE_SUPPORTED_DEVICE("{{Generic,USB Audio}}");
static int index[SNDRV_CARDS] = SNDRV_DEFAULT_IDX; /* Index 0-MAX */
static char *id[SNDRV_CARDS] = SNDRV_DEFAULT_STR; /* ID for this card */
static bool enable[SNDRV_CARDS] = SNDRV_DEFAULT_ENABLE_PNP;/* Enable this card */
/* Vendor/product IDs for this card */
static int vid[SNDRV_CARDS] = { [0 ... (SNDRV_CARDS-1)] = -1 };
static int pid[SNDRV_CARDS] = { [0 ... (SNDRV_CARDS-1)] = -1 };
static int device_setup[SNDRV_CARDS]; /* device parameter for this card */
static bool ignore_ctl_error;
static bool autoclock = true;
static char *quirk_alias[SNDRV_CARDS];
module_param_array(index, int, NULL, 0444);
MODULE_PARM_DESC(index, "Index value for the USB audio adapter.");
module_param_array(id, charp, NULL, 0444);
MODULE_PARM_DESC(id, "ID string for the USB audio adapter.");
module_param_array(enable, bool, NULL, 0444);
MODULE_PARM_DESC(enable, "Enable USB audio adapter.");
module_param_array(vid, int, NULL, 0444);
MODULE_PARM_DESC(vid, "Vendor ID for the USB audio device.");
module_param_array(pid, int, NULL, 0444);
MODULE_PARM_DESC(pid, "Product ID for the USB audio device.");
module_param_array(device_setup, int, NULL, 0444);
MODULE_PARM_DESC(device_setup, "Specific device setup (if needed).");
module_param(ignore_ctl_error, bool, 0444);
MODULE_PARM_DESC(ignore_ctl_error,
"Ignore errors from USB controller for mixer interfaces.");
module_param(autoclock, bool, 0444);
MODULE_PARM_DESC(autoclock, "Enable auto-clock selection for UAC2 devices (default: yes).");
module_param_array(quirk_alias, charp, NULL, 0444);
MODULE_PARM_DESC(quirk_alias, "Quirk aliases, e.g. 0123abcd:5678beef.");
/*
* we keep the snd_usb_audio_t instances by ourselves for merging
* the all interfaces on the same card as one sound device.
*/
static DEFINE_MUTEX(register_mutex);
static struct snd_usb_audio *usb_chip[SNDRV_CARDS];
static struct usb_driver usb_audio_driver;
/*
* disconnect streams
* called from usb_audio_disconnect()
*/
static void snd_usb_stream_disconnect(struct snd_usb_stream *as)
{
int idx;
struct snd_usb_substream *subs;
for (idx = 0; idx < 2; idx++) {
subs = &as->substream[idx];
if (!subs->num_formats)
continue;
subs->interface = -1;
subs->data_endpoint = NULL;
subs->sync_endpoint = NULL;
}
}
static int snd_usb_create_stream(struct snd_usb_audio *chip, int ctrlif, int interface)
{
struct usb_device *dev = chip->dev;
struct usb_host_interface *alts;
struct usb_interface_descriptor *altsd;
struct usb_interface *iface = usb_ifnum_to_if(dev, interface);
if (!iface) {
dev_err(&dev->dev, "%u:%d : does not exist\n",
ctrlif, interface);
return -EINVAL;
}
alts = &iface->altsetting[0];
altsd = get_iface_desc(alts);
/*
* Android with both accessory and audio interfaces enabled gets the
* interface numbers wrong.
*/
if ((chip->usb_id == USB_ID(0x18d1, 0x2d04) ||
chip->usb_id == USB_ID(0x18d1, 0x2d05)) &&
interface == 0 &&
altsd->bInterfaceClass == USB_CLASS_VENDOR_SPEC &&
altsd->bInterfaceSubClass == USB_SUBCLASS_VENDOR_SPEC) {
interface = 2;
iface = usb_ifnum_to_if(dev, interface);
if (!iface)
return -EINVAL;
alts = &iface->altsetting[0];
altsd = get_iface_desc(alts);
}
if (usb_interface_claimed(iface)) {
dev_dbg(&dev->dev, "%d:%d: skipping, already claimed\n",
ctrlif, interface);
return -EINVAL;
}
if ((altsd->bInterfaceClass == USB_CLASS_AUDIO ||
altsd->bInterfaceClass == USB_CLASS_VENDOR_SPEC) &&
altsd->bInterfaceSubClass == USB_SUBCLASS_MIDISTREAMING) {
int err = __snd_usbmidi_create(chip->card, iface,
&chip->midi_list, NULL,
chip->usb_id);
if (err < 0) {
dev_err(&dev->dev,
"%u:%d: cannot create sequencer device\n",
ctrlif, interface);
return -EINVAL;
}
usb_driver_claim_interface(&usb_audio_driver, iface, (void *)-1L);
return 0;
}
if ((altsd->bInterfaceClass != USB_CLASS_AUDIO &&
altsd->bInterfaceClass != USB_CLASS_VENDOR_SPEC) ||
altsd->bInterfaceSubClass != USB_SUBCLASS_AUDIOSTREAMING) {
dev_dbg(&dev->dev,
"%u:%d: skipping non-supported interface %d\n",
ctrlif, interface, altsd->bInterfaceClass);
/* skip non-supported classes */
return -EINVAL;
}
if (snd_usb_get_speed(dev) == USB_SPEED_LOW) {
dev_err(&dev->dev, "low speed audio streaming not supported\n");
return -EINVAL;
}
if (! snd_usb_parse_audio_interface(chip, interface)) {
usb_set_interface(dev, interface, 0); /* reset the current interface */
usb_driver_claim_interface(&usb_audio_driver, iface, (void *)-1L);
}
return 0;
}
/*
* parse audio control descriptor and create pcm/midi streams
*/
static int snd_usb_create_streams(struct snd_usb_audio *chip, int ctrlif)
{
struct usb_device *dev = chip->dev;
struct usb_host_interface *host_iface;
struct usb_interface_descriptor *altsd;
void *control_header;
int i, protocol;
int rest_bytes;
/* find audiocontrol interface */
host_iface = &usb_ifnum_to_if(dev, ctrlif)->altsetting[0];
control_header = snd_usb_find_csint_desc(host_iface->extra,
host_iface->extralen,
NULL, UAC_HEADER);
altsd = get_iface_desc(host_iface);
protocol = altsd->bInterfaceProtocol;
if (!control_header) {
dev_err(&dev->dev, "cannot find UAC_HEADER\n");
return -EINVAL;
}
rest_bytes = (void *)(host_iface->extra + host_iface->extralen) -
control_header;
/* just to be sure -- this shouldn't hit at all */
if (rest_bytes <= 0) {
dev_err(&dev->dev, "invalid control header\n");
return -EINVAL;
}
switch (protocol) {
default:
dev_warn(&dev->dev,
"unknown interface protocol %#02x, assuming v1\n",
protocol);
/* fall through */
case UAC_VERSION_1: {
struct uac1_ac_header_descriptor *h1 = control_header;
if (rest_bytes < sizeof(*h1)) {
dev_err(&dev->dev, "too short v1 buffer descriptor\n");
return -EINVAL;
}
if (!h1->bInCollection) {
dev_info(&dev->dev, "skipping empty audio interface (v1)\n");
return -EINVAL;
}
if (rest_bytes < h1->bLength) {
dev_err(&dev->dev, "invalid buffer length (v1)\n");
return -EINVAL;
}
if (h1->bLength < sizeof(*h1) + h1->bInCollection) {
dev_err(&dev->dev, "invalid UAC_HEADER (v1)\n");
return -EINVAL;
}
for (i = 0; i < h1->bInCollection; i++)
snd_usb_create_stream(chip, ctrlif, h1->baInterfaceNr[i]);
break;
}
case UAC_VERSION_2: {
struct usb_interface_assoc_descriptor *assoc =
usb_ifnum_to_if(dev, ctrlif)->intf_assoc;
if (!assoc) {
/*
* Firmware writers cannot count to three. So to find
* the IAD on the NuForce UDH-100, also check the next
* interface.
*/
struct usb_interface *iface =
usb_ifnum_to_if(dev, ctrlif + 1);
if (iface &&
iface->intf_assoc &&
iface->intf_assoc->bFunctionClass == USB_CLASS_AUDIO &&
iface->intf_assoc->bFunctionProtocol == UAC_VERSION_2)
assoc = iface->intf_assoc;
}
if (!assoc) {
dev_err(&dev->dev, "Audio class v2 interfaces need an interface association\n");
return -EINVAL;
}
for (i = 0; i < assoc->bInterfaceCount; i++) {
int intf = assoc->bFirstInterface + i;
if (intf != ctrlif)
snd_usb_create_stream(chip, ctrlif, intf);
}
break;
}
}
return 0;
}
/*
* free the chip instance
*
* here we have to do not much, since pcm and controls are already freed
*
*/
static int snd_usb_audio_free(struct snd_usb_audio *chip)
{
struct snd_usb_endpoint *ep, *n;
list_for_each_entry_safe(ep, n, &chip->ep_list, list)
snd_usb_endpoint_free(ep);
mutex_destroy(&chip->mutex);
if (!atomic_read(&chip->shutdown))
dev_set_drvdata(&chip->dev->dev, NULL);
kfree(chip);
return 0;
}
static int snd_usb_audio_dev_free(struct snd_device *device)
{
struct snd_usb_audio *chip = device->device_data;
return snd_usb_audio_free(chip);
}
/*
* create a chip instance and set its names.
*/
static int snd_usb_audio_create(struct usb_interface *intf,
struct usb_device *dev, int idx,
const struct snd_usb_audio_quirk *quirk,
unsigned int usb_id,
struct snd_usb_audio **rchip)
{
struct snd_card *card;
struct snd_usb_audio *chip;
int err, len;
char component[14];
static struct snd_device_ops ops = {
.dev_free = snd_usb_audio_dev_free,
};
*rchip = NULL;
switch (snd_usb_get_speed(dev)) {
case USB_SPEED_LOW:
case USB_SPEED_FULL:
case USB_SPEED_HIGH:
case USB_SPEED_WIRELESS:
case USB_SPEED_SUPER:
case USB_SPEED_SUPER_PLUS:
break;
default:
dev_err(&dev->dev, "unknown device speed %d\n", snd_usb_get_speed(dev));
return -ENXIO;
}
err = snd_card_new(&intf->dev, index[idx], id[idx], THIS_MODULE,
0, &card);
if (err < 0) {
dev_err(&dev->dev, "cannot create card instance %d\n", idx);
return err;
}
chip = kzalloc(sizeof(*chip), GFP_KERNEL);
if (! chip) {
snd_card_free(card);
return -ENOMEM;
}
mutex_init(&chip->mutex);
init_waitqueue_head(&chip->shutdown_wait);
chip->index = idx;
chip->dev = dev;
chip->card = card;
chip->setup = device_setup[idx];
chip->autoclock = autoclock;
atomic_set(&chip->active, 1); /* avoid autopm during probing */
atomic_set(&chip->usage_count, 0);
atomic_set(&chip->shutdown, 0);
chip->usb_id = usb_id;
INIT_LIST_HEAD(&chip->pcm_list);
INIT_LIST_HEAD(&chip->ep_list);
INIT_LIST_HEAD(&chip->midi_list);
INIT_LIST_HEAD(&chip->mixer_list);
if ((err = snd_device_new(card, SNDRV_DEV_LOWLEVEL, chip, &ops)) < 0) {
snd_usb_audio_free(chip);
snd_card_free(card);
return err;
}
strcpy(card->driver, "USB-Audio");
sprintf(component, "USB%04x:%04x",
USB_ID_VENDOR(chip->usb_id), USB_ID_PRODUCT(chip->usb_id));
snd_component_add(card, component);
/* retrieve the device string as shortname */
if (quirk && quirk->product_name && *quirk->product_name) {
strlcpy(card->shortname, quirk->product_name, sizeof(card->shortname));
} else {
if (!dev->descriptor.iProduct ||
usb_string(dev, dev->descriptor.iProduct,
card->shortname, sizeof(card->shortname)) <= 0) {
/* no name available from anywhere, so use ID */
sprintf(card->shortname, "USB Device %#04x:%#04x",
USB_ID_VENDOR(chip->usb_id),
USB_ID_PRODUCT(chip->usb_id));
}
}
strim(card->shortname);
/* retrieve the vendor and device strings as longname */
if (quirk && quirk->vendor_name && *quirk->vendor_name) {
len = strlcpy(card->longname, quirk->vendor_name, sizeof(card->longname));
} else {
if (dev->descriptor.iManufacturer)
len = usb_string(dev, dev->descriptor.iManufacturer,
card->longname, sizeof(card->longname));
else
len = 0;
/* we don't really care if there isn't any vendor string */
}
if (len > 0) {
strim(card->longname);
if (*card->longname)
strlcat(card->longname, " ", sizeof(card->longname));
}
strlcat(card->longname, card->shortname, sizeof(card->longname));
len = strlcat(card->longname, " at ", sizeof(card->longname));
if (len < sizeof(card->longname))
usb_make_path(dev, card->longname + len, sizeof(card->longname) - len);
switch (snd_usb_get_speed(dev)) {
case USB_SPEED_LOW:
strlcat(card->longname, ", low speed", sizeof(card->longname));
break;
case USB_SPEED_FULL:
strlcat(card->longname, ", full speed", sizeof(card->longname));
break;
case USB_SPEED_HIGH:
strlcat(card->longname, ", high speed", sizeof(card->longname));
break;
case USB_SPEED_SUPER:
strlcat(card->longname, ", super speed", sizeof(card->longname));
break;
case USB_SPEED_SUPER_PLUS:
strlcat(card->longname, ", super speed plus", sizeof(card->longname));
break;
default:
break;
}
snd_usb_audio_create_proc(chip);
*rchip = chip;
return 0;
}
/* look for a matching quirk alias id */
static bool get_alias_id(struct usb_device *dev, unsigned int *id)
{
int i;
unsigned int src, dst;
for (i = 0; i < ARRAY_SIZE(quirk_alias); i++) {
if (!quirk_alias[i] ||
sscanf(quirk_alias[i], "%x:%x", &src, &dst) != 2 ||
src != *id)
continue;
dev_info(&dev->dev,
"device (%04x:%04x): applying quirk alias %04x:%04x\n",
USB_ID_VENDOR(*id), USB_ID_PRODUCT(*id),
USB_ID_VENDOR(dst), USB_ID_PRODUCT(dst));
*id = dst;
return true;
}
return false;
}
static const struct usb_device_id usb_audio_ids[]; /* defined below */
/* look for the corresponding quirk */
static const struct snd_usb_audio_quirk *
get_alias_quirk(struct usb_device *dev, unsigned int id)
{
const struct usb_device_id *p;
for (p = usb_audio_ids; p->match_flags; p++) {
/* FIXME: this checks only vendor:product pair in the list */
if ((p->match_flags & USB_DEVICE_ID_MATCH_DEVICE) ==
USB_DEVICE_ID_MATCH_DEVICE &&
p->idVendor == USB_ID_VENDOR(id) &&
p->idProduct == USB_ID_PRODUCT(id))
return (const struct snd_usb_audio_quirk *)p->driver_info;
}
return NULL;
}
/*
* probe the active usb device
*
* note that this can be called multiple times per a device, when it
* includes multiple audio control interfaces.
*
* thus we check the usb device pointer and creates the card instance
* only at the first time. the successive calls of this function will
* append the pcm interface to the corresponding card.
*/
static int usb_audio_probe(struct usb_interface *intf,
const struct usb_device_id *usb_id)
{
struct usb_device *dev = interface_to_usbdev(intf);
const struct snd_usb_audio_quirk *quirk =
(const struct snd_usb_audio_quirk *)usb_id->driver_info;
struct snd_usb_audio *chip;
int i, err;
struct usb_host_interface *alts;
int ifnum;
u32 id;
alts = &intf->altsetting[0];
ifnum = get_iface_desc(alts)->bInterfaceNumber;
id = USB_ID(le16_to_cpu(dev->descriptor.idVendor),
le16_to_cpu(dev->descriptor.idProduct));
if (get_alias_id(dev, &id))
quirk = get_alias_quirk(dev, id);
if (quirk && quirk->ifnum >= 0 && ifnum != quirk->ifnum)
return -ENXIO;
err = snd_usb_apply_boot_quirk(dev, intf, quirk, id);
if (err < 0)
return err;
/*
* found a config. now register to ALSA
*/
/* check whether it's already registered */
chip = NULL;
mutex_lock(®ister_mutex);
for (i = 0; i < SNDRV_CARDS; i++) {
if (usb_chip[i] && usb_chip[i]->dev == dev) {
if (atomic_read(&usb_chip[i]->shutdown)) {
dev_err(&dev->dev, "USB device is in the shutdown state, cannot create a card instance\n");
err = -EIO;
goto __error;
}
chip = usb_chip[i];
atomic_inc(&chip->active); /* avoid autopm */
break;
}
}
if (! chip) {
/* it's a fresh one.
* now look for an empty slot and create a new card instance
*/
for (i = 0; i < SNDRV_CARDS; i++)
if (enable[i] && ! usb_chip[i] &&
(vid[i] == -1 || vid[i] == USB_ID_VENDOR(id)) &&
(pid[i] == -1 || pid[i] == USB_ID_PRODUCT(id))) {
err = snd_usb_audio_create(intf, dev, i, quirk,
id, &chip);
if (err < 0)
goto __error;
chip->pm_intf = intf;
break;
}
if (!chip) {
dev_err(&dev->dev, "no available usb audio device\n");
err = -ENODEV;
goto __error;
}
}
dev_set_drvdata(&dev->dev, chip);
/*
* For devices with more than one control interface, we assume the
* first contains the audio controls. We might need a more specific
* check here in the future.
*/
if (!chip->ctrl_intf)
chip->ctrl_intf = alts;
chip->txfr_quirk = 0;
err = 1; /* continue */
if (quirk && quirk->ifnum != QUIRK_NO_INTERFACE) {
/* need some special handlings */
err = snd_usb_create_quirk(chip, intf, &usb_audio_driver, quirk);
if (err < 0)
goto __error;
}
if (err > 0) {
/* create normal USB audio interfaces */
err = snd_usb_create_streams(chip, ifnum);
if (err < 0)
goto __error;
err = snd_usb_create_mixer(chip, ifnum, ignore_ctl_error);
if (err < 0)
goto __error;
}
/* we are allowed to call snd_card_register() many times */
err = snd_card_register(chip->card);
if (err < 0)
goto __error;
usb_chip[chip->index] = chip;
chip->num_interfaces++;
usb_set_intfdata(intf, chip);
atomic_dec(&chip->active);
mutex_unlock(®ister_mutex);
return 0;
__error:
if (chip) {
if (!chip->num_interfaces)
snd_card_free(chip->card);
atomic_dec(&chip->active);
}
mutex_unlock(®ister_mutex);
return err;
}
/*
* we need to take care of counter, since disconnection can be called also
* many times as well as usb_audio_probe().
*/
static void usb_audio_disconnect(struct usb_interface *intf)
{
struct snd_usb_audio *chip = usb_get_intfdata(intf);
struct snd_card *card;
struct list_head *p;
if (chip == (void *)-1L)
return;
card = chip->card;
mutex_lock(®ister_mutex);
if (atomic_inc_return(&chip->shutdown) == 1) {
struct snd_usb_stream *as;
struct snd_usb_endpoint *ep;
struct usb_mixer_interface *mixer;
/* wait until all pending tasks done;
* they are protected by snd_usb_lock_shutdown()
*/
wait_event(chip->shutdown_wait,
!atomic_read(&chip->usage_count));
snd_card_disconnect(card);
/* release the pcm resources */
list_for_each_entry(as, &chip->pcm_list, list) {
snd_usb_stream_disconnect(as);
}
/* release the endpoint resources */
list_for_each_entry(ep, &chip->ep_list, list) {
snd_usb_endpoint_release(ep);
}
/* release the midi resources */
list_for_each(p, &chip->midi_list) {
snd_usbmidi_disconnect(p);
}
/* release mixer resources */
list_for_each_entry(mixer, &chip->mixer_list, list) {
snd_usb_mixer_disconnect(mixer);
}
}
chip->num_interfaces--;
if (chip->num_interfaces <= 0) {
usb_chip[chip->index] = NULL;
mutex_unlock(®ister_mutex);
snd_card_free_when_closed(card);
} else {
mutex_unlock(®ister_mutex);
}
}
/* lock the shutdown (disconnect) task and autoresume */
int snd_usb_lock_shutdown(struct snd_usb_audio *chip)
{
int err;
atomic_inc(&chip->usage_count);
if (atomic_read(&chip->shutdown)) {
err = -EIO;
goto error;
}
err = snd_usb_autoresume(chip);
if (err < 0)
goto error;
return 0;
error:
if (atomic_dec_and_test(&chip->usage_count))
wake_up(&chip->shutdown_wait);
return err;
}
/* autosuspend and unlock the shutdown */
void snd_usb_unlock_shutdown(struct snd_usb_audio *chip)
{
snd_usb_autosuspend(chip);
if (atomic_dec_and_test(&chip->usage_count))
wake_up(&chip->shutdown_wait);
}
#ifdef CONFIG_PM
int snd_usb_autoresume(struct snd_usb_audio *chip)
{
if (atomic_read(&chip->shutdown))
return -EIO;
if (atomic_inc_return(&chip->active) == 1)
return usb_autopm_get_interface(chip->pm_intf);
return 0;
}
void snd_usb_autosuspend(struct snd_usb_audio *chip)
{
if (atomic_read(&chip->shutdown))
return;
if (atomic_dec_and_test(&chip->active))
usb_autopm_put_interface(chip->pm_intf);
}
static int usb_audio_suspend(struct usb_interface *intf, pm_message_t message)
{
struct snd_usb_audio *chip = usb_get_intfdata(intf);
struct snd_usb_stream *as;
struct usb_mixer_interface *mixer;
struct list_head *p;
if (chip == (void *)-1L)
return 0;
chip->autosuspended = !!PMSG_IS_AUTO(message);
if (!chip->autosuspended)
snd_power_change_state(chip->card, SNDRV_CTL_POWER_D3hot);
if (!chip->num_suspended_intf++) {
list_for_each_entry(as, &chip->pcm_list, list) {
snd_pcm_suspend_all(as->pcm);
as->substream[0].need_setup_ep =
as->substream[1].need_setup_ep = true;
}
list_for_each(p, &chip->midi_list)
snd_usbmidi_suspend(p);
list_for_each_entry(mixer, &chip->mixer_list, list)
snd_usb_mixer_suspend(mixer);
}
return 0;
}
static int __usb_audio_resume(struct usb_interface *intf, bool reset_resume)
{
struct snd_usb_audio *chip = usb_get_intfdata(intf);
struct usb_mixer_interface *mixer;
struct list_head *p;
int err = 0;
if (chip == (void *)-1L)
return 0;
if (--chip->num_suspended_intf)
return 0;
atomic_inc(&chip->active); /* avoid autopm */
/*
* ALSA leaves material resumption to user space
* we just notify and restart the mixers
*/
list_for_each_entry(mixer, &chip->mixer_list, list) {
err = snd_usb_mixer_resume(mixer, reset_resume);
if (err < 0)
goto err_out;
}
list_for_each(p, &chip->midi_list) {
snd_usbmidi_resume(p);
}
if (!chip->autosuspended)
snd_power_change_state(chip->card, SNDRV_CTL_POWER_D0);
chip->autosuspended = 0;
err_out:
atomic_dec(&chip->active); /* allow autopm after this point */
return err;
}
static int usb_audio_resume(struct usb_interface *intf)
{
return __usb_audio_resume(intf, false);
}
static int usb_audio_reset_resume(struct usb_interface *intf)
{
return __usb_audio_resume(intf, true);
}
#else
#define usb_audio_suspend NULL
#define usb_audio_resume NULL
#define usb_audio_reset_resume NULL
#endif /* CONFIG_PM */
static const struct usb_device_id usb_audio_ids [] = {
#include "quirks-table.h"
{ .match_flags = (USB_DEVICE_ID_MATCH_INT_CLASS | USB_DEVICE_ID_MATCH_INT_SUBCLASS),
.bInterfaceClass = USB_CLASS_AUDIO,
.bInterfaceSubClass = USB_SUBCLASS_AUDIOCONTROL },
{ } /* Terminating entry */
};
MODULE_DEVICE_TABLE(usb, usb_audio_ids);
/*
* entry point for linux usb interface
*/
static struct usb_driver usb_audio_driver = {
.name = "snd-usb-audio",
.probe = usb_audio_probe,
.disconnect = usb_audio_disconnect,
.suspend = usb_audio_suspend,
.resume = usb_audio_resume,
.reset_resume = usb_audio_reset_resume,
.id_table = usb_audio_ids,
.supports_autosuspend = 1,
};
module_usb_driver(usb_audio_driver);
| ./CrossVul/dataset_final_sorted/CWE-125/c/good_2910_0 |
crossvul-cpp_data_bad_351_13 | /*
* card-setcos.c: Support for PKI cards by Setec
*
* Copyright (C) 2001, 2002 Juha Yrjölä <juha.yrjola@iki.fi>
* Copyright (C) 2005 Antti Tapaninen <aet@cc.hut.fi>
* Copyright (C) 2005 Zetes
*
* 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 "internal.h"
#include "asn1.h"
#include "cardctl.h"
#define _FINEID_BROKEN_SELECT_FLAG 1
static struct sc_atr_table setcos_atrs[] = {
/* some Nokia branded SC */
{ "3B:1F:11:00:67:80:42:46:49:53:45:10:52:66:FF:81:90:00", NULL, NULL, SC_CARD_TYPE_SETCOS_GENERIC, 0, NULL },
/* RSA SecurID 3100 */
{ "3B:9F:94:40:1E:00:67:16:43:46:49:53:45:10:52:66:FF:81:90:00", NULL, NULL, SC_CARD_TYPE_SETCOS_PKI, 0, NULL },
/* FINEID 1016 (SetCOS 4.3.1B3/PKCS#15, VRK) */
{ "3b:9f:94:40:1e:00:67:00:43:46:49:53:45:10:52:66:ff:81:90:00", "ff:ff:ff:ff:ff:ff:ff:00:ff:ff:ff:ff:ff:ff:ff:ff:ff:ff:ff:ff", NULL, SC_CARD_TYPE_SETCOS_FINEID, SC_CARD_FLAG_RNG, NULL },
/* FINEID 2032 (EIDApplet/7816-15, VRK test) */
{ "3b:6b:00:ff:80:62:00:a2:56:46:69:6e:45:49:44", "ff:ff:00:ff:ff:ff:00:ff:ff:ff:ff:ff:ff:ff:ff", NULL, SC_CARD_TYPE_SETCOS_FINEID_V2, 0, NULL },
/* FINEID 2132 (EIDApplet/7816-15, 3rdparty test) */
{ "3b:64:00:ff:80:62:00:a2", "ff:ff:00:ff:ff:ff:00:ff", NULL, SC_CARD_TYPE_SETCOS_FINEID_V2, 0, NULL },
/* FINEID 2064 (EIDApplet/7816-15, VRK) */
{ "3b:7b:00:00:00:80:62:00:51:56:46:69:6e:45:49:44", "ff:ff:00:ff:ff:ff:ff:f0:ff:ff:ff:ff:ff:ff:ff:ff", NULL, SC_CARD_TYPE_SETCOS_FINEID_V2, 0, NULL },
/* FINEID 2164 (EIDApplet/7816-15, 3rdparty) */
{ "3b:64:00:00:80:62:00:51", "ff:ff:ff:ff:ff:ff:f0:ff", NULL, SC_CARD_TYPE_SETCOS_FINEID_V2, 0, NULL },
/* FINEID 2264 (EIDApplet/7816-15, OPK/EMV/AVANT) */
{ "3b:6e:00:00:00:62:00:00:57:41:56:41:4e:54:10:81:90:00", NULL, NULL, SC_CARD_TYPE_SETCOS_FINEID_V2, 0, NULL },
{ "3b:7b:94:00:00:80:62:11:51:56:46:69:6e:45:49:44", NULL, NULL, SC_CARD_TYPE_SETCOS_FINEID_V2, 0, NULL },
/* FINEID cards 1.3.2011 with Samsung chips (round connector) that supports 2048 bit keys. */
{ "3b:7b:94:00:00:80:62:12:51:56:46:69:6e:45:49:44", NULL, NULL, SC_CARD_TYPE_SETCOS_FINEID_V2_2048, 0, NULL },
/* FINEID card for organisations, chip unknown. */
{ "3b:7b:18:00:00:80:62:01:54:56:46:69:6e:45:49:44", NULL, NULL, SC_CARD_TYPE_SETCOS_FINEID_V2, _FINEID_BROKEN_SELECT_FLAG, NULL },
/* Swedish NIDEL card */
{ "3b:9f:94:80:1f:c3:00:68:10:44:05:01:46:49:53:45:31:c8:07:90:00:18", NULL, NULL, SC_CARD_TYPE_SETCOS_NIDEL, 0, NULL },
/* Setcos 4.4.1 */
{ "3b:9f:94:80:1f:c3:00:68:11:44:05:01:46:49:53:45:31:c8:00:00:00:00", "ff:ff:ff:ff:ff:ff:ff:ff:ff:ff:ff:ff:ff:ff:ff:ff:ff:ff:00:00:00:00", NULL, SC_CARD_TYPE_SETCOS_44, 0, NULL },
{ NULL, NULL, NULL, 0, 0, NULL }
};
#define SETCOS_IS_EID_APPLET(card) ((card)->type == SC_CARD_TYPE_SETCOS_EID_V2_0 || (card)->type == SC_CARD_TYPE_SETCOS_EID_V2_1)
/* Setcos 4.4 Life Cycle Status Integer */
#define SETEC_LCSI_CREATE 0x01
#define SETEC_LCSI_INIT 0x03
#define SETEC_LCSI_ACTIVATED 0x07
#define SETEC_LCSI_DEACTIVATE 0x06
#define SETEC_LCSI_TEMINATE 0x0F /* MF only */
static struct sc_card_operations setcos_ops;
static struct sc_card_driver setcos_drv = {
"Setec cards",
"setcos",
&setcos_ops,
NULL, 0, NULL
};
static int match_hist_bytes(sc_card_t *card, const char *str, size_t len)
{
const char *src = (const char *) card->reader->atr_info.hist_bytes;
size_t srclen = card->reader->atr_info.hist_bytes_len;
size_t offset = 0;
if (len == 0)
len = strlen(str);
if (srclen < len)
return 0;
while (srclen - offset > len) {
if (memcmp(src + offset, str, len) == 0) {
return 1;
}
offset++;
}
return 0;
}
static int setcos_match_card(sc_card_t *card)
{
sc_apdu_t apdu;
u8 buf[6];
int i;
i = _sc_match_atr(card, setcos_atrs, &card->type);
if (i < 0) {
/* Unknown card, but has the FinEID application for sure */
if (match_hist_bytes(card, "FinEID", 0)) {
card->type = SC_CARD_TYPE_SETCOS_FINEID_V2_2048;
return 1;
}
if (match_hist_bytes(card, "FISE", 0)) {
card->type = SC_CARD_TYPE_SETCOS_GENERIC;
return 1;
}
/* Check if it's a EID2.x applet by reading the version info */
sc_format_apdu(card, &apdu, SC_APDU_CASE_2_SHORT, 0xCA, 0xDF, 0x30);
apdu.cla = 0x00;
apdu.resp = buf;
apdu.resplen = 5;
apdu.le = 5;
i = sc_transmit_apdu(card, &apdu);
if (i == 0 && apdu.sw1 == 0x90 && apdu.sw2 == 0x00 && apdu.resplen == 5) {
if (memcmp(buf, "v2.0", 4) == 0)
card->type = SC_CARD_TYPE_SETCOS_EID_V2_0;
else if (memcmp(buf, "v2.1", 4) == 0)
card->type = SC_CARD_TYPE_SETCOS_EID_V2_1;
else {
buf[sizeof(buf) - 1] = '\0';
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "SetCOS EID applet %s is not supported", (char *) buf);
return 0;
}
return 1;
}
return 0;
}
card->flags = setcos_atrs[i].flags;
return 1;
}
static int select_pkcs15_app(sc_card_t * card)
{
sc_path_t app;
int r;
/* Regular PKCS#15 AID */
sc_format_path("A000000063504B43532D3135", &app);
app.type = SC_PATH_TYPE_DF_NAME;
r = sc_select_file(card, &app, NULL);
return r;
}
static int setcos_init(sc_card_t *card)
{
card->name = "SetCOS";
/* Handle unknown or forced cards */
if (card->type < 0) {
card->type = SC_CARD_TYPE_SETCOS_GENERIC;
}
switch (card->type) {
case SC_CARD_TYPE_SETCOS_FINEID:
case SC_CARD_TYPE_SETCOS_FINEID_V2_2048:
case SC_CARD_TYPE_SETCOS_NIDEL:
card->cla = 0x00;
select_pkcs15_app(card);
if (card->flags & SC_CARD_FLAG_RNG)
card->caps |= SC_CARD_CAP_RNG;
break;
case SC_CARD_TYPE_SETCOS_44:
case SC_CARD_TYPE_SETCOS_EID_V2_0:
case SC_CARD_TYPE_SETCOS_EID_V2_1:
card->cla = 0x00;
card->caps |= SC_CARD_CAP_USE_FCI_AC;
card->caps |= SC_CARD_CAP_RNG;
card->caps |= SC_CARD_CAP_APDU_EXT;
break;
default:
/* XXX: Get SetCOS version */
card->cla = 0x80; /* SetCOS 4.3.x */
/* State that we have an RNG */
card->caps |= SC_CARD_CAP_RNG;
break;
}
switch (card->type) {
case SC_CARD_TYPE_SETCOS_PKI:
case SC_CARD_TYPE_SETCOS_FINEID_V2_2048:
{
unsigned long flags;
flags = SC_ALGORITHM_RSA_RAW | SC_ALGORITHM_RSA_PAD_PKCS1;
flags |= SC_ALGORITHM_RSA_HASH_NONE | SC_ALGORITHM_RSA_HASH_SHA1;
_sc_card_add_rsa_alg(card, 1024, flags, 0);
_sc_card_add_rsa_alg(card, 2048, flags, 0);
}
break;
case SC_CARD_TYPE_SETCOS_44:
case SC_CARD_TYPE_SETCOS_NIDEL:
case SC_CARD_TYPE_SETCOS_EID_V2_0:
case SC_CARD_TYPE_SETCOS_EID_V2_1:
{
unsigned long flags;
flags = SC_ALGORITHM_RSA_RAW | SC_ALGORITHM_RSA_PAD_PKCS1;
flags |= SC_ALGORITHM_RSA_HASH_NONE | SC_ALGORITHM_RSA_HASH_SHA1;
flags |= SC_ALGORITHM_ONBOARD_KEY_GEN;
_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);
_sc_card_add_rsa_alg(card, 2048, flags, 0);
}
break;
}
return 0;
}
static const struct sc_card_operations *iso_ops = NULL;
static int setcos_construct_fci_44(sc_card_t *card, const sc_file_t *file, u8 *out, size_t *outlen)
{
u8 *p = out;
u8 buf[64];
const u8 *pin_key_info;
int len;
/* Command */
*p++ = 0x6F;
p++;
/* Size (set to 0 for keys/PINs on a Java card) */
if (SETCOS_IS_EID_APPLET(card) &&
(file->type == SC_FILE_TYPE_INTERNAL_EF ||
(file->type == SC_FILE_TYPE_WORKING_EF && file->ef_structure == 0x22)))
buf[0] = buf[1] = 0x00;
else {
buf[0] = (file->size >> 8) & 0xFF;
buf[1] = file->size & 0xFF;
}
sc_asn1_put_tag(0x81, buf, 2, p, *outlen - (p - out), &p);
/* Type */
if (file->type_attr_len) {
memcpy(buf, file->type_attr, file->type_attr_len);
sc_asn1_put_tag(0x82, buf, file->type_attr_len, p, *outlen - (p - out), &p);
} else {
u8 bLen = 1;
buf[0] = file->shareable ? 0x40 : 0;
switch (file->type) {
case SC_FILE_TYPE_INTERNAL_EF: /* RSA keyfile */
buf[0] = 0x11;
break;
case SC_FILE_TYPE_WORKING_EF:
if (file->ef_structure == 0x22) { /* pin-file */
buf[0] = 0x0A; /* EF linear fixed EF for ISF keys */
if (SETCOS_IS_EID_APPLET(card))
bLen = 1;
else {
/* Setcos V4.4 */
bLen = 5;
buf[1] = 0x41; /* fixed */
buf[2] = file->record_length >> 8; /* 2 byte record length */
buf[3] = file->record_length & 0xFF;
buf[4] = file->size / file->record_length; /* record count */
}
} else {
buf[0] |= file->ef_structure & 7; /* set file-type, only for EF, not for DF objects */
}
break;
case SC_FILE_TYPE_DF:
buf[0] = 0x38;
break;
default:
return SC_ERROR_NOT_SUPPORTED;
}
sc_asn1_put_tag(0x82, buf, bLen, p, *outlen - (p - out), &p);
}
/* File ID */
buf[0] = (file->id >> 8) & 0xFF;
buf[1] = file->id & 0xFF;
sc_asn1_put_tag(0x83, buf, 2, p, *outlen - (p - out), &p);
/* DF name */
if (file->type == SC_FILE_TYPE_DF) {
if (file->name[0] != 0)
sc_asn1_put_tag(0x84, (u8 *) file->name, file->namelen, p, *outlen - (p - out), &p);
else { /* Name required -> take the FID if not specified */
buf[0] = (file->id >> 8) & 0xFF;
buf[1] = file->id & 0xFF;
sc_asn1_put_tag(0x84, buf, 2, p, *outlen - (p - out), &p);
}
}
/* Security Attributes */
memcpy(buf, file->sec_attr, file->sec_attr_len);
sc_asn1_put_tag(0x86, buf, file->sec_attr_len, p, *outlen - (p - out), &p);
/* Life cycle status */
if (file->prop_attr_len) {
memcpy(buf, file->prop_attr, file->prop_attr_len);
sc_asn1_put_tag(0x8A, buf, file->prop_attr_len, p, *outlen - (p - out), &p);
}
/* PIN definitions */
if (file->type == SC_FILE_TYPE_DF) {
if (card->type == SC_CARD_TYPE_SETCOS_EID_V2_1) {
pin_key_info = (const u8*)"\xC1\x04\x81\x82\x83\x84";
len = 6;
}
else if (card->type == SC_CARD_TYPE_SETCOS_EID_V2_0) {
pin_key_info = (const u8*)"\xC1\x04\x81\x82"; /* Max 2 PINs supported */
len = 4;
}
else {
/* Pin/key info: define 4 pins, no keys */
if(file->path.len == 2)
pin_key_info = (const u8*)"\xC1\x04\x81\x82\x83\x84\xC2\x00"; /* root-MF: use local pin-file */
else
pin_key_info = (const u8 *)"\xC1\x04\x01\x02\x03\x04\xC2\x00"; /* sub-DF: use parent pin-file in root-MF */
len = 8;
}
sc_asn1_put_tag(0xA5, pin_key_info, len, p, *outlen - (p - out), &p);
}
/* Length */
out[1] = p - out - 2;
*outlen = p - out;
return 0;
}
static int setcos_construct_fci(sc_card_t *card, const sc_file_t *file, u8 *out, size_t *outlen)
{
if (card->type == SC_CARD_TYPE_SETCOS_44 ||
card->type == SC_CARD_TYPE_SETCOS_NIDEL ||
SETCOS_IS_EID_APPLET(card))
return setcos_construct_fci_44(card, file, out, outlen);
else
return iso_ops->construct_fci(card, file, out, outlen);
}
static u8 acl_to_byte(const sc_acl_entry_t *e)
{
switch (e->method) {
case SC_AC_NONE:
return 0x00;
case SC_AC_CHV:
switch (e->key_ref) {
case 1:
return 0x01;
break;
case 2:
return 0x02;
break;
default:
return 0x00;
}
break;
case SC_AC_TERM:
return 0x04;
case SC_AC_NEVER:
return 0x0F;
}
return 0x00;
}
static unsigned int acl_to_byte_44(const struct sc_acl_entry *e, u8* p_bNumber)
{
/* Handle special fixed values */
if (e == (sc_acl_entry_t *) 1) /* SC_AC_NEVER */
return SC_AC_NEVER;
else if ((e == (sc_acl_entry_t *) 2) || /* SC_AC_NONE */
(e == (sc_acl_entry_t *) 3) || /* SC_AC_UNKNOWN */
(e == (sc_acl_entry_t *) 0))
return SC_AC_NONE;
/* Handle standard values */
*p_bNumber = e->key_ref;
return(e->method);
}
/* If pin is present in the pins list, return it's index.
* If it's not yet present, add it to the list and return the index. */
static int setcos_pin_index_44(int *pins, int len, int pin)
{
int i;
for (i = 0; i < len; i++) {
if (pins[i] == pin)
return i;
if (pins[i] == -1) {
pins[i] = pin;
return i;
}
}
assert(i != len); /* Too much PINs, shouldn't happen */
return 0;
}
/* The ACs are always for the SETEC_LCSI_ACTIVATED state, even if
* we have to create the file in the SC_FILE_STATUS_INITIALISATION state. */
static int setcos_create_file_44(sc_card_t *card, sc_file_t *file)
{
const u8 bFileStatus = file->status == SC_FILE_STATUS_CREATION ?
SETEC_LCSI_CREATE : SETEC_LCSI_ACTIVATED;
u8 bCommands_always = 0;
int pins[] = {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1};
u8 bCommands_pin[sizeof(pins)/sizeof(pins[0])]; /* both 7 entries big */
u8 bCommands_key = 0;
u8 bNumber = 0;
u8 bKeyNumber = 0;
unsigned int bMethod = 0;
/* -1 means RFU */
const int df_idx[8] = { /* byte 1 = OpenSC type of AC Bit0, byte 2 = OpenSC type of AC Bit1 ...*/
SC_AC_OP_DELETE, SC_AC_OP_CREATE, SC_AC_OP_CREATE,
SC_AC_OP_INVALIDATE, SC_AC_OP_REHABILITATE,
SC_AC_OP_LOCK, SC_AC_OP_DELETE, -1};
const int ef_idx[8] = { /* note: SC_AC_OP_SELECT to be ignored, actually RFU */
SC_AC_OP_READ, SC_AC_OP_UPDATE, SC_AC_OP_WRITE,
SC_AC_OP_INVALIDATE, SC_AC_OP_REHABILITATE,
-1, SC_AC_OP_ERASE, -1};
const int efi_idx[8] = { /* internal EF used for RSA keys */
SC_AC_OP_READ, SC_AC_OP_ERASE, SC_AC_OP_UPDATE,
SC_AC_OP_INVALIDATE, SC_AC_OP_REHABILITATE,
-1, SC_AC_OP_ERASE, -1};
/* Set file creation status */
sc_file_set_prop_attr(file, &bFileStatus, 1);
/* Build ACI from local structure = get AC for each operation group */
if (file->sec_attr_len == 0) {
const int* p_idx;
int i;
int len = 0;
u8 bBuf[64];
/* Get specific operation groups for specified file-type */
switch (file->type){
case SC_FILE_TYPE_DF: /* DF */
p_idx = df_idx;
break;
case SC_FILE_TYPE_INTERNAL_EF: /* EF for RSA keys */
p_idx = efi_idx;
break;
default: /* SC_FILE_TYPE_WORKING_EF */
p_idx = ef_idx;
break;
}
/* Get enabled commands + required Keys/Pins */
memset(bCommands_pin, 0, sizeof(bCommands_pin));
for (i = 7; i >= 0; i--) { /* for each AC Setcos operation */
bCommands_always <<= 1;
bCommands_key <<= 1;
if (p_idx[i] == -1) /* -1 means that bit is RFU -> set to 0 */
continue;
bMethod = acl_to_byte_44(file->acl[ p_idx[i] ], &bNumber);
/* Convert to OpenSc-index, convert to pin/key number */
switch(bMethod){
case SC_AC_NONE: /* always allowed */
bCommands_always |= 1;
break;
case SC_AC_CHV: /* pin */
if ((bNumber & 0x7F) == 0 || (bNumber & 0x7F) > 7) {
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "SetCOS 4.4 PIN refs can only be 1..7\n");
return SC_ERROR_INVALID_ARGUMENTS;
}
bCommands_pin[setcos_pin_index_44(pins, sizeof(pins), (int) bNumber)] |= 1 << i;
break;
case SC_AC_TERM: /* key */
bKeyNumber = bNumber; /* There should be only 1 key */
bCommands_key |= 1;
break;
}
}
/* Add the commands that are always allowed */
if (bCommands_always) {
bBuf[len++] = 1;
bBuf[len++] = bCommands_always;
}
/* Add commands that require pins */
for (i = 0; i < (int)sizeof(bCommands_pin) && pins[i] != -1; i++) {
bBuf[len++] = 2;
bBuf[len++] = bCommands_pin[i];
if (SETCOS_IS_EID_APPLET(card))
bBuf[len++] = pins[i]; /* pin ref */
else
bBuf[len++] = pins[i] & 0x07; /* pin ref */
}
/* Add commands that require the key */
if (bCommands_key) {
bBuf[len++] = 2 | 0x20; /* indicate keyNumber present */
bBuf[len++] = bCommands_key;
bBuf[len++] = bKeyNumber;
}
/* RSA signing/decryption requires AC adaptive coding, can't be put
in AC simple coding. Only implemented for pins, not for a key. */
if ( (file->type == SC_FILE_TYPE_INTERNAL_EF) &&
(acl_to_byte_44(file->acl[SC_AC_OP_CRYPTO], &bNumber) == SC_AC_CHV) ) {
bBuf[len++] = 0x83;
bBuf[len++] = 0x01;
bBuf[len++] = 0x2A; /* INS byte for the sign/decrypt APDU */
bBuf[len++] = bNumber & 0x07; /* pin ref */
}
sc_file_set_sec_attr(file, bBuf, len);
}
return iso_ops->create_file(card, file);
}
static int setcos_create_file(sc_card_t *card, sc_file_t *file)
{
if (card->type == SC_CARD_TYPE_SETCOS_44 || SETCOS_IS_EID_APPLET(card))
return setcos_create_file_44(card, file);
if (file->prop_attr_len == 0)
sc_file_set_prop_attr(file, (const u8 *) "\x03\x00\x00", 3);
if (file->sec_attr_len == 0) {
int idx[6], i;
u8 buf[6];
if (file->type == SC_FILE_TYPE_DF) {
const int df_idx[6] = {
SC_AC_OP_SELECT, SC_AC_OP_LOCK, SC_AC_OP_DELETE,
SC_AC_OP_CREATE, SC_AC_OP_REHABILITATE,
SC_AC_OP_INVALIDATE
};
for (i = 0; i < 6; i++)
idx[i] = df_idx[i];
} else {
const int ef_idx[6] = {
SC_AC_OP_READ, SC_AC_OP_UPDATE, SC_AC_OP_WRITE,
SC_AC_OP_ERASE, SC_AC_OP_REHABILITATE,
SC_AC_OP_INVALIDATE
};
for (i = 0; i < 6; i++)
idx[i] = ef_idx[i];
}
for (i = 0; i < 6; i++) {
const struct sc_acl_entry *entry;
entry = sc_file_get_acl_entry(file, idx[i]);
buf[i] = acl_to_byte(entry);
}
sc_file_set_sec_attr(file, buf, 6);
}
return iso_ops->create_file(card, file);
}
static int setcos_set_security_env2(sc_card_t *card,
const sc_security_env_t *env, int se_num)
{
sc_apdu_t apdu;
u8 sbuf[SC_MAX_APDU_BUFFER_SIZE];
u8 *p;
int r, locked = 0;
assert(card != NULL && env != NULL);
if (card->type == SC_CARD_TYPE_SETCOS_44 ||
card->type == SC_CARD_TYPE_SETCOS_NIDEL ||
SETCOS_IS_EID_APPLET(card)) {
if (env->flags & SC_SEC_ENV_KEY_REF_SYMMETRIC) {
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "symmetric keyref not supported.\n");
return SC_ERROR_NOT_SUPPORTED;
}
if (se_num > 0) {
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "restore security environment not supported.\n");
return SC_ERROR_NOT_SUPPORTED;
}
}
sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x22, 0, 0);
switch (env->operation) {
case SC_SEC_OPERATION_DECIPHER:
/* Should be 0x81 */
apdu.p1 = 0x41;
apdu.p2 = 0xB8;
break;
case SC_SEC_OPERATION_SIGN:
/* Should be 0x41 */
apdu.p1 = ((card->type == SC_CARD_TYPE_SETCOS_FINEID_V2) ||
(card->type == SC_CARD_TYPE_SETCOS_FINEID_V2_2048) ||
(card->type == SC_CARD_TYPE_SETCOS_44) ||
(card->type == SC_CARD_TYPE_SETCOS_NIDEL) ||
SETCOS_IS_EID_APPLET(card)) ? 0x41 : 0x81;
apdu.p2 = 0xB6;
break;
default:
return SC_ERROR_INVALID_ARGUMENTS;
}
apdu.le = 0;
p = sbuf;
if (env->flags & SC_SEC_ENV_ALG_REF_PRESENT) {
*p++ = 0x80; /* algorithm reference */
*p++ = 0x01;
*p++ = env->algorithm_ref & 0xFF;
}
if (env->flags & SC_SEC_ENV_FILE_REF_PRESENT) {
*p++ = 0x81;
*p++ = env->file_ref.len;
memcpy(p, env->file_ref.value, env->file_ref.len);
p += env->file_ref.len;
}
if (env->flags & SC_SEC_ENV_KEY_REF_PRESENT &&
!(card->type == SC_CARD_TYPE_SETCOS_NIDEL ||
card->type == SC_CARD_TYPE_SETCOS_FINEID_V2_2048)) {
if (env->flags & SC_SEC_ENV_KEY_REF_SYMMETRIC)
*p++ = 0x83;
else
*p++ = 0x84;
*p++ = env->key_ref_len;
memcpy(p, env->key_ref, env->key_ref_len);
p += env->key_ref_len;
}
r = p - sbuf;
apdu.lc = r;
apdu.datalen = r;
apdu.data = sbuf;
apdu.resplen = 0;
if (se_num > 0) {
r = sc_lock(card);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "sc_lock() failed");
locked = 1;
}
if (apdu.datalen != 0) {
r = sc_transmit_apdu(card, &apdu);
if (r) {
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL,
"%s: APDU transmit failed", sc_strerror(r));
goto err;
}
r = sc_check_sw(card, apdu.sw1, apdu.sw2);
if (r) {
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL,
"%s: Card returned error", sc_strerror(r));
goto err;
}
}
if (se_num <= 0)
return 0;
sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x22, 0xF2, se_num);
r = sc_transmit_apdu(card, &apdu);
sc_unlock(card);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed");
return sc_check_sw(card, apdu.sw1, apdu.sw2);
err:
if (locked)
sc_unlock(card);
return r;
}
static int setcos_set_security_env(sc_card_t *card,
const sc_security_env_t *env, int se_num)
{
if (env->flags & SC_SEC_ENV_ALG_PRESENT) {
sc_security_env_t tmp;
tmp = *env;
tmp.flags &= ~SC_SEC_ENV_ALG_PRESENT;
tmp.flags |= SC_SEC_ENV_ALG_REF_PRESENT;
if (tmp.algorithm != SC_ALGORITHM_RSA) {
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Only RSA algorithm supported.\n");
return SC_ERROR_NOT_SUPPORTED;
}
switch (card->type) {
case SC_CARD_TYPE_SETCOS_PKI:
case SC_CARD_TYPE_SETCOS_FINEID:
case SC_CARD_TYPE_SETCOS_FINEID_V2_2048:
case SC_CARD_TYPE_SETCOS_NIDEL:
case SC_CARD_TYPE_SETCOS_44:
case SC_CARD_TYPE_SETCOS_EID_V2_0:
case SC_CARD_TYPE_SETCOS_EID_V2_1:
break;
default:
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Card does not support RSA.\n");
return SC_ERROR_NOT_SUPPORTED;
break;
}
tmp.algorithm_ref = 0x00;
/* potential FIXME: return an error, if an unsupported
* pad or hash was requested, although this shouldn't happen.
*/
if (env->algorithm_flags & SC_ALGORITHM_RSA_PAD_PKCS1)
tmp.algorithm_ref = 0x02;
if (tmp.algorithm_flags & SC_ALGORITHM_RSA_HASH_SHA1)
tmp.algorithm_ref |= 0x10;
return setcos_set_security_env2(card, &tmp, se_num);
}
return setcos_set_security_env2(card, env, se_num);
}
static void add_acl_entry(sc_file_t *file, int op, u8 byte)
{
unsigned int method, key_ref = SC_AC_KEY_REF_NONE;
switch (byte >> 4) {
case 0:
method = SC_AC_NONE;
break;
case 1:
method = SC_AC_CHV;
key_ref = 1;
break;
case 2:
method = SC_AC_CHV;
key_ref = 2;
break;
case 4:
method = SC_AC_TERM;
break;
case 15:
method = SC_AC_NEVER;
break;
default:
method = SC_AC_UNKNOWN;
break;
}
sc_file_add_acl_entry(file, op, method, key_ref);
}
static void parse_sec_attr(sc_file_t *file, const u8 * buf, size_t len)
{
int i;
int idx[6];
if (len < 6)
return;
if (file->type == SC_FILE_TYPE_DF) {
const int df_idx[6] = {
SC_AC_OP_SELECT, SC_AC_OP_LOCK, SC_AC_OP_DELETE,
SC_AC_OP_CREATE, SC_AC_OP_REHABILITATE,
SC_AC_OP_INVALIDATE
};
for (i = 0; i < 6; i++)
idx[i] = df_idx[i];
} else {
const int ef_idx[6] = {
SC_AC_OP_READ, SC_AC_OP_UPDATE, SC_AC_OP_WRITE,
SC_AC_OP_ERASE, SC_AC_OP_REHABILITATE,
SC_AC_OP_INVALIDATE
};
for (i = 0; i < 6; i++)
idx[i] = ef_idx[i];
}
for (i = 0; i < 6; i++)
add_acl_entry(file, idx[i], buf[i]);
}
static void parse_sec_attr_44(sc_file_t *file, const u8 *buf, size_t len)
{
/* OpenSc Operation values for each command operation-type */
const int df_idx[8] = { /* byte 1 = OpenSC type of AC Bit0, byte 2 = OpenSC type of AC Bit1 ...*/
SC_AC_OP_DELETE, SC_AC_OP_CREATE, SC_AC_OP_CREATE,
SC_AC_OP_INVALIDATE, SC_AC_OP_REHABILITATE,
SC_AC_OP_LOCK, SC_AC_OP_DELETE, -1};
const int ef_idx[8] = {
SC_AC_OP_READ, SC_AC_OP_UPDATE, SC_AC_OP_WRITE,
SC_AC_OP_INVALIDATE, SC_AC_OP_REHABILITATE,
-1, SC_AC_OP_ERASE, -1};
const int efi_idx[8] = { /* internal EF used for RSA keys */
SC_AC_OP_READ, SC_AC_OP_ERASE, SC_AC_OP_UPDATE,
SC_AC_OP_INVALIDATE, SC_AC_OP_REHABILITATE,
-1, SC_AC_OP_ERASE, -1};
u8 bValue;
int i;
int iKeyRef = 0;
int iMethod;
int iPinCount;
int iOffset = 0;
int iOperation;
const int* p_idx;
/* Check all sub-AC definitions within the total AC */
while (len > 1) { /* minimum length = 2 */
int iACLen = buf[iOffset] & 0x0F;
iPinCount = -1; /* default no pin required */
iMethod = SC_AC_NONE; /* default no authentication required */
if (buf[iOffset] & 0X80) { /* AC in adaptive coding */
/* Evaluates only the command-byte, not the optional P1/P2/Option bytes */
int iParmLen = 1; /* command-byte is always present */
int iKeyLen = 0; /* Encryption key is optional */
if (buf[iOffset] & 0x20) iKeyLen++;
if (buf[iOffset+1] & 0x40) iParmLen++;
if (buf[iOffset+1] & 0x20) iParmLen++;
if (buf[iOffset+1] & 0x10) iParmLen++;
if (buf[iOffset+1] & 0x08) iParmLen++;
/* Get KeyNumber if available */
if(iKeyLen) {
int iSC = buf[iOffset+iACLen];
switch( (iSC>>5) & 0x03 ){
case 0:
iMethod = SC_AC_TERM; /* key authentication */
break;
case 1:
iMethod = SC_AC_AUT; /* key authentication */
break;
case 2:
case 3:
iMethod = SC_AC_PRO; /* secure messaging */
break;
}
iKeyRef = iSC & 0x1F; /* get key number */
}
/* Get PinNumber if available */
if (iACLen > (1+iParmLen+iKeyLen)) { /* check via total length if pin is present */
iKeyRef = buf[iOffset+1+1+iParmLen]; /* PTL + AM-header + parameter-bytes */
iMethod = SC_AC_CHV;
}
/* Convert SETCOS command to OpenSC command group */
switch(buf[iOffset+2]){
case 0x2A: /* crypto operation */
iOperation = SC_AC_OP_CRYPTO;
break;
case 0x46: /* key-generation operation */
iOperation = SC_AC_OP_UPDATE;
break;
default:
iOperation = SC_AC_OP_SELECT;
break;
}
sc_file_add_acl_entry(file, iOperation, iMethod, iKeyRef);
}
else { /* AC in simple coding */
/* Initial AC is treated as an operational AC */
/* Get specific Cmd groups for specified file-type */
switch (file->type) {
case SC_FILE_TYPE_DF: /* DF */
p_idx = df_idx;
break;
case SC_FILE_TYPE_INTERNAL_EF: /* EF for RSA keys */
p_idx = efi_idx;
break;
default: /* EF */
p_idx = ef_idx;
break;
}
/* Encryption key present ? */
iPinCount = iACLen - 1;
if (buf[iOffset] & 0x20) {
int iSC = buf[iOffset + iACLen];
switch( (iSC>>5) & 0x03 ) {
case 0:
iMethod = SC_AC_TERM; /* key authentication */
break;
case 1:
iMethod = SC_AC_AUT; /* key authentication */
break;
case 2:
case 3:
iMethod = SC_AC_PRO; /* secure messaging */
break;
}
iKeyRef = iSC & 0x1F; /* get key number */
iPinCount--; /* one byte used for keyReference */
}
/* Pin present ? */
if ( iPinCount > 0 ) {
iKeyRef = buf[iOffset + 2]; /* pin ref */
iMethod = SC_AC_CHV;
}
/* Add AC for each command-operationType into OpenSc structure */
bValue = buf[iOffset + 1];
for (i = 0; i < 8; i++) {
if((bValue & 1) && (p_idx[i] >= 0))
sc_file_add_acl_entry(file, p_idx[i], iMethod, iKeyRef);
bValue >>= 1;
}
}
/* Current field treated, get next AC sub-field */
iOffset += iACLen +1; /* AC + PTL-byte */
len -= iACLen +1;
}
}
static int setcos_select_file(sc_card_t *card,
const sc_path_t *in_path, sc_file_t **file)
{
int r;
r = iso_ops->select_file(card, in_path, file);
/* Certain FINeID cards for organisations return 6A88 instead of 6A82 for missing files */
if (card->flags & _FINEID_BROKEN_SELECT_FLAG && r == SC_ERROR_DATA_OBJECT_NOT_FOUND)
return SC_ERROR_FILE_NOT_FOUND;
if (r)
return r;
if (file != NULL) {
if (card->type == SC_CARD_TYPE_SETCOS_44 ||
card->type == SC_CARD_TYPE_SETCOS_NIDEL ||
SETCOS_IS_EID_APPLET(card))
parse_sec_attr_44(*file, (*file)->sec_attr, (*file)->sec_attr_len);
else
parse_sec_attr(*file, (*file)->sec_attr, (*file)->sec_attr_len);
}
return 0;
}
static int setcos_list_files(sc_card_t *card, u8 * buf, size_t buflen)
{
sc_apdu_t apdu;
int r;
sc_format_apdu(card, &apdu, SC_APDU_CASE_2_SHORT, 0xAA, 0, 0);
if (card->type == SC_CARD_TYPE_SETCOS_44 ||
card->type == SC_CARD_TYPE_SETCOS_NIDEL ||
SETCOS_IS_EID_APPLET(card))
apdu.cla = 0x80;
apdu.resp = buf;
apdu.resplen = buflen;
apdu.le = buflen > 256 ? 256 : buflen;
r = sc_transmit_apdu(card, &apdu);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed");
if (card->type == SC_CARD_TYPE_SETCOS_44 && apdu.sw1 == 0x6A && apdu.sw2 == 0x82)
return 0; /* no files found */
if (apdu.resplen == 0)
return sc_check_sw(card, apdu.sw1, apdu.sw2);
return apdu.resplen;
}
static int setcos_process_fci(sc_card_t *card, sc_file_t *file,
const u8 *buf, size_t buflen)
{
int r = iso_ops->process_fci(card, file, buf, buflen);
/* SetCOS 4.4: RSA key file is an internal EF but it's
* file descriptor doesn't seem to follow ISO7816. */
if (r >= 0 && (card->type == SC_CARD_TYPE_SETCOS_44 ||
SETCOS_IS_EID_APPLET(card))) {
const u8 *tag;
size_t taglen = 1;
tag = (u8 *) sc_asn1_find_tag(card->ctx, buf, buflen, 0x82, &taglen);
if (tag != NULL && taglen == 1 && *tag == 0x11)
file->type = SC_FILE_TYPE_INTERNAL_EF;
}
return r;
}
/* Write internal data, e.g. add default pin-records to pin-file */
static int setcos_putdata(struct sc_card *card, struct sc_cardctl_setcos_data_obj* data_obj)
{
int r;
struct sc_apdu apdu;
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
memset(&apdu, 0, sizeof(apdu));
apdu.cse = SC_APDU_CASE_3_SHORT;
apdu.cla = 0x00;
apdu.ins = 0xDA;
apdu.p1 = data_obj->P1;
apdu.p2 = data_obj->P2;
apdu.lc = data_obj->DataLen;
apdu.datalen = data_obj->DataLen;
apdu.data = data_obj->Data;
r = sc_transmit_apdu(card, &apdu);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed");
r = sc_check_sw(card, apdu.sw1, apdu.sw2);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "PUT_DATA returned error");
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, r);
}
/* Read internal data, e.g. get RSA public key */
static int setcos_getdata(struct sc_card *card, struct sc_cardctl_setcos_data_obj* data_obj)
{
int r;
struct sc_apdu apdu;
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
memset(&apdu, 0, sizeof(apdu));
apdu.cse = SC_APDU_CASE_2_SHORT;
apdu.cla = 0x00;
apdu.ins = 0xCA; /* GET DATA */
apdu.p1 = data_obj->P1;
apdu.p2 = data_obj->P2;
apdu.lc = 0;
apdu.datalen = 0;
apdu.data = data_obj->Data;
apdu.le = 256;
apdu.resp = data_obj->Data;
apdu.resplen = data_obj->DataLen;
r = sc_transmit_apdu(card, &apdu);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed");
r = sc_check_sw(card, apdu.sw1, apdu.sw2);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "GET_DATA returned error");
if (apdu.resplen > data_obj->DataLen)
r = SC_ERROR_WRONG_LENGTH;
else
data_obj->DataLen = apdu.resplen;
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, r);
}
/* Generate or store a key */
static int setcos_generate_store_key(sc_card_t *card,
struct sc_cardctl_setcos_gen_store_key_info *data)
{
struct sc_apdu apdu;
u8 sbuf[SC_MAX_APDU_BUFFER_SIZE];
int r, len;
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
/* Setup key-generation parameters */
len = 0;
if (data->op_type == OP_TYPE_GENERATE)
sbuf[len++] = 0x92; /* algo ID: RSA CRT */
else
sbuf[len++] = 0x9A; /* algo ID: EXTERNALLY GENERATED RSA CRT */
sbuf[len++] = 0x00;
sbuf[len++] = data->mod_len / 256; /* 2 bytes for modulus bitlength */
sbuf[len++] = data->mod_len % 256;
sbuf[len++] = data->pubexp_len / 256; /* 2 bytes for pubexp bitlength */
sbuf[len++] = data->pubexp_len % 256;
memcpy(sbuf + len, data->pubexp, (data->pubexp_len + 7) / 8);
len += (data->pubexp_len + 7) / 8;
if (data->op_type == OP_TYPE_STORE) {
sbuf[len++] = data->primep_len / 256;
sbuf[len++] = data->primep_len % 256;
memcpy(sbuf + len, data->primep, (data->primep_len + 7) / 8);
len += (data->primep_len + 7) / 8;
sbuf[len++] = data->primeq_len / 256;
sbuf[len++] = data->primeq_len % 256;
memcpy(sbuf + len, data->primeq, (data->primeq_len + 7) / 8);
len += (data->primeq_len + 7) / 8;
}
sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x46, 0x00, 0x00);
apdu.cla = 0x00;
apdu.data = sbuf;
apdu.datalen = len;
apdu.lc = len;
r = sc_transmit_apdu(card, &apdu);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed");
r = sc_check_sw(card, apdu.sw1, apdu.sw2);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "STORE/GENERATE_KEY returned error");
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, r);
}
static int setcos_activate_file(sc_card_t *card)
{
int r;
u8 sbuf[2];
sc_apdu_t apdu;
sc_format_apdu(card, &apdu, SC_APDU_CASE_1, 0x44, 0x00, 0x00);
apdu.data = sbuf;
r = sc_transmit_apdu(card, &apdu);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed");
r = sc_check_sw(card, apdu.sw1, apdu.sw2);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "ACTIVATE_FILE returned error");
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, r);
}
static int setcos_card_ctl(sc_card_t *card, unsigned long cmd, void *ptr)
{
if (card->type != SC_CARD_TYPE_SETCOS_44 && !SETCOS_IS_EID_APPLET(card))
return SC_ERROR_NOT_SUPPORTED;
switch(cmd) {
case SC_CARDCTL_SETCOS_PUTDATA:
return setcos_putdata(card,
(struct sc_cardctl_setcos_data_obj*) ptr);
break;
case SC_CARDCTL_SETCOS_GETDATA:
return setcos_getdata(card,
(struct sc_cardctl_setcos_data_obj*) ptr);
break;
case SC_CARDCTL_SETCOS_GENERATE_STORE_KEY:
return setcos_generate_store_key(card,
(struct sc_cardctl_setcos_gen_store_key_info *) ptr);
case SC_CARDCTL_SETCOS_ACTIVATE_FILE:
return setcos_activate_file(card);
}
return SC_ERROR_NOT_SUPPORTED;
}
static struct sc_card_driver *sc_get_driver(void)
{
struct sc_card_driver *iso_drv = sc_get_iso7816_driver();
setcos_ops = *iso_drv->ops;
setcos_ops.match_card = setcos_match_card;
setcos_ops.init = setcos_init;
if (iso_ops == NULL)
iso_ops = iso_drv->ops;
setcos_ops.create_file = setcos_create_file;
setcos_ops.set_security_env = setcos_set_security_env;
setcos_ops.select_file = setcos_select_file;
setcos_ops.list_files = setcos_list_files;
setcos_ops.process_fci = setcos_process_fci;
setcos_ops.construct_fci = setcos_construct_fci;
setcos_ops.card_ctl = setcos_card_ctl;
return &setcos_drv;
}
struct sc_card_driver *sc_get_setcos_driver(void)
{
return sc_get_driver();
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_351_13 |
crossvul-cpp_data_bad_2669_0 | /*
* Copyright (c) 1995, 1996
* The Regents of the University of California. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that: (1) source code distributions
* retain the above copyright notice and this paragraph in its entirety, (2)
* distributions including binary code include the above copyright notice and
* this paragraph in its entirety in the documentation or other materials
* provided with the distribution, and (3) all advertising materials mentioning
* features or use of this software display the following acknowledgement:
* ``This product includes software developed by the University of California,
* Lawrence Berkeley Laboratory and its contributors.'' Neither the name of
* the University nor the names of its contributors may be used to endorse
* or promote products derived from this software without specific prior
* written permission.
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
/* \summary: Protocol Independent Multicast (PIM) printer */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <netdissect-stdinc.h>
#include "netdissect.h"
#include "addrtoname.h"
#include "extract.h"
#include "ip.h"
#include "ip6.h"
#include "ipproto.h"
#define PIMV1_TYPE_QUERY 0
#define PIMV1_TYPE_REGISTER 1
#define PIMV1_TYPE_REGISTER_STOP 2
#define PIMV1_TYPE_JOIN_PRUNE 3
#define PIMV1_TYPE_RP_REACHABILITY 4
#define PIMV1_TYPE_ASSERT 5
#define PIMV1_TYPE_GRAFT 6
#define PIMV1_TYPE_GRAFT_ACK 7
static const struct tok pimv1_type_str[] = {
{ PIMV1_TYPE_QUERY, "Query" },
{ PIMV1_TYPE_REGISTER, "Register" },
{ PIMV1_TYPE_REGISTER_STOP, "Register-Stop" },
{ PIMV1_TYPE_JOIN_PRUNE, "Join/Prune" },
{ PIMV1_TYPE_RP_REACHABILITY, "RP-reachable" },
{ PIMV1_TYPE_ASSERT, "Assert" },
{ PIMV1_TYPE_GRAFT, "Graft" },
{ PIMV1_TYPE_GRAFT_ACK, "Graft-ACK" },
{ 0, NULL }
};
#define PIMV2_TYPE_HELLO 0
#define PIMV2_TYPE_REGISTER 1
#define PIMV2_TYPE_REGISTER_STOP 2
#define PIMV2_TYPE_JOIN_PRUNE 3
#define PIMV2_TYPE_BOOTSTRAP 4
#define PIMV2_TYPE_ASSERT 5
#define PIMV2_TYPE_GRAFT 6
#define PIMV2_TYPE_GRAFT_ACK 7
#define PIMV2_TYPE_CANDIDATE_RP 8
#define PIMV2_TYPE_PRUNE_REFRESH 9
#define PIMV2_TYPE_DF_ELECTION 10
#define PIMV2_TYPE_ECMP_REDIRECT 11
static const struct tok pimv2_type_values[] = {
{ PIMV2_TYPE_HELLO, "Hello" },
{ PIMV2_TYPE_REGISTER, "Register" },
{ PIMV2_TYPE_REGISTER_STOP, "Register Stop" },
{ PIMV2_TYPE_JOIN_PRUNE, "Join / Prune" },
{ PIMV2_TYPE_BOOTSTRAP, "Bootstrap" },
{ PIMV2_TYPE_ASSERT, "Assert" },
{ PIMV2_TYPE_GRAFT, "Graft" },
{ PIMV2_TYPE_GRAFT_ACK, "Graft Acknowledgement" },
{ PIMV2_TYPE_CANDIDATE_RP, "Candidate RP Advertisement" },
{ PIMV2_TYPE_PRUNE_REFRESH, "Prune Refresh" },
{ PIMV2_TYPE_DF_ELECTION, "DF Election" },
{ PIMV2_TYPE_ECMP_REDIRECT, "ECMP Redirect" },
{ 0, NULL}
};
#define PIMV2_HELLO_OPTION_HOLDTIME 1
#define PIMV2_HELLO_OPTION_LANPRUNEDELAY 2
#define PIMV2_HELLO_OPTION_DR_PRIORITY_OLD 18
#define PIMV2_HELLO_OPTION_DR_PRIORITY 19
#define PIMV2_HELLO_OPTION_GENID 20
#define PIMV2_HELLO_OPTION_REFRESH_CAP 21
#define PIMV2_HELLO_OPTION_BIDIR_CAP 22
#define PIMV2_HELLO_OPTION_ADDRESS_LIST 24
#define PIMV2_HELLO_OPTION_ADDRESS_LIST_OLD 65001
static const struct tok pimv2_hello_option_values[] = {
{ PIMV2_HELLO_OPTION_HOLDTIME, "Hold Time" },
{ PIMV2_HELLO_OPTION_LANPRUNEDELAY, "LAN Prune Delay" },
{ PIMV2_HELLO_OPTION_DR_PRIORITY_OLD, "DR Priority (Old)" },
{ PIMV2_HELLO_OPTION_DR_PRIORITY, "DR Priority" },
{ PIMV2_HELLO_OPTION_GENID, "Generation ID" },
{ PIMV2_HELLO_OPTION_REFRESH_CAP, "State Refresh Capability" },
{ PIMV2_HELLO_OPTION_BIDIR_CAP, "Bi-Directional Capability" },
{ PIMV2_HELLO_OPTION_ADDRESS_LIST, "Address List" },
{ PIMV2_HELLO_OPTION_ADDRESS_LIST_OLD, "Address List (Old)" },
{ 0, NULL}
};
#define PIMV2_REGISTER_FLAG_LEN 4
#define PIMV2_REGISTER_FLAG_BORDER 0x80000000
#define PIMV2_REGISTER_FLAG_NULL 0x40000000
static const struct tok pimv2_register_flag_values[] = {
{ PIMV2_REGISTER_FLAG_BORDER, "Border" },
{ PIMV2_REGISTER_FLAG_NULL, "Null" },
{ 0, NULL}
};
/*
* XXX: We consider a case where IPv6 is not ready yet for portability,
* but PIM dependent defintions should be independent of IPv6...
*/
struct pim {
uint8_t pim_typever;
/* upper 4bit: PIM version number; 2 for PIMv2 */
/* lower 4bit: the PIM message type, currently they are:
* Hello, Register, Register-Stop, Join/Prune,
* Bootstrap, Assert, Graft (PIM-DM only),
* Graft-Ack (PIM-DM only), C-RP-Adv
*/
#define PIM_VER(x) (((x) & 0xf0) >> 4)
#define PIM_TYPE(x) ((x) & 0x0f)
u_char pim_rsv; /* Reserved */
u_short pim_cksum; /* IP style check sum */
};
static void pimv2_print(netdissect_options *, register const u_char *bp, register u_int len, const u_char *);
static void
pimv1_join_prune_print(netdissect_options *ndo,
register const u_char *bp, register u_int len)
{
int ngroups, njoin, nprune;
int njp;
/* If it's a single group and a single source, use 1-line output. */
if (ND_TTEST2(bp[0], 30) && bp[11] == 1 &&
((njoin = EXTRACT_16BITS(&bp[20])) + EXTRACT_16BITS(&bp[22])) == 1) {
int hold;
ND_PRINT((ndo, " RPF %s ", ipaddr_string(ndo, bp)));
hold = EXTRACT_16BITS(&bp[6]);
if (hold != 180) {
ND_PRINT((ndo, "Hold "));
unsigned_relts_print(ndo, hold);
}
ND_PRINT((ndo, "%s (%s/%d, %s", njoin ? "Join" : "Prune",
ipaddr_string(ndo, &bp[26]), bp[25] & 0x3f,
ipaddr_string(ndo, &bp[12])));
if (EXTRACT_32BITS(&bp[16]) != 0xffffffff)
ND_PRINT((ndo, "/%s", ipaddr_string(ndo, &bp[16])));
ND_PRINT((ndo, ") %s%s %s",
(bp[24] & 0x01) ? "Sparse" : "Dense",
(bp[25] & 0x80) ? " WC" : "",
(bp[25] & 0x40) ? "RP" : "SPT"));
return;
}
ND_TCHECK2(bp[0], sizeof(struct in_addr));
if (ndo->ndo_vflag > 1)
ND_PRINT((ndo, "\n"));
ND_PRINT((ndo, " Upstream Nbr: %s", ipaddr_string(ndo, bp)));
ND_TCHECK2(bp[6], 2);
if (ndo->ndo_vflag > 1)
ND_PRINT((ndo, "\n"));
ND_PRINT((ndo, " Hold time: "));
unsigned_relts_print(ndo, EXTRACT_16BITS(&bp[6]));
if (ndo->ndo_vflag < 2)
return;
bp += 8;
len -= 8;
ND_TCHECK2(bp[0], 4);
ngroups = bp[3];
bp += 4;
len -= 4;
while (ngroups--) {
/*
* XXX - does the address have length "addrlen" and the
* mask length "maddrlen"?
*/
ND_TCHECK2(bp[0], sizeof(struct in_addr));
ND_PRINT((ndo, "\n\tGroup: %s", ipaddr_string(ndo, bp)));
ND_TCHECK2(bp[4], sizeof(struct in_addr));
if (EXTRACT_32BITS(&bp[4]) != 0xffffffff)
ND_PRINT((ndo, "/%s", ipaddr_string(ndo, &bp[4])));
ND_TCHECK2(bp[8], 4);
njoin = EXTRACT_16BITS(&bp[8]);
nprune = EXTRACT_16BITS(&bp[10]);
ND_PRINT((ndo, " joined: %d pruned: %d", njoin, nprune));
bp += 12;
len -= 12;
for (njp = 0; njp < (njoin + nprune); njp++) {
const char *type;
if (njp < njoin)
type = "Join ";
else
type = "Prune";
ND_TCHECK2(bp[0], 6);
ND_PRINT((ndo, "\n\t%s %s%s%s%s/%d", type,
(bp[0] & 0x01) ? "Sparse " : "Dense ",
(bp[1] & 0x80) ? "WC " : "",
(bp[1] & 0x40) ? "RP " : "SPT ",
ipaddr_string(ndo, &bp[2]), bp[1] & 0x3f));
bp += 6;
len -= 6;
}
}
return;
trunc:
ND_PRINT((ndo, "[|pim]"));
return;
}
void
pimv1_print(netdissect_options *ndo,
register const u_char *bp, register u_int len)
{
register const u_char *ep;
register u_char type;
ep = (const u_char *)ndo->ndo_snapend;
if (bp >= ep)
return;
ND_TCHECK(bp[1]);
type = bp[1];
ND_PRINT((ndo, " %s", tok2str(pimv1_type_str, "[type %u]", type)));
switch (type) {
case PIMV1_TYPE_QUERY:
if (ND_TTEST(bp[8])) {
switch (bp[8] >> 4) {
case 0:
ND_PRINT((ndo, " Dense-mode"));
break;
case 1:
ND_PRINT((ndo, " Sparse-mode"));
break;
case 2:
ND_PRINT((ndo, " Sparse-Dense-mode"));
break;
default:
ND_PRINT((ndo, " mode-%d", bp[8] >> 4));
break;
}
}
if (ndo->ndo_vflag) {
ND_TCHECK2(bp[10],2);
ND_PRINT((ndo, " (Hold-time "));
unsigned_relts_print(ndo, EXTRACT_16BITS(&bp[10]));
ND_PRINT((ndo, ")"));
}
break;
case PIMV1_TYPE_REGISTER:
ND_TCHECK2(bp[8], 20); /* ip header */
ND_PRINT((ndo, " for %s > %s", ipaddr_string(ndo, &bp[20]),
ipaddr_string(ndo, &bp[24])));
break;
case PIMV1_TYPE_REGISTER_STOP:
ND_TCHECK2(bp[12], sizeof(struct in_addr));
ND_PRINT((ndo, " for %s > %s", ipaddr_string(ndo, &bp[8]),
ipaddr_string(ndo, &bp[12])));
break;
case PIMV1_TYPE_RP_REACHABILITY:
if (ndo->ndo_vflag) {
ND_TCHECK2(bp[22], 2);
ND_PRINT((ndo, " group %s", ipaddr_string(ndo, &bp[8])));
if (EXTRACT_32BITS(&bp[12]) != 0xffffffff)
ND_PRINT((ndo, "/%s", ipaddr_string(ndo, &bp[12])));
ND_PRINT((ndo, " RP %s hold ", ipaddr_string(ndo, &bp[16])));
unsigned_relts_print(ndo, EXTRACT_16BITS(&bp[22]));
}
break;
case PIMV1_TYPE_ASSERT:
ND_TCHECK2(bp[16], sizeof(struct in_addr));
ND_PRINT((ndo, " for %s > %s", ipaddr_string(ndo, &bp[16]),
ipaddr_string(ndo, &bp[8])));
if (EXTRACT_32BITS(&bp[12]) != 0xffffffff)
ND_PRINT((ndo, "/%s", ipaddr_string(ndo, &bp[12])));
ND_TCHECK2(bp[24], 4);
ND_PRINT((ndo, " %s pref %d metric %d",
(bp[20] & 0x80) ? "RP-tree" : "SPT",
EXTRACT_32BITS(&bp[20]) & 0x7fffffff,
EXTRACT_32BITS(&bp[24])));
break;
case PIMV1_TYPE_JOIN_PRUNE:
case PIMV1_TYPE_GRAFT:
case PIMV1_TYPE_GRAFT_ACK:
if (ndo->ndo_vflag)
pimv1_join_prune_print(ndo, &bp[8], len - 8);
break;
}
ND_TCHECK(bp[4]);
if ((bp[4] >> 4) != 1)
ND_PRINT((ndo, " [v%d]", bp[4] >> 4));
return;
trunc:
ND_PRINT((ndo, "[|pim]"));
return;
}
/*
* auto-RP is a cisco protocol, documented at
* ftp://ftpeng.cisco.com/ipmulticast/specs/pim-autorp-spec01.txt
*
* This implements version 1+, dated Sept 9, 1998.
*/
void
cisco_autorp_print(netdissect_options *ndo,
register const u_char *bp, register u_int len)
{
int type;
int numrps;
int hold;
ND_TCHECK(bp[0]);
ND_PRINT((ndo, " auto-rp "));
type = bp[0];
switch (type) {
case 0x11:
ND_PRINT((ndo, "candidate-advert"));
break;
case 0x12:
ND_PRINT((ndo, "mapping"));
break;
default:
ND_PRINT((ndo, "type-0x%02x", type));
break;
}
ND_TCHECK(bp[1]);
numrps = bp[1];
ND_TCHECK2(bp[2], 2);
ND_PRINT((ndo, " Hold "));
hold = EXTRACT_16BITS(&bp[2]);
if (hold)
unsigned_relts_print(ndo, EXTRACT_16BITS(&bp[2]));
else
ND_PRINT((ndo, "FOREVER"));
/* Next 4 bytes are reserved. */
bp += 8; len -= 8;
/*XXX skip unless -v? */
/*
* Rest of packet:
* numrps entries of the form:
* 32 bits: RP
* 6 bits: reserved
* 2 bits: PIM version supported, bit 0 is "supports v1", 1 is "v2".
* 8 bits: # of entries for this RP
* each entry: 7 bits: reserved, 1 bit: negative,
* 8 bits: mask 32 bits: source
* lather, rinse, repeat.
*/
while (numrps--) {
int nentries;
char s;
ND_TCHECK2(bp[0], 4);
ND_PRINT((ndo, " RP %s", ipaddr_string(ndo, bp)));
ND_TCHECK(bp[4]);
switch (bp[4] & 0x3) {
case 0: ND_PRINT((ndo, " PIMv?"));
break;
case 1: ND_PRINT((ndo, " PIMv1"));
break;
case 2: ND_PRINT((ndo, " PIMv2"));
break;
case 3: ND_PRINT((ndo, " PIMv1+2"));
break;
}
if (bp[4] & 0xfc)
ND_PRINT((ndo, " [rsvd=0x%02x]", bp[4] & 0xfc));
ND_TCHECK(bp[5]);
nentries = bp[5];
bp += 6; len -= 6;
s = ' ';
for (; nentries; nentries--) {
ND_TCHECK2(bp[0], 6);
ND_PRINT((ndo, "%c%s%s/%d", s, bp[0] & 1 ? "!" : "",
ipaddr_string(ndo, &bp[2]), bp[1]));
if (bp[0] & 0x02) {
ND_PRINT((ndo, " bidir"));
}
if (bp[0] & 0xfc) {
ND_PRINT((ndo, "[rsvd=0x%02x]", bp[0] & 0xfc));
}
s = ',';
bp += 6; len -= 6;
}
}
return;
trunc:
ND_PRINT((ndo, "[|autorp]"));
return;
}
void
pim_print(netdissect_options *ndo,
register const u_char *bp, register u_int len, const u_char *bp2)
{
register const u_char *ep;
register const struct pim *pim = (const struct pim *)bp;
ep = (const u_char *)ndo->ndo_snapend;
if (bp >= ep)
return;
#ifdef notyet /* currently we see only version and type */
ND_TCHECK(pim->pim_rsv);
#endif
switch (PIM_VER(pim->pim_typever)) {
case 2:
if (!ndo->ndo_vflag) {
ND_PRINT((ndo, "PIMv%u, %s, length %u",
PIM_VER(pim->pim_typever),
tok2str(pimv2_type_values,"Unknown Type",PIM_TYPE(pim->pim_typever)),
len));
return;
} else {
ND_PRINT((ndo, "PIMv%u, length %u\n\t%s",
PIM_VER(pim->pim_typever),
len,
tok2str(pimv2_type_values,"Unknown Type",PIM_TYPE(pim->pim_typever))));
pimv2_print(ndo, bp, len, bp2);
}
break;
default:
ND_PRINT((ndo, "PIMv%u, length %u",
PIM_VER(pim->pim_typever),
len));
break;
}
return;
}
/*
* PIMv2 uses encoded address representations.
*
* The last PIM-SM I-D before RFC2117 was published specified the
* following representation for unicast addresses. However, RFC2117
* specified no encoding for unicast addresses with the unicast
* address length specified in the header. Therefore, we have to
* guess which encoding is being used (Cisco's PIMv2 implementation
* uses the non-RFC encoding). RFC2117 turns a previously "Reserved"
* field into a 'unicast-address-length-in-bytes' field. We guess
* that it's the draft encoding if this reserved field is zero.
*
* RFC2362 goes back to the encoded format, and calls the addr length
* field "reserved" again.
*
* The first byte is the address family, from:
*
* 0 Reserved
* 1 IP (IP version 4)
* 2 IP6 (IP version 6)
* 3 NSAP
* 4 HDLC (8-bit multidrop)
* 5 BBN 1822
* 6 802 (includes all 802 media plus Ethernet "canonical format")
* 7 E.163
* 8 E.164 (SMDS, Frame Relay, ATM)
* 9 F.69 (Telex)
* 10 X.121 (X.25, Frame Relay)
* 11 IPX
* 12 Appletalk
* 13 Decnet IV
* 14 Banyan Vines
* 15 E.164 with NSAP format subaddress
*
* In addition, the second byte is an "Encoding". 0 is the default
* encoding for the address family, and no other encodings are currently
* specified.
*
*/
static int pimv2_addr_len;
enum pimv2_addrtype {
pimv2_unicast, pimv2_group, pimv2_source
};
/* 0 1 2 3
* 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Addr Family | Encoding Type | Unicast Address |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+++++++
* 0 1 2 3
* 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Addr Family | Encoding Type | Reserved | Mask Len |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Group multicast Address |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* 0 1 2 3
* 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Addr Family | Encoding Type | Rsrvd |S|W|R| Mask Len |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Source Address |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*/
static int
pimv2_addr_print(netdissect_options *ndo,
const u_char *bp, enum pimv2_addrtype at, int silent)
{
int af;
int len, hdrlen;
ND_TCHECK(bp[0]);
if (pimv2_addr_len == 0) {
ND_TCHECK(bp[1]);
switch (bp[0]) {
case 1:
af = AF_INET;
len = sizeof(struct in_addr);
break;
case 2:
af = AF_INET6;
len = sizeof(struct in6_addr);
break;
default:
return -1;
}
if (bp[1] != 0)
return -1;
hdrlen = 2;
} else {
switch (pimv2_addr_len) {
case sizeof(struct in_addr):
af = AF_INET;
break;
case sizeof(struct in6_addr):
af = AF_INET6;
break;
default:
return -1;
break;
}
len = pimv2_addr_len;
hdrlen = 0;
}
bp += hdrlen;
switch (at) {
case pimv2_unicast:
ND_TCHECK2(bp[0], len);
if (af == AF_INET) {
if (!silent)
ND_PRINT((ndo, "%s", ipaddr_string(ndo, bp)));
}
else if (af == AF_INET6) {
if (!silent)
ND_PRINT((ndo, "%s", ip6addr_string(ndo, bp)));
}
return hdrlen + len;
case pimv2_group:
case pimv2_source:
ND_TCHECK2(bp[0], len + 2);
if (af == AF_INET) {
if (!silent) {
ND_PRINT((ndo, "%s", ipaddr_string(ndo, bp + 2)));
if (bp[1] != 32)
ND_PRINT((ndo, "/%u", bp[1]));
}
}
else if (af == AF_INET6) {
if (!silent) {
ND_PRINT((ndo, "%s", ip6addr_string(ndo, bp + 2)));
if (bp[1] != 128)
ND_PRINT((ndo, "/%u", bp[1]));
}
}
if (bp[0] && !silent) {
if (at == pimv2_group) {
ND_PRINT((ndo, "(0x%02x)", bp[0]));
} else {
ND_PRINT((ndo, "(%s%s%s",
bp[0] & 0x04 ? "S" : "",
bp[0] & 0x02 ? "W" : "",
bp[0] & 0x01 ? "R" : ""));
if (bp[0] & 0xf8) {
ND_PRINT((ndo, "+0x%02x", bp[0] & 0xf8));
}
ND_PRINT((ndo, ")"));
}
}
return hdrlen + 2 + len;
default:
return -1;
}
trunc:
return -1;
}
enum checksum_status {
CORRECT,
INCORRECT,
UNVERIFIED
};
static enum checksum_status
pimv2_check_checksum(netdissect_options *ndo, const u_char *bp,
const u_char *bp2, u_int len)
{
const struct ip *ip;
u_int cksum;
if (!ND_TTEST2(bp[0], len)) {
/* We don't have all the data. */
return (UNVERIFIED);
}
ip = (const struct ip *)bp2;
if (IP_V(ip) == 4) {
struct cksum_vec vec[1];
vec[0].ptr = bp;
vec[0].len = len;
cksum = in_cksum(vec, 1);
return (cksum ? INCORRECT : CORRECT);
} else if (IP_V(ip) == 6) {
const struct ip6_hdr *ip6;
ip6 = (const struct ip6_hdr *)bp2;
cksum = nextproto6_cksum(ndo, ip6, bp, len, len, IPPROTO_PIM);
return (cksum ? INCORRECT : CORRECT);
} else {
return (UNVERIFIED);
}
}
static void
pimv2_print(netdissect_options *ndo,
register const u_char *bp, register u_int len, const u_char *bp2)
{
register const u_char *ep;
register const struct pim *pim = (const struct pim *)bp;
int advance;
enum checksum_status cksum_status;
ep = (const u_char *)ndo->ndo_snapend;
if (bp >= ep)
return;
if (ep > bp + len)
ep = bp + len;
ND_TCHECK(pim->pim_rsv);
pimv2_addr_len = pim->pim_rsv;
if (pimv2_addr_len != 0)
ND_PRINT((ndo, ", RFC2117-encoding"));
ND_PRINT((ndo, ", cksum 0x%04x ", EXTRACT_16BITS(&pim->pim_cksum)));
if (EXTRACT_16BITS(&pim->pim_cksum) == 0) {
ND_PRINT((ndo, "(unverified)"));
} else {
if (PIM_TYPE(pim->pim_typever) == PIMV2_TYPE_REGISTER) {
/*
* The checksum only covers the packet header,
* not the encapsulated packet.
*/
cksum_status = pimv2_check_checksum(ndo, bp, bp2, 8);
if (cksum_status == INCORRECT) {
/*
* To quote RFC 4601, "For interoperability
* reasons, a message carrying a checksum
* calculated over the entire PIM Register
* message should also be accepted."
*/
cksum_status = pimv2_check_checksum(ndo, bp, bp2, len);
}
} else {
/*
* The checksum covers the entire packet.
*/
cksum_status = pimv2_check_checksum(ndo, bp, bp2, len);
}
switch (cksum_status) {
case CORRECT:
ND_PRINT((ndo, "(correct)"));
break;
case INCORRECT:
ND_PRINT((ndo, "(incorrect)"));
break;
case UNVERIFIED:
ND_PRINT((ndo, "(unverified)"));
break;
}
}
switch (PIM_TYPE(pim->pim_typever)) {
case PIMV2_TYPE_HELLO:
{
uint16_t otype, olen;
bp += 4;
while (bp < ep) {
ND_TCHECK2(bp[0], 4);
otype = EXTRACT_16BITS(&bp[0]);
olen = EXTRACT_16BITS(&bp[2]);
ND_TCHECK2(bp[0], 4 + olen);
ND_PRINT((ndo, "\n\t %s Option (%u), length %u, Value: ",
tok2str(pimv2_hello_option_values, "Unknown", otype),
otype,
olen));
bp += 4;
switch (otype) {
case PIMV2_HELLO_OPTION_HOLDTIME:
unsigned_relts_print(ndo, EXTRACT_16BITS(bp));
break;
case PIMV2_HELLO_OPTION_LANPRUNEDELAY:
if (olen != 4) {
ND_PRINT((ndo, "ERROR: Option Length != 4 Bytes (%u)", olen));
} else {
char t_bit;
uint16_t lan_delay, override_interval;
lan_delay = EXTRACT_16BITS(bp);
override_interval = EXTRACT_16BITS(bp+2);
t_bit = (lan_delay & 0x8000)? 1 : 0;
lan_delay &= ~0x8000;
ND_PRINT((ndo, "\n\t T-bit=%d, LAN delay %dms, Override interval %dms",
t_bit, lan_delay, override_interval));
}
break;
case PIMV2_HELLO_OPTION_DR_PRIORITY_OLD:
case PIMV2_HELLO_OPTION_DR_PRIORITY:
switch (olen) {
case 0:
ND_PRINT((ndo, "Bi-Directional Capability (Old)"));
break;
case 4:
ND_PRINT((ndo, "%u", EXTRACT_32BITS(bp)));
break;
default:
ND_PRINT((ndo, "ERROR: Option Length != 4 Bytes (%u)", olen));
break;
}
break;
case PIMV2_HELLO_OPTION_GENID:
ND_PRINT((ndo, "0x%08x", EXTRACT_32BITS(bp)));
break;
case PIMV2_HELLO_OPTION_REFRESH_CAP:
ND_PRINT((ndo, "v%d", *bp));
if (*(bp+1) != 0) {
ND_PRINT((ndo, ", interval "));
unsigned_relts_print(ndo, *(bp+1));
}
if (EXTRACT_16BITS(bp+2) != 0) {
ND_PRINT((ndo, " ?0x%04x?", EXTRACT_16BITS(bp+2)));
}
break;
case PIMV2_HELLO_OPTION_BIDIR_CAP:
break;
case PIMV2_HELLO_OPTION_ADDRESS_LIST_OLD:
case PIMV2_HELLO_OPTION_ADDRESS_LIST:
if (ndo->ndo_vflag > 1) {
const u_char *ptr = bp;
while (ptr < (bp+olen)) {
ND_PRINT((ndo, "\n\t "));
advance = pimv2_addr_print(ndo, ptr, pimv2_unicast, 0);
if (advance < 0) {
ND_PRINT((ndo, "..."));
break;
}
ptr += advance;
}
}
break;
default:
if (ndo->ndo_vflag <= 1)
print_unknown_data(ndo, bp, "\n\t ", olen);
break;
}
/* do we want to see an additionally hexdump ? */
if (ndo->ndo_vflag> 1)
print_unknown_data(ndo, bp, "\n\t ", olen);
bp += olen;
}
break;
}
case PIMV2_TYPE_REGISTER:
{
const struct ip *ip;
ND_TCHECK2(*(bp + 4), PIMV2_REGISTER_FLAG_LEN);
ND_PRINT((ndo, ", Flags [ %s ]\n\t",
tok2str(pimv2_register_flag_values,
"none",
EXTRACT_32BITS(bp+4))));
bp += 8; len -= 8;
/* encapsulated multicast packet */
ip = (const struct ip *)bp;
switch (IP_V(ip)) {
case 0: /* Null header */
ND_PRINT((ndo, "IP-Null-header %s > %s",
ipaddr_string(ndo, &ip->ip_src),
ipaddr_string(ndo, &ip->ip_dst)));
break;
case 4: /* IPv4 */
ip_print(ndo, bp, len);
break;
case 6: /* IPv6 */
ip6_print(ndo, bp, len);
break;
default:
ND_PRINT((ndo, "IP ver %d", IP_V(ip)));
break;
}
break;
}
case PIMV2_TYPE_REGISTER_STOP:
bp += 4; len -= 4;
if (bp >= ep)
break;
ND_PRINT((ndo, " group="));
if ((advance = pimv2_addr_print(ndo, bp, pimv2_group, 0)) < 0) {
ND_PRINT((ndo, "..."));
break;
}
bp += advance; len -= advance;
if (bp >= ep)
break;
ND_PRINT((ndo, " source="));
if ((advance = pimv2_addr_print(ndo, bp, pimv2_unicast, 0)) < 0) {
ND_PRINT((ndo, "..."));
break;
}
bp += advance; len -= advance;
break;
case PIMV2_TYPE_JOIN_PRUNE:
case PIMV2_TYPE_GRAFT:
case PIMV2_TYPE_GRAFT_ACK:
/*
* 0 1 2 3
* 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* |PIM Ver| Type | Addr length | Checksum |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Unicast-Upstream Neighbor Address |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Reserved | Num groups | Holdtime |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Encoded-Multicast Group Address-1 |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Number of Joined Sources | Number of Pruned Sources |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Encoded-Joined Source Address-1 |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | . |
* | . |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Encoded-Joined Source Address-n |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Encoded-Pruned Source Address-1 |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | . |
* | . |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Encoded-Pruned Source Address-n |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | . |
* | . |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Encoded-Multicast Group Address-n |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*/
{
uint8_t ngroup;
uint16_t holdtime;
uint16_t njoin;
uint16_t nprune;
int i, j;
bp += 4; len -= 4;
if (PIM_TYPE(pim->pim_typever) != 7) { /*not for Graft-ACK*/
if (bp >= ep)
break;
ND_PRINT((ndo, ", upstream-neighbor: "));
if ((advance = pimv2_addr_print(ndo, bp, pimv2_unicast, 0)) < 0) {
ND_PRINT((ndo, "..."));
break;
}
bp += advance; len -= advance;
}
if (bp + 4 > ep)
break;
ngroup = bp[1];
holdtime = EXTRACT_16BITS(&bp[2]);
ND_PRINT((ndo, "\n\t %u group(s)", ngroup));
if (PIM_TYPE(pim->pim_typever) != 7) { /*not for Graft-ACK*/
ND_PRINT((ndo, ", holdtime: "));
if (holdtime == 0xffff)
ND_PRINT((ndo, "infinite"));
else
unsigned_relts_print(ndo, holdtime);
}
bp += 4; len -= 4;
for (i = 0; i < ngroup; i++) {
if (bp >= ep)
goto jp_done;
ND_PRINT((ndo, "\n\t group #%u: ", i+1));
if ((advance = pimv2_addr_print(ndo, bp, pimv2_group, 0)) < 0) {
ND_PRINT((ndo, "...)"));
goto jp_done;
}
bp += advance; len -= advance;
if (bp + 4 > ep) {
ND_PRINT((ndo, "...)"));
goto jp_done;
}
njoin = EXTRACT_16BITS(&bp[0]);
nprune = EXTRACT_16BITS(&bp[2]);
ND_PRINT((ndo, ", joined sources: %u, pruned sources: %u", njoin, nprune));
bp += 4; len -= 4;
for (j = 0; j < njoin; j++) {
ND_PRINT((ndo, "\n\t joined source #%u: ", j+1));
if ((advance = pimv2_addr_print(ndo, bp, pimv2_source, 0)) < 0) {
ND_PRINT((ndo, "...)"));
goto jp_done;
}
bp += advance; len -= advance;
}
for (j = 0; j < nprune; j++) {
ND_PRINT((ndo, "\n\t pruned source #%u: ", j+1));
if ((advance = pimv2_addr_print(ndo, bp, pimv2_source, 0)) < 0) {
ND_PRINT((ndo, "...)"));
goto jp_done;
}
bp += advance; len -= advance;
}
}
jp_done:
break;
}
case PIMV2_TYPE_BOOTSTRAP:
{
int i, j, frpcnt;
bp += 4;
/* Fragment Tag, Hash Mask len, and BSR-priority */
if (bp + sizeof(uint16_t) >= ep) break;
ND_PRINT((ndo, " tag=%x", EXTRACT_16BITS(bp)));
bp += sizeof(uint16_t);
if (bp >= ep) break;
ND_PRINT((ndo, " hashmlen=%d", bp[0]));
if (bp + 1 >= ep) break;
ND_PRINT((ndo, " BSRprio=%d", bp[1]));
bp += 2;
/* Encoded-Unicast-BSR-Address */
if (bp >= ep) break;
ND_PRINT((ndo, " BSR="));
if ((advance = pimv2_addr_print(ndo, bp, pimv2_unicast, 0)) < 0) {
ND_PRINT((ndo, "..."));
break;
}
bp += advance;
for (i = 0; bp < ep; i++) {
/* Encoded-Group Address */
ND_PRINT((ndo, " (group%d: ", i));
if ((advance = pimv2_addr_print(ndo, bp, pimv2_group, 0))
< 0) {
ND_PRINT((ndo, "...)"));
goto bs_done;
}
bp += advance;
/* RP-Count, Frag RP-Cnt, and rsvd */
if (bp >= ep) {
ND_PRINT((ndo, "...)"));
goto bs_done;
}
ND_PRINT((ndo, " RPcnt=%d", bp[0]));
if (bp + 1 >= ep) {
ND_PRINT((ndo, "...)"));
goto bs_done;
}
ND_PRINT((ndo, " FRPcnt=%d", frpcnt = bp[1]));
bp += 4;
for (j = 0; j < frpcnt && bp < ep; j++) {
/* each RP info */
ND_PRINT((ndo, " RP%d=", j));
if ((advance = pimv2_addr_print(ndo, bp,
pimv2_unicast,
0)) < 0) {
ND_PRINT((ndo, "...)"));
goto bs_done;
}
bp += advance;
if (bp + 1 >= ep) {
ND_PRINT((ndo, "...)"));
goto bs_done;
}
ND_PRINT((ndo, ",holdtime="));
unsigned_relts_print(ndo, EXTRACT_16BITS(bp));
if (bp + 2 >= ep) {
ND_PRINT((ndo, "...)"));
goto bs_done;
}
ND_PRINT((ndo, ",prio=%d", bp[2]));
bp += 4;
}
ND_PRINT((ndo, ")"));
}
bs_done:
break;
}
case PIMV2_TYPE_ASSERT:
bp += 4; len -= 4;
if (bp >= ep)
break;
ND_PRINT((ndo, " group="));
if ((advance = pimv2_addr_print(ndo, bp, pimv2_group, 0)) < 0) {
ND_PRINT((ndo, "..."));
break;
}
bp += advance; len -= advance;
if (bp >= ep)
break;
ND_PRINT((ndo, " src="));
if ((advance = pimv2_addr_print(ndo, bp, pimv2_unicast, 0)) < 0) {
ND_PRINT((ndo, "..."));
break;
}
bp += advance; len -= advance;
if (bp + 8 > ep)
break;
if (bp[0] & 0x80)
ND_PRINT((ndo, " RPT"));
ND_PRINT((ndo, " pref=%u", EXTRACT_32BITS(&bp[0]) & 0x7fffffff));
ND_PRINT((ndo, " metric=%u", EXTRACT_32BITS(&bp[4])));
break;
case PIMV2_TYPE_CANDIDATE_RP:
{
int i, pfxcnt;
bp += 4;
/* Prefix-Cnt, Priority, and Holdtime */
if (bp >= ep) break;
ND_PRINT((ndo, " prefix-cnt=%d", bp[0]));
pfxcnt = bp[0];
if (bp + 1 >= ep) break;
ND_PRINT((ndo, " prio=%d", bp[1]));
if (bp + 3 >= ep) break;
ND_PRINT((ndo, " holdtime="));
unsigned_relts_print(ndo, EXTRACT_16BITS(&bp[2]));
bp += 4;
/* Encoded-Unicast-RP-Address */
if (bp >= ep) break;
ND_PRINT((ndo, " RP="));
if ((advance = pimv2_addr_print(ndo, bp, pimv2_unicast, 0)) < 0) {
ND_PRINT((ndo, "..."));
break;
}
bp += advance;
/* Encoded-Group Addresses */
for (i = 0; i < pfxcnt && bp < ep; i++) {
ND_PRINT((ndo, " Group%d=", i));
if ((advance = pimv2_addr_print(ndo, bp, pimv2_group, 0))
< 0) {
ND_PRINT((ndo, "..."));
break;
}
bp += advance;
}
break;
}
case PIMV2_TYPE_PRUNE_REFRESH:
ND_PRINT((ndo, " src="));
if ((advance = pimv2_addr_print(ndo, bp, pimv2_unicast, 0)) < 0) {
ND_PRINT((ndo, "..."));
break;
}
bp += advance;
ND_PRINT((ndo, " grp="));
if ((advance = pimv2_addr_print(ndo, bp, pimv2_group, 0)) < 0) {
ND_PRINT((ndo, "..."));
break;
}
bp += advance;
ND_PRINT((ndo, " forwarder="));
if ((advance = pimv2_addr_print(ndo, bp, pimv2_unicast, 0)) < 0) {
ND_PRINT((ndo, "..."));
break;
}
bp += advance;
ND_TCHECK2(bp[0], 2);
ND_PRINT((ndo, " TUNR "));
unsigned_relts_print(ndo, EXTRACT_16BITS(bp));
break;
default:
ND_PRINT((ndo, " [type %d]", PIM_TYPE(pim->pim_typever)));
break;
}
return;
trunc:
ND_PRINT((ndo, "[|pim]"));
}
/*
* Local Variables:
* c-style: whitesmith
* c-basic-offset: 8
* End:
*/
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_2669_0 |
crossvul-cpp_data_bad_2644_11 | /*
* Copyright (c) 1990, 1991, 1993, 1994, 1995, 1996, 1997
* The Regents of the University of California. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that: (1) source code distributions
* retain the above copyright notice and this paragraph in its entirety, (2)
* distributions including binary code include the above copyright notice and
* this paragraph in its entirety in the documentation or other materials
* provided with the distribution, and (3) all advertising materials mentioning
* features or use of this software display the following acknowledgement:
* ``This product includes software developed by the University of California,
* Lawrence Berkeley Laboratory and its contributors.'' Neither the name of
* the University nor the names of its contributors may be used to endorse
* or promote products derived from this software without specific prior
* written permission.
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*
* Extensively modified by Motonori Shindo (mshindo@mshindo.net) for more
* complete PPP support.
*/
/* \summary: Point to Point Protocol (PPP) printer */
/*
* TODO:
* o resolve XXX as much as possible
* o MP support
* o BAP support
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <netdissect-stdinc.h>
#ifdef __bsdi__
#include <net/slcompress.h>
#include <net/if_ppp.h>
#endif
#include <stdlib.h>
#include "netdissect.h"
#include "extract.h"
#include "addrtoname.h"
#include "ppp.h"
#include "chdlc.h"
#include "ethertype.h"
#include "oui.h"
/*
* The following constatns are defined by IANA. Please refer to
* http://www.isi.edu/in-notes/iana/assignments/ppp-numbers
* for the up-to-date information.
*/
/* Protocol Codes defined in ppp.h */
static const struct tok ppptype2str[] = {
{ PPP_IP, "IP" },
{ PPP_OSI, "OSI" },
{ PPP_NS, "NS" },
{ PPP_DECNET, "DECNET" },
{ PPP_APPLE, "APPLE" },
{ PPP_IPX, "IPX" },
{ PPP_VJC, "VJC IP" },
{ PPP_VJNC, "VJNC IP" },
{ PPP_BRPDU, "BRPDU" },
{ PPP_STII, "STII" },
{ PPP_VINES, "VINES" },
{ PPP_MPLS_UCAST, "MPLS" },
{ PPP_MPLS_MCAST, "MPLS" },
{ PPP_COMP, "Compressed"},
{ PPP_ML, "MLPPP"},
{ PPP_IPV6, "IP6"},
{ PPP_HELLO, "HELLO" },
{ PPP_LUXCOM, "LUXCOM" },
{ PPP_SNS, "SNS" },
{ PPP_IPCP, "IPCP" },
{ PPP_OSICP, "OSICP" },
{ PPP_NSCP, "NSCP" },
{ PPP_DECNETCP, "DECNETCP" },
{ PPP_APPLECP, "APPLECP" },
{ PPP_IPXCP, "IPXCP" },
{ PPP_STIICP, "STIICP" },
{ PPP_VINESCP, "VINESCP" },
{ PPP_IPV6CP, "IP6CP" },
{ PPP_MPLSCP, "MPLSCP" },
{ PPP_LCP, "LCP" },
{ PPP_PAP, "PAP" },
{ PPP_LQM, "LQM" },
{ PPP_CHAP, "CHAP" },
{ PPP_EAP, "EAP" },
{ PPP_SPAP, "SPAP" },
{ PPP_SPAP_OLD, "Old-SPAP" },
{ PPP_BACP, "BACP" },
{ PPP_BAP, "BAP" },
{ PPP_MPCP, "MLPPP-CP" },
{ PPP_CCP, "CCP" },
{ 0, NULL }
};
/* Control Protocols (LCP/IPCP/CCP etc.) Codes defined in RFC 1661 */
#define CPCODES_VEXT 0 /* Vendor-Specific (RFC2153) */
#define CPCODES_CONF_REQ 1 /* Configure-Request */
#define CPCODES_CONF_ACK 2 /* Configure-Ack */
#define CPCODES_CONF_NAK 3 /* Configure-Nak */
#define CPCODES_CONF_REJ 4 /* Configure-Reject */
#define CPCODES_TERM_REQ 5 /* Terminate-Request */
#define CPCODES_TERM_ACK 6 /* Terminate-Ack */
#define CPCODES_CODE_REJ 7 /* Code-Reject */
#define CPCODES_PROT_REJ 8 /* Protocol-Reject (LCP only) */
#define CPCODES_ECHO_REQ 9 /* Echo-Request (LCP only) */
#define CPCODES_ECHO_RPL 10 /* Echo-Reply (LCP only) */
#define CPCODES_DISC_REQ 11 /* Discard-Request (LCP only) */
#define CPCODES_ID 12 /* Identification (LCP only) RFC1570 */
#define CPCODES_TIME_REM 13 /* Time-Remaining (LCP only) RFC1570 */
#define CPCODES_RESET_REQ 14 /* Reset-Request (CCP only) RFC1962 */
#define CPCODES_RESET_REP 15 /* Reset-Reply (CCP only) */
static const struct tok cpcodes[] = {
{CPCODES_VEXT, "Vendor-Extension"}, /* RFC2153 */
{CPCODES_CONF_REQ, "Conf-Request"},
{CPCODES_CONF_ACK, "Conf-Ack"},
{CPCODES_CONF_NAK, "Conf-Nack"},
{CPCODES_CONF_REJ, "Conf-Reject"},
{CPCODES_TERM_REQ, "Term-Request"},
{CPCODES_TERM_ACK, "Term-Ack"},
{CPCODES_CODE_REJ, "Code-Reject"},
{CPCODES_PROT_REJ, "Prot-Reject"},
{CPCODES_ECHO_REQ, "Echo-Request"},
{CPCODES_ECHO_RPL, "Echo-Reply"},
{CPCODES_DISC_REQ, "Disc-Req"},
{CPCODES_ID, "Ident"}, /* RFC1570 */
{CPCODES_TIME_REM, "Time-Rem"}, /* RFC1570 */
{CPCODES_RESET_REQ, "Reset-Req"}, /* RFC1962 */
{CPCODES_RESET_REP, "Reset-Ack"}, /* RFC1962 */
{0, NULL}
};
/* LCP Config Options */
#define LCPOPT_VEXT 0
#define LCPOPT_MRU 1
#define LCPOPT_ACCM 2
#define LCPOPT_AP 3
#define LCPOPT_QP 4
#define LCPOPT_MN 5
#define LCPOPT_DEP6 6
#define LCPOPT_PFC 7
#define LCPOPT_ACFC 8
#define LCPOPT_FCSALT 9
#define LCPOPT_SDP 10
#define LCPOPT_NUMMODE 11
#define LCPOPT_DEP12 12
#define LCPOPT_CBACK 13
#define LCPOPT_DEP14 14
#define LCPOPT_DEP15 15
#define LCPOPT_DEP16 16
#define LCPOPT_MLMRRU 17
#define LCPOPT_MLSSNHF 18
#define LCPOPT_MLED 19
#define LCPOPT_PROP 20
#define LCPOPT_DCEID 21
#define LCPOPT_MPP 22
#define LCPOPT_LD 23
#define LCPOPT_LCPAOPT 24
#define LCPOPT_COBS 25
#define LCPOPT_PE 26
#define LCPOPT_MLHF 27
#define LCPOPT_I18N 28
#define LCPOPT_SDLOS 29
#define LCPOPT_PPPMUX 30
#define LCPOPT_MIN LCPOPT_VEXT
#define LCPOPT_MAX LCPOPT_PPPMUX
static const char *lcpconfopts[] = {
"Vend-Ext", /* (0) */
"MRU", /* (1) */
"ACCM", /* (2) */
"Auth-Prot", /* (3) */
"Qual-Prot", /* (4) */
"Magic-Num", /* (5) */
"deprecated(6)", /* used to be a Quality Protocol */
"PFC", /* (7) */
"ACFC", /* (8) */
"FCS-Alt", /* (9) */
"SDP", /* (10) */
"Num-Mode", /* (11) */
"deprecated(12)", /* used to be a Multi-Link-Procedure*/
"Call-Back", /* (13) */
"deprecated(14)", /* used to be a Connect-Time */
"deprecated(15)", /* used to be a Compund-Frames */
"deprecated(16)", /* used to be a Nominal-Data-Encap */
"MRRU", /* (17) */
"12-Bit seq #", /* (18) */
"End-Disc", /* (19) */
"Proprietary", /* (20) */
"DCE-Id", /* (21) */
"MP+", /* (22) */
"Link-Disc", /* (23) */
"LCP-Auth-Opt", /* (24) */
"COBS", /* (25) */
"Prefix-elision", /* (26) */
"Multilink-header-Form",/* (27) */
"I18N", /* (28) */
"SDL-over-SONET/SDH", /* (29) */
"PPP-Muxing", /* (30) */
};
/* ECP - to be supported */
/* CCP Config Options */
#define CCPOPT_OUI 0 /* RFC1962 */
#define CCPOPT_PRED1 1 /* RFC1962 */
#define CCPOPT_PRED2 2 /* RFC1962 */
#define CCPOPT_PJUMP 3 /* RFC1962 */
/* 4-15 unassigned */
#define CCPOPT_HPPPC 16 /* RFC1962 */
#define CCPOPT_STACLZS 17 /* RFC1974 */
#define CCPOPT_MPPC 18 /* RFC2118 */
#define CCPOPT_GFZA 19 /* RFC1962 */
#define CCPOPT_V42BIS 20 /* RFC1962 */
#define CCPOPT_BSDCOMP 21 /* RFC1977 */
/* 22 unassigned */
#define CCPOPT_LZSDCP 23 /* RFC1967 */
#define CCPOPT_MVRCA 24 /* RFC1975 */
#define CCPOPT_DEC 25 /* RFC1976 */
#define CCPOPT_DEFLATE 26 /* RFC1979 */
/* 27-254 unassigned */
#define CCPOPT_RESV 255 /* RFC1962 */
static const struct tok ccpconfopts_values[] = {
{ CCPOPT_OUI, "OUI" },
{ CCPOPT_PRED1, "Pred-1" },
{ CCPOPT_PRED2, "Pred-2" },
{ CCPOPT_PJUMP, "Puddle" },
{ CCPOPT_HPPPC, "HP-PPC" },
{ CCPOPT_STACLZS, "Stac-LZS" },
{ CCPOPT_MPPC, "MPPC" },
{ CCPOPT_GFZA, "Gand-FZA" },
{ CCPOPT_V42BIS, "V.42bis" },
{ CCPOPT_BSDCOMP, "BSD-Comp" },
{ CCPOPT_LZSDCP, "LZS-DCP" },
{ CCPOPT_MVRCA, "MVRCA" },
{ CCPOPT_DEC, "DEC" },
{ CCPOPT_DEFLATE, "Deflate" },
{ CCPOPT_RESV, "Reserved"},
{0, NULL}
};
/* BACP Config Options */
#define BACPOPT_FPEER 1 /* RFC2125 */
static const struct tok bacconfopts_values[] = {
{ BACPOPT_FPEER, "Favored-Peer" },
{0, NULL}
};
/* SDCP - to be supported */
/* IPCP Config Options */
#define IPCPOPT_2ADDR 1 /* RFC1172, RFC1332 (deprecated) */
#define IPCPOPT_IPCOMP 2 /* RFC1332 */
#define IPCPOPT_ADDR 3 /* RFC1332 */
#define IPCPOPT_MOBILE4 4 /* RFC2290 */
#define IPCPOPT_PRIDNS 129 /* RFC1877 */
#define IPCPOPT_PRINBNS 130 /* RFC1877 */
#define IPCPOPT_SECDNS 131 /* RFC1877 */
#define IPCPOPT_SECNBNS 132 /* RFC1877 */
static const struct tok ipcpopt_values[] = {
{ IPCPOPT_2ADDR, "IP-Addrs" },
{ IPCPOPT_IPCOMP, "IP-Comp" },
{ IPCPOPT_ADDR, "IP-Addr" },
{ IPCPOPT_MOBILE4, "Home-Addr" },
{ IPCPOPT_PRIDNS, "Pri-DNS" },
{ IPCPOPT_PRINBNS, "Pri-NBNS" },
{ IPCPOPT_SECDNS, "Sec-DNS" },
{ IPCPOPT_SECNBNS, "Sec-NBNS" },
{ 0, NULL }
};
#define IPCPOPT_IPCOMP_HDRCOMP 0x61 /* rfc3544 */
#define IPCPOPT_IPCOMP_MINLEN 14
static const struct tok ipcpopt_compproto_values[] = {
{ PPP_VJC, "VJ-Comp" },
{ IPCPOPT_IPCOMP_HDRCOMP, "IP Header Compression" },
{ 0, NULL }
};
static const struct tok ipcpopt_compproto_subopt_values[] = {
{ 1, "RTP-Compression" },
{ 2, "Enhanced RTP-Compression" },
{ 0, NULL }
};
/* IP6CP Config Options */
#define IP6CP_IFID 1
static const struct tok ip6cpopt_values[] = {
{ IP6CP_IFID, "Interface-ID" },
{ 0, NULL }
};
/* ATCP - to be supported */
/* OSINLCP - to be supported */
/* BVCP - to be supported */
/* BCP - to be supported */
/* IPXCP - to be supported */
/* MPLSCP - to be supported */
/* Auth Algorithms */
/* 0-4 Reserved (RFC1994) */
#define AUTHALG_CHAPMD5 5 /* RFC1994 */
#define AUTHALG_MSCHAP1 128 /* RFC2433 */
#define AUTHALG_MSCHAP2 129 /* RFC2795 */
static const struct tok authalg_values[] = {
{ AUTHALG_CHAPMD5, "MD5" },
{ AUTHALG_MSCHAP1, "MS-CHAPv1" },
{ AUTHALG_MSCHAP2, "MS-CHAPv2" },
{ 0, NULL }
};
/* FCS Alternatives - to be supported */
/* Multilink Endpoint Discriminator (RFC1717) */
#define MEDCLASS_NULL 0 /* Null Class */
#define MEDCLASS_LOCAL 1 /* Locally Assigned */
#define MEDCLASS_IPV4 2 /* Internet Protocol (IPv4) */
#define MEDCLASS_MAC 3 /* IEEE 802.1 global MAC address */
#define MEDCLASS_MNB 4 /* PPP Magic Number Block */
#define MEDCLASS_PSNDN 5 /* Public Switched Network Director Number */
/* PPP LCP Callback */
#define CALLBACK_AUTH 0 /* Location determined by user auth */
#define CALLBACK_DSTR 1 /* Dialing string */
#define CALLBACK_LID 2 /* Location identifier */
#define CALLBACK_E164 3 /* E.164 number */
#define CALLBACK_X500 4 /* X.500 distinguished name */
#define CALLBACK_CBCP 6 /* Location is determined during CBCP nego */
static const struct tok ppp_callback_values[] = {
{ CALLBACK_AUTH, "UserAuth" },
{ CALLBACK_DSTR, "DialString" },
{ CALLBACK_LID, "LocalID" },
{ CALLBACK_E164, "E.164" },
{ CALLBACK_X500, "X.500" },
{ CALLBACK_CBCP, "CBCP" },
{ 0, NULL }
};
/* CHAP */
#define CHAP_CHAL 1
#define CHAP_RESP 2
#define CHAP_SUCC 3
#define CHAP_FAIL 4
static const struct tok chapcode_values[] = {
{ CHAP_CHAL, "Challenge" },
{ CHAP_RESP, "Response" },
{ CHAP_SUCC, "Success" },
{ CHAP_FAIL, "Fail" },
{ 0, NULL}
};
/* PAP */
#define PAP_AREQ 1
#define PAP_AACK 2
#define PAP_ANAK 3
static const struct tok papcode_values[] = {
{ PAP_AREQ, "Auth-Req" },
{ PAP_AACK, "Auth-ACK" },
{ PAP_ANAK, "Auth-NACK" },
{ 0, NULL }
};
/* BAP */
#define BAP_CALLREQ 1
#define BAP_CALLRES 2
#define BAP_CBREQ 3
#define BAP_CBRES 4
#define BAP_LDQREQ 5
#define BAP_LDQRES 6
#define BAP_CSIND 7
#define BAP_CSRES 8
static int print_lcp_config_options(netdissect_options *, const u_char *p, int);
static int print_ipcp_config_options(netdissect_options *, const u_char *p, int);
static int print_ip6cp_config_options(netdissect_options *, const u_char *p, int);
static int print_ccp_config_options(netdissect_options *, const u_char *p, int);
static int print_bacp_config_options(netdissect_options *, const u_char *p, int);
static void handle_ppp(netdissect_options *, u_int proto, const u_char *p, int length);
/* generic Control Protocol (e.g. LCP, IPCP, CCP, etc.) handler */
static void
handle_ctrl_proto(netdissect_options *ndo,
u_int proto, const u_char *pptr, int length)
{
const char *typestr;
u_int code, len;
int (*pfunc)(netdissect_options *, const u_char *, int);
int x, j;
const u_char *tptr;
tptr=pptr;
typestr = tok2str(ppptype2str, "unknown ctrl-proto (0x%04x)", proto);
ND_PRINT((ndo, "%s, ", typestr));
if (length < 4) /* FIXME weak boundary checking */
goto trunc;
ND_TCHECK2(*tptr, 2);
code = *tptr++;
ND_PRINT((ndo, "%s (0x%02x), id %u, length %u",
tok2str(cpcodes, "Unknown Opcode",code),
code,
*tptr++, /* ID */
length + 2));
if (!ndo->ndo_vflag)
return;
if (length <= 4)
return; /* there may be a NULL confreq etc. */
ND_TCHECK2(*tptr, 2);
len = EXTRACT_16BITS(tptr);
tptr += 2;
ND_PRINT((ndo, "\n\tencoded length %u (=Option(s) length %u)", len, len - 4));
if (ndo->ndo_vflag > 1)
print_unknown_data(ndo, pptr - 2, "\n\t", 6);
switch (code) {
case CPCODES_VEXT:
if (length < 11)
break;
ND_TCHECK2(*tptr, 4);
ND_PRINT((ndo, "\n\t Magic-Num 0x%08x", EXTRACT_32BITS(tptr)));
tptr += 4;
ND_TCHECK2(*tptr, 3);
ND_PRINT((ndo, " Vendor: %s (%u)",
tok2str(oui_values,"Unknown",EXTRACT_24BITS(tptr)),
EXTRACT_24BITS(tptr)));
/* XXX: need to decode Kind and Value(s)? */
break;
case CPCODES_CONF_REQ:
case CPCODES_CONF_ACK:
case CPCODES_CONF_NAK:
case CPCODES_CONF_REJ:
x = len - 4; /* Code(1), Identifier(1) and Length(2) */
do {
switch (proto) {
case PPP_LCP:
pfunc = print_lcp_config_options;
break;
case PPP_IPCP:
pfunc = print_ipcp_config_options;
break;
case PPP_IPV6CP:
pfunc = print_ip6cp_config_options;
break;
case PPP_CCP:
pfunc = print_ccp_config_options;
break;
case PPP_BACP:
pfunc = print_bacp_config_options;
break;
default:
/*
* No print routine for the options for
* this protocol.
*/
pfunc = NULL;
break;
}
if (pfunc == NULL) /* catch the above null pointer if unknown CP */
break;
if ((j = (*pfunc)(ndo, tptr, len)) == 0)
break;
x -= j;
tptr += j;
} while (x > 0);
break;
case CPCODES_TERM_REQ:
case CPCODES_TERM_ACK:
/* XXX: need to decode Data? */
break;
case CPCODES_CODE_REJ:
/* XXX: need to decode Rejected-Packet? */
break;
case CPCODES_PROT_REJ:
if (length < 6)
break;
ND_TCHECK2(*tptr, 2);
ND_PRINT((ndo, "\n\t Rejected %s Protocol (0x%04x)",
tok2str(ppptype2str,"unknown", EXTRACT_16BITS(tptr)),
EXTRACT_16BITS(tptr)));
/* XXX: need to decode Rejected-Information? - hexdump for now */
if (len > 6) {
ND_PRINT((ndo, "\n\t Rejected Packet"));
print_unknown_data(ndo, tptr + 2, "\n\t ", len - 2);
}
break;
case CPCODES_ECHO_REQ:
case CPCODES_ECHO_RPL:
case CPCODES_DISC_REQ:
if (length < 8)
break;
ND_TCHECK2(*tptr, 4);
ND_PRINT((ndo, "\n\t Magic-Num 0x%08x", EXTRACT_32BITS(tptr)));
/* XXX: need to decode Data? - hexdump for now */
if (len > 8) {
ND_PRINT((ndo, "\n\t -----trailing data-----"));
ND_TCHECK2(tptr[4], len - 8);
print_unknown_data(ndo, tptr + 4, "\n\t ", len - 8);
}
break;
case CPCODES_ID:
if (length < 8)
break;
ND_TCHECK2(*tptr, 4);
ND_PRINT((ndo, "\n\t Magic-Num 0x%08x", EXTRACT_32BITS(tptr)));
/* RFC 1661 says this is intended to be human readable */
if (len > 8) {
ND_PRINT((ndo, "\n\t Message\n\t "));
if (fn_printn(ndo, tptr + 4, len - 4, ndo->ndo_snapend))
goto trunc;
}
break;
case CPCODES_TIME_REM:
if (length < 12)
break;
ND_TCHECK2(*tptr, 4);
ND_PRINT((ndo, "\n\t Magic-Num 0x%08x", EXTRACT_32BITS(tptr)));
ND_TCHECK2(*(tptr + 4), 4);
ND_PRINT((ndo, ", Seconds-Remaining %us", EXTRACT_32BITS(tptr + 4)));
/* XXX: need to decode Message? */
break;
default:
/* XXX this is dirty but we do not get the
* original pointer passed to the begin
* the PPP packet */
if (ndo->ndo_vflag <= 1)
print_unknown_data(ndo, pptr - 2, "\n\t ", length + 2);
break;
}
return;
trunc:
ND_PRINT((ndo, "[|%s]", typestr));
}
/* LCP config options */
static int
print_lcp_config_options(netdissect_options *ndo,
const u_char *p, int length)
{
int len, opt;
if (length < 2)
return 0;
ND_TCHECK2(*p, 2);
len = p[1];
opt = p[0];
if (length < len)
return 0;
if (len < 2) {
if ((opt >= LCPOPT_MIN) && (opt <= LCPOPT_MAX))
ND_PRINT((ndo, "\n\t %s Option (0x%02x), length %u (length bogus, should be >= 2)",
lcpconfopts[opt], opt, len));
else
ND_PRINT((ndo, "\n\tunknown LCP option 0x%02x", opt));
return 0;
}
if ((opt >= LCPOPT_MIN) && (opt <= LCPOPT_MAX))
ND_PRINT((ndo, "\n\t %s Option (0x%02x), length %u", lcpconfopts[opt], opt, len));
else {
ND_PRINT((ndo, "\n\tunknown LCP option 0x%02x", opt));
return len;
}
switch (opt) {
case LCPOPT_VEXT:
if (len < 6) {
ND_PRINT((ndo, " (length bogus, should be >= 6)"));
return len;
}
ND_TCHECK2(*(p + 2), 3);
ND_PRINT((ndo, ": Vendor: %s (%u)",
tok2str(oui_values,"Unknown",EXTRACT_24BITS(p+2)),
EXTRACT_24BITS(p + 2)));
#if 0
ND_TCHECK(p[5]);
ND_PRINT((ndo, ", kind: 0x%02x", p[5]));
ND_PRINT((ndo, ", Value: 0x"));
for (i = 0; i < len - 6; i++) {
ND_TCHECK(p[6 + i]);
ND_PRINT((ndo, "%02x", p[6 + i]));
}
#endif
break;
case LCPOPT_MRU:
if (len != 4) {
ND_PRINT((ndo, " (length bogus, should be = 4)"));
return len;
}
ND_TCHECK2(*(p + 2), 2);
ND_PRINT((ndo, ": %u", EXTRACT_16BITS(p + 2)));
break;
case LCPOPT_ACCM:
if (len != 6) {
ND_PRINT((ndo, " (length bogus, should be = 6)"));
return len;
}
ND_TCHECK2(*(p + 2), 4);
ND_PRINT((ndo, ": 0x%08x", EXTRACT_32BITS(p + 2)));
break;
case LCPOPT_AP:
if (len < 4) {
ND_PRINT((ndo, " (length bogus, should be >= 4)"));
return len;
}
ND_TCHECK2(*(p + 2), 2);
ND_PRINT((ndo, ": %s", tok2str(ppptype2str, "Unknown Auth Proto (0x04x)", EXTRACT_16BITS(p + 2))));
switch (EXTRACT_16BITS(p+2)) {
case PPP_CHAP:
ND_TCHECK(p[4]);
ND_PRINT((ndo, ", %s", tok2str(authalg_values, "Unknown Auth Alg %u", p[4])));
break;
case PPP_PAP: /* fall through */
case PPP_EAP:
case PPP_SPAP:
case PPP_SPAP_OLD:
break;
default:
print_unknown_data(ndo, p, "\n\t", len);
}
break;
case LCPOPT_QP:
if (len < 4) {
ND_PRINT((ndo, " (length bogus, should be >= 4)"));
return 0;
}
ND_TCHECK2(*(p + 2), 2);
if (EXTRACT_16BITS(p+2) == PPP_LQM)
ND_PRINT((ndo, ": LQR"));
else
ND_PRINT((ndo, ": unknown"));
break;
case LCPOPT_MN:
if (len != 6) {
ND_PRINT((ndo, " (length bogus, should be = 6)"));
return 0;
}
ND_TCHECK2(*(p + 2), 4);
ND_PRINT((ndo, ": 0x%08x", EXTRACT_32BITS(p + 2)));
break;
case LCPOPT_PFC:
break;
case LCPOPT_ACFC:
break;
case LCPOPT_LD:
if (len != 4) {
ND_PRINT((ndo, " (length bogus, should be = 4)"));
return 0;
}
ND_TCHECK2(*(p + 2), 2);
ND_PRINT((ndo, ": 0x%04x", EXTRACT_16BITS(p + 2)));
break;
case LCPOPT_CBACK:
if (len < 3) {
ND_PRINT((ndo, " (length bogus, should be >= 3)"));
return 0;
}
ND_PRINT((ndo, ": "));
ND_TCHECK(p[2]);
ND_PRINT((ndo, ": Callback Operation %s (%u)",
tok2str(ppp_callback_values, "Unknown", p[2]),
p[2]));
break;
case LCPOPT_MLMRRU:
if (len != 4) {
ND_PRINT((ndo, " (length bogus, should be = 4)"));
return 0;
}
ND_TCHECK2(*(p + 2), 2);
ND_PRINT((ndo, ": %u", EXTRACT_16BITS(p + 2)));
break;
case LCPOPT_MLED:
if (len < 3) {
ND_PRINT((ndo, " (length bogus, should be >= 3)"));
return 0;
}
ND_TCHECK(p[2]);
switch (p[2]) { /* class */
case MEDCLASS_NULL:
ND_PRINT((ndo, ": Null"));
break;
case MEDCLASS_LOCAL:
ND_PRINT((ndo, ": Local")); /* XXX */
break;
case MEDCLASS_IPV4:
if (len != 7) {
ND_PRINT((ndo, " (length bogus, should be = 7)"));
return 0;
}
ND_TCHECK2(*(p + 3), 4);
ND_PRINT((ndo, ": IPv4 %s", ipaddr_string(ndo, p + 3)));
break;
case MEDCLASS_MAC:
if (len != 9) {
ND_PRINT((ndo, " (length bogus, should be = 9)"));
return 0;
}
ND_TCHECK2(*(p + 3), 6);
ND_PRINT((ndo, ": MAC %s", etheraddr_string(ndo, p + 3)));
break;
case MEDCLASS_MNB:
ND_PRINT((ndo, ": Magic-Num-Block")); /* XXX */
break;
case MEDCLASS_PSNDN:
ND_PRINT((ndo, ": PSNDN")); /* XXX */
break;
default:
ND_PRINT((ndo, ": Unknown class %u", p[2]));
break;
}
break;
/* XXX: to be supported */
#if 0
case LCPOPT_DEP6:
case LCPOPT_FCSALT:
case LCPOPT_SDP:
case LCPOPT_NUMMODE:
case LCPOPT_DEP12:
case LCPOPT_DEP14:
case LCPOPT_DEP15:
case LCPOPT_DEP16:
case LCPOPT_MLSSNHF:
case LCPOPT_PROP:
case LCPOPT_DCEID:
case LCPOPT_MPP:
case LCPOPT_LCPAOPT:
case LCPOPT_COBS:
case LCPOPT_PE:
case LCPOPT_MLHF:
case LCPOPT_I18N:
case LCPOPT_SDLOS:
case LCPOPT_PPPMUX:
break;
#endif
default:
/*
* Unknown option; dump it as raw bytes now if we're
* not going to do so below.
*/
if (ndo->ndo_vflag < 2)
print_unknown_data(ndo, &p[2], "\n\t ", len - 2);
break;
}
if (ndo->ndo_vflag > 1)
print_unknown_data(ndo, &p[2], "\n\t ", len - 2); /* exclude TLV header */
return len;
trunc:
ND_PRINT((ndo, "[|lcp]"));
return 0;
}
/* ML-PPP*/
static const struct tok ppp_ml_flag_values[] = {
{ 0x80, "begin" },
{ 0x40, "end" },
{ 0, NULL }
};
static void
handle_mlppp(netdissect_options *ndo,
const u_char *p, int length)
{
if (!ndo->ndo_eflag)
ND_PRINT((ndo, "MLPPP, "));
ND_PRINT((ndo, "seq 0x%03x, Flags [%s], length %u",
(EXTRACT_16BITS(p))&0x0fff, /* only support 12-Bit sequence space for now */
bittok2str(ppp_ml_flag_values, "none", *p & 0xc0),
length));
}
/* CHAP */
static void
handle_chap(netdissect_options *ndo,
const u_char *p, int length)
{
u_int code, len;
int val_size, name_size, msg_size;
const u_char *p0;
int i;
p0 = p;
if (length < 1) {
ND_PRINT((ndo, "[|chap]"));
return;
} else if (length < 4) {
ND_TCHECK(*p);
ND_PRINT((ndo, "[|chap 0x%02x]", *p));
return;
}
ND_TCHECK(*p);
code = *p;
ND_PRINT((ndo, "CHAP, %s (0x%02x)",
tok2str(chapcode_values,"unknown",code),
code));
p++;
ND_TCHECK(*p);
ND_PRINT((ndo, ", id %u", *p)); /* ID */
p++;
ND_TCHECK2(*p, 2);
len = EXTRACT_16BITS(p);
p += 2;
/*
* Note that this is a generic CHAP decoding routine. Since we
* don't know which flavor of CHAP (i.e. CHAP-MD5, MS-CHAPv1,
* MS-CHAPv2) is used at this point, we can't decode packet
* specifically to each algorithms. Instead, we simply decode
* the GCD (Gratest Common Denominator) for all algorithms.
*/
switch (code) {
case CHAP_CHAL:
case CHAP_RESP:
if (length - (p - p0) < 1)
return;
ND_TCHECK(*p);
val_size = *p; /* value size */
p++;
if (length - (p - p0) < val_size)
return;
ND_PRINT((ndo, ", Value "));
for (i = 0; i < val_size; i++) {
ND_TCHECK(*p);
ND_PRINT((ndo, "%02x", *p++));
}
name_size = len - (p - p0);
ND_PRINT((ndo, ", Name "));
for (i = 0; i < name_size; i++) {
ND_TCHECK(*p);
safeputchar(ndo, *p++);
}
break;
case CHAP_SUCC:
case CHAP_FAIL:
msg_size = len - (p - p0);
ND_PRINT((ndo, ", Msg "));
for (i = 0; i< msg_size; i++) {
ND_TCHECK(*p);
safeputchar(ndo, *p++);
}
break;
}
return;
trunc:
ND_PRINT((ndo, "[|chap]"));
}
/* PAP (see RFC 1334) */
static void
handle_pap(netdissect_options *ndo,
const u_char *p, int length)
{
u_int code, len;
int peerid_len, passwd_len, msg_len;
const u_char *p0;
int i;
p0 = p;
if (length < 1) {
ND_PRINT((ndo, "[|pap]"));
return;
} else if (length < 4) {
ND_TCHECK(*p);
ND_PRINT((ndo, "[|pap 0x%02x]", *p));
return;
}
ND_TCHECK(*p);
code = *p;
ND_PRINT((ndo, "PAP, %s (0x%02x)",
tok2str(papcode_values, "unknown", code),
code));
p++;
ND_TCHECK(*p);
ND_PRINT((ndo, ", id %u", *p)); /* ID */
p++;
ND_TCHECK2(*p, 2);
len = EXTRACT_16BITS(p);
p += 2;
if ((int)len > length) {
ND_PRINT((ndo, ", length %u > packet size", len));
return;
}
length = len;
if (length < (p - p0)) {
ND_PRINT((ndo, ", length %u < PAP header length", length));
return;
}
switch (code) {
case PAP_AREQ:
/* A valid Authenticate-Request is 6 or more octets long. */
if (len < 6)
goto trunc;
if (length - (p - p0) < 1)
return;
ND_TCHECK(*p);
peerid_len = *p; /* Peer-ID Length */
p++;
if (length - (p - p0) < peerid_len)
return;
ND_PRINT((ndo, ", Peer "));
for (i = 0; i < peerid_len; i++) {
ND_TCHECK(*p);
safeputchar(ndo, *p++);
}
if (length - (p - p0) < 1)
return;
ND_TCHECK(*p);
passwd_len = *p; /* Password Length */
p++;
if (length - (p - p0) < passwd_len)
return;
ND_PRINT((ndo, ", Name "));
for (i = 0; i < passwd_len; i++) {
ND_TCHECK(*p);
safeputchar(ndo, *p++);
}
break;
case PAP_AACK:
case PAP_ANAK:
/* Although some implementations ignore truncation at
* this point and at least one generates a truncated
* packet, RFC 1334 section 2.2.2 clearly states that
* both AACK and ANAK are at least 5 bytes long.
*/
if (len < 5)
goto trunc;
if (length - (p - p0) < 1)
return;
ND_TCHECK(*p);
msg_len = *p; /* Msg-Length */
p++;
if (length - (p - p0) < msg_len)
return;
ND_PRINT((ndo, ", Msg "));
for (i = 0; i< msg_len; i++) {
ND_TCHECK(*p);
safeputchar(ndo, *p++);
}
break;
}
return;
trunc:
ND_PRINT((ndo, "[|pap]"));
}
/* BAP */
static void
handle_bap(netdissect_options *ndo _U_,
const u_char *p _U_, int length _U_)
{
/* XXX: to be supported!! */
}
/* IPCP config options */
static int
print_ipcp_config_options(netdissect_options *ndo,
const u_char *p, int length)
{
int len, opt;
u_int compproto, ipcomp_subopttotallen, ipcomp_subopt, ipcomp_suboptlen;
if (length < 2)
return 0;
ND_TCHECK2(*p, 2);
len = p[1];
opt = p[0];
if (length < len)
return 0;
if (len < 2) {
ND_PRINT((ndo, "\n\t %s Option (0x%02x), length %u (length bogus, should be >= 2)",
tok2str(ipcpopt_values,"unknown",opt),
opt,
len));
return 0;
}
ND_PRINT((ndo, "\n\t %s Option (0x%02x), length %u",
tok2str(ipcpopt_values,"unknown",opt),
opt,
len));
switch (opt) {
case IPCPOPT_2ADDR: /* deprecated */
if (len != 10) {
ND_PRINT((ndo, " (length bogus, should be = 10)"));
return len;
}
ND_TCHECK2(*(p + 6), 4);
ND_PRINT((ndo, ": src %s, dst %s",
ipaddr_string(ndo, p + 2),
ipaddr_string(ndo, p + 6)));
break;
case IPCPOPT_IPCOMP:
if (len < 4) {
ND_PRINT((ndo, " (length bogus, should be >= 4)"));
return 0;
}
ND_TCHECK2(*(p + 2), 2);
compproto = EXTRACT_16BITS(p+2);
ND_PRINT((ndo, ": %s (0x%02x):",
tok2str(ipcpopt_compproto_values, "Unknown", compproto),
compproto));
switch (compproto) {
case PPP_VJC:
/* XXX: VJ-Comp parameters should be decoded */
break;
case IPCPOPT_IPCOMP_HDRCOMP:
if (len < IPCPOPT_IPCOMP_MINLEN) {
ND_PRINT((ndo, " (length bogus, should be >= %u)",
IPCPOPT_IPCOMP_MINLEN));
return 0;
}
ND_TCHECK2(*(p + 2), IPCPOPT_IPCOMP_MINLEN);
ND_PRINT((ndo, "\n\t TCP Space %u, non-TCP Space %u" \
", maxPeriod %u, maxTime %u, maxHdr %u",
EXTRACT_16BITS(p+4),
EXTRACT_16BITS(p+6),
EXTRACT_16BITS(p+8),
EXTRACT_16BITS(p+10),
EXTRACT_16BITS(p+12)));
/* suboptions present ? */
if (len > IPCPOPT_IPCOMP_MINLEN) {
ipcomp_subopttotallen = len - IPCPOPT_IPCOMP_MINLEN;
p += IPCPOPT_IPCOMP_MINLEN;
ND_PRINT((ndo, "\n\t Suboptions, length %u", ipcomp_subopttotallen));
while (ipcomp_subopttotallen >= 2) {
ND_TCHECK2(*p, 2);
ipcomp_subopt = *p;
ipcomp_suboptlen = *(p+1);
/* sanity check */
if (ipcomp_subopt == 0 ||
ipcomp_suboptlen == 0 )
break;
/* XXX: just display the suboptions for now */
ND_PRINT((ndo, "\n\t\t%s Suboption #%u, length %u",
tok2str(ipcpopt_compproto_subopt_values,
"Unknown",
ipcomp_subopt),
ipcomp_subopt,
ipcomp_suboptlen));
ipcomp_subopttotallen -= ipcomp_suboptlen;
p += ipcomp_suboptlen;
}
}
break;
default:
break;
}
break;
case IPCPOPT_ADDR: /* those options share the same format - fall through */
case IPCPOPT_MOBILE4:
case IPCPOPT_PRIDNS:
case IPCPOPT_PRINBNS:
case IPCPOPT_SECDNS:
case IPCPOPT_SECNBNS:
if (len != 6) {
ND_PRINT((ndo, " (length bogus, should be = 6)"));
return 0;
}
ND_TCHECK2(*(p + 2), 4);
ND_PRINT((ndo, ": %s", ipaddr_string(ndo, p + 2)));
break;
default:
/*
* Unknown option; dump it as raw bytes now if we're
* not going to do so below.
*/
if (ndo->ndo_vflag < 2)
print_unknown_data(ndo, &p[2], "\n\t ", len - 2);
break;
}
if (ndo->ndo_vflag > 1)
print_unknown_data(ndo, &p[2], "\n\t ", len - 2); /* exclude TLV header */
return len;
trunc:
ND_PRINT((ndo, "[|ipcp]"));
return 0;
}
/* IP6CP config options */
static int
print_ip6cp_config_options(netdissect_options *ndo,
const u_char *p, int length)
{
int len, opt;
if (length < 2)
return 0;
ND_TCHECK2(*p, 2);
len = p[1];
opt = p[0];
if (length < len)
return 0;
if (len < 2) {
ND_PRINT((ndo, "\n\t %s Option (0x%02x), length %u (length bogus, should be >= 2)",
tok2str(ip6cpopt_values,"unknown",opt),
opt,
len));
return 0;
}
ND_PRINT((ndo, "\n\t %s Option (0x%02x), length %u",
tok2str(ip6cpopt_values,"unknown",opt),
opt,
len));
switch (opt) {
case IP6CP_IFID:
if (len != 10) {
ND_PRINT((ndo, " (length bogus, should be = 10)"));
return len;
}
ND_TCHECK2(*(p + 2), 8);
ND_PRINT((ndo, ": %04x:%04x:%04x:%04x",
EXTRACT_16BITS(p + 2),
EXTRACT_16BITS(p + 4),
EXTRACT_16BITS(p + 6),
EXTRACT_16BITS(p + 8)));
break;
default:
/*
* Unknown option; dump it as raw bytes now if we're
* not going to do so below.
*/
if (ndo->ndo_vflag < 2)
print_unknown_data(ndo, &p[2], "\n\t ", len - 2);
break;
}
if (ndo->ndo_vflag > 1)
print_unknown_data(ndo, &p[2], "\n\t ", len - 2); /* exclude TLV header */
return len;
trunc:
ND_PRINT((ndo, "[|ip6cp]"));
return 0;
}
/* CCP config options */
static int
print_ccp_config_options(netdissect_options *ndo,
const u_char *p, int length)
{
int len, opt;
if (length < 2)
return 0;
ND_TCHECK2(*p, 2);
len = p[1];
opt = p[0];
if (length < len)
return 0;
if (len < 2) {
ND_PRINT((ndo, "\n\t %s Option (0x%02x), length %u (length bogus, should be >= 2)",
tok2str(ccpconfopts_values, "Unknown", opt),
opt,
len));
return 0;
}
ND_PRINT((ndo, "\n\t %s Option (0x%02x), length %u",
tok2str(ccpconfopts_values, "Unknown", opt),
opt,
len));
switch (opt) {
case CCPOPT_BSDCOMP:
if (len < 3) {
ND_PRINT((ndo, " (length bogus, should be >= 3)"));
return len;
}
ND_TCHECK2(*(p + 2), 1);
ND_PRINT((ndo, ": Version: %u, Dictionary Bits: %u",
p[2] >> 5, p[2] & 0x1f));
break;
case CCPOPT_MVRCA:
if (len < 4) {
ND_PRINT((ndo, " (length bogus, should be >= 4)"));
return len;
}
ND_TCHECK2(*(p + 2), 1);
ND_PRINT((ndo, ": Features: %u, PxP: %s, History: %u, #CTX-ID: %u",
(p[2] & 0xc0) >> 6,
(p[2] & 0x20) ? "Enabled" : "Disabled",
p[2] & 0x1f, p[3]));
break;
case CCPOPT_DEFLATE:
if (len < 4) {
ND_PRINT((ndo, " (length bogus, should be >= 4)"));
return len;
}
ND_TCHECK2(*(p + 2), 1);
ND_PRINT((ndo, ": Window: %uK, Method: %s (0x%x), MBZ: %u, CHK: %u",
(p[2] & 0xf0) >> 4,
((p[2] & 0x0f) == 8) ? "zlib" : "unknown",
p[2] & 0x0f, (p[3] & 0xfc) >> 2, p[3] & 0x03));
break;
/* XXX: to be supported */
#if 0
case CCPOPT_OUI:
case CCPOPT_PRED1:
case CCPOPT_PRED2:
case CCPOPT_PJUMP:
case CCPOPT_HPPPC:
case CCPOPT_STACLZS:
case CCPOPT_MPPC:
case CCPOPT_GFZA:
case CCPOPT_V42BIS:
case CCPOPT_LZSDCP:
case CCPOPT_DEC:
case CCPOPT_RESV:
break;
#endif
default:
/*
* Unknown option; dump it as raw bytes now if we're
* not going to do so below.
*/
if (ndo->ndo_vflag < 2)
print_unknown_data(ndo, &p[2], "\n\t ", len - 2);
break;
}
if (ndo->ndo_vflag > 1)
print_unknown_data(ndo, &p[2], "\n\t ", len - 2); /* exclude TLV header */
return len;
trunc:
ND_PRINT((ndo, "[|ccp]"));
return 0;
}
/* BACP config options */
static int
print_bacp_config_options(netdissect_options *ndo,
const u_char *p, int length)
{
int len, opt;
if (length < 2)
return 0;
ND_TCHECK2(*p, 2);
len = p[1];
opt = p[0];
if (length < len)
return 0;
if (len < 2) {
ND_PRINT((ndo, "\n\t %s Option (0x%02x), length %u (length bogus, should be >= 2)",
tok2str(bacconfopts_values, "Unknown", opt),
opt,
len));
return 0;
}
ND_PRINT((ndo, "\n\t %s Option (0x%02x), length %u",
tok2str(bacconfopts_values, "Unknown", opt),
opt,
len));
switch (opt) {
case BACPOPT_FPEER:
if (len != 6) {
ND_PRINT((ndo, " (length bogus, should be = 6)"));
return len;
}
ND_TCHECK2(*(p + 2), 4);
ND_PRINT((ndo, ": Magic-Num 0x%08x", EXTRACT_32BITS(p + 2)));
break;
default:
/*
* Unknown option; dump it as raw bytes now if we're
* not going to do so below.
*/
if (ndo->ndo_vflag < 2)
print_unknown_data(ndo, &p[2], "\n\t ", len - 2);
break;
}
if (ndo->ndo_vflag > 1)
print_unknown_data(ndo, &p[2], "\n\t ", len - 2); /* exclude TLV header */
return len;
trunc:
ND_PRINT((ndo, "[|bacp]"));
return 0;
}
static void
ppp_hdlc(netdissect_options *ndo,
const u_char *p, int length)
{
u_char *b, *t, c;
const u_char *s;
int i, proto;
const void *se;
if (length <= 0)
return;
b = (u_char *)malloc(length);
if (b == NULL)
return;
/*
* Unescape all the data into a temporary, private, buffer.
* Do this so that we dont overwrite the original packet
* contents.
*/
for (s = p, t = b, i = length; i > 0 && ND_TTEST(*s); i--) {
c = *s++;
if (c == 0x7d) {
if (i <= 1 || !ND_TTEST(*s))
break;
i--;
c = *s++ ^ 0x20;
}
*t++ = c;
}
se = ndo->ndo_snapend;
ndo->ndo_snapend = t;
length = t - b;
/* now lets guess about the payload codepoint format */
if (length < 1)
goto trunc;
proto = *b; /* start with a one-octet codepoint guess */
switch (proto) {
case PPP_IP:
ip_print(ndo, b + 1, length - 1);
goto cleanup;
case PPP_IPV6:
ip6_print(ndo, b + 1, length - 1);
goto cleanup;
default: /* no luck - try next guess */
break;
}
if (length < 2)
goto trunc;
proto = EXTRACT_16BITS(b); /* next guess - load two octets */
switch (proto) {
case (PPP_ADDRESS << 8 | PPP_CONTROL): /* looks like a PPP frame */
if (length < 4)
goto trunc;
proto = EXTRACT_16BITS(b+2); /* load the PPP proto-id */
handle_ppp(ndo, proto, b + 4, length - 4);
break;
default: /* last guess - proto must be a PPP proto-id */
handle_ppp(ndo, proto, b + 2, length - 2);
break;
}
cleanup:
ndo->ndo_snapend = se;
free(b);
return;
trunc:
ndo->ndo_snapend = se;
free(b);
ND_PRINT((ndo, "[|ppp]"));
}
/* PPP */
static void
handle_ppp(netdissect_options *ndo,
u_int proto, const u_char *p, int length)
{
if ((proto & 0xff00) == 0x7e00) { /* is this an escape code ? */
ppp_hdlc(ndo, p - 1, length);
return;
}
switch (proto) {
case PPP_LCP: /* fall through */
case PPP_IPCP:
case PPP_OSICP:
case PPP_MPLSCP:
case PPP_IPV6CP:
case PPP_CCP:
case PPP_BACP:
handle_ctrl_proto(ndo, proto, p, length);
break;
case PPP_ML:
handle_mlppp(ndo, p, length);
break;
case PPP_CHAP:
handle_chap(ndo, p, length);
break;
case PPP_PAP:
handle_pap(ndo, p, length);
break;
case PPP_BAP: /* XXX: not yet completed */
handle_bap(ndo, p, length);
break;
case ETHERTYPE_IP: /*XXX*/
case PPP_VJNC:
case PPP_IP:
ip_print(ndo, p, length);
break;
case ETHERTYPE_IPV6: /*XXX*/
case PPP_IPV6:
ip6_print(ndo, p, length);
break;
case ETHERTYPE_IPX: /*XXX*/
case PPP_IPX:
ipx_print(ndo, p, length);
break;
case PPP_OSI:
isoclns_print(ndo, p, length, length);
break;
case PPP_MPLS_UCAST:
case PPP_MPLS_MCAST:
mpls_print(ndo, p, length);
break;
case PPP_COMP:
ND_PRINT((ndo, "compressed PPP data"));
break;
default:
ND_PRINT((ndo, "%s ", tok2str(ppptype2str, "unknown PPP protocol (0x%04x)", proto)));
print_unknown_data(ndo, p, "\n\t", length);
break;
}
}
/* Standard PPP printer */
u_int
ppp_print(netdissect_options *ndo,
register const u_char *p, u_int length)
{
u_int proto,ppp_header;
u_int olen = length; /* _o_riginal length */
u_int hdr_len = 0;
/*
* Here, we assume that p points to the Address and Control
* field (if they present).
*/
if (length < 2)
goto trunc;
ND_TCHECK2(*p, 2);
ppp_header = EXTRACT_16BITS(p);
switch(ppp_header) {
case (PPP_WITHDIRECTION_IN << 8 | PPP_CONTROL):
if (ndo->ndo_eflag) ND_PRINT((ndo, "In "));
p += 2;
length -= 2;
hdr_len += 2;
break;
case (PPP_WITHDIRECTION_OUT << 8 | PPP_CONTROL):
if (ndo->ndo_eflag) ND_PRINT((ndo, "Out "));
p += 2;
length -= 2;
hdr_len += 2;
break;
case (PPP_ADDRESS << 8 | PPP_CONTROL):
p += 2; /* ACFC not used */
length -= 2;
hdr_len += 2;
break;
default:
break;
}
if (length < 2)
goto trunc;
ND_TCHECK(*p);
if (*p % 2) {
proto = *p; /* PFC is used */
p++;
length--;
hdr_len++;
} else {
ND_TCHECK2(*p, 2);
proto = EXTRACT_16BITS(p);
p += 2;
length -= 2;
hdr_len += 2;
}
if (ndo->ndo_eflag)
ND_PRINT((ndo, "%s (0x%04x), length %u: ",
tok2str(ppptype2str, "unknown", proto),
proto,
olen));
handle_ppp(ndo, proto, p, length);
return (hdr_len);
trunc:
ND_PRINT((ndo, "[|ppp]"));
return (0);
}
/* PPP I/F printer */
u_int
ppp_if_print(netdissect_options *ndo,
const struct pcap_pkthdr *h, register const u_char *p)
{
register u_int length = h->len;
register u_int caplen = h->caplen;
if (caplen < PPP_HDRLEN) {
ND_PRINT((ndo, "[|ppp]"));
return (caplen);
}
#if 0
/*
* XXX: seems to assume that there are 2 octets prepended to an
* actual PPP frame. The 1st octet looks like Input/Output flag
* while 2nd octet is unknown, at least to me
* (mshindo@mshindo.net).
*
* That was what the original tcpdump code did.
*
* FreeBSD's "if_ppp.c" *does* set the first octet to 1 for outbound
* packets and 0 for inbound packets - but only if the
* protocol field has the 0x8000 bit set (i.e., it's a network
* control protocol); it does so before running the packet through
* "bpf_filter" to see if it should be discarded, and to see
* if we should update the time we sent the most recent packet...
*
* ...but it puts the original address field back after doing
* so.
*
* NetBSD's "if_ppp.c" doesn't set the first octet in that fashion.
*
* I don't know if any PPP implementation handed up to a BPF
* device packets with the first octet being 1 for outbound and
* 0 for inbound packets, so I (guy@alum.mit.edu) don't know
* whether that ever needs to be checked or not.
*
* Note that NetBSD has a DLT_PPP_SERIAL, which it uses for PPP,
* and its tcpdump appears to assume that the frame always
* begins with an address field and a control field, and that
* the address field might be 0x0f or 0x8f, for Cisco
* point-to-point with HDLC framing as per section 4.3.1 of RFC
* 1547, as well as 0xff, for PPP in HDLC-like framing as per
* RFC 1662.
*
* (Is the Cisco framing in question what DLT_C_HDLC, in
* BSD/OS, is?)
*/
if (ndo->ndo_eflag)
ND_PRINT((ndo, "%c %4d %02x ", p[0] ? 'O' : 'I', length, p[1]));
#endif
ppp_print(ndo, p, length);
return (0);
}
/*
* PPP I/F printer to use if we know that RFC 1662-style PPP in HDLC-like
* framing, or Cisco PPP with HDLC framing as per section 4.3.1 of RFC 1547,
* is being used (i.e., we don't check for PPP_ADDRESS and PPP_CONTROL,
* discard them *if* those are the first two octets, and parse the remaining
* packet as a PPP packet, as "ppp_print()" does).
*
* This handles, for example, DLT_PPP_SERIAL in NetBSD.
*/
u_int
ppp_hdlc_if_print(netdissect_options *ndo,
const struct pcap_pkthdr *h, register const u_char *p)
{
register u_int length = h->len;
register u_int caplen = h->caplen;
u_int proto;
u_int hdrlen = 0;
if (caplen < 2) {
ND_PRINT((ndo, "[|ppp]"));
return (caplen);
}
switch (p[0]) {
case PPP_ADDRESS:
if (caplen < 4) {
ND_PRINT((ndo, "[|ppp]"));
return (caplen);
}
if (ndo->ndo_eflag)
ND_PRINT((ndo, "%02x %02x %d ", p[0], p[1], length));
p += 2;
length -= 2;
hdrlen += 2;
proto = EXTRACT_16BITS(p);
p += 2;
length -= 2;
hdrlen += 2;
ND_PRINT((ndo, "%s: ", tok2str(ppptype2str, "unknown PPP protocol (0x%04x)", proto)));
handle_ppp(ndo, proto, p, length);
break;
case CHDLC_UNICAST:
case CHDLC_BCAST:
return (chdlc_if_print(ndo, h, p));
default:
if (caplen < 4) {
ND_PRINT((ndo, "[|ppp]"));
return (caplen);
}
if (ndo->ndo_eflag)
ND_PRINT((ndo, "%02x %02x %d ", p[0], p[1], length));
p += 2;
hdrlen += 2;
/*
* XXX - NetBSD's "ppp_netbsd_serial_if_print()" treats
* the next two octets as an Ethernet type; does that
* ever happen?
*/
ND_PRINT((ndo, "unknown addr %02x; ctrl %02x", p[0], p[1]));
break;
}
return (hdrlen);
}
#define PPP_BSDI_HDRLEN 24
/* BSD/OS specific PPP printer */
u_int
ppp_bsdos_if_print(netdissect_options *ndo _U_,
const struct pcap_pkthdr *h _U_, register const u_char *p _U_)
{
register int hdrlength;
#ifdef __bsdi__
register u_int length = h->len;
register u_int caplen = h->caplen;
uint16_t ptype;
const u_char *q;
int i;
if (caplen < PPP_BSDI_HDRLEN) {
ND_PRINT((ndo, "[|ppp]"));
return (caplen)
}
hdrlength = 0;
#if 0
if (p[0] == PPP_ADDRESS && p[1] == PPP_CONTROL) {
if (ndo->ndo_eflag)
ND_PRINT((ndo, "%02x %02x ", p[0], p[1]));
p += 2;
hdrlength = 2;
}
if (ndo->ndo_eflag)
ND_PRINT((ndo, "%d ", length));
/* Retrieve the protocol type */
if (*p & 01) {
/* Compressed protocol field */
ptype = *p;
if (ndo->ndo_eflag)
ND_PRINT((ndo, "%02x ", ptype));
p++;
hdrlength += 1;
} else {
/* Un-compressed protocol field */
ptype = EXTRACT_16BITS(p);
if (ndo->ndo_eflag)
ND_PRINT((ndo, "%04x ", ptype));
p += 2;
hdrlength += 2;
}
#else
ptype = 0; /*XXX*/
if (ndo->ndo_eflag)
ND_PRINT((ndo, "%c ", p[SLC_DIR] ? 'O' : 'I'));
if (p[SLC_LLHL]) {
/* link level header */
struct ppp_header *ph;
q = p + SLC_BPFHDRLEN;
ph = (struct ppp_header *)q;
if (ph->phdr_addr == PPP_ADDRESS
&& ph->phdr_ctl == PPP_CONTROL) {
if (ndo->ndo_eflag)
ND_PRINT((ndo, "%02x %02x ", q[0], q[1]));
ptype = EXTRACT_16BITS(&ph->phdr_type);
if (ndo->ndo_eflag && (ptype == PPP_VJC || ptype == PPP_VJNC)) {
ND_PRINT((ndo, "%s ", tok2str(ppptype2str,
"proto-#%d", ptype)));
}
} else {
if (ndo->ndo_eflag) {
ND_PRINT((ndo, "LLH=["));
for (i = 0; i < p[SLC_LLHL]; i++)
ND_PRINT((ndo, "%02x", q[i]));
ND_PRINT((ndo, "] "));
}
}
}
if (ndo->ndo_eflag)
ND_PRINT((ndo, "%d ", length));
if (p[SLC_CHL]) {
q = p + SLC_BPFHDRLEN + p[SLC_LLHL];
switch (ptype) {
case PPP_VJC:
ptype = vjc_print(ndo, q, ptype);
hdrlength = PPP_BSDI_HDRLEN;
p += hdrlength;
switch (ptype) {
case PPP_IP:
ip_print(ndo, p, length);
break;
case PPP_IPV6:
ip6_print(ndo, p, length);
break;
case PPP_MPLS_UCAST:
case PPP_MPLS_MCAST:
mpls_print(ndo, p, length);
break;
}
goto printx;
case PPP_VJNC:
ptype = vjc_print(ndo, q, ptype);
hdrlength = PPP_BSDI_HDRLEN;
p += hdrlength;
switch (ptype) {
case PPP_IP:
ip_print(ndo, p, length);
break;
case PPP_IPV6:
ip6_print(ndo, p, length);
break;
case PPP_MPLS_UCAST:
case PPP_MPLS_MCAST:
mpls_print(ndo, p, length);
break;
}
goto printx;
default:
if (ndo->ndo_eflag) {
ND_PRINT((ndo, "CH=["));
for (i = 0; i < p[SLC_LLHL]; i++)
ND_PRINT((ndo, "%02x", q[i]));
ND_PRINT((ndo, "] "));
}
break;
}
}
hdrlength = PPP_BSDI_HDRLEN;
#endif
length -= hdrlength;
p += hdrlength;
switch (ptype) {
case PPP_IP:
ip_print(p, length);
break;
case PPP_IPV6:
ip6_print(ndo, p, length);
break;
case PPP_MPLS_UCAST:
case PPP_MPLS_MCAST:
mpls_print(ndo, p, length);
break;
default:
ND_PRINT((ndo, "%s ", tok2str(ppptype2str, "unknown PPP protocol (0x%04x)", ptype)));
}
printx:
#else /* __bsdi */
hdrlength = 0;
#endif /* __bsdi__ */
return (hdrlength);
}
/*
* Local Variables:
* c-style: whitesmith
* c-basic-offset: 8
* End:
*/
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_2644_11 |
crossvul-cpp_data_good_351_6 | /*
* Support for ePass2003 smart cards
*
* Copyright (C) 2008, Weitao Sun <weitao@ftsafe.com>
* Copyright (C) 2011, Xiaoshuo Wu <xiaoshuo@ftsafe.com>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.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
#ifdef ENABLE_SM /* empty file without SM enabled */
#ifdef ENABLE_OPENSSL /* empty file without openssl */
#include <ctype.h>
#include <stdlib.h>
#include <string.h>
#include <openssl/evp.h>
#include <openssl/sha.h>
#include "internal.h"
#include "asn1.h"
#include <ctype.h>
#include <stdlib.h>
#include <string.h>
#include <openssl/evp.h>
#include <openssl/sha.h>
#include "internal.h"
#include "asn1.h"
#include "cardctl.h"
static struct sc_atr_table epass2003_atrs[] = {
/* This is a FIPS certified card using SCP01 security messaging. */
{"3B:9F:95:81:31:FE:9F:00:66:46:53:05:10:00:11:71:df:00:00:00:6a:82:5e",
"FF:FF:FF:FF:FF:00:FF:FF:FF:FF:FF:FF:00:00:00:ff:00:ff:ff:00:00:00:00",
"FTCOS/ePass2003", SC_CARD_TYPE_ENTERSAFE_FTCOS_EPASS2003, 0, NULL },
{NULL, NULL, NULL, 0, 0, NULL}
};
static struct sc_card_operations *iso_ops = NULL;
static struct sc_card_operations epass2003_ops;
static struct sc_card_driver epass2003_drv = {
"epass2003",
"epass2003",
&epass2003_ops,
NULL, 0, NULL
};
#define KEY_TYPE_AES 0x01 /* FIPS mode */
#define KEY_TYPE_DES 0x02 /* Non-FIPS mode */
#define KEY_LEN_AES 16
#define KEY_LEN_DES 8
#define KEY_LEN_DES3 24
#define HASH_LEN 24
static unsigned char PIN_ID[2] = { ENTERSAFE_USER_PIN_ID, ENTERSAFE_SO_PIN_ID };
/*0x00:plain; 0x01:scp01 sm*/
#define SM_PLAIN 0x00
#define SM_SCP01 0x01
static unsigned char g_init_key_enc[16] = {
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C,
0x0D, 0x0E, 0x0F, 0x10
};
static unsigned char g_init_key_mac[16] = {
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C,
0x0D, 0x0E, 0x0F, 0x10
};
static unsigned char g_random[8] = {
0xBF, 0xC3, 0x29, 0x11, 0xC7, 0x18, 0xC3, 0x40
};
typedef struct epass2003_exdata_st {
unsigned char sm; /* SM_PLAIN or SM_SCP01 */
unsigned char smtype; /* KEY_TYPE_AES or KEY_TYPE_DES */
unsigned char sk_enc[16]; /* encrypt session key */
unsigned char sk_mac[16]; /* mac session key */
unsigned char icv_mac[16]; /* instruction counter vector(for sm) */
unsigned char currAlg; /* current Alg */
unsigned int ecAlgFlags; /* Ec Alg mechanism type*/
} epass2003_exdata;
#define REVERSE_ORDER4(x) ( \
((unsigned long)x & 0xFF000000)>> 24 | \
((unsigned long)x & 0x00FF0000)>> 8 | \
((unsigned long)x & 0x0000FF00)<< 8 | \
((unsigned long)x & 0x000000FF)<< 24)
static const struct sc_card_error epass2003_errors[] = {
{ 0x6200, SC_ERROR_CARD_CMD_FAILED, "Warning: no information given, non-volatile memory is unchanged" },
{ 0x6281, SC_ERROR_CORRUPTED_DATA, "Part of returned data may be corrupted" },
{ 0x6282, SC_ERROR_FILE_END_REACHED, "End of file/record reached before reading Le bytes" },
{ 0x6283, SC_ERROR_CARD_CMD_FAILED, "Selected file invalidated" },
{ 0x6284, SC_ERROR_CARD_CMD_FAILED, "FCI not formatted according to ISO 7816-4" },
{ 0x6300, SC_ERROR_PIN_CODE_INCORRECT, "Authentication failed"},
{ 0x63C1, SC_ERROR_PIN_CODE_INCORRECT, "Authentication failed. One tries left"},
{ 0x63C2, SC_ERROR_PIN_CODE_INCORRECT, "Authentication failed. Two tries left"},
{ 0x63C3, SC_ERROR_PIN_CODE_INCORRECT, "Authentication failed"},
{ 0x63C4, SC_ERROR_PIN_CODE_INCORRECT, "Authentication failed"},
{ 0x63C5, SC_ERROR_PIN_CODE_INCORRECT, "Authentication failed"},
{ 0x63C6, SC_ERROR_PIN_CODE_INCORRECT, "Authentication failed"},
{ 0x63C7, SC_ERROR_PIN_CODE_INCORRECT, "Authentication failed"},
{ 0x63C8, SC_ERROR_PIN_CODE_INCORRECT, "Authentication failed"},
{ 0x63C9, SC_ERROR_PIN_CODE_INCORRECT, "Authentication failed"},
{ 0x63CA, SC_ERROR_PIN_CODE_INCORRECT, "Authentication failed"},
{ 0x6381, SC_ERROR_CARD_CMD_FAILED, "Warning: file filled up by last write" },
{ 0x6581, SC_ERROR_MEMORY_FAILURE, "Memory failure" },
{ 0x6700, SC_ERROR_WRONG_LENGTH, "Wrong length" },
{ 0x6800, SC_ERROR_NO_CARD_SUPPORT, "Functions in CLA not supported" },
{ 0x6881, SC_ERROR_NO_CARD_SUPPORT, "Logical channel not supported" },
{ 0x6882, SC_ERROR_NO_CARD_SUPPORT, "Secure messaging not supported" },
{ 0x6900, SC_ERROR_NOT_ALLOWED, "Command not allowed" },
{ 0x6981, SC_ERROR_CARD_CMD_FAILED, "Command incompatible with file structure" },
{ 0x6982, SC_ERROR_SECURITY_STATUS_NOT_SATISFIED, "Security status not satisfied" },
{ 0x6983, SC_ERROR_AUTH_METHOD_BLOCKED, "Authentication method blocked" },
{ 0x6984, SC_ERROR_REF_DATA_NOT_USABLE, "Referenced data not usable" },
{ 0x6985, SC_ERROR_NOT_ALLOWED, "Conditions of use not satisfied" },
{ 0x6986, SC_ERROR_NOT_ALLOWED, "Command not allowed (no current EF)" },
{ 0x6987, SC_ERROR_INCORRECT_PARAMETERS,"Expected SM data objects missing" },
{ 0x6988, SC_ERROR_INCORRECT_PARAMETERS,"SM data objects incorrect" },
{ 0x6A00, SC_ERROR_INCORRECT_PARAMETERS,"Wrong parameter(s) P1-P2" },
{ 0x6A80, SC_ERROR_INCORRECT_PARAMETERS,"Incorrect parameters in the data field" },
{ 0x6A81, SC_ERROR_NO_CARD_SUPPORT, "Function not supported" },
{ 0x6A82, SC_ERROR_FILE_NOT_FOUND, "File not found" },
{ 0x6A83, SC_ERROR_RECORD_NOT_FOUND, "Record not found" },
{ 0x6A84, SC_ERROR_NOT_ENOUGH_MEMORY, "Not enough memory space in the file" },
{ 0x6A85, SC_ERROR_INCORRECT_PARAMETERS,"Lc inconsistent with TLV structure" },
{ 0x6A86, SC_ERROR_INCORRECT_PARAMETERS,"Incorrect parameters P1-P2" },
{ 0x6A87, SC_ERROR_INCORRECT_PARAMETERS,"Lc inconsistent with P1-P2" },
{ 0x6A88, SC_ERROR_DATA_OBJECT_NOT_FOUND,"Referenced data not found" },
{ 0x6A89, SC_ERROR_FILE_ALREADY_EXISTS, "File already exists"},
{ 0x6A8A, SC_ERROR_FILE_ALREADY_EXISTS, "DF name already exists"},
{ 0x6B00, SC_ERROR_INCORRECT_PARAMETERS,"Wrong parameter(s) P1-P2" },
{ 0x6D00, SC_ERROR_INS_NOT_SUPPORTED, "Instruction code not supported or invalid" },
{ 0x6E00, SC_ERROR_CLASS_NOT_SUPPORTED, "Class not supported" },
{ 0x6F00, SC_ERROR_CARD_CMD_FAILED, "No precise diagnosis" },
{ 0x9000,SC_SUCCESS, NULL }
};
static int epass2003_transmit_apdu(struct sc_card *card, struct sc_apdu *apdu);
static int epass2003_select_file(struct sc_card *card, const sc_path_t * in_path, sc_file_t ** file_out);
int epass2003_refresh(struct sc_card *card);
static int hash_data(const unsigned char *data, size_t datalen, unsigned char *hash, unsigned int mechanismType);
static int
epass2003_check_sw(struct sc_card *card, unsigned int sw1, unsigned int sw2)
{
const int err_count = sizeof(epass2003_errors)/sizeof(epass2003_errors[0]);
int i;
/* Handle special cases here */
if (sw1 == 0x6C) {
sc_log(card->ctx, "Wrong length; correct length is %d", sw2);
return SC_ERROR_WRONG_LENGTH;
}
for (i = 0; i < err_count; i++) {
if (epass2003_errors[i].SWs == ((sw1 << 8) | sw2)) {
sc_log(card->ctx, "%s", epass2003_errors[i].errorstr);
return epass2003_errors[i].errorno;
}
}
sc_log(card->ctx, "Unknown SWs; SW1=%02X, SW2=%02X", sw1, sw2);
return SC_ERROR_CARD_CMD_FAILED;
}
static int
sc_transmit_apdu_t(sc_card_t *card, sc_apdu_t *apdu)
{
int r = sc_transmit_apdu(card, apdu);
if ( ((0x69 == apdu->sw1) && (0x85 == apdu->sw2)) || ((0x69 == apdu->sw1) && (0x88 == apdu->sw2)))
{
epass2003_refresh(card);
r = sc_transmit_apdu(card, apdu);
}
return r;
}
static int
openssl_enc(const EVP_CIPHER * cipher, const unsigned char *key, const unsigned char *iv,
const unsigned char *input, size_t length, unsigned char *output)
{
int r = SC_ERROR_INTERNAL;
EVP_CIPHER_CTX * ctx = NULL;
int outl = 0;
int outl_tmp = 0;
unsigned char iv_tmp[EVP_MAX_IV_LENGTH] = { 0 };
memcpy(iv_tmp, iv, EVP_MAX_IV_LENGTH);
ctx = EVP_CIPHER_CTX_new();
if (ctx == NULL)
goto out;
EVP_EncryptInit_ex(ctx, cipher, NULL, key, iv_tmp);
EVP_CIPHER_CTX_set_padding(ctx, 0);
if (!EVP_EncryptUpdate(ctx, output, &outl, input, length))
goto out;
if (!EVP_EncryptFinal_ex(ctx, output + outl, &outl_tmp))
goto out;
r = SC_SUCCESS;
out:
if (ctx)
EVP_CIPHER_CTX_free(ctx);
return r;
}
static int
openssl_dec(const EVP_CIPHER * cipher, const unsigned char *key, const unsigned char *iv,
const unsigned char *input, size_t length, unsigned char *output)
{
int r = SC_ERROR_INTERNAL;
EVP_CIPHER_CTX * ctx = NULL;
int outl = 0;
int outl_tmp = 0;
unsigned char iv_tmp[EVP_MAX_IV_LENGTH] = { 0 };
memcpy(iv_tmp, iv, EVP_MAX_IV_LENGTH);
ctx = EVP_CIPHER_CTX_new();
if (ctx == NULL)
goto out;
EVP_DecryptInit_ex(ctx, cipher, NULL, key, iv_tmp);
EVP_CIPHER_CTX_set_padding(ctx, 0);
if (!EVP_DecryptUpdate(ctx, output, &outl, input, length))
goto out;
if (!EVP_DecryptFinal_ex(ctx, output + outl, &outl_tmp))
goto out;
r = SC_SUCCESS;
out:
if (ctx)
EVP_CIPHER_CTX_free(ctx);
return r;
}
static int
aes128_encrypt_ecb(const unsigned char *key, int keysize,
const unsigned char *input, size_t length, unsigned char *output)
{
unsigned char iv[EVP_MAX_IV_LENGTH] = { 0 };
return openssl_enc(EVP_aes_128_ecb(), key, iv, input, length, output);
}
static int
aes128_encrypt_cbc(const unsigned char *key, int keysize, unsigned char iv[16],
const unsigned char *input, size_t length, unsigned char *output)
{
return openssl_enc(EVP_aes_128_cbc(), key, iv, input, length, output);
}
static int
aes128_decrypt_cbc(const unsigned char *key, int keysize, unsigned char iv[16],
const unsigned char *input, size_t length, unsigned char *output)
{
return openssl_dec(EVP_aes_128_cbc(), key, iv, input, length, output);
}
static int
des3_encrypt_ecb(const unsigned char *key, int keysize,
const unsigned char *input, int length, unsigned char *output)
{
unsigned char iv[EVP_MAX_IV_LENGTH] = { 0 };
unsigned char bKey[24] = { 0 };
if (keysize == 16) {
memcpy(&bKey[0], key, 16);
memcpy(&bKey[16], key, 8);
}
else {
memcpy(&bKey[0], key, 24);
}
return openssl_enc(EVP_des_ede3(), bKey, iv, input, length, output);
}
static int
des3_encrypt_cbc(const unsigned char *key, int keysize, unsigned char iv[EVP_MAX_IV_LENGTH],
const unsigned char *input, size_t length, unsigned char *output)
{
unsigned char bKey[24] = { 0 };
if (keysize == 16) {
memcpy(&bKey[0], key, 16);
memcpy(&bKey[16], key, 8);
}
else {
memcpy(&bKey[0], key, 24);
}
return openssl_enc(EVP_des_ede3_cbc(), bKey, iv, input, length, output);
}
static int
des3_decrypt_cbc(const unsigned char *key, int keysize, unsigned char iv[EVP_MAX_IV_LENGTH],
const unsigned char *input, size_t length, unsigned char *output)
{
unsigned char bKey[24] = { 0 };
if (keysize == 16) {
memcpy(&bKey[0], key, 16);
memcpy(&bKey[16], key, 8);
}
else {
memcpy(&bKey[0], key, 24);
}
return openssl_dec(EVP_des_ede3_cbc(), bKey, iv, input, length, output);
}
static int
des_encrypt_cbc(const unsigned char *key, int keysize, unsigned char iv[EVP_MAX_IV_LENGTH],
const unsigned char *input, size_t length, unsigned char *output)
{
return openssl_enc(EVP_des_cbc(), key, iv, input, length, output);
}
static int
des_decrypt_cbc(const unsigned char *key, int keysize, unsigned char iv[EVP_MAX_IV_LENGTH],
const unsigned char *input, size_t length, unsigned char *output)
{
return openssl_dec(EVP_des_cbc(), key, iv, input, length, output);
}
static int
openssl_dig(const EVP_MD * digest, const unsigned char *input, size_t length,
unsigned char *output)
{
int r = 0;
EVP_MD_CTX *ctx = NULL;
unsigned outl = 0;
ctx = EVP_MD_CTX_create();
if (ctx == NULL) {
r = SC_ERROR_OUT_OF_MEMORY;
goto err;
}
EVP_MD_CTX_init(ctx);
EVP_DigestInit_ex(ctx, digest, NULL);
if (!EVP_DigestUpdate(ctx, input, length)) {
r = SC_ERROR_INTERNAL;
goto err;
}
if (!EVP_DigestFinal_ex(ctx, output, &outl)) {
r = SC_ERROR_INTERNAL;
goto err;
}
r = SC_SUCCESS;
err:
if (ctx)
EVP_MD_CTX_destroy(ctx);
return r;
}
static int
sha1_digest(const unsigned char *input, size_t length, unsigned char *output)
{
return openssl_dig(EVP_sha1(), input, length, output);
}
static int
sha256_digest(const unsigned char *input, size_t length, unsigned char *output)
{
return openssl_dig(EVP_sha256(), input, length, output);
}
static int
gen_init_key(struct sc_card *card, unsigned char *key_enc, unsigned char *key_mac,
unsigned char *result, unsigned char key_type)
{
int r;
struct sc_apdu apdu;
unsigned char data[256] = { 0 };
unsigned char tmp_sm;
unsigned long blocksize = 0;
unsigned char cryptogram[256] = { 0 }; /* host cryptogram */
unsigned char iv[16] = { 0 };
epass2003_exdata *exdata = NULL;
if (!card->drv_data)
return SC_ERROR_INVALID_ARGUMENTS;
exdata = (epass2003_exdata *)card->drv_data;
LOG_FUNC_CALLED(card->ctx);
sc_format_apdu(card, &apdu, SC_APDU_CASE_4_SHORT, 0x50, 0x00, 0x00);
apdu.cla = 0x80;
apdu.lc = apdu.datalen = sizeof(g_random);
apdu.data = g_random; /* host random */
apdu.le = apdu.resplen = 28;
apdu.resp = result; /* card random is result[12~19] */
tmp_sm = exdata->sm;
exdata->sm = SM_PLAIN;
r = epass2003_transmit_apdu(card, &apdu);
exdata->sm = tmp_sm;
LOG_TEST_RET(card->ctx, r, "APDU gen_init_key failed");
r = sc_check_sw(card, apdu.sw1, apdu.sw2);
LOG_TEST_RET(card->ctx, r, "gen_init_key failed");
/* Step 1 - Generate Derivation data */
memcpy(data, &result[16], 4);
memcpy(&data[4], g_random, 4);
memcpy(&data[8], &result[12], 4);
memcpy(&data[12], &g_random[4], 4);
/* Step 2,3 - Create S-ENC/S-MAC Session Key */
if (KEY_TYPE_AES == key_type) {
aes128_encrypt_ecb(key_enc, 16, data, 16, exdata->sk_enc);
aes128_encrypt_ecb(key_mac, 16, data, 16, exdata->sk_mac);
}
else {
des3_encrypt_ecb(key_enc, 16, data, 16, exdata->sk_enc);
des3_encrypt_ecb(key_mac, 16, data, 16, exdata->sk_mac);
}
memcpy(data, g_random, 8);
memcpy(&data[8], &result[12], 8);
data[16] = 0x80;
blocksize = (key_type == KEY_TYPE_AES ? 16 : 8);
memset(&data[17], 0x00, blocksize - 1);
/* calculate host cryptogram */
if (KEY_TYPE_AES == key_type)
aes128_encrypt_cbc(exdata->sk_enc, 16, iv, data, 16 + blocksize, cryptogram);
else
des3_encrypt_cbc(exdata->sk_enc, 16, iv, data, 16 + blocksize, cryptogram);
/* verify card cryptogram */
if (0 != memcmp(&cryptogram[16], &result[20], 8))
LOG_FUNC_RETURN(card->ctx, SC_ERROR_CARD_CMD_FAILED);
LOG_FUNC_RETURN(card->ctx, SC_SUCCESS);
}
static int
verify_init_key(struct sc_card *card, unsigned char *ran_key, unsigned char key_type)
{
int r;
struct sc_apdu apdu;
unsigned long blocksize = (key_type == KEY_TYPE_AES ? 16 : 8);
unsigned char data[256] = { 0 };
unsigned char cryptogram[256] = { 0 }; /* host cryptogram */
unsigned char iv[16] = { 0 };
unsigned char mac[256] = { 0 };
unsigned long i;
unsigned char tmp_sm;
epass2003_exdata *exdata = NULL;
if (!card->drv_data)
return SC_ERROR_INVALID_ARGUMENTS;
exdata = (epass2003_exdata *)card->drv_data;
LOG_FUNC_CALLED(card->ctx);
memcpy(data, ran_key, 8);
memcpy(&data[8], g_random, 8);
data[16] = 0x80;
memset(&data[17], 0x00, blocksize - 1);
memset(iv, 0, 16);
/* calculate host cryptogram */
if (KEY_TYPE_AES == key_type) {
aes128_encrypt_cbc(exdata->sk_enc, 16, iv, data, 16 + blocksize,
cryptogram);
} else {
des3_encrypt_cbc(exdata->sk_enc, 16, iv, data, 16 + blocksize,
cryptogram);
}
memset(data, 0, sizeof(data));
memcpy(data, "\x84\x82\x03\x00\x10", 5);
memcpy(&data[5], &cryptogram[16], 8);
memcpy(&data[13], "\x80\x00\x00", 3);
/* calculate mac icv */
memset(iv, 0x00, 16);
if (KEY_TYPE_AES == key_type) {
aes128_encrypt_cbc(exdata->sk_mac, 16, iv, data, 16, mac);
i = 0;
} else {
des3_encrypt_cbc(exdata->sk_mac, 16, iv, data, 16, mac);
i = 8;
}
/* save mac icv */
memset(exdata->icv_mac, 0x00, 16);
memcpy(exdata->icv_mac, &mac[i], 8);
/* verify host cryptogram */
memcpy(data, &cryptogram[16], 8);
memcpy(&data[8], &mac[i], 8);
sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x82, 0x03, 0x00);
apdu.cla = 0x84;
apdu.lc = apdu.datalen = 16;
apdu.data = data;
tmp_sm = exdata->sm;
exdata->sm = SM_PLAIN;
r = epass2003_transmit_apdu(card, &apdu);
exdata->sm = tmp_sm;
LOG_TEST_RET(card->ctx, r,
"APDU verify_init_key failed");
r = sc_check_sw(card, apdu.sw1, apdu.sw2);
LOG_TEST_RET(card->ctx, r,
"verify_init_key failed");
return r;
}
static int
mutual_auth(struct sc_card *card, unsigned char *key_enc,
unsigned char *key_mac)
{
struct sc_context *ctx = card->ctx;
int r;
unsigned char result[256] = { 0 };
unsigned char ran_key[8] = { 0 };
epass2003_exdata *exdata = NULL;
if (!card->drv_data)
return SC_ERROR_INVALID_ARGUMENTS;
exdata = (epass2003_exdata *)card->drv_data;
LOG_FUNC_CALLED(ctx);
r = gen_init_key(card, key_enc, key_mac, result, exdata->smtype);
LOG_TEST_RET(ctx, r, "gen_init_key failed");
memcpy(ran_key, &result[12], 8);
r = verify_init_key(card, ran_key, exdata->smtype);
LOG_TEST_RET(ctx, r, "verify_init_key failed");
LOG_FUNC_RETURN(ctx, r);
}
int
epass2003_refresh(struct sc_card *card)
{
int r = SC_SUCCESS;
epass2003_exdata *exdata = NULL;
if (!card->drv_data)
return SC_ERROR_INVALID_ARGUMENTS;
exdata = (epass2003_exdata *)card->drv_data;
if (exdata->sm) {
card->sm_ctx.sm_mode = 0;
r = mutual_auth(card, g_init_key_enc, g_init_key_mac);
card->sm_ctx.sm_mode = SM_MODE_TRANSMIT;
LOG_TEST_RET(card->ctx, r, "mutual_auth failed");
}
return r;
}
/* Data(TLV)=0x87|L|0x01+Cipher */
static int
construct_data_tlv(struct sc_card *card, struct sc_apdu *apdu, unsigned char *apdu_buf,
unsigned char *data_tlv, size_t * data_tlv_len, const unsigned char key_type)
{
size_t block_size = (KEY_TYPE_AES == key_type ? 16 : 8);
unsigned char pad[4096] = { 0 };
size_t pad_len;
size_t tlv_more; /* increased tlv length */
unsigned char iv[16] = { 0 };
epass2003_exdata *exdata = NULL;
if (!card->drv_data)
return SC_ERROR_INVALID_ARGUMENTS;
exdata = (epass2003_exdata *)card->drv_data;
/* padding */
apdu_buf[block_size] = 0x87;
memcpy(pad, apdu->data, apdu->lc);
pad[apdu->lc] = 0x80;
if ((apdu->lc + 1) % block_size)
pad_len = ((apdu->lc + 1) / block_size + 1) * block_size;
else
pad_len = apdu->lc + 1;
/* encode Lc' */
if (pad_len > 0x7E) {
/* Lc' > 0x7E, use extended APDU */
apdu_buf[block_size + 1] = 0x82;
apdu_buf[block_size + 2] = (unsigned char)((pad_len + 1) / 0x100);
apdu_buf[block_size + 3] = (unsigned char)((pad_len + 1) % 0x100);
apdu_buf[block_size + 4] = 0x01;
tlv_more = 5;
}
else {
apdu_buf[block_size + 1] = (unsigned char)pad_len + 1;
apdu_buf[block_size + 2] = 0x01;
tlv_more = 3;
}
memcpy(data_tlv, &apdu_buf[block_size], tlv_more);
/* encrypt Data */
if (KEY_TYPE_AES == key_type)
aes128_encrypt_cbc(exdata->sk_enc, 16, iv, pad, pad_len, apdu_buf + block_size + tlv_more);
else
des3_encrypt_cbc(exdata->sk_enc, 16, iv, pad, pad_len, apdu_buf + block_size + tlv_more);
memcpy(data_tlv + tlv_more, apdu_buf + block_size + tlv_more, pad_len);
*data_tlv_len = tlv_more + pad_len;
return 0;
}
/* Le(TLV)=0x97|L|Le */
static int
construct_le_tlv(struct sc_apdu *apdu, unsigned char *apdu_buf, size_t data_tlv_len,
unsigned char *le_tlv, size_t * le_tlv_len, const unsigned char key_type)
{
size_t block_size = (KEY_TYPE_AES == key_type ? 16 : 8);
*(apdu_buf + block_size + data_tlv_len) = 0x97;
if (apdu->le > 0x7F) {
/* Le' > 0x7E, use extended APDU */
*(apdu_buf + block_size + data_tlv_len + 1) = 2;
*(apdu_buf + block_size + data_tlv_len + 2) = (unsigned char)(apdu->le / 0x100);
*(apdu_buf + block_size + data_tlv_len + 3) = (unsigned char)(apdu->le % 0x100);
memcpy(le_tlv, apdu_buf + block_size + data_tlv_len, 4);
*le_tlv_len = 4;
}
else {
*(apdu_buf + block_size + data_tlv_len + 1) = 1;
*(apdu_buf + block_size + data_tlv_len + 2) = (unsigned char)apdu->le;
memcpy(le_tlv, apdu_buf + block_size + data_tlv_len, 3);
*le_tlv_len = 3;
}
return 0;
}
/* MAC(TLV)=0x8e|0x08|MAC */
static int
construct_mac_tlv(struct sc_card *card, unsigned char *apdu_buf, size_t data_tlv_len, size_t le_tlv_len,
unsigned char *mac_tlv, size_t * mac_tlv_len, const unsigned char key_type)
{
size_t block_size = (KEY_TYPE_AES == key_type ? 16 : 8);
unsigned char mac[4096] = { 0 };
size_t mac_len;
unsigned char icv[16] = { 0 };
int i = (KEY_TYPE_AES == key_type ? 15 : 7);
epass2003_exdata *exdata = NULL;
if (!card->drv_data)
return SC_ERROR_INVALID_ARGUMENTS;
exdata = (epass2003_exdata *)card->drv_data;
if (0 == data_tlv_len && 0 == le_tlv_len) {
mac_len = block_size;
}
else {
/* padding */
*(apdu_buf + block_size + data_tlv_len + le_tlv_len) = 0x80;
if ((data_tlv_len + le_tlv_len + 1) % block_size)
mac_len = (((data_tlv_len + le_tlv_len + 1) / block_size) +
1) * block_size + block_size;
else
mac_len = data_tlv_len + le_tlv_len + 1 + block_size;
memset((apdu_buf + block_size + data_tlv_len + le_tlv_len + 1),
0, (mac_len - (data_tlv_len + le_tlv_len + 1)));
}
/* increase icv */
for (; i >= 0; i--) {
if (exdata->icv_mac[i] == 0xff) {
exdata->icv_mac[i] = 0;
}
else {
exdata->icv_mac[i]++;
break;
}
}
/* calculate MAC */
memset(icv, 0, sizeof(icv));
memcpy(icv, exdata->icv_mac, 16);
if (KEY_TYPE_AES == key_type) {
aes128_encrypt_cbc(exdata->sk_mac, 16, icv, apdu_buf, mac_len, mac);
memcpy(mac_tlv + 2, &mac[mac_len - 16], 8);
}
else {
unsigned char iv[EVP_MAX_IV_LENGTH] = { 0 };
unsigned char tmp[8] = { 0 };
des_encrypt_cbc(exdata->sk_mac, 8, icv, apdu_buf, mac_len, mac);
des_decrypt_cbc(&exdata->sk_mac[8], 8, iv, &mac[mac_len - 8], 8, tmp);
memset(iv, 0x00, sizeof iv);
des_encrypt_cbc(exdata->sk_mac, 8, iv, tmp, 8, mac_tlv + 2);
}
*mac_tlv_len = 2 + 8;
return 0;
}
/* According to GlobalPlatform Card Specification's SCP01
* encode APDU from
* CLA INS P1 P2 [Lc] Data [Le]
* to
* CLA INS P1 P2 Lc' Data' [Le]
* where
* Data'=Data(TLV)+Le(TLV)+MAC(TLV) */
static int
encode_apdu(struct sc_card *card, struct sc_apdu *plain, struct sc_apdu *sm,
unsigned char *apdu_buf, size_t * apdu_buf_len)
{
size_t block_size = 0;
unsigned char dataTLV[4096] = { 0 };
size_t data_tlv_len = 0;
unsigned char le_tlv[256] = { 0 };
size_t le_tlv_len = 0;
size_t mac_tlv_len = 10;
size_t tmp_lc = 0;
size_t tmp_le = 0;
unsigned char mac_tlv[256] = { 0 };
epass2003_exdata *exdata = NULL;
mac_tlv[0] = 0x8E;
mac_tlv[1] = 8;
/* size_t plain_le = 0; */
if (!card->drv_data)
return SC_ERROR_INVALID_ARGUMENTS;
exdata = (epass2003_exdata*)card->drv_data;
block_size = (KEY_TYPE_DES == exdata->smtype ? 16 : 8);
sm->cse = SC_APDU_CASE_4_SHORT;
apdu_buf[0] = (unsigned char)plain->cla;
apdu_buf[1] = (unsigned char)plain->ins;
apdu_buf[2] = (unsigned char)plain->p1;
apdu_buf[3] = (unsigned char)plain->p2;
/* plain_le = plain->le; */
/* padding */
apdu_buf[4] = 0x80;
memset(&apdu_buf[5], 0x00, block_size - 5);
/* Data -> Data' */
if (plain->lc != 0)
if (0 != construct_data_tlv(card, plain, apdu_buf, dataTLV, &data_tlv_len, exdata->smtype))
return -1;
if (plain->le != 0 || (plain->le == 0 && plain->resplen != 0))
if (0 != construct_le_tlv(plain, apdu_buf, data_tlv_len, le_tlv,
&le_tlv_len, exdata->smtype))
return -1;
if (0 != construct_mac_tlv(card, apdu_buf, data_tlv_len, le_tlv_len, mac_tlv, &mac_tlv_len, exdata->smtype))
return -1;
memset(apdu_buf + 4, 0, *apdu_buf_len - 4);
sm->lc = sm->datalen = data_tlv_len + le_tlv_len + mac_tlv_len;
if (sm->lc > 0xFF) {
sm->cse = SC_APDU_CASE_4_EXT;
apdu_buf[4] = (unsigned char)((sm->lc) / 0x10000);
apdu_buf[5] = (unsigned char)(((sm->lc) / 0x100) % 0x100);
apdu_buf[6] = (unsigned char)((sm->lc) % 0x100);
tmp_lc = 3;
}
else {
apdu_buf[4] = (unsigned char)sm->lc;
tmp_lc = 1;
}
memcpy(apdu_buf + 4 + tmp_lc, dataTLV, data_tlv_len);
memcpy(apdu_buf + 4 + tmp_lc + data_tlv_len, le_tlv, le_tlv_len);
memcpy(apdu_buf + 4 + tmp_lc + data_tlv_len + le_tlv_len, mac_tlv, mac_tlv_len);
memcpy((unsigned char *)sm->data, apdu_buf + 4 + tmp_lc, sm->datalen);
*apdu_buf_len = 0;
if (4 == le_tlv_len) {
sm->cse = SC_APDU_CASE_4_EXT;
*(apdu_buf + 4 + tmp_lc + sm->lc) = (unsigned char)(plain->le / 0x100);
*(apdu_buf + 4 + tmp_lc + sm->lc + 1) = (unsigned char)(plain->le % 0x100);
tmp_le = 2;
}
else if (3 == le_tlv_len) {
*(apdu_buf + 4 + tmp_lc + sm->lc) = (unsigned char)plain->le;
tmp_le = 1;
}
*apdu_buf_len += 4 + tmp_lc + data_tlv_len + le_tlv_len + mac_tlv_len + tmp_le;
/* sm->le = calc_le(plain_le); */
return 0;
}
static int
epass2003_sm_wrap_apdu(struct sc_card *card, struct sc_apdu *plain, struct sc_apdu *sm)
{
unsigned char buf[4096] = { 0 }; /* APDU buffer */
size_t buf_len = sizeof(buf);
epass2003_exdata *exdata = NULL;
if (!card->drv_data)
return SC_ERROR_INVALID_ARGUMENTS;
exdata = (epass2003_exdata *)card->drv_data;
LOG_FUNC_CALLED(card->ctx);
if (exdata->sm)
plain->cla |= 0x0C;
sm->cse = plain->cse;
sm->cla = plain->cla;
sm->ins = plain->ins;
sm->p1 = plain->p1;
sm->p2 = plain->p2;
sm->lc = plain->lc;
sm->le = plain->le;
sm->control = plain->control;
sm->flags = plain->flags;
switch (sm->cla & 0x0C) {
case 0x00:
case 0x04:
sm->datalen = plain->datalen;
memcpy((void *)sm->data, plain->data, plain->datalen);
sm->resplen = plain->resplen;
memcpy(sm->resp, plain->resp, plain->resplen);
break;
case 0x0C:
memset(buf, 0, sizeof(buf));
if (0 != encode_apdu(card, plain, sm, buf, &buf_len))
return SC_ERROR_CARD_CMD_FAILED;
break;
default:
return SC_ERROR_INCORRECT_PARAMETERS;
}
return SC_SUCCESS;
}
/* According to GlobalPlatform Card Specification's SCP01
* decrypt APDU response from
* ResponseData' SW1 SW2
* to
* ResponseData SW1 SW2
* where
* ResponseData'=Data(TLV)+SW12(TLV)+MAC(TLV)
* where
* Data(TLV)=0x87|L|Cipher
* SW12(TLV)=0x99|0x02|SW1+SW2
* MAC(TLV)=0x8e|0x08|MAC */
static int
decrypt_response(struct sc_card *card, unsigned char *in, size_t inlen, unsigned char *out, size_t * out_len)
{
size_t cipher_len;
size_t i;
unsigned char iv[16] = { 0 };
unsigned char plaintext[4096] = { 0 };
epass2003_exdata *exdata = NULL;
if (!card->drv_data)
return SC_ERROR_INVALID_ARGUMENTS;
exdata = (epass2003_exdata *)card->drv_data;
/* no cipher */
if (in[0] == 0x99)
return 0;
/* parse cipher length */
if (0x01 == in[2] && 0x82 != in[1]) {
cipher_len = in[1];
i = 3;
}
else if (0x01 == in[3] && 0x81 == in[1]) {
cipher_len = in[2];
i = 4;
}
else if (0x01 == in[4] && 0x82 == in[1]) {
cipher_len = in[2] * 0x100;
cipher_len += in[3];
i = 5;
}
else {
return -1;
}
if (cipher_len < 2 || i+cipher_len > inlen || cipher_len > sizeof plaintext)
return -1;
/* decrypt */
if (KEY_TYPE_AES == exdata->smtype)
aes128_decrypt_cbc(exdata->sk_enc, 16, iv, &in[i], cipher_len - 1, plaintext);
else
des3_decrypt_cbc(exdata->sk_enc, 16, iv, &in[i], cipher_len - 1, plaintext);
/* unpadding */
while (0x80 != plaintext[cipher_len - 2] && (cipher_len - 2 > 0))
cipher_len--;
if (2 == cipher_len)
return -1;
memcpy(out, plaintext, cipher_len - 2);
*out_len = cipher_len - 2;
return 0;
}
static int
epass2003_sm_unwrap_apdu(struct sc_card *card, struct sc_apdu *sm, struct sc_apdu *plain)
{
int r;
size_t len = 0;
epass2003_exdata *exdata = NULL;
if (!card->drv_data)
return SC_ERROR_INVALID_ARGUMENTS;
exdata = (epass2003_exdata *)card->drv_data;
LOG_FUNC_CALLED(card->ctx);
r = sc_check_sw(card, sm->sw1, sm->sw2);
if (r == SC_SUCCESS) {
if (exdata->sm) {
if (0 != decrypt_response(card, sm->resp, sm->resplen, plain->resp, &len))
return SC_ERROR_CARD_CMD_FAILED;
}
else {
memcpy(plain->resp, sm->resp, sm->resplen);
len = sm->resplen;
}
}
plain->resplen = len;
plain->sw1 = sm->sw1;
plain->sw2 = sm->sw2;
sc_log(card->ctx,
"unwrapped APDU: resplen %"SC_FORMAT_LEN_SIZE_T"u, SW %02X%02X",
plain->resplen, plain->sw1, plain->sw2);
LOG_FUNC_RETURN(card->ctx, SC_SUCCESS);
}
static int
epass2003_sm_free_wrapped_apdu(struct sc_card *card,
struct sc_apdu *plain, struct sc_apdu **sm_apdu)
{
struct sc_context *ctx = card->ctx;
int rv = SC_SUCCESS;
LOG_FUNC_CALLED(ctx);
if (!sm_apdu)
LOG_FUNC_RETURN(ctx, SC_ERROR_INVALID_ARGUMENTS);
if (!(*sm_apdu))
LOG_FUNC_RETURN(ctx, SC_SUCCESS);
if (plain)
rv = epass2003_sm_unwrap_apdu(card, *sm_apdu, plain);
if ((*sm_apdu)->data) {
unsigned char * p = (unsigned char *)((*sm_apdu)->data);
free(p);
}
if ((*sm_apdu)->resp) {
free((*sm_apdu)->resp);
}
free(*sm_apdu);
*sm_apdu = NULL;
LOG_FUNC_RETURN(ctx, rv);
}
static int
epass2003_sm_get_wrapped_apdu(struct sc_card *card,
struct sc_apdu *plain, struct sc_apdu **sm_apdu)
{
struct sc_context *ctx = card->ctx;
struct sc_apdu *apdu = NULL;
int rv;
LOG_FUNC_CALLED(ctx);
if (!plain || !sm_apdu)
LOG_FUNC_RETURN(ctx, SC_ERROR_INVALID_ARGUMENTS);
*sm_apdu = NULL;
//construct new SM apdu from original apdu
apdu = calloc(1, sizeof(struct sc_apdu));
if (!apdu) {
rv = SC_ERROR_OUT_OF_MEMORY;
goto err;
}
apdu->data = calloc (1, SC_MAX_EXT_APDU_BUFFER_SIZE);
if (!apdu->data) {
rv = SC_ERROR_OUT_OF_MEMORY;
goto err;
}
apdu->resp = calloc (1, SC_MAX_EXT_APDU_BUFFER_SIZE);
if (!apdu->resp) {
rv = SC_ERROR_OUT_OF_MEMORY;
goto err;
}
apdu->datalen = SC_MAX_EXT_APDU_BUFFER_SIZE;
apdu->resplen = SC_MAX_EXT_APDU_BUFFER_SIZE;
rv = epass2003_sm_wrap_apdu(card, plain, apdu);
if (rv) {
rv = epass2003_sm_free_wrapped_apdu(card, NULL, &apdu);
if (rv < 0)
goto err;
}
*sm_apdu = apdu;
apdu = NULL;
err:
if (apdu) {
free((unsigned char *) apdu->data);
free(apdu->resp);
free(apdu);
apdu = NULL;
}
LOG_FUNC_RETURN(ctx, rv);
}
static int
epass2003_transmit_apdu(struct sc_card *card, struct sc_apdu *apdu)
{
int r;
LOG_FUNC_CALLED(card->ctx);
r = sc_transmit_apdu_t(card, apdu);
LOG_TEST_RET(card->ctx, r, "APDU transmit failed");
return r;
}
static int
get_data(struct sc_card *card, unsigned char type, unsigned char *data, size_t datalen)
{
int r;
struct sc_apdu apdu;
unsigned char resp[SC_MAX_APDU_BUFFER_SIZE] = { 0 };
size_t resplen = SC_MAX_APDU_BUFFER_SIZE;
epass2003_exdata *exdata = NULL;
if (!card->drv_data)
return SC_ERROR_INVALID_ARGUMENTS;
exdata = (epass2003_exdata *)card->drv_data;
LOG_FUNC_CALLED(card->ctx);
sc_format_apdu(card, &apdu, SC_APDU_CASE_2_SHORT, 0xca, 0x01, type);
apdu.resp = resp;
apdu.le = 0;
apdu.resplen = resplen;
if (0x86 == type) {
/* No SM temporarily */
unsigned char tmp_sm = exdata->sm;
exdata->sm = SM_PLAIN;
r = sc_transmit_apdu(card, &apdu);
exdata->sm = tmp_sm;
}
else {
r = sc_transmit_apdu_t(card, &apdu);
}
LOG_TEST_RET(card->ctx, r, "APDU get_data failed");
r = sc_check_sw(card, apdu.sw1, apdu.sw2);
LOG_TEST_RET(card->ctx, r, "get_data failed");
memcpy(data, resp, datalen);
return r;
}
/* card driver functions */
static int epass2003_match_card(struct sc_card *card)
{
int r;
LOG_FUNC_CALLED(card->ctx);
r = _sc_match_atr(card, epass2003_atrs, &card->type);
if (r < 0)
return 0;
return 1;
}
static int
epass2003_init(struct sc_card *card)
{
unsigned int flags;
unsigned int ext_flags;
unsigned char data[SC_MAX_APDU_BUFFER_SIZE] = { 0 };
size_t datalen = SC_MAX_APDU_BUFFER_SIZE;
epass2003_exdata *exdata = NULL;
LOG_FUNC_CALLED(card->ctx);
card->name = "epass2003";
card->cla = 0x00;
exdata = (epass2003_exdata *)calloc(1, sizeof(epass2003_exdata));
if (!exdata)
return SC_ERROR_OUT_OF_MEMORY;
card->drv_data = exdata;
exdata->sm = SM_SCP01;
/* decide FIPS/Non-FIPS mode */
if (SC_SUCCESS != get_data(card, 0x86, data, datalen))
return SC_ERROR_INVALID_CARD;
if (0x01 == data[2])
exdata->smtype = KEY_TYPE_AES;
else
exdata->smtype = KEY_TYPE_DES;
if (0x84 == data[14]) {
if (0x00 == data[16]) {
exdata->sm = SM_PLAIN;
}
}
/* mutual authentication */
card->max_recv_size = 0xD8;
card->max_send_size = 0xE8;
card->sm_ctx.ops.open = epass2003_refresh;
card->sm_ctx.ops.get_sm_apdu = epass2003_sm_get_wrapped_apdu;
card->sm_ctx.ops.free_sm_apdu = epass2003_sm_free_wrapped_apdu;
/* FIXME (VT): rather then set/unset 'g_sm', better to implement filter for APDUs to be wrapped */
epass2003_refresh(card);
card->sm_ctx.sm_mode = SM_MODE_TRANSMIT;
flags = SC_ALGORITHM_ONBOARD_KEY_GEN | SC_ALGORITHM_RSA_RAW | 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);
_sc_card_add_rsa_alg(card, 2048, flags, 0);
//set EC Alg Flags
flags = SC_ALGORITHM_ONBOARD_KEY_GEN|SC_ALGORITHM_ECDSA_HASH_SHA1|SC_ALGORITHM_ECDSA_HASH_SHA256|SC_ALGORITHM_ECDSA_HASH_NONE|SC_ALGORITHM_ECDSA_RAW;
ext_flags = 0;
_sc_card_add_ec_alg(card, 256, flags, ext_flags, NULL);
card->caps = SC_CARD_CAP_RNG | SC_CARD_CAP_APDU_EXT;
LOG_FUNC_RETURN(card->ctx, SC_SUCCESS);
}
static int
epass2003_finish(sc_card_t *card)
{
epass2003_exdata *exdata = (epass2003_exdata *)card->drv_data;
if (exdata)
free(exdata);
return SC_SUCCESS;
}
/* COS implement SFI as lower 5 bits of FID, and not allow same SFI at the
* same DF, so use hook functions to increase/decrease FID by 0x20 */
static int
epass2003_hook_path(struct sc_path *path, int inc)
{
u8 fid_h = path->value[path->len - 2];
u8 fid_l = path->value[path->len - 1];
switch (fid_h) {
case 0x29:
case 0x30:
case 0x31:
case 0x32:
case 0x33:
case 0x34:
if (inc)
fid_l = fid_l * FID_STEP;
else
fid_l = fid_l / FID_STEP;
path->value[path->len - 1] = fid_l;
return 1;
default:
break;
}
return 0;
}
static void
epass2003_hook_file(struct sc_file *file, int inc)
{
int fidl = file->id & 0xff;
int fidh = file->id & 0xff00;
if (epass2003_hook_path(&file->path, inc)) {
if (inc)
file->id = fidh + fidl * FID_STEP;
else
file->id = fidh + fidl / FID_STEP;
}
}
static int
epass2003_select_fid_(struct sc_card *card, sc_path_t * in_path, sc_file_t ** file_out)
{
struct sc_apdu apdu;
u8 buf[SC_MAX_APDU_BUFFER_SIZE] = { 0 };
u8 pathbuf[SC_MAX_PATH_SIZE], *path = pathbuf;
int r, pathlen;
sc_file_t *file = NULL;
epass2003_hook_path(in_path, 1);
memcpy(path, in_path->value, in_path->len);
pathlen = in_path->len;
sc_format_apdu(card, &apdu, SC_APDU_CASE_4_SHORT, 0xA4, 0x00, 0x00);
switch (in_path->type) {
case SC_PATH_TYPE_FILE_ID:
apdu.p1 = 0;
if (pathlen != 2)
return SC_ERROR_INVALID_ARGUMENTS;
break;
default:
LOG_FUNC_RETURN(card->ctx, SC_ERROR_INVALID_ARGUMENTS);
}
apdu.p2 = 0; /* first record, return FCI */
apdu.lc = pathlen;
apdu.data = path;
apdu.datalen = pathlen;
if (file_out != NULL) {
apdu.resp = buf;
apdu.resplen = sizeof(buf);
apdu.le = 0;
}
else {
apdu.cse = (apdu.lc == 0) ? SC_APDU_CASE_1 : SC_APDU_CASE_3_SHORT;
}
if (path[0] == 0x29) { /* TODO:0x29 accords with FID prefix in profile */
/* Not allowed to select private key file, so fake fci. */
/* 62 16 82 02 11 00 83 02 29 00 85 02 08 00 86 08 FF 90 90 90 FF FF FF FF */
apdu.resplen = 0x18;
memcpy(apdu.resp,
"\x6f\x16\x82\x02\x11\x00\x83\x02\x29\x00\x85\x02\x08\x00\x86\x08\xff\x90\x90\x90\xff\xff\xff\xff",
apdu.resplen);
apdu.resp[9] = path[1];
apdu.sw1 = 0x90;
apdu.sw2 = 0x00;
}
else {
r = sc_transmit_apdu_t(card, &apdu);
LOG_TEST_RET(card->ctx, r, "APDU transmit failed");
}
if (file_out == NULL) {
if (apdu.sw1 == 0x61)
LOG_FUNC_RETURN(card->ctx, 0);
LOG_FUNC_RETURN(card->ctx, sc_check_sw(card, apdu.sw1, apdu.sw2));
}
r = sc_check_sw(card, apdu.sw1, apdu.sw2);
if (r)
LOG_FUNC_RETURN(card->ctx, r);
if (apdu.resplen < 2)
LOG_FUNC_RETURN(card->ctx, SC_ERROR_UNKNOWN_DATA_RECEIVED);
switch (apdu.resp[0]) {
case 0x6F:
file = sc_file_new();
if (file == NULL)
LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY);
file->path = *in_path;
if (card->ops->process_fci == NULL) {
sc_file_free(file);
LOG_FUNC_RETURN(card->ctx, SC_ERROR_NOT_SUPPORTED);
}
if ((size_t) apdu.resp[1] + 2 <= apdu.resplen)
card->ops->process_fci(card, file, apdu.resp + 2, apdu.resp[1]);
epass2003_hook_file(file, 0);
*file_out = file;
break;
case 0x00: /* proprietary coding */
LOG_FUNC_RETURN(card->ctx, SC_ERROR_UNKNOWN_DATA_RECEIVED);
break;
default:
LOG_FUNC_RETURN(card->ctx, SC_ERROR_UNKNOWN_DATA_RECEIVED);
}
return 0;
}
static int
epass2003_select_fid(struct sc_card *card, unsigned int id_hi, unsigned int id_lo,
sc_file_t ** file_out)
{
int r;
sc_file_t *file = 0;
sc_path_t path;
memset(&path, 0, sizeof(path));
path.type = SC_PATH_TYPE_FILE_ID;
path.value[0] = id_hi;
path.value[1] = id_lo;
path.len = 2;
r = epass2003_select_fid_(card, &path, &file);
LOG_TEST_RET(card->ctx, r, "APDU transmit failed");
/* update cache */
if (file && file->type == SC_FILE_TYPE_DF) {
card->cache.current_path.type = SC_PATH_TYPE_PATH;
card->cache.current_path.value[0] = 0x3f;
card->cache.current_path.value[1] = 0x00;
if (id_hi == 0x3f && id_lo == 0x00) {
card->cache.current_path.len = 2;
}
else {
card->cache.current_path.len = 4;
card->cache.current_path.value[2] = id_hi;
card->cache.current_path.value[3] = id_lo;
}
}
if (file_out)
*file_out = file;
LOG_FUNC_RETURN(card->ctx, SC_SUCCESS);
}
static int
epass2003_select_aid(struct sc_card *card, const sc_path_t * in_path, sc_file_t ** file_out)
{
int r = 0;
if (card->cache.valid
&& card->cache.current_path.type == SC_PATH_TYPE_DF_NAME
&& card->cache.current_path.len == in_path->len
&& memcmp(card->cache.current_path.value, in_path->value, in_path->len) == 0) {
if (file_out) {
*file_out = sc_file_new();
if (!file_out)
LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY);
}
}
else {
r = iso_ops->select_file(card, in_path, file_out);
LOG_TEST_RET(card->ctx, r, "APDU transmit failed");
/* update cache */
card->cache.current_path.type = SC_PATH_TYPE_DF_NAME;
card->cache.current_path.len = in_path->len;
memcpy(card->cache.current_path.value, in_path->value, in_path->len);
}
if (file_out) {
sc_file_t *file = *file_out;
file->type = SC_FILE_TYPE_DF;
file->ef_structure = SC_FILE_EF_UNKNOWN;
file->path.len = 0;
file->size = 0;
/* AID */
memcpy(file->name, in_path->value, in_path->len);
file->namelen = in_path->len;
file->id = 0x0000;
}
LOG_FUNC_RETURN(card->ctx, r);
}
static int
epass2003_select_path(struct sc_card *card, const u8 pathbuf[16], const size_t len,
sc_file_t ** file_out)
{
u8 n_pathbuf[SC_MAX_PATH_SIZE];
const u8 *path = pathbuf;
size_t pathlen = len;
int bMatch = -1;
unsigned int i;
int r;
if (pathlen % 2 != 0 || pathlen > 6 || pathlen <= 0)
LOG_FUNC_RETURN(card->ctx, SC_ERROR_INVALID_ARGUMENTS);
/* if pathlen == 6 then the first FID must be MF (== 3F00) */
if (pathlen == 6 && (path[0] != 0x3f || path[1] != 0x00))
LOG_FUNC_RETURN(card->ctx, SC_ERROR_INVALID_ARGUMENTS);
/* unify path (the first FID should be MF) */
if (path[0] != 0x3f || path[1] != 0x00) {
n_pathbuf[0] = 0x3f;
n_pathbuf[1] = 0x00;
for (i = 0; i < pathlen; i++)
n_pathbuf[i + 2] = pathbuf[i];
path = n_pathbuf;
pathlen += 2;
}
/* check current working directory */
if (card->cache.valid
&& card->cache.current_path.type == SC_PATH_TYPE_PATH
&& card->cache.current_path.len >= 2
&& card->cache.current_path.len <= pathlen) {
bMatch = 0;
for (i = 0; i < card->cache.current_path.len; i += 2)
if (card->cache.current_path.value[i] == path[i]
&& card->cache.current_path.value[i + 1] == path[i + 1])
bMatch += 2;
}
if (card->cache.valid && bMatch > 2) {
if (pathlen - bMatch == 2) {
/* we are in the right directory */
return epass2003_select_fid(card, path[bMatch], path[bMatch + 1], file_out);
}
else if (pathlen - bMatch > 2) {
/* two more steps to go */
sc_path_t new_path;
/* first step: change directory */
r = epass2003_select_fid(card, path[bMatch], path[bMatch + 1], NULL);
LOG_TEST_RET(card->ctx, r, "SELECT FILE (DF-ID) failed");
new_path.type = SC_PATH_TYPE_PATH;
new_path.len = pathlen - bMatch - 2;
memcpy(new_path.value, &(path[bMatch + 2]), new_path.len);
/* final step: select file */
return epass2003_select_file(card, &new_path, file_out);
}
else { /* if (bMatch - pathlen == 0) */
/* done: we are already in the
* requested directory */
sc_log(card->ctx, "cache hit\n");
/* copy file info (if necessary) */
if (file_out) {
sc_file_t *file = sc_file_new();
if (!file)
LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY);
file->id = (path[pathlen - 2] << 8) + path[pathlen - 1];
file->path = card->cache.current_path;
file->type = SC_FILE_TYPE_DF;
file->ef_structure = SC_FILE_EF_UNKNOWN;
file->size = 0;
file->namelen = 0;
file->magic = SC_FILE_MAGIC;
*file_out = file;
}
/* nothing left to do */
return SC_SUCCESS;
}
}
else {
/* no usable cache */
for (i = 0; i < pathlen - 2; i += 2) {
r = epass2003_select_fid(card, path[i], path[i + 1], NULL);
LOG_TEST_RET(card->ctx, r, "SELECT FILE (DF-ID) failed");
}
return epass2003_select_fid(card, path[pathlen - 2], path[pathlen - 1], file_out);
}
}
static int
epass2003_select_file(struct sc_card *card, const sc_path_t * in_path,
sc_file_t ** file_out)
{
int r;
char pbuf[SC_MAX_PATH_STRING_SIZE];
LOG_FUNC_CALLED(card->ctx);
r = sc_path_print(pbuf, sizeof(pbuf), &card->cache.current_path);
if (r != SC_SUCCESS)
pbuf[0] = '\0';
sc_log(card->ctx,
"current path (%s, %s): %s (len: %"SC_FORMAT_LEN_SIZE_T"u)\n",
card->cache.current_path.type == SC_PATH_TYPE_DF_NAME ?
"aid" : "path",
card->cache.valid ? "valid" : "invalid", pbuf,
card->cache.current_path.len);
switch (in_path->type) {
case SC_PATH_TYPE_FILE_ID:
if (in_path->len != 2)
LOG_FUNC_RETURN(card->ctx, SC_ERROR_INVALID_ARGUMENTS);
return epass2003_select_fid(card, in_path->value[0], in_path->value[1], file_out);
case SC_PATH_TYPE_DF_NAME:
return epass2003_select_aid(card, in_path, file_out);
case SC_PATH_TYPE_PATH:
return epass2003_select_path(card, in_path->value, in_path->len, file_out);
default:
LOG_FUNC_RETURN(card->ctx, SC_ERROR_INVALID_ARGUMENTS);
}
}
static int
epass2003_set_security_env(struct sc_card *card, const sc_security_env_t * env, int se_num)
{
struct sc_apdu apdu;
u8 sbuf[SC_MAX_APDU_BUFFER_SIZE] = { 0 };
u8 *p;
unsigned short fid = 0;
int r, locked = 0;
epass2003_exdata *exdata = NULL;
if (!card->drv_data)
return SC_ERROR_INVALID_ARGUMENTS;
exdata = (epass2003_exdata *)card->drv_data;
sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x22, 0x41, 0);
p = sbuf;
*p++ = 0x80; /* algorithm reference */
*p++ = 0x01;
*p++ = 0x84;
*p++ = 0x81;
*p++ = 0x02;
fid = 0x2900;
fid += (unsigned short)(0x20 * (env->key_ref[0] & 0xff));
*p++ = fid >> 8;
*p++ = fid & 0xff;
r = p - sbuf;
apdu.lc = r;
apdu.datalen = r;
apdu.data = sbuf;
if (env->algorithm == SC_ALGORITHM_EC)
{
apdu.p2 = 0xB6;
exdata->currAlg = SC_ALGORITHM_EC;
if(env->algorithm_flags & SC_ALGORITHM_ECDSA_HASH_SHA1)
{
sbuf[2] = 0x91;
exdata->ecAlgFlags = SC_ALGORITHM_ECDSA_HASH_SHA1;
}
else if (env->algorithm_flags & SC_ALGORITHM_ECDSA_HASH_SHA256)
{
sbuf[2] = 0x92;
exdata->ecAlgFlags = SC_ALGORITHM_ECDSA_HASH_SHA256;
}
else
{
sc_log(card->ctx, "%0x Alg Not Support! ", env->algorithm_flags);
goto err;
}
}
else if(env->algorithm == SC_ALGORITHM_RSA)
{
exdata->currAlg = SC_ALGORITHM_RSA;
apdu.p2 = 0xB8;
sc_log(card->ctx, "setenv RSA Algorithm alg_flags = %0x\n",env->algorithm_flags);
}
else
{
sc_log(card->ctx, "%0x Alg Not Support! ", env->algorithm);
}
if (se_num > 0) {
r = sc_lock(card);
LOG_TEST_RET(card->ctx, r, "sc_lock() failed");
locked = 1;
}
if (apdu.datalen != 0) {
r = sc_transmit_apdu_t(card, &apdu);
if (r) {
sc_log(card->ctx, "%s: APDU transmit failed", sc_strerror(r));
goto err;
}
r = sc_check_sw(card, apdu.sw1, apdu.sw2);
if (r) {
sc_log(card->ctx, "%s: Card returned error", sc_strerror(r));
goto err;
}
}
if (se_num <= 0)
return 0;
sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x22, 0xF2, se_num);
r = sc_transmit_apdu_t(card, &apdu);
sc_unlock(card);
LOG_TEST_RET(card->ctx, r, "APDU transmit failed");
return sc_check_sw(card, apdu.sw1, apdu.sw2);
err:
if (locked)
sc_unlock(card);
return r;
}
static int
epass2003_restore_security_env(struct sc_card *card, int se_num)
{
LOG_FUNC_CALLED(card->ctx);
LOG_FUNC_RETURN(card->ctx, SC_SUCCESS);
}
static int epass2003_decipher(struct sc_card *card, const u8 * data, size_t datalen,
u8 * out, size_t outlen)
{
int r;
struct sc_apdu apdu;
u8 rbuf[SC_MAX_APDU_BUFFER_SIZE] = { 0 };
u8 sbuf[SC_MAX_APDU_BUFFER_SIZE] = { 0 };
epass2003_exdata *exdata = NULL;
LOG_FUNC_CALLED(card->ctx);
if (!card->drv_data)
return SC_ERROR_INVALID_ARGUMENTS;
exdata = (epass2003_exdata *)card->drv_data;
if(exdata->currAlg == SC_ALGORITHM_EC)
{
if(exdata->ecAlgFlags & SC_ALGORITHM_ECDSA_HASH_SHA1)
{
r = hash_data(data, datalen, sbuf, SC_ALGORITHM_ECDSA_HASH_SHA1);
LOG_TEST_RET(card->ctx, r, "hash_data failed");
sc_format_apdu(card, &apdu, SC_APDU_CASE_3,0x2A, 0x9E, 0x9A);
apdu.data = sbuf;
apdu.lc = 0x14;
apdu.datalen = 0x14;
}
else if (exdata->ecAlgFlags & SC_ALGORITHM_ECDSA_HASH_SHA256)
{
r = hash_data(data, datalen, sbuf, SC_ALGORITHM_ECDSA_HASH_SHA256);
LOG_TEST_RET(card->ctx, r, "hash_data failed");
sc_format_apdu(card, &apdu, SC_APDU_CASE_3,0x2A, 0x9E, 0x9A);
apdu.data = sbuf;
apdu.lc = 0x20;
apdu.datalen = 0x20;
}
else
{
return SC_ERROR_NOT_SUPPORTED;
}
apdu.resp = rbuf;
apdu.resplen = sizeof(rbuf);
apdu.le = 0;
r = sc_transmit_apdu_t(card, &apdu);
LOG_TEST_RET(card->ctx, 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);
LOG_FUNC_RETURN(card->ctx, len);
}
LOG_FUNC_RETURN(card->ctx, sc_check_sw(card, apdu.sw1, apdu.sw2));
}
else if(exdata->currAlg == SC_ALGORITHM_RSA)
{
sc_format_apdu(card, &apdu, SC_APDU_CASE_4_EXT, 0x2A, 0x80, 0x86);
apdu.resp = rbuf;
apdu.resplen = sizeof(rbuf);
apdu.le = 0;
memcpy(sbuf, data, datalen);
apdu.data = sbuf;
apdu.lc = datalen;
apdu.datalen = datalen;
}
else
{
sc_format_apdu(card, &apdu, SC_APDU_CASE_4_EXT, 0x2A, 0x80, 0x86);
apdu.resp = rbuf;
apdu.resplen = sizeof(rbuf);
apdu.le = 256;
memcpy(sbuf, data, datalen);
apdu.data = sbuf;
apdu.lc = datalen;
apdu.datalen = datalen;
}
r = sc_transmit_apdu_t(card, &apdu);
LOG_TEST_RET(card->ctx, 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);
LOG_FUNC_RETURN(card->ctx, len);
}
LOG_FUNC_RETURN(card->ctx, sc_check_sw(card, apdu.sw1, apdu.sw2));
}
static int
acl_to_ac_byte(struct sc_card *card, const struct sc_acl_entry *e)
{
if (e == NULL)
return SC_ERROR_OBJECT_NOT_FOUND;
switch (e->method) {
case SC_AC_NONE:
LOG_FUNC_RETURN(card->ctx, EPASS2003_AC_MAC_NOLESS | EPASS2003_AC_EVERYONE);
case SC_AC_NEVER:
LOG_FUNC_RETURN(card->ctx, EPASS2003_AC_MAC_NOLESS | EPASS2003_AC_NOONE);
default:
LOG_FUNC_RETURN(card->ctx, EPASS2003_AC_MAC_NOLESS | EPASS2003_AC_USER);
}
LOG_FUNC_RETURN(card->ctx, SC_ERROR_INCORRECT_PARAMETERS);
}
static int
epass2003_process_fci(struct sc_card *card, sc_file_t * file, const u8 * buf, size_t buflen)
{
sc_context_t *ctx = card->ctx;
size_t taglen, len = buflen;
const u8 *tag = NULL, *p = buf;
sc_log(ctx, "processing FCI bytes");
tag = sc_asn1_find_tag(ctx, p, len, 0x83, &taglen);
if (tag != NULL && taglen == 2) {
file->id = (tag[0] << 8) | tag[1];
sc_log(ctx, " file identifier: 0x%02X%02X", tag[0], tag[1]);
}
tag = sc_asn1_find_tag(ctx, p, len, 0x80, &taglen);
if (tag != NULL && taglen > 0 && taglen < 3) {
file->size = tag[0];
if (taglen == 2)
file->size = (file->size << 8) + tag[1];
sc_log(ctx, " bytes in file: %"SC_FORMAT_LEN_SIZE_T"u",
file->size);
}
if (tag == NULL) {
tag = sc_asn1_find_tag(ctx, p, len, 0x81, &taglen);
if (tag != NULL && taglen >= 2) {
int bytes = (tag[0] << 8) + tag[1];
sc_log(ctx, " bytes in file: %d", bytes);
file->size = bytes;
}
}
tag = sc_asn1_find_tag(ctx, p, len, 0x82, &taglen);
if (tag != NULL) {
if (taglen > 0) {
unsigned char byte = tag[0];
const char *type;
if (byte == 0x38) {
type = "DF";
file->type = SC_FILE_TYPE_DF;
}
else if (0x01 <= byte && byte <= 0x07) {
type = "working EF";
file->type = SC_FILE_TYPE_WORKING_EF;
switch (byte) {
case 0x01:
file->ef_structure = SC_FILE_EF_TRANSPARENT;
break;
case 0x02:
file->ef_structure = SC_FILE_EF_LINEAR_FIXED;
break;
case 0x04:
file->ef_structure = SC_FILE_EF_LINEAR_FIXED;
break;
case 0x03:
case 0x05:
case 0x06:
case 0x07:
break;
default:
break;
}
}
else if (0x10 == byte) {
type = "BSO";
file->type = SC_FILE_TYPE_BSO;
}
else if (0x11 <= byte) {
type = "internal EF";
file->type = SC_FILE_TYPE_INTERNAL_EF;
switch (byte) {
case 0x11:
break;
case 0x12:
break;
default:
break;
}
}
else {
type = "unknown";
file->type = SC_FILE_TYPE_INTERNAL_EF;
}
sc_log(ctx, "type %s, EF structure %d", type, byte);
}
}
tag = sc_asn1_find_tag(ctx, p, len, 0x84, &taglen);
if (tag != NULL && taglen > 0 && taglen <= 16) {
memcpy(file->name, tag, taglen);
file->namelen = taglen;
sc_log_hex(ctx, "File name", file->name, file->namelen);
if (!file->type)
file->type = SC_FILE_TYPE_DF;
}
tag = sc_asn1_find_tag(ctx, p, len, 0x85, &taglen);
if (tag != NULL && taglen)
sc_file_set_prop_attr(file, tag, taglen);
else
file->prop_attr_len = 0;
tag = sc_asn1_find_tag(ctx, p, len, 0xA5, &taglen);
if (tag != NULL && taglen)
sc_file_set_prop_attr(file, tag, taglen);
tag = sc_asn1_find_tag(ctx, p, len, 0x86, &taglen);
if (tag != NULL && taglen)
sc_file_set_sec_attr(file, tag, taglen);
tag = sc_asn1_find_tag(ctx, p, len, 0x8A, &taglen);
if (tag != NULL && taglen == 1) {
if (tag[0] == 0x01)
file->status = SC_FILE_STATUS_CREATION;
else if (tag[0] == 0x07 || tag[0] == 0x05)
file->status = SC_FILE_STATUS_ACTIVATED;
else if (tag[0] == 0x06 || tag[0] == 0x04)
file->status = SC_FILE_STATUS_INVALIDATED;
}
file->magic = SC_FILE_MAGIC;
return 0;
}
static int
epass2003_construct_fci(struct sc_card *card, const sc_file_t * file,
u8 * out, size_t * outlen)
{
u8 *p = out;
u8 buf[64];
unsigned char ops[8] = { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF };
int rv;
unsigned ii;
if (*outlen < 2)
return SC_ERROR_BUFFER_TOO_SMALL;
*p++ = 0x62;
p++;
if (file->type == SC_FILE_TYPE_WORKING_EF) {
if (file->ef_structure == SC_FILE_EF_TRANSPARENT) {
buf[0] = (file->size >> 8) & 0xFF;
buf[1] = file->size & 0xFF;
sc_asn1_put_tag(0x80, buf, 2, p, *outlen - (p - out), &p);
}
}
if (file->type == SC_FILE_TYPE_DF) {
buf[0] = 0x38;
buf[1] = 0x00;
sc_asn1_put_tag(0x82, buf, 2, p, *outlen - (p - out), &p);
}
else if (file->type == SC_FILE_TYPE_WORKING_EF) {
buf[0] = file->ef_structure & 7;
if (file->ef_structure == SC_FILE_EF_TRANSPARENT) {
buf[1] = 0x00;
sc_asn1_put_tag(0x82, buf, 2, p, *outlen - (p - out), &p);
}
else if (file->ef_structure == SC_FILE_EF_LINEAR_FIXED
|| file->ef_structure == SC_FILE_EF_LINEAR_VARIABLE) {
buf[1] = 0x00;
buf[2] = 0x00;
buf[3] = 0x40; /* record length */
buf[4] = 0x00; /* record count */
sc_asn1_put_tag(0x82, buf, 5, p, *outlen - (p - out), &p);
}
else {
return SC_ERROR_NOT_SUPPORTED;
}
}
else if (file->type == SC_FILE_TYPE_INTERNAL_EF) {
if (file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_RSA_CRT ||
file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_EC_CRT) {
buf[0] = 0x11;
buf[1] = 0x00;
}
else if (file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_RSA_PUBLIC ||
file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_EC_PUBLIC) {
buf[0] = 0x12;
buf[1] = 0x00;
}
else {
return SC_ERROR_NOT_SUPPORTED;
}
sc_asn1_put_tag(0x82, buf, 2, p, *outlen - (p - out), &p);
}
else if (file->type == SC_FILE_TYPE_BSO) {
buf[0] = 0x10;
buf[1] = 0x00;
sc_asn1_put_tag(0x82, buf, 2, p, *outlen - (p - out), &p);
}
buf[0] = (file->id >> 8) & 0xFF;
buf[1] = file->id & 0xFF;
sc_asn1_put_tag(0x83, buf, 2, p, *outlen - (p - out), &p);
if (file->type == SC_FILE_TYPE_DF) {
if (file->namelen != 0) {
sc_asn1_put_tag(0x84, file->name, file->namelen, p, *outlen - (p - out), &p);
}
else {
return SC_ERROR_INVALID_ARGUMENTS;
}
}
if (file->type == SC_FILE_TYPE_DF) {
unsigned char data[2] = {0x00, 0x7F};
/* 127 files at most */
sc_asn1_put_tag(0x85, data, sizeof(data), p, *outlen - (p - out), &p);
}
else if (file->type == SC_FILE_TYPE_BSO) {
buf[0] = file->size & 0xff;
sc_asn1_put_tag(0x85, buf, 1, p, *outlen - (p - out), &p);
}
else if (file->type == SC_FILE_TYPE_INTERNAL_EF) {
if (file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_RSA_CRT ||
file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_RSA_PUBLIC||
file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_EC_CRT||
file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_EC_PUBLIC) {
buf[0] = (file->size >> 8) & 0xFF;
buf[1] = file->size & 0xFF;
sc_asn1_put_tag(0x85, buf, 2, p, *outlen - (p - out), &p);
}
}
if (file->sec_attr_len) {
memcpy(buf, file->sec_attr, file->sec_attr_len);
sc_asn1_put_tag(0x86, buf, file->sec_attr_len, p, *outlen - (p - out), &p);
}
else {
sc_log(card->ctx, "SC_FILE_ACL");
if (file->type == SC_FILE_TYPE_DF) {
ops[0] = SC_AC_OP_LIST_FILES;
ops[1] = SC_AC_OP_CREATE;
ops[3] = SC_AC_OP_DELETE;
}
else if (file->type == SC_FILE_TYPE_WORKING_EF) {
if (file->ef_structure == SC_FILE_EF_TRANSPARENT) {
ops[0] = SC_AC_OP_READ;
ops[1] = SC_AC_OP_UPDATE;
ops[3] = SC_AC_OP_DELETE;
}
else if (file->ef_structure == SC_FILE_EF_LINEAR_FIXED
|| file->ef_structure == SC_FILE_EF_LINEAR_VARIABLE) {
ops[0] = SC_AC_OP_READ;
ops[1] = SC_AC_OP_UPDATE;
ops[2] = SC_AC_OP_WRITE;
ops[3] = SC_AC_OP_DELETE;
}
else {
return SC_ERROR_NOT_SUPPORTED;
}
}
else if (file->type == SC_FILE_TYPE_BSO) {
ops[0] = SC_AC_OP_UPDATE;
ops[3] = SC_AC_OP_DELETE;
}
else if (file->type == SC_FILE_TYPE_INTERNAL_EF) {
if (file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_RSA_CRT ||
file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_EC_CRT) {
ops[1] = SC_AC_OP_UPDATE;
ops[2] = SC_AC_OP_CRYPTO;
ops[3] = SC_AC_OP_DELETE;
}
else if (file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_RSA_PUBLIC||
file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_EC_PUBLIC) {
ops[0] = SC_AC_OP_READ;
ops[1] = SC_AC_OP_UPDATE;
ops[2] = SC_AC_OP_CRYPTO;
ops[3] = SC_AC_OP_DELETE;
}
}
else {
return SC_ERROR_NOT_SUPPORTED;
}
for (ii = 0; ii < sizeof(ops); ii++) {
const struct sc_acl_entry *entry;
buf[ii] = 0xFF;
if (ops[ii] == 0xFF)
continue;
entry = sc_file_get_acl_entry(file, ops[ii]);
rv = acl_to_ac_byte(card, entry);
LOG_TEST_RET(card->ctx, rv, "Invalid ACL");
buf[ii] = rv;
}
sc_asn1_put_tag(0x86, buf, sizeof(ops), p, *outlen - (p - out), &p);
if(file->size == 256)
{
out[4]= 0x13;
}
}
/* VT ??? */
if (file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_RSA_PUBLIC||
file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_EC_PUBLIC) {
unsigned char data[2] = {0x00, 0x66};
sc_asn1_put_tag(0x87, data, sizeof(data), p, *outlen - (p - out), &p);
if(file->size == 256)
{
out[4]= 0x14;
}
}
out[1] = p - out - 2;
*outlen = p - out;
return 0;
}
static int
epass2003_create_file(struct sc_card *card, sc_file_t * file)
{
int r;
size_t len;
u8 sbuf[SC_MAX_APDU_BUFFER_SIZE] = { 0 };
struct sc_apdu apdu;
len = SC_MAX_APDU_BUFFER_SIZE;
epass2003_hook_file(file, 1);
if (card->ops->construct_fci == NULL)
LOG_FUNC_RETURN(card->ctx, SC_ERROR_NOT_SUPPORTED);
r = epass2003_construct_fci(card, file, sbuf, &len);
LOG_TEST_RET(card->ctx, r, "construct_fci() failed");
sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0xE0, 0x00, 0x00);
apdu.lc = len;
apdu.datalen = len;
apdu.data = sbuf;
r = sc_transmit_apdu_t(card, &apdu);
LOG_TEST_RET(card->ctx, r, "APDU transmit failed");
r = sc_check_sw(card, apdu.sw1, apdu.sw2);
LOG_TEST_RET(card->ctx, r, "APDU sw1/2 wrong");
epass2003_hook_file(file, 0);
return r;
}
static int
epass2003_delete_file(struct sc_card *card, const sc_path_t * path)
{
int r;
u8 sbuf[2];
struct sc_apdu apdu;
LOG_FUNC_CALLED(card->ctx);
r = sc_select_file(card, path, NULL);
epass2003_hook_path((struct sc_path *)path, 1);
if (r == SC_SUCCESS) {
sbuf[0] = path->value[path->len - 2];
sbuf[1] = path->value[path->len - 1];
sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0xE4, 0x00, 0x00);
apdu.lc = 2;
apdu.datalen = 2;
apdu.data = sbuf;
}
else {
LOG_FUNC_RETURN(card->ctx, SC_ERROR_INVALID_ARGUMENTS);
}
r = sc_transmit_apdu_t(card, &apdu);
LOG_TEST_RET(card->ctx, r, "APDU transmit failed");
r = sc_check_sw(card, apdu.sw1, apdu.sw2);
LOG_TEST_RET(card->ctx, r, "Delete file failed");
LOG_FUNC_RETURN(card->ctx, r);
}
static int
epass2003_list_files(struct sc_card *card, unsigned char *buf, size_t buflen)
{
struct sc_apdu apdu;
unsigned char rbuf[SC_MAX_APDU_BUFFER_SIZE] = { 0 };
int r;
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
sc_format_apdu(card, &apdu, SC_APDU_CASE_1, 0x34, 0x00, 0x00);
apdu.cla = 0x80;
apdu.le = 0;
apdu.resplen = sizeof(rbuf);
apdu.resp = rbuf;
r = sc_transmit_apdu_t(card, &apdu);
LOG_TEST_RET(card->ctx, r, "APDU transmit failed");
r = sc_check_sw(card, apdu.sw1, apdu.sw2);
LOG_TEST_RET(card->ctx, r, "Card returned error");
if (apdu.resplen == 0x100 && rbuf[0] == 0 && rbuf[1] == 0)
LOG_FUNC_RETURN(card->ctx, 0);
buflen = buflen < apdu.resplen ? buflen : apdu.resplen;
memcpy(buf, rbuf, buflen);
LOG_FUNC_RETURN(card->ctx, buflen);
}
static int
internal_write_rsa_key_factor(struct sc_card *card, unsigned short fid, u8 factor,
sc_pkcs15_bignum_t data)
{
int r;
struct sc_apdu apdu;
u8 sbuff[SC_MAX_EXT_APDU_BUFFER_SIZE] = { 0 };
LOG_FUNC_CALLED(card->ctx);
sbuff[0] = ((fid & 0xff00) >> 8);
sbuff[1] = (fid & 0x00ff);
memcpy(&sbuff[2], data.data, data.len);
// sc_mem_reverse(&sbuff[2], data.len);
sc_format_apdu(card, &apdu, SC_APDU_CASE_3, 0xe7, factor, 0x00);
apdu.cla = 0x80;
apdu.lc = apdu.datalen = 2 + data.len;
apdu.data = sbuff;
r = sc_transmit_apdu_t(card, &apdu);
LOG_TEST_RET(card->ctx, r, "APDU transmit failed");
r = sc_check_sw(card, apdu.sw1, apdu.sw2);
LOG_TEST_RET(card->ctx, r, "Write rsa key factor failed");
LOG_FUNC_RETURN(card->ctx, SC_SUCCESS);
}
static int
internal_write_rsa_key(struct sc_card *card, unsigned short fid, struct sc_pkcs15_prkey_rsa *rsa)
{
int r;
LOG_FUNC_CALLED(card->ctx);
r = internal_write_rsa_key_factor(card, fid, 0x02, rsa->modulus);
LOG_TEST_RET(card->ctx, r, "write n failed");
r = internal_write_rsa_key_factor(card, fid, 0x03, rsa->d);
LOG_TEST_RET(card->ctx, r, "write d failed");
LOG_FUNC_RETURN(card->ctx, SC_SUCCESS);
}
static int
hash_data(const unsigned char *data, size_t datalen, unsigned char *hash, unsigned int mechanismType)
{
if ((NULL == data) || (NULL == hash))
return SC_ERROR_INVALID_ARGUMENTS;
if(mechanismType & SC_ALGORITHM_ECDSA_HASH_SHA1)
{
unsigned char data_hash[24] = { 0 };
size_t len = 0;
sha1_digest(data, datalen, data_hash);
len = REVERSE_ORDER4(datalen);
memcpy(&data_hash[20], &len, 4);
memcpy(hash, data_hash, 24);
}
else if(mechanismType & SC_ALGORITHM_ECDSA_HASH_SHA256)
{
unsigned char data_hash[36] = { 0 };
size_t len = 0;
sha256_digest(data, datalen, data_hash);
len = REVERSE_ORDER4(datalen);
memcpy(&data_hash[32], &len, 4);
memcpy(hash, data_hash, 36);
}
else
{
return SC_ERROR_NOT_SUPPORTED;
}
return SC_SUCCESS;
}
static int
install_secret_key(struct sc_card *card, unsigned char ktype, unsigned char kid,
unsigned char useac, unsigned char modifyac, unsigned char EC,
unsigned char *data, unsigned long dataLen)
{
int r;
struct sc_apdu apdu;
unsigned char isapp = 0x00; /* appendable */
unsigned char tmp_data[256] = { 0 };
tmp_data[0] = ktype;
tmp_data[1] = kid;
tmp_data[2] = useac;
tmp_data[3] = modifyac;
tmp_data[8] = 0xFF;
if (0x04 == ktype || 0x06 == ktype) {
tmp_data[4] = EPASS2003_AC_MAC_NOLESS | EPASS2003_AC_SO;
tmp_data[5] = EPASS2003_AC_MAC_NOLESS | EPASS2003_AC_SO;
tmp_data[7] = (kid == PIN_ID[0] ? EPASS2003_AC_USER : EPASS2003_AC_SO);
tmp_data[9] = (EC << 4) | EC;
}
memcpy(&tmp_data[10], data, dataLen);
sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0xe3, isapp, 0x00);
apdu.cla = 0x80;
apdu.lc = apdu.datalen = 10 + dataLen;
apdu.data = tmp_data;
r = sc_transmit_apdu_t(card, &apdu);
LOG_TEST_RET(card->ctx, r, "APDU install_secret_key failed");
r = sc_check_sw(card, apdu.sw1, apdu.sw2);
LOG_TEST_RET(card->ctx, r, "install_secret_key failed");
return r;
}
static int
internal_install_pre(struct sc_card *card)
{
int r;
/* init key for enc */
r = install_secret_key(card, 0x01, 0x00,
EPASS2003_AC_MAC_NOLESS | EPASS2003_AC_EVERYONE,
EPASS2003_AC_MAC_NOLESS | EPASS2003_AC_EVERYONE,
0, g_init_key_enc, 16);
LOG_TEST_RET(card->ctx, r, "Install init key failed");
/* init key for mac */
r = install_secret_key(card, 0x02, 0x00,
EPASS2003_AC_MAC_NOLESS | EPASS2003_AC_EVERYONE,
EPASS2003_AC_MAC_NOLESS | EPASS2003_AC_EVERYONE,
0, g_init_key_mac, 16);
LOG_TEST_RET(card->ctx, r, "Install init key failed");
return r;
}
/* use external auth secret as pin */
static int
internal_install_pin(struct sc_card *card, sc_epass2003_wkey_data * pin)
{
int r;
unsigned char hash[HASH_LEN] = { 0 };
r = hash_data(pin->key_data.es_secret.key_val, pin->key_data.es_secret.key_len, hash, SC_ALGORITHM_ECDSA_HASH_SHA1);
LOG_TEST_RET(card->ctx, r, "hash data failed");
r = install_secret_key(card, 0x04, pin->key_data.es_secret.kid,
pin->key_data.es_secret.ac[0],
pin->key_data.es_secret.ac[1],
pin->key_data.es_secret.EC, hash, HASH_LEN);
LOG_TEST_RET(card->ctx, r, "Install failed");
return r;
}
static int
epass2003_write_key(struct sc_card *card, sc_epass2003_wkey_data * data)
{
LOG_FUNC_CALLED(card->ctx);
if (data->type & SC_EPASS2003_KEY) {
if (data->type == SC_EPASS2003_KEY_RSA)
return internal_write_rsa_key(card, data->key_data.es_key.fid,
data->key_data.es_key.rsa);
else
LOG_FUNC_RETURN(card->ctx, SC_ERROR_NOT_SUPPORTED);
} else if (data->type & SC_EPASS2003_SECRET) {
if (data->type == SC_EPASS2003_SECRET_PRE)
return internal_install_pre(card);
else if (data->type == SC_EPASS2003_SECRET_PIN)
return internal_install_pin(card, data);
else
LOG_FUNC_RETURN(card->ctx, SC_ERROR_NOT_SUPPORTED);
}
else {
LOG_FUNC_RETURN(card->ctx, SC_ERROR_NOT_SUPPORTED);
}
LOG_FUNC_RETURN(card->ctx, SC_SUCCESS);
}
static int
epass2003_gen_key(struct sc_card *card, sc_epass2003_gen_key_data * data)
{
int r;
size_t len = data->key_length;
struct sc_apdu apdu;
u8 rbuf[SC_MAX_EXT_APDU_BUFFER_SIZE] = { 0 };
u8 sbuf[SC_MAX_EXT_APDU_BUFFER_SIZE] = { 0 };
LOG_FUNC_CALLED(card->ctx);
if(len == 256)
{
sbuf[0] = 0x02;
}
else
{
sbuf[0] = 0x01;
}
sbuf[1] = (u8) ((len >> 8) & 0xff);
sbuf[2] = (u8) (len & 0xff);
sbuf[3] = (u8) ((data->prkey_id >> 8) & 0xFF);
sbuf[4] = (u8) ((data->prkey_id) & 0xFF);
sbuf[5] = (u8) ((data->pukey_id >> 8) & 0xFF);
sbuf[6] = (u8) ((data->pukey_id) & 0xFF);
/* generate key */
sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x46, 0x00, 0x00);
apdu.lc = apdu.datalen = 7;
apdu.data = sbuf;
r = sc_transmit_apdu_t(card, &apdu);
LOG_TEST_RET(card->ctx, r, "APDU transmit failed");
r = sc_check_sw(card, apdu.sw1, apdu.sw2);
LOG_TEST_RET(card->ctx, r, "generate keypair failed");
/* read public key */
sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0xb4, 0x02, 0x00);
if(len == 256)
{
apdu.p1 = 0x00;
}
apdu.cla = 0x80;
apdu.lc = apdu.datalen = 2;
apdu.data = &sbuf[5];
apdu.resp = rbuf;
apdu.resplen = sizeof(rbuf);
apdu.le = 0x00;
r = sc_transmit_apdu_t(card, &apdu);
LOG_TEST_RET(card->ctx, r, "APDU transmit failed");
r = sc_check_sw(card, apdu.sw1, apdu.sw2);
LOG_TEST_RET(card->ctx, r, "get pukey failed");
if (len < apdu.resplen)
LOG_FUNC_RETURN(card->ctx, SC_ERROR_INVALID_ARGUMENTS);
data->modulus = (u8 *) malloc(len);
if (!data->modulus)
LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY);
memcpy(data->modulus, rbuf, len);
LOG_FUNC_RETURN(card->ctx, SC_SUCCESS);
}
static int
epass2003_erase_card(struct sc_card *card)
{
int r;
LOG_FUNC_CALLED(card->ctx);
sc_invalidate_cache(card);
r = sc_delete_file(card, sc_get_mf_path());
LOG_TEST_RET(card->ctx, r, "delete MF failed");
LOG_FUNC_RETURN(card->ctx, r);
}
static int
epass2003_get_serialnr(struct sc_card *card, sc_serial_number_t * serial)
{
u8 rbuf[8];
size_t rbuf_len = sizeof(rbuf);
LOG_FUNC_CALLED(card->ctx);
if (SC_SUCCESS != get_data(card, 0x80, rbuf, rbuf_len))
return SC_ERROR_CARD_CMD_FAILED;
card->serialnr.len = serial->len = 8;
memcpy(card->serialnr.value, rbuf, 8);
memcpy(serial->value, rbuf, 8);
LOG_FUNC_RETURN(card->ctx, SC_SUCCESS);
}
static int
epass2003_card_ctl(struct sc_card *card, unsigned long cmd, void *ptr)
{
LOG_FUNC_CALLED(card->ctx);
sc_log(card->ctx, "cmd is %0lx", cmd);
switch (cmd) {
case SC_CARDCTL_ENTERSAFE_WRITE_KEY:
return epass2003_write_key(card, (sc_epass2003_wkey_data *) ptr);
case SC_CARDCTL_ENTERSAFE_GENERATE_KEY:
return epass2003_gen_key(card, (sc_epass2003_gen_key_data *) ptr);
case SC_CARDCTL_ERASE_CARD:
return epass2003_erase_card(card);
case SC_CARDCTL_GET_SERIALNR:
return epass2003_get_serialnr(card, (sc_serial_number_t *) ptr);
default:
return SC_ERROR_NOT_SUPPORTED;
}
}
static void
internal_sanitize_pin_info(struct sc_pin_cmd_pin *pin, unsigned int num)
{
pin->encoding = SC_PIN_ENCODING_ASCII;
pin->min_length = 4;
pin->max_length = 16;
pin->pad_length = 16;
pin->offset = 5 + num * 16;
pin->pad_char = 0x00;
}
static int
get_external_key_maxtries(struct sc_card *card, unsigned char *maxtries)
{
unsigned char maxcounter[2] = { 0 };
static const sc_path_t file_path = {
{0x3f, 0x00, 0x50, 0x15, 0x9f, 0x00, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, 6,
0,
0,
SC_PATH_TYPE_PATH,
{{0}, 0}
};
int ret;
ret = sc_select_file(card, &file_path, NULL);
LOG_TEST_RET(card->ctx, ret, "select max counter file failed");
ret = sc_read_binary(card, 0, maxcounter, 2, 0);
LOG_TEST_RET(card->ctx, ret, "read max counter file failed");
*maxtries = maxcounter[0];
return SC_SUCCESS;
}
static int
get_external_key_retries(struct sc_card *card, unsigned char kid, unsigned char *retries)
{
int r;
struct sc_apdu apdu;
unsigned char random[16] = { 0 };
r = sc_get_challenge(card, random, 8);
LOG_TEST_RET(card->ctx, r, "get challenge get_external_key_retries failed");
sc_format_apdu(card, &apdu, SC_APDU_CASE_1, 0x82, 0x01, 0x80 | kid);
apdu.resp = NULL;
apdu.resplen = 0;
r = sc_transmit_apdu_t(card, &apdu);
LOG_TEST_RET(card->ctx, r, "APDU get_external_key_retries failed");
if (retries && ((0x63 == (apdu.sw1 & 0xff)) && (0xC0 == (apdu.sw2 & 0xf0)))) {
*retries = (apdu.sw2 & 0x0f);
r = SC_SUCCESS;
}
else {
LOG_TEST_RET(card->ctx, r, "get_external_key_retries failed");
r = SC_ERROR_CARD_CMD_FAILED;
}
return r;
}
static int
epass2003_get_challenge(sc_card_t *card, u8 *rnd, size_t len)
{
u8 rbuf[16];
size_t out_len;
int r;
LOG_FUNC_CALLED(card->ctx);
r = iso_ops->get_challenge(card, rbuf, sizeof rbuf);
LOG_TEST_RET(card->ctx, r, "GET CHALLENGE cmd failed");
if (len < (size_t) r) {
out_len = len;
} else {
out_len = (size_t) r;
}
memcpy(rnd, rbuf, out_len);
LOG_FUNC_RETURN(card->ctx, (int) out_len);
}
static int
external_key_auth(struct sc_card *card, unsigned char kid,
unsigned char *data, size_t datalen)
{
int r;
struct sc_apdu apdu;
unsigned char random[16] = { 0 };
unsigned char tmp_data[16] = { 0 };
unsigned char hash[HASH_LEN] = { 0 };
unsigned char iv[16] = { 0 };
r = sc_get_challenge(card, random, 8);
LOG_TEST_RET(card->ctx, r, "get challenge external_key_auth failed");
r = hash_data(data, datalen, hash, SC_ALGORITHM_ECDSA_HASH_SHA1);
LOG_TEST_RET(card->ctx, r, "hash data failed");
des3_encrypt_cbc(hash, HASH_LEN, iv, random, 8, tmp_data);
sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x82, 0x01, 0x80 | kid);
apdu.lc = apdu.datalen = 8;
apdu.data = tmp_data;
r = sc_transmit_apdu_t(card, &apdu);
LOG_TEST_RET(card->ctx, r, "APDU external_key_auth failed");
r = sc_check_sw(card, apdu.sw1, apdu.sw2);
LOG_TEST_RET(card->ctx, r, "external_key_auth failed");
return r;
}
static int
update_secret_key(struct sc_card *card, unsigned char ktype, unsigned char kid,
const unsigned char *data, unsigned long datalen)
{
int r;
struct sc_apdu apdu;
unsigned char hash[HASH_LEN] = { 0 };
unsigned char tmp_data[256] = { 0 };
unsigned char maxtries = 0;
r = hash_data(data, datalen, hash, SC_ALGORITHM_ECDSA_HASH_SHA1);
LOG_TEST_RET(card->ctx, r, "hash data failed");
r = get_external_key_maxtries(card, &maxtries);
LOG_TEST_RET(card->ctx, r, "get max counter failed");
tmp_data[0] = (maxtries << 4) | maxtries;
memcpy(&tmp_data[1], hash, HASH_LEN);
sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0xe5, ktype, kid);
apdu.cla = 0x80;
apdu.lc = apdu.datalen = 1 + HASH_LEN;
apdu.data = tmp_data;
r = sc_transmit_apdu_t(card, &apdu);
LOG_TEST_RET(card->ctx, r, "APDU update_secret_key failed");
r = sc_check_sw(card, apdu.sw1, apdu.sw2);
LOG_TEST_RET(card->ctx, r, "update_secret_key failed");
return r;
}
/* use external auth secret as pin */
static int
epass2003_pin_cmd(struct sc_card *card, struct sc_pin_cmd_data *data, int *tries_left)
{
int r;
u8 kid;
u8 retries = 0;
u8 pin_low = 3;
unsigned char maxtries = 0;
LOG_FUNC_CALLED(card->ctx);
internal_sanitize_pin_info(&data->pin1, 0);
internal_sanitize_pin_info(&data->pin2, 1);
data->flags |= SC_PIN_CMD_NEED_PADDING;
kid = data->pin_reference;
/* get pin retries */
if (data->cmd == SC_PIN_CMD_GET_INFO) {
r = get_external_key_retries(card, 0x80 | kid, &retries);
if (r == SC_SUCCESS) {
data->pin1.tries_left = retries;
if (tries_left)
*tries_left = retries;
r = get_external_key_maxtries(card, &maxtries);
LOG_TEST_RET(card->ctx, r, "get max counter failed");
data->pin1.max_tries = maxtries;
}
//remove below code, because the old implement only return PIN retries, now modify the code and return PIN status
// return r;
}
else if (data->cmd == SC_PIN_CMD_UNBLOCK) { /* verify */
r = external_key_auth(card, (kid + 1), (unsigned char *)data->pin1.data,
data->pin1.len);
LOG_TEST_RET(card->ctx, r, "verify pin failed");
}
else if (data->cmd == SC_PIN_CMD_CHANGE || data->cmd == SC_PIN_CMD_UNBLOCK) { /* change */
r = update_secret_key(card, 0x04, kid, data->pin2.data,
(unsigned long)data->pin2.len);
LOG_TEST_RET(card->ctx, r, "verify pin failed");
}
else {
r = external_key_auth(card, kid, (unsigned char *)data->pin1.data,
data->pin1.len);
get_external_key_retries(card, 0x80 | kid, &retries);
if (retries < pin_low)
sc_log(card->ctx, "Verification failed (remaining tries: %d)", retries);
}
LOG_TEST_RET(card->ctx, r, "verify pin failed");
if (r == SC_SUCCESS)
{
data->pin1.logged_in = SC_PIN_STATE_LOGGED_IN;
}
return r;
}
static struct sc_card_driver *sc_get_driver(void)
{
struct sc_card_driver *iso_drv = sc_get_iso7816_driver();
if (iso_ops == NULL)
iso_ops = iso_drv->ops;
epass2003_ops = *iso_ops;
epass2003_ops.match_card = epass2003_match_card;
epass2003_ops.init = epass2003_init;
epass2003_ops.finish = epass2003_finish;
epass2003_ops.write_binary = NULL;
epass2003_ops.write_record = NULL;
epass2003_ops.select_file = epass2003_select_file;
epass2003_ops.get_response = NULL;
epass2003_ops.restore_security_env = epass2003_restore_security_env;
epass2003_ops.set_security_env = epass2003_set_security_env;
epass2003_ops.decipher = epass2003_decipher;
epass2003_ops.compute_signature = epass2003_decipher;
epass2003_ops.create_file = epass2003_create_file;
epass2003_ops.delete_file = epass2003_delete_file;
epass2003_ops.list_files = epass2003_list_files;
epass2003_ops.card_ctl = epass2003_card_ctl;
epass2003_ops.process_fci = epass2003_process_fci;
epass2003_ops.construct_fci = epass2003_construct_fci;
epass2003_ops.pin_cmd = epass2003_pin_cmd;
epass2003_ops.check_sw = epass2003_check_sw;
epass2003_ops.get_challenge = epass2003_get_challenge;
return &epass2003_drv;
}
struct sc_card_driver *sc_get_epass2003_driver(void)
{
return sc_get_driver();
}
#endif /* #ifdef ENABLE_OPENSSL */
#endif /* #ifdef ENABLE_SM */
| ./CrossVul/dataset_final_sorted/CWE-125/c/good_351_6 |
crossvul-cpp_data_bad_2641_0 | /*
* Copyright (c) 1988, 1989, 1990, 1991, 1993, 1994, 1995, 1996
* The Regents of the University of California. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that: (1) source code distributions
* retain the above copyright notice and this paragraph in its entirety, (2)
* distributions including binary code include the above copyright notice and
* this paragraph in its entirety in the documentation or other materials
* provided with the distribution, and (3) all advertising materials mentioning
* features or use of this software display the following acknowledgement:
* ``This product includes software developed by the University of California,
* Lawrence Berkeley Laboratory and its contributors.'' Neither the name of
* the University nor the names of its contributors may be used to endorse
* or promote products derived from this software without specific prior
* written permission.
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
/* \summary: Internet Control Message Protocol (ICMP) printer */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <netdissect-stdinc.h>
#include <stdio.h>
#include <string.h>
#include "netdissect.h"
#include "addrtoname.h"
#include "extract.h"
#include "ip.h"
#include "udp.h"
#include "ipproto.h"
#include "mpls.h"
/*
* Interface Control Message Protocol Definitions.
* Per RFC 792, September 1981.
*/
/*
* Structure of an icmp header.
*/
struct icmp {
uint8_t icmp_type; /* type of message, see below */
uint8_t icmp_code; /* type sub code */
uint16_t icmp_cksum; /* ones complement cksum of struct */
union {
uint8_t ih_pptr; /* ICMP_PARAMPROB */
struct in_addr ih_gwaddr; /* ICMP_REDIRECT */
struct ih_idseq {
uint16_t icd_id;
uint16_t icd_seq;
} ih_idseq;
uint32_t ih_void;
} icmp_hun;
#define icmp_pptr icmp_hun.ih_pptr
#define icmp_gwaddr icmp_hun.ih_gwaddr
#define icmp_id icmp_hun.ih_idseq.icd_id
#define icmp_seq icmp_hun.ih_idseq.icd_seq
#define icmp_void icmp_hun.ih_void
union {
struct id_ts {
uint32_t its_otime;
uint32_t its_rtime;
uint32_t its_ttime;
} id_ts;
struct id_ip {
struct ip idi_ip;
/* options and then 64 bits of data */
} id_ip;
uint32_t id_mask;
uint8_t id_data[1];
} icmp_dun;
#define icmp_otime icmp_dun.id_ts.its_otime
#define icmp_rtime icmp_dun.id_ts.its_rtime
#define icmp_ttime icmp_dun.id_ts.its_ttime
#define icmp_ip icmp_dun.id_ip.idi_ip
#define icmp_mask icmp_dun.id_mask
#define icmp_data icmp_dun.id_data
};
#define ICMP_MPLS_EXT_EXTRACT_VERSION(x) (((x)&0xf0)>>4)
#define ICMP_MPLS_EXT_VERSION 2
/*
* Lower bounds on packet lengths for various types.
* For the error advice packets must first insure that the
* packet is large enought to contain the returned ip header.
* Only then can we do the check to see if 64 bits of packet
* data have been returned, since we need to check the returned
* ip header length.
*/
#define ICMP_MINLEN 8 /* abs minimum */
#define ICMP_EXTD_MINLEN (156 - sizeof (struct ip)) /* draft-bonica-internet-icmp-08 */
#define ICMP_TSLEN (8 + 3 * sizeof (uint32_t)) /* timestamp */
#define ICMP_MASKLEN 12 /* address mask */
#define ICMP_ADVLENMIN (8 + sizeof (struct ip) + 8) /* min */
#define ICMP_ADVLEN(p) (8 + (IP_HL(&(p)->icmp_ip) << 2) + 8)
/* N.B.: must separately check that ip_hl >= 5 */
/*
* Definition of type and code field values.
*/
#define ICMP_ECHOREPLY 0 /* echo reply */
#define ICMP_UNREACH 3 /* dest unreachable, codes: */
#define ICMP_UNREACH_NET 0 /* bad net */
#define ICMP_UNREACH_HOST 1 /* bad host */
#define ICMP_UNREACH_PROTOCOL 2 /* bad protocol */
#define ICMP_UNREACH_PORT 3 /* bad port */
#define ICMP_UNREACH_NEEDFRAG 4 /* IP_DF caused drop */
#define ICMP_UNREACH_SRCFAIL 5 /* src route failed */
#define ICMP_UNREACH_NET_UNKNOWN 6 /* unknown net */
#define ICMP_UNREACH_HOST_UNKNOWN 7 /* unknown host */
#define ICMP_UNREACH_ISOLATED 8 /* src host isolated */
#define ICMP_UNREACH_NET_PROHIB 9 /* prohibited access */
#define ICMP_UNREACH_HOST_PROHIB 10 /* ditto */
#define ICMP_UNREACH_TOSNET 11 /* bad tos for net */
#define ICMP_UNREACH_TOSHOST 12 /* bad tos for host */
#define ICMP_SOURCEQUENCH 4 /* packet lost, slow down */
#define ICMP_REDIRECT 5 /* shorter route, codes: */
#define ICMP_REDIRECT_NET 0 /* for network */
#define ICMP_REDIRECT_HOST 1 /* for host */
#define ICMP_REDIRECT_TOSNET 2 /* for tos and net */
#define ICMP_REDIRECT_TOSHOST 3 /* for tos and host */
#define ICMP_ECHO 8 /* echo service */
#define ICMP_ROUTERADVERT 9 /* router advertisement */
#define ICMP_ROUTERSOLICIT 10 /* router solicitation */
#define ICMP_TIMXCEED 11 /* time exceeded, code: */
#define ICMP_TIMXCEED_INTRANS 0 /* ttl==0 in transit */
#define ICMP_TIMXCEED_REASS 1 /* ttl==0 in reass */
#define ICMP_PARAMPROB 12 /* ip header bad */
#define ICMP_PARAMPROB_OPTABSENT 1 /* req. opt. absent */
#define ICMP_TSTAMP 13 /* timestamp request */
#define ICMP_TSTAMPREPLY 14 /* timestamp reply */
#define ICMP_IREQ 15 /* information request */
#define ICMP_IREQREPLY 16 /* information reply */
#define ICMP_MASKREQ 17 /* address mask request */
#define ICMP_MASKREPLY 18 /* address mask reply */
#define ICMP_MAXTYPE 18
#define ICMP_ERRTYPE(type) \
((type) == ICMP_UNREACH || (type) == ICMP_SOURCEQUENCH || \
(type) == ICMP_REDIRECT || (type) == ICMP_TIMXCEED || \
(type) == ICMP_PARAMPROB)
#define ICMP_MPLS_EXT_TYPE(type) \
((type) == ICMP_UNREACH || \
(type) == ICMP_TIMXCEED || \
(type) == ICMP_PARAMPROB)
/* rfc1700 */
#ifndef ICMP_UNREACH_NET_UNKNOWN
#define ICMP_UNREACH_NET_UNKNOWN 6 /* destination net unknown */
#endif
#ifndef ICMP_UNREACH_HOST_UNKNOWN
#define ICMP_UNREACH_HOST_UNKNOWN 7 /* destination host unknown */
#endif
#ifndef ICMP_UNREACH_ISOLATED
#define ICMP_UNREACH_ISOLATED 8 /* source host isolated */
#endif
#ifndef ICMP_UNREACH_NET_PROHIB
#define ICMP_UNREACH_NET_PROHIB 9 /* admin prohibited net */
#endif
#ifndef ICMP_UNREACH_HOST_PROHIB
#define ICMP_UNREACH_HOST_PROHIB 10 /* admin prohibited host */
#endif
#ifndef ICMP_UNREACH_TOSNET
#define ICMP_UNREACH_TOSNET 11 /* tos prohibited net */
#endif
#ifndef ICMP_UNREACH_TOSHOST
#define ICMP_UNREACH_TOSHOST 12 /* tos prohibited host */
#endif
/* rfc1716 */
#ifndef ICMP_UNREACH_FILTER_PROHIB
#define ICMP_UNREACH_FILTER_PROHIB 13 /* admin prohibited filter */
#endif
#ifndef ICMP_UNREACH_HOST_PRECEDENCE
#define ICMP_UNREACH_HOST_PRECEDENCE 14 /* host precedence violation */
#endif
#ifndef ICMP_UNREACH_PRECEDENCE_CUTOFF
#define ICMP_UNREACH_PRECEDENCE_CUTOFF 15 /* precedence cutoff */
#endif
/* Most of the icmp types */
static const struct tok icmp2str[] = {
{ ICMP_ECHOREPLY, "echo reply" },
{ ICMP_SOURCEQUENCH, "source quench" },
{ ICMP_ECHO, "echo request" },
{ ICMP_ROUTERSOLICIT, "router solicitation" },
{ ICMP_TSTAMP, "time stamp request" },
{ ICMP_TSTAMPREPLY, "time stamp reply" },
{ ICMP_IREQ, "information request" },
{ ICMP_IREQREPLY, "information reply" },
{ ICMP_MASKREQ, "address mask request" },
{ 0, NULL }
};
/* Formats for most of the ICMP_UNREACH codes */
static const struct tok unreach2str[] = {
{ ICMP_UNREACH_NET, "net %s unreachable" },
{ ICMP_UNREACH_HOST, "host %s unreachable" },
{ ICMP_UNREACH_SRCFAIL,
"%s unreachable - source route failed" },
{ ICMP_UNREACH_NET_UNKNOWN, "net %s unreachable - unknown" },
{ ICMP_UNREACH_HOST_UNKNOWN, "host %s unreachable - unknown" },
{ ICMP_UNREACH_ISOLATED,
"%s unreachable - source host isolated" },
{ ICMP_UNREACH_NET_PROHIB,
"net %s unreachable - admin prohibited" },
{ ICMP_UNREACH_HOST_PROHIB,
"host %s unreachable - admin prohibited" },
{ ICMP_UNREACH_TOSNET,
"net %s unreachable - tos prohibited" },
{ ICMP_UNREACH_TOSHOST,
"host %s unreachable - tos prohibited" },
{ ICMP_UNREACH_FILTER_PROHIB,
"host %s unreachable - admin prohibited filter" },
{ ICMP_UNREACH_HOST_PRECEDENCE,
"host %s unreachable - host precedence violation" },
{ ICMP_UNREACH_PRECEDENCE_CUTOFF,
"host %s unreachable - precedence cutoff" },
{ 0, NULL }
};
/* Formats for the ICMP_REDIRECT codes */
static const struct tok type2str[] = {
{ ICMP_REDIRECT_NET, "redirect %s to net %s" },
{ ICMP_REDIRECT_HOST, "redirect %s to host %s" },
{ ICMP_REDIRECT_TOSNET, "redirect-tos %s to net %s" },
{ ICMP_REDIRECT_TOSHOST, "redirect-tos %s to host %s" },
{ 0, NULL }
};
/* rfc1191 */
struct mtu_discovery {
uint16_t unused;
uint16_t nexthopmtu;
};
/* rfc1256 */
struct ih_rdiscovery {
uint8_t ird_addrnum;
uint8_t ird_addrsiz;
uint16_t ird_lifetime;
};
struct id_rdiscovery {
uint32_t ird_addr;
uint32_t ird_pref;
};
/*
* draft-bonica-internet-icmp-08
*
* The Destination Unreachable, Time Exceeded
* and Parameter Problem messages are slighly changed as per
* the above draft. A new Length field gets added to give
* the caller an idea about the length of the piggypacked
* IP packet before the MPLS extension header starts.
*
* The Length field represents length of the padded "original datagram"
* field measured in 32-bit words.
*
* 0 1 2 3
* 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Type | Code | Checksum |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | unused | Length | unused |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Internet Header + leading octets of original datagram |
* | |
* | // |
* | |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*/
struct icmp_ext_t {
uint8_t icmp_type;
uint8_t icmp_code;
uint8_t icmp_checksum[2];
uint8_t icmp_reserved;
uint8_t icmp_length;
uint8_t icmp_reserved2[2];
uint8_t icmp_ext_legacy_header[128]; /* extension header starts 128 bytes after ICMP header */
uint8_t icmp_ext_version_res[2];
uint8_t icmp_ext_checksum[2];
uint8_t icmp_ext_data[1];
};
struct icmp_mpls_ext_object_header_t {
uint8_t length[2];
uint8_t class_num;
uint8_t ctype;
};
static const struct tok icmp_mpls_ext_obj_values[] = {
{ 1, "MPLS Stack Entry" },
{ 2, "Extended Payload" },
{ 0, NULL}
};
/* prototypes */
const char *icmp_tstamp_print(u_int);
/* print the milliseconds since midnight UTC */
const char *
icmp_tstamp_print(u_int tstamp)
{
u_int msec,sec,min,hrs;
static char buf[64];
msec = tstamp % 1000;
sec = tstamp / 1000;
min = sec / 60; sec -= min * 60;
hrs = min / 60; min -= hrs * 60;
snprintf(buf, sizeof(buf), "%02u:%02u:%02u.%03u",hrs,min,sec,msec);
return buf;
}
void
icmp_print(netdissect_options *ndo, const u_char *bp, u_int plen, const u_char *bp2,
int fragmented)
{
char *cp;
const struct icmp *dp;
const struct icmp_ext_t *ext_dp;
const struct ip *ip;
const char *str, *fmt;
const struct ip *oip;
const struct udphdr *ouh;
const uint8_t *obj_tptr;
uint32_t raw_label;
const u_char *snapend_save;
const struct icmp_mpls_ext_object_header_t *icmp_mpls_ext_object_header;
u_int hlen, dport, mtu, obj_tlen, obj_class_num, obj_ctype;
char buf[MAXHOSTNAMELEN + 100];
struct cksum_vec vec[1];
dp = (const struct icmp *)bp;
ext_dp = (const struct icmp_ext_t *)bp;
ip = (const struct ip *)bp2;
str = buf;
ND_TCHECK(dp->icmp_code);
switch (dp->icmp_type) {
case ICMP_ECHO:
case ICMP_ECHOREPLY:
ND_TCHECK(dp->icmp_seq);
(void)snprintf(buf, sizeof(buf), "echo %s, id %u, seq %u",
dp->icmp_type == ICMP_ECHO ?
"request" : "reply",
EXTRACT_16BITS(&dp->icmp_id),
EXTRACT_16BITS(&dp->icmp_seq));
break;
case ICMP_UNREACH:
ND_TCHECK(dp->icmp_ip.ip_dst);
switch (dp->icmp_code) {
case ICMP_UNREACH_PROTOCOL:
ND_TCHECK(dp->icmp_ip.ip_p);
(void)snprintf(buf, sizeof(buf),
"%s protocol %d unreachable",
ipaddr_string(ndo, &dp->icmp_ip.ip_dst),
dp->icmp_ip.ip_p);
break;
case ICMP_UNREACH_PORT:
ND_TCHECK(dp->icmp_ip.ip_p);
oip = &dp->icmp_ip;
hlen = IP_HL(oip) * 4;
ouh = (const struct udphdr *)(((const u_char *)oip) + hlen);
ND_TCHECK(ouh->uh_dport);
dport = EXTRACT_16BITS(&ouh->uh_dport);
switch (oip->ip_p) {
case IPPROTO_TCP:
(void)snprintf(buf, sizeof(buf),
"%s tcp port %s unreachable",
ipaddr_string(ndo, &oip->ip_dst),
tcpport_string(ndo, dport));
break;
case IPPROTO_UDP:
(void)snprintf(buf, sizeof(buf),
"%s udp port %s unreachable",
ipaddr_string(ndo, &oip->ip_dst),
udpport_string(ndo, dport));
break;
default:
(void)snprintf(buf, sizeof(buf),
"%s protocol %d port %d unreachable",
ipaddr_string(ndo, &oip->ip_dst),
oip->ip_p, dport);
break;
}
break;
case ICMP_UNREACH_NEEDFRAG:
{
register const struct mtu_discovery *mp;
mp = (const struct mtu_discovery *)(const u_char *)&dp->icmp_void;
mtu = EXTRACT_16BITS(&mp->nexthopmtu);
if (mtu) {
(void)snprintf(buf, sizeof(buf),
"%s unreachable - need to frag (mtu %d)",
ipaddr_string(ndo, &dp->icmp_ip.ip_dst), mtu);
} else {
(void)snprintf(buf, sizeof(buf),
"%s unreachable - need to frag",
ipaddr_string(ndo, &dp->icmp_ip.ip_dst));
}
}
break;
default:
fmt = tok2str(unreach2str, "#%d %%s unreachable",
dp->icmp_code);
(void)snprintf(buf, sizeof(buf), fmt,
ipaddr_string(ndo, &dp->icmp_ip.ip_dst));
break;
}
break;
case ICMP_REDIRECT:
ND_TCHECK(dp->icmp_ip.ip_dst);
fmt = tok2str(type2str, "redirect-#%d %%s to net %%s",
dp->icmp_code);
(void)snprintf(buf, sizeof(buf), fmt,
ipaddr_string(ndo, &dp->icmp_ip.ip_dst),
ipaddr_string(ndo, &dp->icmp_gwaddr));
break;
case ICMP_ROUTERADVERT:
{
register const struct ih_rdiscovery *ihp;
register const struct id_rdiscovery *idp;
u_int lifetime, num, size;
(void)snprintf(buf, sizeof(buf), "router advertisement");
cp = buf + strlen(buf);
ihp = (const struct ih_rdiscovery *)&dp->icmp_void;
ND_TCHECK(*ihp);
(void)strncpy(cp, " lifetime ", sizeof(buf) - (cp - buf));
cp = buf + strlen(buf);
lifetime = EXTRACT_16BITS(&ihp->ird_lifetime);
if (lifetime < 60) {
(void)snprintf(cp, sizeof(buf) - (cp - buf), "%u",
lifetime);
} else if (lifetime < 60 * 60) {
(void)snprintf(cp, sizeof(buf) - (cp - buf), "%u:%02u",
lifetime / 60, lifetime % 60);
} else {
(void)snprintf(cp, sizeof(buf) - (cp - buf),
"%u:%02u:%02u",
lifetime / 3600,
(lifetime % 3600) / 60,
lifetime % 60);
}
cp = buf + strlen(buf);
num = ihp->ird_addrnum;
(void)snprintf(cp, sizeof(buf) - (cp - buf), " %d:", num);
cp = buf + strlen(buf);
size = ihp->ird_addrsiz;
if (size != 2) {
(void)snprintf(cp, sizeof(buf) - (cp - buf),
" [size %d]", size);
break;
}
idp = (const struct id_rdiscovery *)&dp->icmp_data;
while (num-- > 0) {
ND_TCHECK(*idp);
(void)snprintf(cp, sizeof(buf) - (cp - buf), " {%s %u}",
ipaddr_string(ndo, &idp->ird_addr),
EXTRACT_32BITS(&idp->ird_pref));
cp = buf + strlen(buf);
++idp;
}
}
break;
case ICMP_TIMXCEED:
ND_TCHECK(dp->icmp_ip.ip_dst);
switch (dp->icmp_code) {
case ICMP_TIMXCEED_INTRANS:
str = "time exceeded in-transit";
break;
case ICMP_TIMXCEED_REASS:
str = "ip reassembly time exceeded";
break;
default:
(void)snprintf(buf, sizeof(buf), "time exceeded-#%d",
dp->icmp_code);
break;
}
break;
case ICMP_PARAMPROB:
if (dp->icmp_code)
(void)snprintf(buf, sizeof(buf),
"parameter problem - code %d", dp->icmp_code);
else {
ND_TCHECK(dp->icmp_pptr);
(void)snprintf(buf, sizeof(buf),
"parameter problem - octet %d", dp->icmp_pptr);
}
break;
case ICMP_MASKREPLY:
ND_TCHECK(dp->icmp_mask);
(void)snprintf(buf, sizeof(buf), "address mask is 0x%08x",
EXTRACT_32BITS(&dp->icmp_mask));
break;
case ICMP_TSTAMP:
ND_TCHECK(dp->icmp_seq);
(void)snprintf(buf, sizeof(buf),
"time stamp query id %u seq %u",
EXTRACT_16BITS(&dp->icmp_id),
EXTRACT_16BITS(&dp->icmp_seq));
break;
case ICMP_TSTAMPREPLY:
ND_TCHECK(dp->icmp_ttime);
(void)snprintf(buf, sizeof(buf),
"time stamp reply id %u seq %u: org %s",
EXTRACT_16BITS(&dp->icmp_id),
EXTRACT_16BITS(&dp->icmp_seq),
icmp_tstamp_print(EXTRACT_32BITS(&dp->icmp_otime)));
(void)snprintf(buf+strlen(buf),sizeof(buf)-strlen(buf),", recv %s",
icmp_tstamp_print(EXTRACT_32BITS(&dp->icmp_rtime)));
(void)snprintf(buf+strlen(buf),sizeof(buf)-strlen(buf),", xmit %s",
icmp_tstamp_print(EXTRACT_32BITS(&dp->icmp_ttime)));
break;
default:
str = tok2str(icmp2str, "type-#%d", dp->icmp_type);
break;
}
ND_PRINT((ndo, "ICMP %s, length %u", str, plen));
if (ndo->ndo_vflag && !fragmented) { /* don't attempt checksumming if this is a frag */
uint16_t sum, icmp_sum;
if (ND_TTEST2(*bp, plen)) {
vec[0].ptr = (const uint8_t *)(const void *)dp;
vec[0].len = plen;
sum = in_cksum(vec, 1);
if (sum != 0) {
icmp_sum = EXTRACT_16BITS(&dp->icmp_cksum);
ND_PRINT((ndo, " (wrong icmp cksum %x (->%x)!)",
icmp_sum,
in_cksum_shouldbe(icmp_sum, sum)));
}
}
}
/*
* print the remnants of the IP packet.
* save the snaplength as this may get overidden in the IP printer.
*/
if (ndo->ndo_vflag >= 1 && ICMP_ERRTYPE(dp->icmp_type)) {
bp += 8;
ND_PRINT((ndo, "\n\t"));
ip = (const struct ip *)bp;
snapend_save = ndo->ndo_snapend;
ip_print(ndo, bp, EXTRACT_16BITS(&ip->ip_len));
ndo->ndo_snapend = snapend_save;
}
/*
* Attempt to decode the MPLS extensions only for some ICMP types.
*/
if (ndo->ndo_vflag >= 1 && plen > ICMP_EXTD_MINLEN && ICMP_MPLS_EXT_TYPE(dp->icmp_type)) {
ND_TCHECK(*ext_dp);
/*
* Check first if the mpls extension header shows a non-zero length.
* If the length field is not set then silently verify the checksum
* to check if an extension header is present. This is expedient,
* however not all implementations set the length field proper.
*/
if (!ext_dp->icmp_length) {
vec[0].ptr = (const uint8_t *)(const void *)&ext_dp->icmp_ext_version_res;
vec[0].len = plen - ICMP_EXTD_MINLEN;
if (in_cksum(vec, 1)) {
return;
}
}
ND_PRINT((ndo, "\n\tMPLS extension v%u",
ICMP_MPLS_EXT_EXTRACT_VERSION(*(ext_dp->icmp_ext_version_res))));
/*
* Sanity checking of the header.
*/
if (ICMP_MPLS_EXT_EXTRACT_VERSION(*(ext_dp->icmp_ext_version_res)) !=
ICMP_MPLS_EXT_VERSION) {
ND_PRINT((ndo, " packet not supported"));
return;
}
hlen = plen - ICMP_EXTD_MINLEN;
vec[0].ptr = (const uint8_t *)(const void *)&ext_dp->icmp_ext_version_res;
vec[0].len = hlen;
ND_PRINT((ndo, ", checksum 0x%04x (%scorrect), length %u",
EXTRACT_16BITS(ext_dp->icmp_ext_checksum),
in_cksum(vec, 1) ? "in" : "",
hlen));
hlen -= 4; /* subtract common header size */
obj_tptr = (const uint8_t *)ext_dp->icmp_ext_data;
while (hlen > sizeof(struct icmp_mpls_ext_object_header_t)) {
icmp_mpls_ext_object_header = (const struct icmp_mpls_ext_object_header_t *)obj_tptr;
ND_TCHECK(*icmp_mpls_ext_object_header);
obj_tlen = EXTRACT_16BITS(icmp_mpls_ext_object_header->length);
obj_class_num = icmp_mpls_ext_object_header->class_num;
obj_ctype = icmp_mpls_ext_object_header->ctype;
obj_tptr += sizeof(struct icmp_mpls_ext_object_header_t);
ND_PRINT((ndo, "\n\t %s Object (%u), Class-Type: %u, length %u",
tok2str(icmp_mpls_ext_obj_values,"unknown",obj_class_num),
obj_class_num,
obj_ctype,
obj_tlen));
hlen-=sizeof(struct icmp_mpls_ext_object_header_t); /* length field includes tlv header */
/* infinite loop protection */
if ((obj_class_num == 0) ||
(obj_tlen < sizeof(struct icmp_mpls_ext_object_header_t))) {
return;
}
obj_tlen-=sizeof(struct icmp_mpls_ext_object_header_t);
switch (obj_class_num) {
case 1:
switch(obj_ctype) {
case 1:
ND_TCHECK2(*obj_tptr, 4);
raw_label = EXTRACT_32BITS(obj_tptr);
ND_PRINT((ndo, "\n\t label %u, exp %u", MPLS_LABEL(raw_label), MPLS_EXP(raw_label)));
if (MPLS_STACK(raw_label))
ND_PRINT((ndo, ", [S]"));
ND_PRINT((ndo, ", ttl %u", MPLS_TTL(raw_label)));
break;
default:
print_unknown_data(ndo, obj_tptr, "\n\t ", obj_tlen);
}
break;
/*
* FIXME those are the defined objects that lack a decoder
* you are welcome to contribute code ;-)
*/
case 2:
default:
print_unknown_data(ndo, obj_tptr, "\n\t ", obj_tlen);
break;
}
if (hlen < obj_tlen)
break;
hlen -= obj_tlen;
obj_tptr += obj_tlen;
}
}
return;
trunc:
ND_PRINT((ndo, "[|icmp]"));
}
/*
* Local Variables:
* c-style: whitesmith
* c-basic-offset: 8
* End:
*/
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_2641_0 |
crossvul-cpp_data_bad_89_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.142 2018/05/24 18:08:01 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 CAST(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 \
? CAST(void *, &sh32) \
: CAST(void *, &sh64))
#define xsh_sizeof (clazz == ELFCLASS32 \
? sizeof(sh32) \
: sizeof(sh64))
#define xsh_size CAST(size_t, (clazz == ELFCLASS32 \
? elf_getu32(swap, sh32.sh_size) \
: elf_getu64(swap, sh64.sh_size)))
#define xsh_offset CAST(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 \
? CAST(void *, &ph32) \
: CAST(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 CAST(off_t, (clazz == ELFCLASS32 \
? elf_getu32(swap, ph32.p_offset) \
: elf_getu64(swap, ph64.p_offset)))
#define xph_align CAST(size_t, (clazz == ELFCLASS32 \
? CAST(off_t, (ph32.p_align ? \
elf_getu32(swap, ph32.p_align) : 4))\
: CAST(off_t, (ph64.p_align ? \
elf_getu64(swap, ph64.p_align) : 4))))
#define xph_vaddr CAST(size_t, (clazz == ELFCLASS32 \
? CAST(off_t, (ph32.p_vaddr ? \
elf_getu32(swap, ph32.p_vaddr) : 4))\
: CAST(off_t, (ph64.p_vaddr ? \
elf_getu64(swap, ph64.p_vaddr) : 4))))
#define xph_filesz CAST(size_t, (clazz == ELFCLASS32 \
? elf_getu32(swap, ph32.p_filesz) \
: elf_getu64(swap, ph64.p_filesz)))
#define xph_memsz CAST(size_t, ((clazz == ELFCLASS32 \
? elf_getu32(swap, ph32.p_memsz) \
: elf_getu64(swap, ph64.p_memsz))))
#define xnh_addr (clazz == ELFCLASS32 \
? CAST(void *, &nh32) \
: CAST(void *, &nh64))
#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 xdh_addr (clazz == ELFCLASS32 \
? CAST(void *, &dh32) \
: CAST(void *, &dh64))
#define xdh_sizeof (clazz == ELFCLASS32 \
? sizeof(dh32) \
: sizeof(dh64))
#define xdh_tag (clazz == ELFCLASS32 \
? elf_getu32(swap, dh32.d_tag) \
: elf_getu64(swap, dh64.d_tag))
#define xdh_val (clazz == ELFCLASS32 \
? elf_getu32(swap, dh32.d_un.d_val) \
: elf_getu64(swap, dh64.d_un.d_val))
#define xcap_addr (clazz == ELFCLASS32 \
? CAST(void *, &cap32) \
: CAST(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 \
? CAST(void *, &auxv32) \
: CAST(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))
#define prpsoffsets(i) (clazz == ELFCLASS32 \
? prpsoffsets32[i] \
: prpsoffsets64[i])
#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_CORE_STYLE 0x0003
#define FLAGS_DID_CORE 0x0004
#define FLAGS_DID_OS_NOTE 0x0008
#define FLAGS_DID_BUILD_ID 0x0010
#define FLAGS_DID_CORE_STYLE 0x0020
#define FLAGS_DID_NETBSD_PAX 0x0040
#define FLAGS_DID_NETBSD_MARCH 0x0080
#define FLAGS_DID_NETBSD_CMODEL 0x0100
#define FLAGS_DID_NETBSD_EMULATION 0x0200
#define FLAGS_DID_NETBSD_UNKNOWN 0x0400
#define FLAGS_IS_CORE 0x0800
#define FLAGS_DID_AUXV 0x1000
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) <
CAST(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;
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;
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;
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];
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;
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;
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;
*flags |= os_style;
}
switch (os_style) {
case OS_STYLE_NETBSD:
if (type == NT_NETBSD_CORE_PROCINFO) {
char sbuf[512];
struct NetBSD_elfcore_procinfo pi;
memset(&pi, 0, sizeof(pi));
memcpy(&pi, nbuf + doff, descsz);
if (file_printf(ms, ", from '%.31s', pid=%u, uid=%u, "
"gid=%u, nlwps=%u, lwp=%u (signal %u/code %u)",
file_printable(sbuf, sizeof(sbuf),
CAST(char *, pi.cpi_name)),
elf_getu32(swap, (uint32_t)pi.cpi_pid),
elf_getu32(swap, pi.cpi_euid),
elf_getu32(swap, pi.cpi_egid),
elf_getu32(swap, pi.cpi_nlwps),
elf_getu32(swap, (uint32_t)pi.cpi_siglwp),
elf_getu32(swap, pi.cpi_signo),
elf_getu32(swap, pi.cpi_sigcode)) == -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, CAST(size_t, 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;
}
/*ARGSUSED*/
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 ((*flags & (FLAGS_IS_CORE|FLAGS_DID_CORE_STYLE)) !=
(FLAGS_IS_CORE|FLAGS_DID_CORE_STYLE))
return 0;
switch (*flags & FLAGS_CORE_STYLE) {
case OS_STYLE_SVR4:
if (type != NT_AUXV)
return 0;
break;
#ifdef notyet
case OS_STYLE_NETBSD:
if (type != NT_NETBSD_CORE_AUXV)
return 0;
break;
case OS_STYLE_FREEBSD:
if (type != NT_FREEBSD_PROCSTAT_AUXV)
return 0;
break;
#endif
default:
return 0;
}
*flags |= FLAGS_DID_AUXV;
nval = 0;
for (size_t off = 0; off + elsize <= descsz; off += elsize) {
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
dodynamic(struct magic_set *ms, void *vbuf, size_t offset, size_t size,
int clazz, int swap)
{
Elf32_Dyn dh32;
Elf64_Dyn dh64;
unsigned char *dbuf = CAST(unsigned char *, vbuf);
if (xdh_sizeof + offset > size) {
/*
* We're out of note headers.
*/
return xdh_sizeof + offset;
}
memcpy(xdh_addr, &dbuf[offset], xdh_sizeof);
offset += xdh_sizeof;
switch (xdh_tag) {
case DT_FLAGS_1:
if (xdh_val == DF_1_PIE)
ms->mode |= 0111;
else
ms->mode &= ~0111;
break;
default:
break;
}
return offset;
}
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;
}
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) {
file_printf(ms, ", bad note name size %#lx",
CAST(unsigned long, namesz));
return 0;
}
if (descsz & 0x80000000) {
file_printf(ms, ", bad note description size %#lx",
CAST(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(CAST(char *, &nbuf[noff]), "NetBSD") == 0) {
int descw, flag;
const char *str, *tag;
if (descsz > 100)
descsz = 100;
switch (xnh_type) {
case NT_NETBSD_VERSION:
return offset;
case NT_NETBSD_MARCH:
flag = FLAGS_DID_NETBSD_MARCH;
tag = "compiled for";
break;
case NT_NETBSD_CMODEL:
flag = FLAGS_DID_NETBSD_CMODEL;
tag = "compiler model";
break;
case NT_NETBSD_EMULATION:
flag = FLAGS_DID_NETBSD_EMULATION;
tag = "emulation:";
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;
return offset;
}
if (*flags & flag)
return offset;
str = CAST(const char *, &nbuf[doff]);
descw = CAST(int, descsz);
*flags |= flag;
file_printf(ms, ", %s: %.*s", tag, descw, str);
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, has_debug_info = 0;
size_t nbadcap = 0;
void *nbuf;
off_t noff, coff, name_off;
uint64_t cap_hw1 = 0; /* SunOS 5.x hardware capabilities */
uint64_t cap_sf1 = 0; /* SunOS 5.x software capabilities */
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)))
< CAST(ssize_t, xsh_sizeof)) {
if (file_printf(ms, ", missing section headers") == -1)
return -1;
return 0;
}
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) {
has_debug_info = 1;
stripped = 0;
}
if (pread(fd, xsh_addr, xsh_sizeof, off) <
CAST(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 (CAST(uintmax_t, (xsh_size + xsh_offset)) >
CAST(uintmax_t, fsize)) {
if (file_printf(ms,
", note offset/size %#" INTMAX_T_FORMAT
"x+%#" INTMAX_T_FORMAT "x exceeds"
" file size %#" INTMAX_T_FORMAT "x",
CAST(uintmax_t, xsh_offset),
CAST(uintmax_t, xsh_size),
CAST(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) <
CAST(ssize_t, xsh_size)) {
file_badread(ms);
free(nbuf);
return -1;
}
noff = 0;
for (;;) {
if (noff >= CAST(off_t, xsh_size))
break;
noff = donote(ms, nbuf, CAST(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)
== CAST(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) >
CAST(off_t, xsh_size))
break;
if (read(fd, cbuf, CAST(size_t, xcap_sizeof)) !=
CAST(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;
}
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 "
"%#" INT64_T_FORMAT "x = %#"
INT64_T_FORMAT "x",
CAST(unsigned long long, xcap_tag),
CAST(unsigned long long, xcap_val))
== -1)
return -1;
if (nbadcap++ > 2)
coff = xsh_size;
break;
}
}
/*FALLTHROUGH*/
skip:
default:
break;
}
}
if (has_debug_info) {
if (file_printf(ms, ", with debug_info") == -1)
return -1;
}
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 %#"
INT64_T_FORMAT "x",
CAST(unsigned long long, cap_hw1)) == -1)
return -1;
} else {
if (file_printf(ms,
" hardware capability %#" INT64_T_FORMAT "x",
CAST(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 %#"
INT64_T_FORMAT "x",
CAST(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";
unsigned char nbuf[BUFSIZ];
char ibuf[BUFSIZ];
char interp[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;
}
interp[0] = '\0';
for ( ; num; num--) {
int doread;
if (pread(fd, xph_addr, xph_sizeof, off) <
CAST(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";
doread = 1;
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 %#lx",
CAST(unsigned long, align)) == -1)
return -1;
align = 4;
}
/*FALLTHROUGH*/
case PT_INTERP:
doread = 1;
break;
default:
doread = 0;
if (fsize != SIZE_UNKNOWN && xph_offset > fsize) {
/* Maybe warn here? */
continue;
}
break;
}
if (doread) {
len = xph_filesz < sizeof(nbuf) ? xph_filesz
: sizeof(nbuf);
bufsize = pread(fd, nbuf, len, xph_offset);
if (bufsize == -1) {
file_badread(ms);
return -1;
}
} else
len = 0;
/* Things we can determine when we seek */
switch (xph_type) {
case PT_DYNAMIC:
offset = 0;
for (;;) {
if (offset >= (size_t)bufsize)
break;
offset = dodynamic(ms, nbuf, offset,
CAST(size_t, bufsize), clazz, swap);
if (offset == 0)
break;
}
break;
case PT_INTERP:
if (bufsize && nbuf[0]) {
nbuf[bufsize - 1] = '\0';
memcpy(interp, nbuf, bufsize);
} else
strlcpy(interp, "*empty*", sizeof(interp));
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,
CAST(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, const struct buffer *b)
{
int fd = b->fd;
const unsigned char *buf = b->fbuf;
size_t nbytes = b->flen;
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, CAST(off_t, 0), SEEK_SET) == CAST(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-125/c/bad_89_0 |
crossvul-cpp_data_bad_3951_0 | /**
* FreeRDP: A Remote Desktop Protocol Implementation
* Drawing Orders
*
* Copyright 2011 Marc-Andre Moreau <marcandre.moreau@gmail.com>
* Copyright 2016 Armin Novak <armin.novak@thincast.com>
* Copyright 2016 Thincast Technologies GmbH
*
* 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 HAVE_CONFIG_H
#include "config.h"
#endif
#include "window.h"
#include <winpr/wtypes.h>
#include <winpr/crt.h>
#include <freerdp/api.h>
#include <freerdp/log.h>
#include <freerdp/graphics.h>
#include <freerdp/codec/bitmap.h>
#include <freerdp/gdi/gdi.h>
#include "orders.h"
#include "../cache/glyph.h"
#include "../cache/bitmap.h"
#include "../cache/brush.h"
#include "../cache/cache.h"
#define TAG FREERDP_TAG("core.orders")
const BYTE PRIMARY_DRAWING_ORDER_FIELD_BYTES[] = { DSTBLT_ORDER_FIELD_BYTES,
PATBLT_ORDER_FIELD_BYTES,
SCRBLT_ORDER_FIELD_BYTES,
0,
0,
0,
0,
DRAW_NINE_GRID_ORDER_FIELD_BYTES,
MULTI_DRAW_NINE_GRID_ORDER_FIELD_BYTES,
LINE_TO_ORDER_FIELD_BYTES,
OPAQUE_RECT_ORDER_FIELD_BYTES,
SAVE_BITMAP_ORDER_FIELD_BYTES,
0,
MEMBLT_ORDER_FIELD_BYTES,
MEM3BLT_ORDER_FIELD_BYTES,
MULTI_DSTBLT_ORDER_FIELD_BYTES,
MULTI_PATBLT_ORDER_FIELD_BYTES,
MULTI_SCRBLT_ORDER_FIELD_BYTES,
MULTI_OPAQUE_RECT_ORDER_FIELD_BYTES,
FAST_INDEX_ORDER_FIELD_BYTES,
POLYGON_SC_ORDER_FIELD_BYTES,
POLYGON_CB_ORDER_FIELD_BYTES,
POLYLINE_ORDER_FIELD_BYTES,
0,
FAST_GLYPH_ORDER_FIELD_BYTES,
ELLIPSE_SC_ORDER_FIELD_BYTES,
ELLIPSE_CB_ORDER_FIELD_BYTES,
GLYPH_INDEX_ORDER_FIELD_BYTES };
#define PRIMARY_DRAWING_ORDER_COUNT (ARRAYSIZE(PRIMARY_DRAWING_ORDER_FIELD_BYTES))
static const BYTE CBR2_BPP[] = { 0, 0, 0, 8, 16, 24, 32 };
static const BYTE BPP_CBR2[] = { 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0,
0, 0, 0, 0, 5, 0, 0, 0, 0, 0, 0, 0, 6, 0, 0, 0, 0, 0, 0, 0 };
static const BYTE CBR23_BPP[] = { 0, 0, 0, 8, 16, 24, 32 };
static const BYTE BPP_CBR23[] = { 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0,
0, 0, 0, 0, 5, 0, 0, 0, 0, 0, 0, 0, 6, 0, 0, 0, 0, 0, 0, 0 };
static const BYTE BMF_BPP[] = { 0, 1, 0, 8, 16, 24, 32, 0 };
static const BYTE BPP_BMF[] = { 0, 1, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0,
0, 0, 0, 0, 5, 0, 0, 0, 0, 0, 0, 0, 6, 0, 0, 0, 0, 0, 0, 0 };
static BOOL check_order_activated(wLog* log, rdpSettings* settings, const char* orderName,
BOOL condition)
{
if (!condition)
{
if (settings->AllowUnanouncedOrdersFromServer)
{
WLog_Print(log, WLOG_WARN,
"%s - SERVER BUG: The support for this feature was not announced!",
orderName);
return TRUE;
}
else
{
WLog_Print(log, WLOG_ERROR,
"%s - SERVER BUG: The support for this feature was not announced! Use "
"/relax-order-checks to ignore",
orderName);
return FALSE;
}
}
return TRUE;
}
static BOOL check_alt_order_supported(wLog* log, rdpSettings* settings, BYTE orderType,
const char* orderName)
{
BOOL condition = FALSE;
switch (orderType)
{
case ORDER_TYPE_CREATE_OFFSCREEN_BITMAP:
case ORDER_TYPE_SWITCH_SURFACE:
condition = settings->OffscreenSupportLevel != 0;
break;
case ORDER_TYPE_CREATE_NINE_GRID_BITMAP:
condition = settings->DrawNineGridEnabled;
break;
case ORDER_TYPE_FRAME_MARKER:
condition = settings->FrameMarkerCommandEnabled;
break;
case ORDER_TYPE_GDIPLUS_FIRST:
case ORDER_TYPE_GDIPLUS_NEXT:
case ORDER_TYPE_GDIPLUS_END:
case ORDER_TYPE_GDIPLUS_CACHE_FIRST:
case ORDER_TYPE_GDIPLUS_CACHE_NEXT:
case ORDER_TYPE_GDIPLUS_CACHE_END:
condition = settings->DrawGdiPlusCacheEnabled;
break;
case ORDER_TYPE_WINDOW:
condition = settings->RemoteWndSupportLevel != WINDOW_LEVEL_NOT_SUPPORTED;
break;
case ORDER_TYPE_STREAM_BITMAP_FIRST:
case ORDER_TYPE_STREAM_BITMAP_NEXT:
case ORDER_TYPE_COMPDESK_FIRST:
condition = TRUE;
break;
default:
WLog_Print(log, WLOG_WARN, "%s - Alternate Secondary Drawing Order UNKNOWN", orderName);
condition = FALSE;
break;
}
return check_order_activated(log, settings, orderName, condition);
}
static BOOL check_secondary_order_supported(wLog* log, rdpSettings* settings, BYTE orderType,
const char* orderName)
{
BOOL condition = FALSE;
switch (orderType)
{
case ORDER_TYPE_BITMAP_UNCOMPRESSED:
case ORDER_TYPE_CACHE_BITMAP_COMPRESSED:
condition = settings->BitmapCacheEnabled;
break;
case ORDER_TYPE_BITMAP_UNCOMPRESSED_V2:
case ORDER_TYPE_BITMAP_COMPRESSED_V2:
condition = settings->BitmapCacheEnabled;
break;
case ORDER_TYPE_BITMAP_COMPRESSED_V3:
condition = settings->BitmapCacheV3Enabled;
break;
case ORDER_TYPE_CACHE_COLOR_TABLE:
condition = (settings->OrderSupport[NEG_MEMBLT_INDEX] ||
settings->OrderSupport[NEG_MEM3BLT_INDEX]);
break;
case ORDER_TYPE_CACHE_GLYPH:
{
switch (settings->GlyphSupportLevel)
{
case GLYPH_SUPPORT_PARTIAL:
case GLYPH_SUPPORT_FULL:
case GLYPH_SUPPORT_ENCODE:
condition = TRUE;
break;
case GLYPH_SUPPORT_NONE:
default:
condition = FALSE;
break;
}
}
break;
case ORDER_TYPE_CACHE_BRUSH:
condition = TRUE;
break;
default:
WLog_Print(log, WLOG_WARN, "SECONDARY ORDER %s not supported", orderName);
break;
}
return check_order_activated(log, settings, orderName, condition);
}
static BOOL check_primary_order_supported(wLog* log, rdpSettings* settings, UINT32 orderType,
const char* orderName)
{
BOOL condition = FALSE;
switch (orderType)
{
case ORDER_TYPE_DSTBLT:
condition = settings->OrderSupport[NEG_DSTBLT_INDEX];
break;
case ORDER_TYPE_SCRBLT:
condition = settings->OrderSupport[NEG_SCRBLT_INDEX];
break;
case ORDER_TYPE_DRAW_NINE_GRID:
condition = settings->OrderSupport[NEG_DRAWNINEGRID_INDEX];
break;
case ORDER_TYPE_MULTI_DRAW_NINE_GRID:
condition = settings->OrderSupport[NEG_MULTI_DRAWNINEGRID_INDEX];
break;
case ORDER_TYPE_LINE_TO:
condition = settings->OrderSupport[NEG_LINETO_INDEX];
break;
/* [MS-RDPEGDI] 2.2.2.2.1.1.2.5 OpaqueRect (OPAQUERECT_ORDER)
* suggests that PatBlt and OpaqueRect imply each other. */
case ORDER_TYPE_PATBLT:
case ORDER_TYPE_OPAQUE_RECT:
condition = settings->OrderSupport[NEG_OPAQUE_RECT_INDEX] ||
settings->OrderSupport[NEG_PATBLT_INDEX];
break;
case ORDER_TYPE_SAVE_BITMAP:
condition = settings->OrderSupport[NEG_SAVEBITMAP_INDEX];
break;
case ORDER_TYPE_MEMBLT:
condition = settings->OrderSupport[NEG_MEMBLT_INDEX];
break;
case ORDER_TYPE_MEM3BLT:
condition = settings->OrderSupport[NEG_MEM3BLT_INDEX];
break;
case ORDER_TYPE_MULTI_DSTBLT:
condition = settings->OrderSupport[NEG_MULTIDSTBLT_INDEX];
break;
case ORDER_TYPE_MULTI_PATBLT:
condition = settings->OrderSupport[NEG_MULTIPATBLT_INDEX];
break;
case ORDER_TYPE_MULTI_SCRBLT:
condition = settings->OrderSupport[NEG_MULTIDSTBLT_INDEX];
break;
case ORDER_TYPE_MULTI_OPAQUE_RECT:
condition = settings->OrderSupport[NEG_MULTIOPAQUERECT_INDEX];
break;
case ORDER_TYPE_FAST_INDEX:
condition = settings->OrderSupport[NEG_FAST_INDEX_INDEX];
break;
case ORDER_TYPE_POLYGON_SC:
condition = settings->OrderSupport[NEG_POLYGON_SC_INDEX];
break;
case ORDER_TYPE_POLYGON_CB:
condition = settings->OrderSupport[NEG_POLYGON_CB_INDEX];
break;
case ORDER_TYPE_POLYLINE:
condition = settings->OrderSupport[NEG_POLYLINE_INDEX];
break;
case ORDER_TYPE_FAST_GLYPH:
condition = settings->OrderSupport[NEG_FAST_GLYPH_INDEX];
break;
case ORDER_TYPE_ELLIPSE_SC:
condition = settings->OrderSupport[NEG_ELLIPSE_SC_INDEX];
break;
case ORDER_TYPE_ELLIPSE_CB:
condition = settings->OrderSupport[NEG_ELLIPSE_CB_INDEX];
break;
case ORDER_TYPE_GLYPH_INDEX:
condition = settings->OrderSupport[NEG_GLYPH_INDEX_INDEX];
break;
default:
WLog_Print(log, WLOG_WARN, "%s Primary Drawing Order not supported", orderName);
break;
}
return check_order_activated(log, settings, orderName, condition);
}
static const char* primary_order_string(UINT32 orderType)
{
const char* orders[] = { "[0x%02" PRIx8 "] DstBlt",
"[0x%02" PRIx8 "] PatBlt",
"[0x%02" PRIx8 "] ScrBlt",
"[0x%02" PRIx8 "] UNUSED",
"[0x%02" PRIx8 "] UNUSED",
"[0x%02" PRIx8 "] UNUSED",
"[0x%02" PRIx8 "] UNUSED",
"[0x%02" PRIx8 "] DrawNineGrid",
"[0x%02" PRIx8 "] MultiDrawNineGrid",
"[0x%02" PRIx8 "] LineTo",
"[0x%02" PRIx8 "] OpaqueRect",
"[0x%02" PRIx8 "] SaveBitmap",
"[0x%02" PRIx8 "] UNUSED",
"[0x%02" PRIx8 "] MemBlt",
"[0x%02" PRIx8 "] Mem3Blt",
"[0x%02" PRIx8 "] MultiDstBlt",
"[0x%02" PRIx8 "] MultiPatBlt",
"[0x%02" PRIx8 "] MultiScrBlt",
"[0x%02" PRIx8 "] MultiOpaqueRect",
"[0x%02" PRIx8 "] FastIndex",
"[0x%02" PRIx8 "] PolygonSC",
"[0x%02" PRIx8 "] PolygonCB",
"[0x%02" PRIx8 "] Polyline",
"[0x%02" PRIx8 "] UNUSED",
"[0x%02" PRIx8 "] FastGlyph",
"[0x%02" PRIx8 "] EllipseSC",
"[0x%02" PRIx8 "] EllipseCB",
"[0x%02" PRIx8 "] GlyphIndex" };
const char* fmt = "[0x%02" PRIx8 "] UNKNOWN";
static char buffer[64] = { 0 };
if (orderType < ARRAYSIZE(orders))
fmt = orders[orderType];
sprintf_s(buffer, ARRAYSIZE(buffer), fmt, orderType);
return buffer;
}
static const char* secondary_order_string(UINT32 orderType)
{
const char* orders[] = { "[0x%02" PRIx8 "] Cache Bitmap",
"[0x%02" PRIx8 "] Cache Color Table",
"[0x%02" PRIx8 "] Cache Bitmap (Compressed)",
"[0x%02" PRIx8 "] Cache Glyph",
"[0x%02" PRIx8 "] Cache Bitmap V2",
"[0x%02" PRIx8 "] Cache Bitmap V2 (Compressed)",
"[0x%02" PRIx8 "] UNUSED",
"[0x%02" PRIx8 "] Cache Brush",
"[0x%02" PRIx8 "] Cache Bitmap V3" };
const char* fmt = "[0x%02" PRIx8 "] UNKNOWN";
static char buffer[64] = { 0 };
if (orderType < ARRAYSIZE(orders))
fmt = orders[orderType];
sprintf_s(buffer, ARRAYSIZE(buffer), fmt, orderType);
return buffer;
}
static const char* altsec_order_string(BYTE orderType)
{
const char* orders[] = {
"[0x%02" PRIx8 "] Switch Surface", "[0x%02" PRIx8 "] Create Offscreen Bitmap",
"[0x%02" PRIx8 "] Stream Bitmap First", "[0x%02" PRIx8 "] Stream Bitmap Next",
"[0x%02" PRIx8 "] Create NineGrid Bitmap", "[0x%02" PRIx8 "] Draw GDI+ First",
"[0x%02" PRIx8 "] Draw GDI+ Next", "[0x%02" PRIx8 "] Draw GDI+ End",
"[0x%02" PRIx8 "] Draw GDI+ Cache First", "[0x%02" PRIx8 "] Draw GDI+ Cache Next",
"[0x%02" PRIx8 "] Draw GDI+ Cache End", "[0x%02" PRIx8 "] Windowing",
"[0x%02" PRIx8 "] Desktop Composition", "[0x%02" PRIx8 "] Frame Marker"
};
const char* fmt = "[0x%02" PRIx8 "] UNKNOWN";
static char buffer[64] = { 0 };
if (orderType < ARRAYSIZE(orders))
fmt = orders[orderType];
sprintf_s(buffer, ARRAYSIZE(buffer), fmt, orderType);
return buffer;
}
static INLINE BOOL update_read_coord(wStream* s, INT32* coord, BOOL delta)
{
INT8 lsi8;
INT16 lsi16;
if (delta)
{
if (Stream_GetRemainingLength(s) < 1)
return FALSE;
Stream_Read_INT8(s, lsi8);
*coord += lsi8;
}
else
{
if (Stream_GetRemainingLength(s) < 2)
return FALSE;
Stream_Read_INT16(s, lsi16);
*coord = lsi16;
}
return TRUE;
}
static INLINE BOOL update_write_coord(wStream* s, INT32 coord)
{
Stream_Write_UINT16(s, coord);
return TRUE;
}
static INLINE BOOL update_read_color(wStream* s, UINT32* color)
{
BYTE byte;
if (Stream_GetRemainingLength(s) < 3)
return FALSE;
*color = 0;
Stream_Read_UINT8(s, byte);
*color = (UINT32)byte;
Stream_Read_UINT8(s, byte);
*color |= ((UINT32)byte << 8) & 0xFF00;
Stream_Read_UINT8(s, byte);
*color |= ((UINT32)byte << 16) & 0xFF0000;
return TRUE;
}
static INLINE BOOL update_write_color(wStream* s, UINT32 color)
{
BYTE byte;
byte = (color & 0xFF);
Stream_Write_UINT8(s, byte);
byte = ((color >> 8) & 0xFF);
Stream_Write_UINT8(s, byte);
byte = ((color >> 16) & 0xFF);
Stream_Write_UINT8(s, byte);
return TRUE;
}
static INLINE BOOL update_read_colorref(wStream* s, UINT32* color)
{
BYTE byte;
if (Stream_GetRemainingLength(s) < 4)
return FALSE;
*color = 0;
Stream_Read_UINT8(s, byte);
*color = byte;
Stream_Read_UINT8(s, byte);
*color |= ((UINT32)byte << 8);
Stream_Read_UINT8(s, byte);
*color |= ((UINT32)byte << 16);
Stream_Seek_UINT8(s);
return TRUE;
}
static INLINE BOOL update_read_color_quad(wStream* s, UINT32* color)
{
return update_read_colorref(s, color);
}
static INLINE void update_write_color_quad(wStream* s, UINT32 color)
{
BYTE byte;
byte = (color >> 16) & 0xFF;
Stream_Write_UINT8(s, byte);
byte = (color >> 8) & 0xFF;
Stream_Write_UINT8(s, byte);
byte = color & 0xFF;
Stream_Write_UINT8(s, byte);
}
static INLINE BOOL update_read_2byte_unsigned(wStream* s, UINT32* value)
{
BYTE byte;
if (Stream_GetRemainingLength(s) < 1)
return FALSE;
Stream_Read_UINT8(s, byte);
if (byte & 0x80)
{
if (Stream_GetRemainingLength(s) < 1)
return FALSE;
*value = (byte & 0x7F) << 8;
Stream_Read_UINT8(s, byte);
*value |= byte;
}
else
{
*value = (byte & 0x7F);
}
return TRUE;
}
static INLINE BOOL update_write_2byte_unsigned(wStream* s, UINT32 value)
{
BYTE byte;
if (value > 0x7FFF)
return FALSE;
if (value >= 0x7F)
{
byte = ((value & 0x7F00) >> 8);
Stream_Write_UINT8(s, byte | 0x80);
byte = (value & 0xFF);
Stream_Write_UINT8(s, byte);
}
else
{
byte = (value & 0x7F);
Stream_Write_UINT8(s, byte);
}
return TRUE;
}
static INLINE BOOL update_read_2byte_signed(wStream* s, INT32* value)
{
BYTE byte;
BOOL negative;
if (Stream_GetRemainingLength(s) < 1)
return FALSE;
Stream_Read_UINT8(s, byte);
negative = (byte & 0x40) ? TRUE : FALSE;
*value = (byte & 0x3F);
if (byte & 0x80)
{
if (Stream_GetRemainingLength(s) < 1)
return FALSE;
Stream_Read_UINT8(s, byte);
*value = (*value << 8) | byte;
}
if (negative)
*value *= -1;
return TRUE;
}
static INLINE BOOL update_write_2byte_signed(wStream* s, INT32 value)
{
BYTE byte;
BOOL negative = FALSE;
if (value < 0)
{
negative = TRUE;
value *= -1;
}
if (value > 0x3FFF)
return FALSE;
if (value >= 0x3F)
{
byte = ((value & 0x3F00) >> 8);
if (negative)
byte |= 0x40;
Stream_Write_UINT8(s, byte | 0x80);
byte = (value & 0xFF);
Stream_Write_UINT8(s, byte);
}
else
{
byte = (value & 0x3F);
if (negative)
byte |= 0x40;
Stream_Write_UINT8(s, byte);
}
return TRUE;
}
static INLINE BOOL update_read_4byte_unsigned(wStream* s, UINT32* value)
{
BYTE byte;
BYTE count;
if (Stream_GetRemainingLength(s) < 1)
return FALSE;
Stream_Read_UINT8(s, byte);
count = (byte & 0xC0) >> 6;
if (Stream_GetRemainingLength(s) < count)
return FALSE;
switch (count)
{
case 0:
*value = (byte & 0x3F);
break;
case 1:
*value = (byte & 0x3F) << 8;
Stream_Read_UINT8(s, byte);
*value |= byte;
break;
case 2:
*value = (byte & 0x3F) << 16;
Stream_Read_UINT8(s, byte);
*value |= (byte << 8);
Stream_Read_UINT8(s, byte);
*value |= byte;
break;
case 3:
*value = (byte & 0x3F) << 24;
Stream_Read_UINT8(s, byte);
*value |= (byte << 16);
Stream_Read_UINT8(s, byte);
*value |= (byte << 8);
Stream_Read_UINT8(s, byte);
*value |= byte;
break;
default:
break;
}
return TRUE;
}
static INLINE BOOL update_write_4byte_unsigned(wStream* s, UINT32 value)
{
BYTE byte;
if (value <= 0x3F)
{
Stream_Write_UINT8(s, value);
}
else if (value <= 0x3FFF)
{
byte = (value >> 8) & 0x3F;
Stream_Write_UINT8(s, byte | 0x40);
byte = (value & 0xFF);
Stream_Write_UINT8(s, byte);
}
else if (value <= 0x3FFFFF)
{
byte = (value >> 16) & 0x3F;
Stream_Write_UINT8(s, byte | 0x80);
byte = (value >> 8) & 0xFF;
Stream_Write_UINT8(s, byte);
byte = (value & 0xFF);
Stream_Write_UINT8(s, byte);
}
else if (value <= 0x3FFFFFFF)
{
byte = (value >> 24) & 0x3F;
Stream_Write_UINT8(s, byte | 0xC0);
byte = (value >> 16) & 0xFF;
Stream_Write_UINT8(s, byte);
byte = (value >> 8) & 0xFF;
Stream_Write_UINT8(s, byte);
byte = (value & 0xFF);
Stream_Write_UINT8(s, byte);
}
else
return FALSE;
return TRUE;
}
static INLINE BOOL update_read_delta(wStream* s, INT32* value)
{
BYTE byte;
if (Stream_GetRemainingLength(s) < 1)
{
WLog_ERR(TAG, "Stream_GetRemainingLength(s) < 1");
return FALSE;
}
Stream_Read_UINT8(s, byte);
if (byte & 0x40)
*value = (byte | ~0x3F);
else
*value = (byte & 0x3F);
if (byte & 0x80)
{
if (Stream_GetRemainingLength(s) < 1)
{
WLog_ERR(TAG, "Stream_GetRemainingLength(s) < 1");
return FALSE;
}
Stream_Read_UINT8(s, byte);
*value = (*value << 8) | byte;
}
return TRUE;
}
#if 0
static INLINE void update_read_glyph_delta(wStream* s, UINT16* value)
{
BYTE byte;
Stream_Read_UINT8(s, byte);
if (byte == 0x80)
Stream_Read_UINT16(s, *value);
else
*value = (byte & 0x3F);
}
static INLINE void update_seek_glyph_delta(wStream* s)
{
BYTE byte;
Stream_Read_UINT8(s, byte);
if (byte & 0x80)
Stream_Seek_UINT8(s);
}
#endif
static INLINE BOOL update_read_brush(wStream* s, rdpBrush* brush, BYTE fieldFlags)
{
if (fieldFlags & ORDER_FIELD_01)
{
if (Stream_GetRemainingLength(s) < 1)
return FALSE;
Stream_Read_UINT8(s, brush->x);
}
if (fieldFlags & ORDER_FIELD_02)
{
if (Stream_GetRemainingLength(s) < 1)
return FALSE;
Stream_Read_UINT8(s, brush->y);
}
if (fieldFlags & ORDER_FIELD_03)
{
if (Stream_GetRemainingLength(s) < 1)
return FALSE;
Stream_Read_UINT8(s, brush->style);
}
if (fieldFlags & ORDER_FIELD_04)
{
if (Stream_GetRemainingLength(s) < 1)
return FALSE;
Stream_Read_UINT8(s, brush->hatch);
}
if (brush->style & CACHED_BRUSH)
{
brush->index = brush->hatch;
brush->bpp = BMF_BPP[brush->style & 0x07];
if (brush->bpp == 0)
brush->bpp = 1;
}
if (fieldFlags & ORDER_FIELD_05)
{
if (Stream_GetRemainingLength(s) < 7)
return FALSE;
brush->data = (BYTE*)brush->p8x8;
Stream_Read_UINT8(s, brush->data[7]);
Stream_Read_UINT8(s, brush->data[6]);
Stream_Read_UINT8(s, brush->data[5]);
Stream_Read_UINT8(s, brush->data[4]);
Stream_Read_UINT8(s, brush->data[3]);
Stream_Read_UINT8(s, brush->data[2]);
Stream_Read_UINT8(s, brush->data[1]);
brush->data[0] = brush->hatch;
}
return TRUE;
}
static INLINE BOOL update_write_brush(wStream* s, rdpBrush* brush, BYTE fieldFlags)
{
if (fieldFlags & ORDER_FIELD_01)
{
Stream_Write_UINT8(s, brush->x);
}
if (fieldFlags & ORDER_FIELD_02)
{
Stream_Write_UINT8(s, brush->y);
}
if (fieldFlags & ORDER_FIELD_03)
{
Stream_Write_UINT8(s, brush->style);
}
if (brush->style & CACHED_BRUSH)
{
brush->hatch = brush->index;
brush->bpp = BMF_BPP[brush->style & 0x07];
if (brush->bpp == 0)
brush->bpp = 1;
}
if (fieldFlags & ORDER_FIELD_04)
{
Stream_Write_UINT8(s, brush->hatch);
}
if (fieldFlags & ORDER_FIELD_05)
{
brush->data = (BYTE*)brush->p8x8;
Stream_Write_UINT8(s, brush->data[7]);
Stream_Write_UINT8(s, brush->data[6]);
Stream_Write_UINT8(s, brush->data[5]);
Stream_Write_UINT8(s, brush->data[4]);
Stream_Write_UINT8(s, brush->data[3]);
Stream_Write_UINT8(s, brush->data[2]);
Stream_Write_UINT8(s, brush->data[1]);
brush->data[0] = brush->hatch;
}
return TRUE;
}
static INLINE BOOL update_read_delta_rects(wStream* s, DELTA_RECT* rectangles, UINT32* nr)
{
UINT32 number = *nr;
UINT32 i;
BYTE flags = 0;
BYTE* zeroBits;
UINT32 zeroBitsSize;
if (number > 45)
{
WLog_WARN(TAG, "Invalid number of delta rectangles %" PRIu32, number);
return FALSE;
}
zeroBitsSize = ((number + 1) / 2);
if (Stream_GetRemainingLength(s) < zeroBitsSize)
return FALSE;
Stream_GetPointer(s, zeroBits);
Stream_Seek(s, zeroBitsSize);
ZeroMemory(rectangles, sizeof(DELTA_RECT) * number);
for (i = 0; i < number; i++)
{
if (i % 2 == 0)
flags = zeroBits[i / 2];
if ((~flags & 0x80) && !update_read_delta(s, &rectangles[i].left))
return FALSE;
if ((~flags & 0x40) && !update_read_delta(s, &rectangles[i].top))
return FALSE;
if (~flags & 0x20)
{
if (!update_read_delta(s, &rectangles[i].width))
return FALSE;
}
else if (i > 0)
rectangles[i].width = rectangles[i - 1].width;
else
rectangles[i].width = 0;
if (~flags & 0x10)
{
if (!update_read_delta(s, &rectangles[i].height))
return FALSE;
}
else if (i > 0)
rectangles[i].height = rectangles[i - 1].height;
else
rectangles[i].height = 0;
if (i > 0)
{
rectangles[i].left += rectangles[i - 1].left;
rectangles[i].top += rectangles[i - 1].top;
}
flags <<= 4;
}
return TRUE;
}
static INLINE BOOL update_read_delta_points(wStream* s, DELTA_POINT* points, int number, INT16 x,
INT16 y)
{
int i;
BYTE flags = 0;
BYTE* zeroBits;
UINT32 zeroBitsSize;
zeroBitsSize = ((number + 3) / 4);
if (Stream_GetRemainingLength(s) < zeroBitsSize)
{
WLog_ERR(TAG, "Stream_GetRemainingLength(s) < %" PRIu32 "", zeroBitsSize);
return FALSE;
}
Stream_GetPointer(s, zeroBits);
Stream_Seek(s, zeroBitsSize);
ZeroMemory(points, sizeof(DELTA_POINT) * number);
for (i = 0; i < number; i++)
{
if (i % 4 == 0)
flags = zeroBits[i / 4];
if ((~flags & 0x80) && !update_read_delta(s, &points[i].x))
{
WLog_ERR(TAG, "update_read_delta(x) failed");
return FALSE;
}
if ((~flags & 0x40) && !update_read_delta(s, &points[i].y))
{
WLog_ERR(TAG, "update_read_delta(y) failed");
return FALSE;
}
flags <<= 2;
}
return TRUE;
}
#define ORDER_FIELD_BYTE(NO, TARGET) \
do \
{ \
if (orderInfo->fieldFlags & (1 << (NO - 1))) \
{ \
if (Stream_GetRemainingLength(s) < 1) \
{ \
WLog_ERR(TAG, "error reading %s", #TARGET); \
return FALSE; \
} \
Stream_Read_UINT8(s, TARGET); \
} \
} while (0)
#define ORDER_FIELD_2BYTE(NO, TARGET1, TARGET2) \
do \
{ \
if (orderInfo->fieldFlags & (1 << (NO - 1))) \
{ \
if (Stream_GetRemainingLength(s) < 2) \
{ \
WLog_ERR(TAG, "error reading %s or %s", #TARGET1, #TARGET2); \
return FALSE; \
} \
Stream_Read_UINT8(s, TARGET1); \
Stream_Read_UINT8(s, TARGET2); \
} \
} while (0)
#define ORDER_FIELD_UINT16(NO, TARGET) \
do \
{ \
if (orderInfo->fieldFlags & (1 << (NO - 1))) \
{ \
if (Stream_GetRemainingLength(s) < 2) \
{ \
WLog_ERR(TAG, "error reading %s", #TARGET); \
return FALSE; \
} \
Stream_Read_UINT16(s, TARGET); \
} \
} while (0)
#define ORDER_FIELD_UINT32(NO, TARGET) \
do \
{ \
if (orderInfo->fieldFlags & (1 << (NO - 1))) \
{ \
if (Stream_GetRemainingLength(s) < 4) \
{ \
WLog_ERR(TAG, "error reading %s", #TARGET); \
return FALSE; \
} \
Stream_Read_UINT32(s, TARGET); \
} \
} while (0)
#define ORDER_FIELD_COORD(NO, TARGET) \
do \
{ \
if ((orderInfo->fieldFlags & (1 << (NO - 1))) && \
!update_read_coord(s, &TARGET, orderInfo->deltaCoordinates)) \
{ \
WLog_ERR(TAG, "error reading %s", #TARGET); \
return FALSE; \
} \
} while (0)
static INLINE BOOL ORDER_FIELD_COLOR(const ORDER_INFO* orderInfo, wStream* s, UINT32 NO,
UINT32* TARGET)
{
if (!TARGET || !orderInfo)
return FALSE;
if ((orderInfo->fieldFlags & (1 << (NO - 1))) && !update_read_color(s, TARGET))
return FALSE;
return TRUE;
}
static INLINE BOOL FIELD_SKIP_BUFFER16(wStream* s, UINT32 TARGET_LEN)
{
if (Stream_GetRemainingLength(s) < 2)
return FALSE;
Stream_Read_UINT16(s, TARGET_LEN);
if (!Stream_SafeSeek(s, TARGET_LEN))
{
WLog_ERR(TAG, "error skipping %" PRIu32 " bytes", TARGET_LEN);
return FALSE;
}
return TRUE;
}
/* Primary Drawing Orders */
static BOOL update_read_dstblt_order(wStream* s, const ORDER_INFO* orderInfo, DSTBLT_ORDER* dstblt)
{
ORDER_FIELD_COORD(1, dstblt->nLeftRect);
ORDER_FIELD_COORD(2, dstblt->nTopRect);
ORDER_FIELD_COORD(3, dstblt->nWidth);
ORDER_FIELD_COORD(4, dstblt->nHeight);
ORDER_FIELD_BYTE(5, dstblt->bRop);
return TRUE;
}
int update_approximate_dstblt_order(ORDER_INFO* orderInfo, const DSTBLT_ORDER* dstblt)
{
return 32;
}
BOOL update_write_dstblt_order(wStream* s, ORDER_INFO* orderInfo, const DSTBLT_ORDER* dstblt)
{
if (!Stream_EnsureRemainingCapacity(s, update_approximate_dstblt_order(orderInfo, dstblt)))
return FALSE;
orderInfo->fieldFlags = 0;
orderInfo->fieldFlags |= ORDER_FIELD_01;
update_write_coord(s, dstblt->nLeftRect);
orderInfo->fieldFlags |= ORDER_FIELD_02;
update_write_coord(s, dstblt->nTopRect);
orderInfo->fieldFlags |= ORDER_FIELD_03;
update_write_coord(s, dstblt->nWidth);
orderInfo->fieldFlags |= ORDER_FIELD_04;
update_write_coord(s, dstblt->nHeight);
orderInfo->fieldFlags |= ORDER_FIELD_05;
Stream_Write_UINT8(s, dstblt->bRop);
return TRUE;
}
static BOOL update_read_patblt_order(wStream* s, const ORDER_INFO* orderInfo, PATBLT_ORDER* patblt)
{
ORDER_FIELD_COORD(1, patblt->nLeftRect);
ORDER_FIELD_COORD(2, patblt->nTopRect);
ORDER_FIELD_COORD(3, patblt->nWidth);
ORDER_FIELD_COORD(4, patblt->nHeight);
ORDER_FIELD_BYTE(5, patblt->bRop);
ORDER_FIELD_COLOR(orderInfo, s, 6, &patblt->backColor);
ORDER_FIELD_COLOR(orderInfo, s, 7, &patblt->foreColor);
return update_read_brush(s, &patblt->brush, orderInfo->fieldFlags >> 7);
}
int update_approximate_patblt_order(ORDER_INFO* orderInfo, PATBLT_ORDER* patblt)
{
return 32;
}
BOOL update_write_patblt_order(wStream* s, ORDER_INFO* orderInfo, PATBLT_ORDER* patblt)
{
if (!Stream_EnsureRemainingCapacity(s, update_approximate_patblt_order(orderInfo, patblt)))
return FALSE;
orderInfo->fieldFlags = 0;
orderInfo->fieldFlags |= ORDER_FIELD_01;
update_write_coord(s, patblt->nLeftRect);
orderInfo->fieldFlags |= ORDER_FIELD_02;
update_write_coord(s, patblt->nTopRect);
orderInfo->fieldFlags |= ORDER_FIELD_03;
update_write_coord(s, patblt->nWidth);
orderInfo->fieldFlags |= ORDER_FIELD_04;
update_write_coord(s, patblt->nHeight);
orderInfo->fieldFlags |= ORDER_FIELD_05;
Stream_Write_UINT8(s, patblt->bRop);
orderInfo->fieldFlags |= ORDER_FIELD_06;
update_write_color(s, patblt->backColor);
orderInfo->fieldFlags |= ORDER_FIELD_07;
update_write_color(s, patblt->foreColor);
orderInfo->fieldFlags |= ORDER_FIELD_08;
orderInfo->fieldFlags |= ORDER_FIELD_09;
orderInfo->fieldFlags |= ORDER_FIELD_10;
orderInfo->fieldFlags |= ORDER_FIELD_11;
orderInfo->fieldFlags |= ORDER_FIELD_12;
update_write_brush(s, &patblt->brush, orderInfo->fieldFlags >> 7);
return TRUE;
}
static BOOL update_read_scrblt_order(wStream* s, const ORDER_INFO* orderInfo, SCRBLT_ORDER* scrblt)
{
ORDER_FIELD_COORD(1, scrblt->nLeftRect);
ORDER_FIELD_COORD(2, scrblt->nTopRect);
ORDER_FIELD_COORD(3, scrblt->nWidth);
ORDER_FIELD_COORD(4, scrblt->nHeight);
ORDER_FIELD_BYTE(5, scrblt->bRop);
ORDER_FIELD_COORD(6, scrblt->nXSrc);
ORDER_FIELD_COORD(7, scrblt->nYSrc);
return TRUE;
}
int update_approximate_scrblt_order(ORDER_INFO* orderInfo, const SCRBLT_ORDER* scrblt)
{
return 32;
}
BOOL update_write_scrblt_order(wStream* s, ORDER_INFO* orderInfo, const SCRBLT_ORDER* scrblt)
{
if (!Stream_EnsureRemainingCapacity(s, update_approximate_scrblt_order(orderInfo, scrblt)))
return FALSE;
orderInfo->fieldFlags = 0;
orderInfo->fieldFlags |= ORDER_FIELD_01;
update_write_coord(s, scrblt->nLeftRect);
orderInfo->fieldFlags |= ORDER_FIELD_02;
update_write_coord(s, scrblt->nTopRect);
orderInfo->fieldFlags |= ORDER_FIELD_03;
update_write_coord(s, scrblt->nWidth);
orderInfo->fieldFlags |= ORDER_FIELD_04;
update_write_coord(s, scrblt->nHeight);
orderInfo->fieldFlags |= ORDER_FIELD_05;
Stream_Write_UINT8(s, scrblt->bRop);
orderInfo->fieldFlags |= ORDER_FIELD_06;
update_write_coord(s, scrblt->nXSrc);
orderInfo->fieldFlags |= ORDER_FIELD_07;
update_write_coord(s, scrblt->nYSrc);
return TRUE;
}
static BOOL update_read_opaque_rect_order(wStream* s, const ORDER_INFO* orderInfo,
OPAQUE_RECT_ORDER* opaque_rect)
{
BYTE byte;
ORDER_FIELD_COORD(1, opaque_rect->nLeftRect);
ORDER_FIELD_COORD(2, opaque_rect->nTopRect);
ORDER_FIELD_COORD(3, opaque_rect->nWidth);
ORDER_FIELD_COORD(4, opaque_rect->nHeight);
if (orderInfo->fieldFlags & ORDER_FIELD_05)
{
if (Stream_GetRemainingLength(s) < 1)
return FALSE;
Stream_Read_UINT8(s, byte);
opaque_rect->color = (opaque_rect->color & 0x00FFFF00) | ((UINT32)byte);
}
if (orderInfo->fieldFlags & ORDER_FIELD_06)
{
if (Stream_GetRemainingLength(s) < 1)
return FALSE;
Stream_Read_UINT8(s, byte);
opaque_rect->color = (opaque_rect->color & 0x00FF00FF) | ((UINT32)byte << 8);
}
if (orderInfo->fieldFlags & ORDER_FIELD_07)
{
if (Stream_GetRemainingLength(s) < 1)
return FALSE;
Stream_Read_UINT8(s, byte);
opaque_rect->color = (opaque_rect->color & 0x0000FFFF) | ((UINT32)byte << 16);
}
return TRUE;
}
int update_approximate_opaque_rect_order(ORDER_INFO* orderInfo,
const OPAQUE_RECT_ORDER* opaque_rect)
{
return 32;
}
BOOL update_write_opaque_rect_order(wStream* s, ORDER_INFO* orderInfo,
const OPAQUE_RECT_ORDER* opaque_rect)
{
BYTE byte;
int inf = update_approximate_opaque_rect_order(orderInfo, opaque_rect);
if (!Stream_EnsureRemainingCapacity(s, inf))
return FALSE;
// TODO: Color format conversion
orderInfo->fieldFlags = 0;
orderInfo->fieldFlags |= ORDER_FIELD_01;
update_write_coord(s, opaque_rect->nLeftRect);
orderInfo->fieldFlags |= ORDER_FIELD_02;
update_write_coord(s, opaque_rect->nTopRect);
orderInfo->fieldFlags |= ORDER_FIELD_03;
update_write_coord(s, opaque_rect->nWidth);
orderInfo->fieldFlags |= ORDER_FIELD_04;
update_write_coord(s, opaque_rect->nHeight);
orderInfo->fieldFlags |= ORDER_FIELD_05;
byte = opaque_rect->color & 0x000000FF;
Stream_Write_UINT8(s, byte);
orderInfo->fieldFlags |= ORDER_FIELD_06;
byte = (opaque_rect->color & 0x0000FF00) >> 8;
Stream_Write_UINT8(s, byte);
orderInfo->fieldFlags |= ORDER_FIELD_07;
byte = (opaque_rect->color & 0x00FF0000) >> 16;
Stream_Write_UINT8(s, byte);
return TRUE;
}
static BOOL update_read_draw_nine_grid_order(wStream* s, const ORDER_INFO* orderInfo,
DRAW_NINE_GRID_ORDER* draw_nine_grid)
{
ORDER_FIELD_COORD(1, draw_nine_grid->srcLeft);
ORDER_FIELD_COORD(2, draw_nine_grid->srcTop);
ORDER_FIELD_COORD(3, draw_nine_grid->srcRight);
ORDER_FIELD_COORD(4, draw_nine_grid->srcBottom);
ORDER_FIELD_UINT16(5, draw_nine_grid->bitmapId);
return TRUE;
}
static BOOL update_read_multi_dstblt_order(wStream* s, const ORDER_INFO* orderInfo,
MULTI_DSTBLT_ORDER* multi_dstblt)
{
ORDER_FIELD_COORD(1, multi_dstblt->nLeftRect);
ORDER_FIELD_COORD(2, multi_dstblt->nTopRect);
ORDER_FIELD_COORD(3, multi_dstblt->nWidth);
ORDER_FIELD_COORD(4, multi_dstblt->nHeight);
ORDER_FIELD_BYTE(5, multi_dstblt->bRop);
ORDER_FIELD_BYTE(6, multi_dstblt->numRectangles);
if (orderInfo->fieldFlags & ORDER_FIELD_07)
{
if (Stream_GetRemainingLength(s) < 2)
return FALSE;
Stream_Read_UINT16(s, multi_dstblt->cbData);
return update_read_delta_rects(s, multi_dstblt->rectangles, &multi_dstblt->numRectangles);
}
return TRUE;
}
static BOOL update_read_multi_patblt_order(wStream* s, const ORDER_INFO* orderInfo,
MULTI_PATBLT_ORDER* multi_patblt)
{
ORDER_FIELD_COORD(1, multi_patblt->nLeftRect);
ORDER_FIELD_COORD(2, multi_patblt->nTopRect);
ORDER_FIELD_COORD(3, multi_patblt->nWidth);
ORDER_FIELD_COORD(4, multi_patblt->nHeight);
ORDER_FIELD_BYTE(5, multi_patblt->bRop);
ORDER_FIELD_COLOR(orderInfo, s, 6, &multi_patblt->backColor);
ORDER_FIELD_COLOR(orderInfo, s, 7, &multi_patblt->foreColor);
if (!update_read_brush(s, &multi_patblt->brush, orderInfo->fieldFlags >> 7))
return FALSE;
ORDER_FIELD_BYTE(13, multi_patblt->numRectangles);
if (orderInfo->fieldFlags & ORDER_FIELD_14)
{
if (Stream_GetRemainingLength(s) < 2)
return FALSE;
Stream_Read_UINT16(s, multi_patblt->cbData);
if (!update_read_delta_rects(s, multi_patblt->rectangles, &multi_patblt->numRectangles))
return FALSE;
}
return TRUE;
}
static BOOL update_read_multi_scrblt_order(wStream* s, const ORDER_INFO* orderInfo,
MULTI_SCRBLT_ORDER* multi_scrblt)
{
ORDER_FIELD_COORD(1, multi_scrblt->nLeftRect);
ORDER_FIELD_COORD(2, multi_scrblt->nTopRect);
ORDER_FIELD_COORD(3, multi_scrblt->nWidth);
ORDER_FIELD_COORD(4, multi_scrblt->nHeight);
ORDER_FIELD_BYTE(5, multi_scrblt->bRop);
ORDER_FIELD_COORD(6, multi_scrblt->nXSrc);
ORDER_FIELD_COORD(7, multi_scrblt->nYSrc);
ORDER_FIELD_BYTE(8, multi_scrblt->numRectangles);
if (orderInfo->fieldFlags & ORDER_FIELD_09)
{
if (Stream_GetRemainingLength(s) < 2)
return FALSE;
Stream_Read_UINT16(s, multi_scrblt->cbData);
return update_read_delta_rects(s, multi_scrblt->rectangles, &multi_scrblt->numRectangles);
}
return TRUE;
}
static BOOL update_read_multi_opaque_rect_order(wStream* s, const ORDER_INFO* orderInfo,
MULTI_OPAQUE_RECT_ORDER* multi_opaque_rect)
{
BYTE byte;
ORDER_FIELD_COORD(1, multi_opaque_rect->nLeftRect);
ORDER_FIELD_COORD(2, multi_opaque_rect->nTopRect);
ORDER_FIELD_COORD(3, multi_opaque_rect->nWidth);
ORDER_FIELD_COORD(4, multi_opaque_rect->nHeight);
if (orderInfo->fieldFlags & ORDER_FIELD_05)
{
if (Stream_GetRemainingLength(s) < 1)
return FALSE;
Stream_Read_UINT8(s, byte);
multi_opaque_rect->color = (multi_opaque_rect->color & 0x00FFFF00) | ((UINT32)byte);
}
if (orderInfo->fieldFlags & ORDER_FIELD_06)
{
if (Stream_GetRemainingLength(s) < 1)
return FALSE;
Stream_Read_UINT8(s, byte);
multi_opaque_rect->color = (multi_opaque_rect->color & 0x00FF00FF) | ((UINT32)byte << 8);
}
if (orderInfo->fieldFlags & ORDER_FIELD_07)
{
if (Stream_GetRemainingLength(s) < 1)
return FALSE;
Stream_Read_UINT8(s, byte);
multi_opaque_rect->color = (multi_opaque_rect->color & 0x0000FFFF) | ((UINT32)byte << 16);
}
ORDER_FIELD_BYTE(8, multi_opaque_rect->numRectangles);
if (orderInfo->fieldFlags & ORDER_FIELD_09)
{
if (Stream_GetRemainingLength(s) < 2)
return FALSE;
Stream_Read_UINT16(s, multi_opaque_rect->cbData);
return update_read_delta_rects(s, multi_opaque_rect->rectangles,
&multi_opaque_rect->numRectangles);
}
return TRUE;
}
static BOOL update_read_multi_draw_nine_grid_order(wStream* s, const ORDER_INFO* orderInfo,
MULTI_DRAW_NINE_GRID_ORDER* multi_draw_nine_grid)
{
ORDER_FIELD_COORD(1, multi_draw_nine_grid->srcLeft);
ORDER_FIELD_COORD(2, multi_draw_nine_grid->srcTop);
ORDER_FIELD_COORD(3, multi_draw_nine_grid->srcRight);
ORDER_FIELD_COORD(4, multi_draw_nine_grid->srcBottom);
ORDER_FIELD_UINT16(5, multi_draw_nine_grid->bitmapId);
ORDER_FIELD_BYTE(6, multi_draw_nine_grid->nDeltaEntries);
if (orderInfo->fieldFlags & ORDER_FIELD_07)
{
if (Stream_GetRemainingLength(s) < 2)
return FALSE;
Stream_Read_UINT16(s, multi_draw_nine_grid->cbData);
return update_read_delta_rects(s, multi_draw_nine_grid->rectangles,
&multi_draw_nine_grid->nDeltaEntries);
}
return TRUE;
}
static BOOL update_read_line_to_order(wStream* s, const ORDER_INFO* orderInfo,
LINE_TO_ORDER* line_to)
{
ORDER_FIELD_UINT16(1, line_to->backMode);
ORDER_FIELD_COORD(2, line_to->nXStart);
ORDER_FIELD_COORD(3, line_to->nYStart);
ORDER_FIELD_COORD(4, line_to->nXEnd);
ORDER_FIELD_COORD(5, line_to->nYEnd);
ORDER_FIELD_COLOR(orderInfo, s, 6, &line_to->backColor);
ORDER_FIELD_BYTE(7, line_to->bRop2);
ORDER_FIELD_BYTE(8, line_to->penStyle);
ORDER_FIELD_BYTE(9, line_to->penWidth);
ORDER_FIELD_COLOR(orderInfo, s, 10, &line_to->penColor);
return TRUE;
}
int update_approximate_line_to_order(ORDER_INFO* orderInfo, const LINE_TO_ORDER* line_to)
{
return 32;
}
BOOL update_write_line_to_order(wStream* s, ORDER_INFO* orderInfo, const LINE_TO_ORDER* line_to)
{
if (!Stream_EnsureRemainingCapacity(s, update_approximate_line_to_order(orderInfo, line_to)))
return FALSE;
orderInfo->fieldFlags = 0;
orderInfo->fieldFlags |= ORDER_FIELD_01;
Stream_Write_UINT16(s, line_to->backMode);
orderInfo->fieldFlags |= ORDER_FIELD_02;
update_write_coord(s, line_to->nXStart);
orderInfo->fieldFlags |= ORDER_FIELD_03;
update_write_coord(s, line_to->nYStart);
orderInfo->fieldFlags |= ORDER_FIELD_04;
update_write_coord(s, line_to->nXEnd);
orderInfo->fieldFlags |= ORDER_FIELD_05;
update_write_coord(s, line_to->nYEnd);
orderInfo->fieldFlags |= ORDER_FIELD_06;
update_write_color(s, line_to->backColor);
orderInfo->fieldFlags |= ORDER_FIELD_07;
Stream_Write_UINT8(s, line_to->bRop2);
orderInfo->fieldFlags |= ORDER_FIELD_08;
Stream_Write_UINT8(s, line_to->penStyle);
orderInfo->fieldFlags |= ORDER_FIELD_09;
Stream_Write_UINT8(s, line_to->penWidth);
orderInfo->fieldFlags |= ORDER_FIELD_10;
update_write_color(s, line_to->penColor);
return TRUE;
}
static BOOL update_read_polyline_order(wStream* s, const ORDER_INFO* orderInfo,
POLYLINE_ORDER* polyline)
{
UINT16 word;
UINT32 new_num = polyline->numDeltaEntries;
ORDER_FIELD_COORD(1, polyline->xStart);
ORDER_FIELD_COORD(2, polyline->yStart);
ORDER_FIELD_BYTE(3, polyline->bRop2);
ORDER_FIELD_UINT16(4, word);
ORDER_FIELD_COLOR(orderInfo, s, 5, &polyline->penColor);
ORDER_FIELD_BYTE(6, new_num);
if (orderInfo->fieldFlags & ORDER_FIELD_07)
{
DELTA_POINT* new_points;
if (new_num == 0)
return FALSE;
if (Stream_GetRemainingLength(s) < 1)
{
WLog_ERR(TAG, "Stream_GetRemainingLength(s) < 1");
return FALSE;
}
Stream_Read_UINT8(s, polyline->cbData);
new_points = (DELTA_POINT*)realloc(polyline->points, sizeof(DELTA_POINT) * new_num);
if (!new_points)
{
WLog_ERR(TAG, "realloc(%" PRIu32 ") failed", new_num);
return FALSE;
}
polyline->points = new_points;
polyline->numDeltaEntries = new_num;
return update_read_delta_points(s, polyline->points, polyline->numDeltaEntries,
polyline->xStart, polyline->yStart);
}
return TRUE;
}
static BOOL update_read_memblt_order(wStream* s, const ORDER_INFO* orderInfo, MEMBLT_ORDER* memblt)
{
if (!s || !orderInfo || !memblt)
return FALSE;
ORDER_FIELD_UINT16(1, memblt->cacheId);
ORDER_FIELD_COORD(2, memblt->nLeftRect);
ORDER_FIELD_COORD(3, memblt->nTopRect);
ORDER_FIELD_COORD(4, memblt->nWidth);
ORDER_FIELD_COORD(5, memblt->nHeight);
ORDER_FIELD_BYTE(6, memblt->bRop);
ORDER_FIELD_COORD(7, memblt->nXSrc);
ORDER_FIELD_COORD(8, memblt->nYSrc);
ORDER_FIELD_UINT16(9, memblt->cacheIndex);
memblt->colorIndex = (memblt->cacheId >> 8);
memblt->cacheId = (memblt->cacheId & 0xFF);
memblt->bitmap = NULL;
return TRUE;
}
int update_approximate_memblt_order(ORDER_INFO* orderInfo, const MEMBLT_ORDER* memblt)
{
return 64;
}
BOOL update_write_memblt_order(wStream* s, ORDER_INFO* orderInfo, const MEMBLT_ORDER* memblt)
{
UINT16 cacheId;
if (!Stream_EnsureRemainingCapacity(s, update_approximate_memblt_order(orderInfo, memblt)))
return FALSE;
cacheId = (memblt->cacheId & 0xFF) | ((memblt->colorIndex & 0xFF) << 8);
orderInfo->fieldFlags |= ORDER_FIELD_01;
Stream_Write_UINT16(s, cacheId);
orderInfo->fieldFlags |= ORDER_FIELD_02;
update_write_coord(s, memblt->nLeftRect);
orderInfo->fieldFlags |= ORDER_FIELD_03;
update_write_coord(s, memblt->nTopRect);
orderInfo->fieldFlags |= ORDER_FIELD_04;
update_write_coord(s, memblt->nWidth);
orderInfo->fieldFlags |= ORDER_FIELD_05;
update_write_coord(s, memblt->nHeight);
orderInfo->fieldFlags |= ORDER_FIELD_06;
Stream_Write_UINT8(s, memblt->bRop);
orderInfo->fieldFlags |= ORDER_FIELD_07;
update_write_coord(s, memblt->nXSrc);
orderInfo->fieldFlags |= ORDER_FIELD_08;
update_write_coord(s, memblt->nYSrc);
orderInfo->fieldFlags |= ORDER_FIELD_09;
Stream_Write_UINT16(s, memblt->cacheIndex);
return TRUE;
}
static BOOL update_read_mem3blt_order(wStream* s, const ORDER_INFO* orderInfo,
MEM3BLT_ORDER* mem3blt)
{
ORDER_FIELD_UINT16(1, mem3blt->cacheId);
ORDER_FIELD_COORD(2, mem3blt->nLeftRect);
ORDER_FIELD_COORD(3, mem3blt->nTopRect);
ORDER_FIELD_COORD(4, mem3blt->nWidth);
ORDER_FIELD_COORD(5, mem3blt->nHeight);
ORDER_FIELD_BYTE(6, mem3blt->bRop);
ORDER_FIELD_COORD(7, mem3blt->nXSrc);
ORDER_FIELD_COORD(8, mem3blt->nYSrc);
ORDER_FIELD_COLOR(orderInfo, s, 9, &mem3blt->backColor);
ORDER_FIELD_COLOR(orderInfo, s, 10, &mem3blt->foreColor);
if (!update_read_brush(s, &mem3blt->brush, orderInfo->fieldFlags >> 10))
return FALSE;
ORDER_FIELD_UINT16(16, mem3blt->cacheIndex);
mem3blt->colorIndex = (mem3blt->cacheId >> 8);
mem3blt->cacheId = (mem3blt->cacheId & 0xFF);
mem3blt->bitmap = NULL;
return TRUE;
}
static BOOL update_read_save_bitmap_order(wStream* s, const ORDER_INFO* orderInfo,
SAVE_BITMAP_ORDER* save_bitmap)
{
ORDER_FIELD_UINT32(1, save_bitmap->savedBitmapPosition);
ORDER_FIELD_COORD(2, save_bitmap->nLeftRect);
ORDER_FIELD_COORD(3, save_bitmap->nTopRect);
ORDER_FIELD_COORD(4, save_bitmap->nRightRect);
ORDER_FIELD_COORD(5, save_bitmap->nBottomRect);
ORDER_FIELD_BYTE(6, save_bitmap->operation);
return TRUE;
}
static BOOL update_read_glyph_index_order(wStream* s, const ORDER_INFO* orderInfo,
GLYPH_INDEX_ORDER* glyph_index)
{
ORDER_FIELD_BYTE(1, glyph_index->cacheId);
ORDER_FIELD_BYTE(2, glyph_index->flAccel);
ORDER_FIELD_BYTE(3, glyph_index->ulCharInc);
ORDER_FIELD_BYTE(4, glyph_index->fOpRedundant);
ORDER_FIELD_COLOR(orderInfo, s, 5, &glyph_index->backColor);
ORDER_FIELD_COLOR(orderInfo, s, 6, &glyph_index->foreColor);
ORDER_FIELD_UINT16(7, glyph_index->bkLeft);
ORDER_FIELD_UINT16(8, glyph_index->bkTop);
ORDER_FIELD_UINT16(9, glyph_index->bkRight);
ORDER_FIELD_UINT16(10, glyph_index->bkBottom);
ORDER_FIELD_UINT16(11, glyph_index->opLeft);
ORDER_FIELD_UINT16(12, glyph_index->opTop);
ORDER_FIELD_UINT16(13, glyph_index->opRight);
ORDER_FIELD_UINT16(14, glyph_index->opBottom);
if (!update_read_brush(s, &glyph_index->brush, orderInfo->fieldFlags >> 14))
return FALSE;
ORDER_FIELD_UINT16(20, glyph_index->x);
ORDER_FIELD_UINT16(21, glyph_index->y);
if (orderInfo->fieldFlags & ORDER_FIELD_22)
{
if (Stream_GetRemainingLength(s) < 1)
return FALSE;
Stream_Read_UINT8(s, glyph_index->cbData);
if (Stream_GetRemainingLength(s) < glyph_index->cbData)
return FALSE;
CopyMemory(glyph_index->data, Stream_Pointer(s), glyph_index->cbData);
Stream_Seek(s, glyph_index->cbData);
}
return TRUE;
}
int update_approximate_glyph_index_order(ORDER_INFO* orderInfo,
const GLYPH_INDEX_ORDER* glyph_index)
{
return 64;
}
BOOL update_write_glyph_index_order(wStream* s, ORDER_INFO* orderInfo,
GLYPH_INDEX_ORDER* glyph_index)
{
int inf = update_approximate_glyph_index_order(orderInfo, glyph_index);
if (!Stream_EnsureRemainingCapacity(s, inf))
return FALSE;
orderInfo->fieldFlags = 0;
orderInfo->fieldFlags |= ORDER_FIELD_01;
Stream_Write_UINT8(s, glyph_index->cacheId);
orderInfo->fieldFlags |= ORDER_FIELD_02;
Stream_Write_UINT8(s, glyph_index->flAccel);
orderInfo->fieldFlags |= ORDER_FIELD_03;
Stream_Write_UINT8(s, glyph_index->ulCharInc);
orderInfo->fieldFlags |= ORDER_FIELD_04;
Stream_Write_UINT8(s, glyph_index->fOpRedundant);
orderInfo->fieldFlags |= ORDER_FIELD_05;
update_write_color(s, glyph_index->backColor);
orderInfo->fieldFlags |= ORDER_FIELD_06;
update_write_color(s, glyph_index->foreColor);
orderInfo->fieldFlags |= ORDER_FIELD_07;
Stream_Write_UINT16(s, glyph_index->bkLeft);
orderInfo->fieldFlags |= ORDER_FIELD_08;
Stream_Write_UINT16(s, glyph_index->bkTop);
orderInfo->fieldFlags |= ORDER_FIELD_09;
Stream_Write_UINT16(s, glyph_index->bkRight);
orderInfo->fieldFlags |= ORDER_FIELD_10;
Stream_Write_UINT16(s, glyph_index->bkBottom);
orderInfo->fieldFlags |= ORDER_FIELD_11;
Stream_Write_UINT16(s, glyph_index->opLeft);
orderInfo->fieldFlags |= ORDER_FIELD_12;
Stream_Write_UINT16(s, glyph_index->opTop);
orderInfo->fieldFlags |= ORDER_FIELD_13;
Stream_Write_UINT16(s, glyph_index->opRight);
orderInfo->fieldFlags |= ORDER_FIELD_14;
Stream_Write_UINT16(s, glyph_index->opBottom);
orderInfo->fieldFlags |= ORDER_FIELD_15;
orderInfo->fieldFlags |= ORDER_FIELD_16;
orderInfo->fieldFlags |= ORDER_FIELD_17;
orderInfo->fieldFlags |= ORDER_FIELD_18;
orderInfo->fieldFlags |= ORDER_FIELD_19;
update_write_brush(s, &glyph_index->brush, orderInfo->fieldFlags >> 14);
orderInfo->fieldFlags |= ORDER_FIELD_20;
Stream_Write_UINT16(s, glyph_index->x);
orderInfo->fieldFlags |= ORDER_FIELD_21;
Stream_Write_UINT16(s, glyph_index->y);
orderInfo->fieldFlags |= ORDER_FIELD_22;
Stream_Write_UINT8(s, glyph_index->cbData);
Stream_Write(s, glyph_index->data, glyph_index->cbData);
return TRUE;
}
static BOOL update_read_fast_index_order(wStream* s, const ORDER_INFO* orderInfo,
FAST_INDEX_ORDER* fast_index)
{
ORDER_FIELD_BYTE(1, fast_index->cacheId);
ORDER_FIELD_2BYTE(2, fast_index->ulCharInc, fast_index->flAccel);
ORDER_FIELD_COLOR(orderInfo, s, 3, &fast_index->backColor);
ORDER_FIELD_COLOR(orderInfo, s, 4, &fast_index->foreColor);
ORDER_FIELD_COORD(5, fast_index->bkLeft);
ORDER_FIELD_COORD(6, fast_index->bkTop);
ORDER_FIELD_COORD(7, fast_index->bkRight);
ORDER_FIELD_COORD(8, fast_index->bkBottom);
ORDER_FIELD_COORD(9, fast_index->opLeft);
ORDER_FIELD_COORD(10, fast_index->opTop);
ORDER_FIELD_COORD(11, fast_index->opRight);
ORDER_FIELD_COORD(12, fast_index->opBottom);
ORDER_FIELD_COORD(13, fast_index->x);
ORDER_FIELD_COORD(14, fast_index->y);
if (orderInfo->fieldFlags & ORDER_FIELD_15)
{
if (Stream_GetRemainingLength(s) < 1)
return FALSE;
Stream_Read_UINT8(s, fast_index->cbData);
if (Stream_GetRemainingLength(s) < fast_index->cbData)
return FALSE;
CopyMemory(fast_index->data, Stream_Pointer(s), fast_index->cbData);
Stream_Seek(s, fast_index->cbData);
}
return TRUE;
}
static BOOL update_read_fast_glyph_order(wStream* s, const ORDER_INFO* orderInfo,
FAST_GLYPH_ORDER* fastGlyph)
{
GLYPH_DATA_V2* glyph = &fastGlyph->glyphData;
ORDER_FIELD_BYTE(1, fastGlyph->cacheId);
ORDER_FIELD_2BYTE(2, fastGlyph->ulCharInc, fastGlyph->flAccel);
ORDER_FIELD_COLOR(orderInfo, s, 3, &fastGlyph->backColor);
ORDER_FIELD_COLOR(orderInfo, s, 4, &fastGlyph->foreColor);
ORDER_FIELD_COORD(5, fastGlyph->bkLeft);
ORDER_FIELD_COORD(6, fastGlyph->bkTop);
ORDER_FIELD_COORD(7, fastGlyph->bkRight);
ORDER_FIELD_COORD(8, fastGlyph->bkBottom);
ORDER_FIELD_COORD(9, fastGlyph->opLeft);
ORDER_FIELD_COORD(10, fastGlyph->opTop);
ORDER_FIELD_COORD(11, fastGlyph->opRight);
ORDER_FIELD_COORD(12, fastGlyph->opBottom);
ORDER_FIELD_COORD(13, fastGlyph->x);
ORDER_FIELD_COORD(14, fastGlyph->y);
if (orderInfo->fieldFlags & ORDER_FIELD_15)
{
if (Stream_GetRemainingLength(s) < 1)
return FALSE;
Stream_Read_UINT8(s, fastGlyph->cbData);
if (Stream_GetRemainingLength(s) < fastGlyph->cbData)
return FALSE;
CopyMemory(fastGlyph->data, Stream_Pointer(s), fastGlyph->cbData);
if (Stream_GetRemainingLength(s) < fastGlyph->cbData)
return FALSE;
if (!Stream_SafeSeek(s, 1))
return FALSE;
if (fastGlyph->cbData > 1)
{
UINT32 new_cb;
/* parse optional glyph data */
glyph->cacheIndex = fastGlyph->data[0];
if (!update_read_2byte_signed(s, &glyph->x) ||
!update_read_2byte_signed(s, &glyph->y) ||
!update_read_2byte_unsigned(s, &glyph->cx) ||
!update_read_2byte_unsigned(s, &glyph->cy))
return FALSE;
glyph->cb = ((glyph->cx + 7) / 8) * glyph->cy;
glyph->cb += ((glyph->cb % 4) > 0) ? 4 - (glyph->cb % 4) : 0;
new_cb = ((glyph->cx + 7) / 8) * glyph->cy;
new_cb += ((new_cb % 4) > 0) ? 4 - (new_cb % 4) : 0;
if (fastGlyph->cbData < new_cb)
return FALSE;
if (new_cb > 0)
{
BYTE* new_aj;
new_aj = (BYTE*)realloc(glyph->aj, new_cb);
if (!new_aj)
return FALSE;
glyph->aj = new_aj;
glyph->cb = new_cb;
Stream_Read(s, glyph->aj, glyph->cb);
}
Stream_Seek(s, fastGlyph->cbData - new_cb);
}
}
return TRUE;
}
static BOOL update_read_polygon_sc_order(wStream* s, const ORDER_INFO* orderInfo,
POLYGON_SC_ORDER* polygon_sc)
{
UINT32 num = polygon_sc->numPoints;
ORDER_FIELD_COORD(1, polygon_sc->xStart);
ORDER_FIELD_COORD(2, polygon_sc->yStart);
ORDER_FIELD_BYTE(3, polygon_sc->bRop2);
ORDER_FIELD_BYTE(4, polygon_sc->fillMode);
ORDER_FIELD_COLOR(orderInfo, s, 5, &polygon_sc->brushColor);
ORDER_FIELD_BYTE(6, num);
if (orderInfo->fieldFlags & ORDER_FIELD_07)
{
DELTA_POINT* newpoints;
if (num == 0)
return FALSE;
if (Stream_GetRemainingLength(s) < 1)
return FALSE;
Stream_Read_UINT8(s, polygon_sc->cbData);
newpoints = (DELTA_POINT*)realloc(polygon_sc->points, sizeof(DELTA_POINT) * num);
if (!newpoints)
return FALSE;
polygon_sc->points = newpoints;
polygon_sc->numPoints = num;
return update_read_delta_points(s, polygon_sc->points, polygon_sc->numPoints,
polygon_sc->xStart, polygon_sc->yStart);
}
return TRUE;
}
static BOOL update_read_polygon_cb_order(wStream* s, const ORDER_INFO* orderInfo,
POLYGON_CB_ORDER* polygon_cb)
{
UINT32 num = polygon_cb->numPoints;
ORDER_FIELD_COORD(1, polygon_cb->xStart);
ORDER_FIELD_COORD(2, polygon_cb->yStart);
ORDER_FIELD_BYTE(3, polygon_cb->bRop2);
ORDER_FIELD_BYTE(4, polygon_cb->fillMode);
ORDER_FIELD_COLOR(orderInfo, s, 5, &polygon_cb->backColor);
ORDER_FIELD_COLOR(orderInfo, s, 6, &polygon_cb->foreColor);
if (!update_read_brush(s, &polygon_cb->brush, orderInfo->fieldFlags >> 6))
return FALSE;
ORDER_FIELD_BYTE(12, num);
if (orderInfo->fieldFlags & ORDER_FIELD_13)
{
DELTA_POINT* newpoints;
if (num == 0)
return FALSE;
if (Stream_GetRemainingLength(s) < 1)
return FALSE;
Stream_Read_UINT8(s, polygon_cb->cbData);
newpoints = (DELTA_POINT*)realloc(polygon_cb->points, sizeof(DELTA_POINT) * num);
if (!newpoints)
return FALSE;
polygon_cb->points = newpoints;
polygon_cb->numPoints = num;
if (!update_read_delta_points(s, polygon_cb->points, polygon_cb->numPoints,
polygon_cb->xStart, polygon_cb->yStart))
return FALSE;
}
polygon_cb->backMode = (polygon_cb->bRop2 & 0x80) ? BACKMODE_TRANSPARENT : BACKMODE_OPAQUE;
polygon_cb->bRop2 = (polygon_cb->bRop2 & 0x1F);
return TRUE;
}
static BOOL update_read_ellipse_sc_order(wStream* s, const ORDER_INFO* orderInfo,
ELLIPSE_SC_ORDER* ellipse_sc)
{
ORDER_FIELD_COORD(1, ellipse_sc->leftRect);
ORDER_FIELD_COORD(2, ellipse_sc->topRect);
ORDER_FIELD_COORD(3, ellipse_sc->rightRect);
ORDER_FIELD_COORD(4, ellipse_sc->bottomRect);
ORDER_FIELD_BYTE(5, ellipse_sc->bRop2);
ORDER_FIELD_BYTE(6, ellipse_sc->fillMode);
ORDER_FIELD_COLOR(orderInfo, s, 7, &ellipse_sc->color);
return TRUE;
}
static BOOL update_read_ellipse_cb_order(wStream* s, const ORDER_INFO* orderInfo,
ELLIPSE_CB_ORDER* ellipse_cb)
{
ORDER_FIELD_COORD(1, ellipse_cb->leftRect);
ORDER_FIELD_COORD(2, ellipse_cb->topRect);
ORDER_FIELD_COORD(3, ellipse_cb->rightRect);
ORDER_FIELD_COORD(4, ellipse_cb->bottomRect);
ORDER_FIELD_BYTE(5, ellipse_cb->bRop2);
ORDER_FIELD_BYTE(6, ellipse_cb->fillMode);
ORDER_FIELD_COLOR(orderInfo, s, 7, &ellipse_cb->backColor);
ORDER_FIELD_COLOR(orderInfo, s, 8, &ellipse_cb->foreColor);
return update_read_brush(s, &ellipse_cb->brush, orderInfo->fieldFlags >> 8);
}
/* Secondary Drawing Orders */
static CACHE_BITMAP_ORDER* update_read_cache_bitmap_order(rdpUpdate* update, wStream* s,
BOOL compressed, UINT16 flags)
{
CACHE_BITMAP_ORDER* cache_bitmap;
if (!update || !s)
return NULL;
cache_bitmap = calloc(1, sizeof(CACHE_BITMAP_ORDER));
if (!cache_bitmap)
goto fail;
if (Stream_GetRemainingLength(s) < 9)
goto fail;
Stream_Read_UINT8(s, cache_bitmap->cacheId); /* cacheId (1 byte) */
Stream_Seek_UINT8(s); /* pad1Octet (1 byte) */
Stream_Read_UINT8(s, cache_bitmap->bitmapWidth); /* bitmapWidth (1 byte) */
Stream_Read_UINT8(s, cache_bitmap->bitmapHeight); /* bitmapHeight (1 byte) */
Stream_Read_UINT8(s, cache_bitmap->bitmapBpp); /* bitmapBpp (1 byte) */
if ((cache_bitmap->bitmapBpp < 1) || (cache_bitmap->bitmapBpp > 32))
{
WLog_Print(update->log, WLOG_ERROR, "invalid bitmap bpp %" PRIu32 "",
cache_bitmap->bitmapBpp);
goto fail;
}
Stream_Read_UINT16(s, cache_bitmap->bitmapLength); /* bitmapLength (2 bytes) */
Stream_Read_UINT16(s, cache_bitmap->cacheIndex); /* cacheIndex (2 bytes) */
if (compressed)
{
if ((flags & NO_BITMAP_COMPRESSION_HDR) == 0)
{
BYTE* bitmapComprHdr = (BYTE*)&(cache_bitmap->bitmapComprHdr);
if (Stream_GetRemainingLength(s) < 8)
goto fail;
Stream_Read(s, bitmapComprHdr, 8); /* bitmapComprHdr (8 bytes) */
cache_bitmap->bitmapLength -= 8;
}
}
if (cache_bitmap->bitmapLength == 0)
goto fail;
if (Stream_GetRemainingLength(s) < cache_bitmap->bitmapLength)
goto fail;
cache_bitmap->bitmapDataStream = malloc(cache_bitmap->bitmapLength);
if (!cache_bitmap->bitmapDataStream)
goto fail;
Stream_Read(s, cache_bitmap->bitmapDataStream, cache_bitmap->bitmapLength);
cache_bitmap->compressed = compressed;
return cache_bitmap;
fail:
free_cache_bitmap_order(update->context, cache_bitmap);
return NULL;
}
int update_approximate_cache_bitmap_order(const CACHE_BITMAP_ORDER* cache_bitmap, BOOL compressed,
UINT16* flags)
{
return 64 + cache_bitmap->bitmapLength;
}
BOOL update_write_cache_bitmap_order(wStream* s, const CACHE_BITMAP_ORDER* cache_bitmap,
BOOL compressed, UINT16* flags)
{
UINT32 bitmapLength = cache_bitmap->bitmapLength;
int inf = update_approximate_cache_bitmap_order(cache_bitmap, compressed, flags);
if (!Stream_EnsureRemainingCapacity(s, inf))
return FALSE;
*flags = NO_BITMAP_COMPRESSION_HDR;
if ((*flags & NO_BITMAP_COMPRESSION_HDR) == 0)
bitmapLength += 8;
Stream_Write_UINT8(s, cache_bitmap->cacheId); /* cacheId (1 byte) */
Stream_Write_UINT8(s, 0); /* pad1Octet (1 byte) */
Stream_Write_UINT8(s, cache_bitmap->bitmapWidth); /* bitmapWidth (1 byte) */
Stream_Write_UINT8(s, cache_bitmap->bitmapHeight); /* bitmapHeight (1 byte) */
Stream_Write_UINT8(s, cache_bitmap->bitmapBpp); /* bitmapBpp (1 byte) */
Stream_Write_UINT16(s, bitmapLength); /* bitmapLength (2 bytes) */
Stream_Write_UINT16(s, cache_bitmap->cacheIndex); /* cacheIndex (2 bytes) */
if (compressed)
{
if ((*flags & NO_BITMAP_COMPRESSION_HDR) == 0)
{
BYTE* bitmapComprHdr = (BYTE*)&(cache_bitmap->bitmapComprHdr);
Stream_Write(s, bitmapComprHdr, 8); /* bitmapComprHdr (8 bytes) */
bitmapLength -= 8;
}
Stream_Write(s, cache_bitmap->bitmapDataStream, bitmapLength);
}
else
{
Stream_Write(s, cache_bitmap->bitmapDataStream, bitmapLength);
}
return TRUE;
}
static CACHE_BITMAP_V2_ORDER* update_read_cache_bitmap_v2_order(rdpUpdate* update, wStream* s,
BOOL compressed, UINT16 flags)
{
BYTE bitsPerPixelId;
CACHE_BITMAP_V2_ORDER* cache_bitmap_v2;
if (!update || !s)
return NULL;
cache_bitmap_v2 = calloc(1, sizeof(CACHE_BITMAP_V2_ORDER));
if (!cache_bitmap_v2)
goto fail;
cache_bitmap_v2->cacheId = flags & 0x0003;
cache_bitmap_v2->flags = (flags & 0xFF80) >> 7;
bitsPerPixelId = (flags & 0x0078) >> 3;
cache_bitmap_v2->bitmapBpp = CBR2_BPP[bitsPerPixelId];
if (cache_bitmap_v2->flags & CBR2_PERSISTENT_KEY_PRESENT)
{
if (Stream_GetRemainingLength(s) < 8)
goto fail;
Stream_Read_UINT32(s, cache_bitmap_v2->key1); /* key1 (4 bytes) */
Stream_Read_UINT32(s, cache_bitmap_v2->key2); /* key2 (4 bytes) */
}
if (cache_bitmap_v2->flags & CBR2_HEIGHT_SAME_AS_WIDTH)
{
if (!update_read_2byte_unsigned(s, &cache_bitmap_v2->bitmapWidth)) /* bitmapWidth */
goto fail;
cache_bitmap_v2->bitmapHeight = cache_bitmap_v2->bitmapWidth;
}
else
{
if (!update_read_2byte_unsigned(s, &cache_bitmap_v2->bitmapWidth) || /* bitmapWidth */
!update_read_2byte_unsigned(s, &cache_bitmap_v2->bitmapHeight)) /* bitmapHeight */
goto fail;
}
if (!update_read_4byte_unsigned(s, &cache_bitmap_v2->bitmapLength) || /* bitmapLength */
!update_read_2byte_unsigned(s, &cache_bitmap_v2->cacheIndex)) /* cacheIndex */
goto fail;
if (cache_bitmap_v2->flags & CBR2_DO_NOT_CACHE)
cache_bitmap_v2->cacheIndex = BITMAP_CACHE_WAITING_LIST_INDEX;
if (compressed)
{
if (!(cache_bitmap_v2->flags & CBR2_NO_BITMAP_COMPRESSION_HDR))
{
if (Stream_GetRemainingLength(s) < 8)
goto fail;
Stream_Read_UINT16(
s, cache_bitmap_v2->cbCompFirstRowSize); /* cbCompFirstRowSize (2 bytes) */
Stream_Read_UINT16(
s, cache_bitmap_v2->cbCompMainBodySize); /* cbCompMainBodySize (2 bytes) */
Stream_Read_UINT16(s, cache_bitmap_v2->cbScanWidth); /* cbScanWidth (2 bytes) */
Stream_Read_UINT16(
s, cache_bitmap_v2->cbUncompressedSize); /* cbUncompressedSize (2 bytes) */
cache_bitmap_v2->bitmapLength = cache_bitmap_v2->cbCompMainBodySize;
}
}
if (cache_bitmap_v2->bitmapLength == 0)
goto fail;
if (Stream_GetRemainingLength(s) < cache_bitmap_v2->bitmapLength)
goto fail;
if (cache_bitmap_v2->bitmapLength == 0)
goto fail;
cache_bitmap_v2->bitmapDataStream = malloc(cache_bitmap_v2->bitmapLength);
if (!cache_bitmap_v2->bitmapDataStream)
goto fail;
Stream_Read(s, cache_bitmap_v2->bitmapDataStream, cache_bitmap_v2->bitmapLength);
cache_bitmap_v2->compressed = compressed;
return cache_bitmap_v2;
fail:
free_cache_bitmap_v2_order(update->context, cache_bitmap_v2);
return NULL;
}
int update_approximate_cache_bitmap_v2_order(CACHE_BITMAP_V2_ORDER* cache_bitmap_v2,
BOOL compressed, UINT16* flags)
{
return 64 + cache_bitmap_v2->bitmapLength;
}
BOOL update_write_cache_bitmap_v2_order(wStream* s, CACHE_BITMAP_V2_ORDER* cache_bitmap_v2,
BOOL compressed, UINT16* flags)
{
BYTE bitsPerPixelId;
if (!Stream_EnsureRemainingCapacity(
s, update_approximate_cache_bitmap_v2_order(cache_bitmap_v2, compressed, flags)))
return FALSE;
bitsPerPixelId = BPP_CBR2[cache_bitmap_v2->bitmapBpp];
*flags = (cache_bitmap_v2->cacheId & 0x0003) | (bitsPerPixelId << 3) |
((cache_bitmap_v2->flags << 7) & 0xFF80);
if (cache_bitmap_v2->flags & CBR2_PERSISTENT_KEY_PRESENT)
{
Stream_Write_UINT32(s, cache_bitmap_v2->key1); /* key1 (4 bytes) */
Stream_Write_UINT32(s, cache_bitmap_v2->key2); /* key2 (4 bytes) */
}
if (cache_bitmap_v2->flags & CBR2_HEIGHT_SAME_AS_WIDTH)
{
if (!update_write_2byte_unsigned(s, cache_bitmap_v2->bitmapWidth)) /* bitmapWidth */
return FALSE;
}
else
{
if (!update_write_2byte_unsigned(s, cache_bitmap_v2->bitmapWidth) || /* bitmapWidth */
!update_write_2byte_unsigned(s, cache_bitmap_v2->bitmapHeight)) /* bitmapHeight */
return FALSE;
}
if (cache_bitmap_v2->flags & CBR2_DO_NOT_CACHE)
cache_bitmap_v2->cacheIndex = BITMAP_CACHE_WAITING_LIST_INDEX;
if (!update_write_4byte_unsigned(s, cache_bitmap_v2->bitmapLength) || /* bitmapLength */
!update_write_2byte_unsigned(s, cache_bitmap_v2->cacheIndex)) /* cacheIndex */
return FALSE;
if (compressed)
{
if (!(cache_bitmap_v2->flags & CBR2_NO_BITMAP_COMPRESSION_HDR))
{
Stream_Write_UINT16(
s, cache_bitmap_v2->cbCompFirstRowSize); /* cbCompFirstRowSize (2 bytes) */
Stream_Write_UINT16(
s, cache_bitmap_v2->cbCompMainBodySize); /* cbCompMainBodySize (2 bytes) */
Stream_Write_UINT16(s, cache_bitmap_v2->cbScanWidth); /* cbScanWidth (2 bytes) */
Stream_Write_UINT16(
s, cache_bitmap_v2->cbUncompressedSize); /* cbUncompressedSize (2 bytes) */
cache_bitmap_v2->bitmapLength = cache_bitmap_v2->cbCompMainBodySize;
}
if (!Stream_EnsureRemainingCapacity(s, cache_bitmap_v2->bitmapLength))
return FALSE;
Stream_Write(s, cache_bitmap_v2->bitmapDataStream, cache_bitmap_v2->bitmapLength);
}
else
{
if (!Stream_EnsureRemainingCapacity(s, cache_bitmap_v2->bitmapLength))
return FALSE;
Stream_Write(s, cache_bitmap_v2->bitmapDataStream, cache_bitmap_v2->bitmapLength);
}
cache_bitmap_v2->compressed = compressed;
return TRUE;
}
static CACHE_BITMAP_V3_ORDER* update_read_cache_bitmap_v3_order(rdpUpdate* update, wStream* s,
UINT16 flags)
{
BYTE bitsPerPixelId;
BITMAP_DATA_EX* bitmapData;
UINT32 new_len;
BYTE* new_data;
CACHE_BITMAP_V3_ORDER* cache_bitmap_v3;
if (!update || !s)
return NULL;
cache_bitmap_v3 = calloc(1, sizeof(CACHE_BITMAP_V3_ORDER));
if (!cache_bitmap_v3)
goto fail;
cache_bitmap_v3->cacheId = flags & 0x00000003;
cache_bitmap_v3->flags = (flags & 0x0000FF80) >> 7;
bitsPerPixelId = (flags & 0x00000078) >> 3;
cache_bitmap_v3->bpp = CBR23_BPP[bitsPerPixelId];
if (Stream_GetRemainingLength(s) < 21)
goto fail;
Stream_Read_UINT16(s, cache_bitmap_v3->cacheIndex); /* cacheIndex (2 bytes) */
Stream_Read_UINT32(s, cache_bitmap_v3->key1); /* key1 (4 bytes) */
Stream_Read_UINT32(s, cache_bitmap_v3->key2); /* key2 (4 bytes) */
bitmapData = &cache_bitmap_v3->bitmapData;
Stream_Read_UINT8(s, bitmapData->bpp);
if ((bitmapData->bpp < 1) || (bitmapData->bpp > 32))
{
WLog_Print(update->log, WLOG_ERROR, "invalid bpp value %" PRIu32 "", bitmapData->bpp);
goto fail;
}
Stream_Seek_UINT8(s); /* reserved1 (1 byte) */
Stream_Seek_UINT8(s); /* reserved2 (1 byte) */
Stream_Read_UINT8(s, bitmapData->codecID); /* codecID (1 byte) */
Stream_Read_UINT16(s, bitmapData->width); /* width (2 bytes) */
Stream_Read_UINT16(s, bitmapData->height); /* height (2 bytes) */
Stream_Read_UINT32(s, new_len); /* length (4 bytes) */
if ((new_len == 0) || (Stream_GetRemainingLength(s) < new_len))
goto fail;
new_data = (BYTE*)realloc(bitmapData->data, new_len);
if (!new_data)
goto fail;
bitmapData->data = new_data;
bitmapData->length = new_len;
Stream_Read(s, bitmapData->data, bitmapData->length);
return cache_bitmap_v3;
fail:
free_cache_bitmap_v3_order(update->context, cache_bitmap_v3);
return NULL;
}
int update_approximate_cache_bitmap_v3_order(CACHE_BITMAP_V3_ORDER* cache_bitmap_v3, UINT16* flags)
{
BITMAP_DATA_EX* bitmapData = &cache_bitmap_v3->bitmapData;
return 64 + bitmapData->length;
}
BOOL update_write_cache_bitmap_v3_order(wStream* s, CACHE_BITMAP_V3_ORDER* cache_bitmap_v3,
UINT16* flags)
{
BYTE bitsPerPixelId;
BITMAP_DATA_EX* bitmapData;
if (!Stream_EnsureRemainingCapacity(
s, update_approximate_cache_bitmap_v3_order(cache_bitmap_v3, flags)))
return FALSE;
bitmapData = &cache_bitmap_v3->bitmapData;
bitsPerPixelId = BPP_CBR23[cache_bitmap_v3->bpp];
*flags = (cache_bitmap_v3->cacheId & 0x00000003) |
((cache_bitmap_v3->flags << 7) & 0x0000FF80) | ((bitsPerPixelId << 3) & 0x00000078);
Stream_Write_UINT16(s, cache_bitmap_v3->cacheIndex); /* cacheIndex (2 bytes) */
Stream_Write_UINT32(s, cache_bitmap_v3->key1); /* key1 (4 bytes) */
Stream_Write_UINT32(s, cache_bitmap_v3->key2); /* key2 (4 bytes) */
Stream_Write_UINT8(s, bitmapData->bpp);
Stream_Write_UINT8(s, 0); /* reserved1 (1 byte) */
Stream_Write_UINT8(s, 0); /* reserved2 (1 byte) */
Stream_Write_UINT8(s, bitmapData->codecID); /* codecID (1 byte) */
Stream_Write_UINT16(s, bitmapData->width); /* width (2 bytes) */
Stream_Write_UINT16(s, bitmapData->height); /* height (2 bytes) */
Stream_Write_UINT32(s, bitmapData->length); /* length (4 bytes) */
Stream_Write(s, bitmapData->data, bitmapData->length);
return TRUE;
}
static CACHE_COLOR_TABLE_ORDER* update_read_cache_color_table_order(rdpUpdate* update, wStream* s,
UINT16 flags)
{
int i;
UINT32* colorTable;
CACHE_COLOR_TABLE_ORDER* cache_color_table = calloc(1, sizeof(CACHE_COLOR_TABLE_ORDER));
if (!cache_color_table)
goto fail;
if (Stream_GetRemainingLength(s) < 3)
goto fail;
Stream_Read_UINT8(s, cache_color_table->cacheIndex); /* cacheIndex (1 byte) */
Stream_Read_UINT16(s, cache_color_table->numberColors); /* numberColors (2 bytes) */
if (cache_color_table->numberColors != 256)
{
/* This field MUST be set to 256 */
goto fail;
}
if (Stream_GetRemainingLength(s) < cache_color_table->numberColors * 4)
goto fail;
colorTable = (UINT32*)&cache_color_table->colorTable;
for (i = 0; i < (int)cache_color_table->numberColors; i++)
update_read_color_quad(s, &colorTable[i]);
return cache_color_table;
fail:
free_cache_color_table_order(update->context, cache_color_table);
return NULL;
}
int update_approximate_cache_color_table_order(const CACHE_COLOR_TABLE_ORDER* cache_color_table,
UINT16* flags)
{
return 16 + (256 * 4);
}
BOOL update_write_cache_color_table_order(wStream* s,
const CACHE_COLOR_TABLE_ORDER* cache_color_table,
UINT16* flags)
{
int i, inf;
UINT32* colorTable;
if (cache_color_table->numberColors != 256)
return FALSE;
inf = update_approximate_cache_color_table_order(cache_color_table, flags);
if (!Stream_EnsureRemainingCapacity(s, inf))
return FALSE;
Stream_Write_UINT8(s, cache_color_table->cacheIndex); /* cacheIndex (1 byte) */
Stream_Write_UINT16(s, cache_color_table->numberColors); /* numberColors (2 bytes) */
colorTable = (UINT32*)&cache_color_table->colorTable;
for (i = 0; i < (int)cache_color_table->numberColors; i++)
{
update_write_color_quad(s, colorTable[i]);
}
return TRUE;
}
static CACHE_GLYPH_ORDER* update_read_cache_glyph_order(rdpUpdate* update, wStream* s, UINT16 flags)
{
UINT32 i;
CACHE_GLYPH_ORDER* cache_glyph_order = calloc(1, sizeof(CACHE_GLYPH_ORDER));
if (!cache_glyph_order || !update || !s)
goto fail;
if (Stream_GetRemainingLength(s) < 2)
goto fail;
Stream_Read_UINT8(s, cache_glyph_order->cacheId); /* cacheId (1 byte) */
Stream_Read_UINT8(s, cache_glyph_order->cGlyphs); /* cGlyphs (1 byte) */
for (i = 0; i < cache_glyph_order->cGlyphs; i++)
{
GLYPH_DATA* glyph = &cache_glyph_order->glyphData[i];
if (Stream_GetRemainingLength(s) < 10)
goto fail;
Stream_Read_UINT16(s, glyph->cacheIndex);
Stream_Read_INT16(s, glyph->x);
Stream_Read_INT16(s, glyph->y);
Stream_Read_UINT16(s, glyph->cx);
Stream_Read_UINT16(s, glyph->cy);
glyph->cb = ((glyph->cx + 7) / 8) * glyph->cy;
glyph->cb += ((glyph->cb % 4) > 0) ? 4 - (glyph->cb % 4) : 0;
if (Stream_GetRemainingLength(s) < glyph->cb)
goto fail;
glyph->aj = (BYTE*)malloc(glyph->cb);
if (!glyph->aj)
goto fail;
Stream_Read(s, glyph->aj, glyph->cb);
}
if ((flags & CG_GLYPH_UNICODE_PRESENT) && (cache_glyph_order->cGlyphs > 0))
{
cache_glyph_order->unicodeCharacters = calloc(cache_glyph_order->cGlyphs, sizeof(WCHAR));
if (!cache_glyph_order->unicodeCharacters)
goto fail;
if (Stream_GetRemainingLength(s) < sizeof(WCHAR) * cache_glyph_order->cGlyphs)
goto fail;
Stream_Read_UTF16_String(s, cache_glyph_order->unicodeCharacters,
cache_glyph_order->cGlyphs);
}
return cache_glyph_order;
fail:
free_cache_glyph_order(update->context, cache_glyph_order);
return NULL;
}
int update_approximate_cache_glyph_order(const CACHE_GLYPH_ORDER* cache_glyph, UINT16* flags)
{
return 2 + cache_glyph->cGlyphs * 32;
}
BOOL update_write_cache_glyph_order(wStream* s, const CACHE_GLYPH_ORDER* cache_glyph, UINT16* flags)
{
int i, inf;
INT16 lsi16;
const GLYPH_DATA* glyph;
inf = update_approximate_cache_glyph_order(cache_glyph, flags);
if (!Stream_EnsureRemainingCapacity(s, inf))
return FALSE;
Stream_Write_UINT8(s, cache_glyph->cacheId); /* cacheId (1 byte) */
Stream_Write_UINT8(s, cache_glyph->cGlyphs); /* cGlyphs (1 byte) */
for (i = 0; i < (int)cache_glyph->cGlyphs; i++)
{
UINT32 cb;
glyph = &cache_glyph->glyphData[i];
Stream_Write_UINT16(s, glyph->cacheIndex); /* cacheIndex (2 bytes) */
lsi16 = glyph->x;
Stream_Write_UINT16(s, lsi16); /* x (2 bytes) */
lsi16 = glyph->y;
Stream_Write_UINT16(s, lsi16); /* y (2 bytes) */
Stream_Write_UINT16(s, glyph->cx); /* cx (2 bytes) */
Stream_Write_UINT16(s, glyph->cy); /* cy (2 bytes) */
cb = ((glyph->cx + 7) / 8) * glyph->cy;
cb += ((cb % 4) > 0) ? 4 - (cb % 4) : 0;
Stream_Write(s, glyph->aj, cb);
}
if (*flags & CG_GLYPH_UNICODE_PRESENT)
{
Stream_Zero(s, cache_glyph->cGlyphs * 2);
}
return TRUE;
}
static CACHE_GLYPH_V2_ORDER* update_read_cache_glyph_v2_order(rdpUpdate* update, wStream* s,
UINT16 flags)
{
UINT32 i;
CACHE_GLYPH_V2_ORDER* cache_glyph_v2 = calloc(1, sizeof(CACHE_GLYPH_V2_ORDER));
if (!cache_glyph_v2)
goto fail;
cache_glyph_v2->cacheId = (flags & 0x000F);
cache_glyph_v2->flags = (flags & 0x00F0) >> 4;
cache_glyph_v2->cGlyphs = (flags & 0xFF00) >> 8;
for (i = 0; i < cache_glyph_v2->cGlyphs; i++)
{
GLYPH_DATA_V2* glyph = &cache_glyph_v2->glyphData[i];
if (Stream_GetRemainingLength(s) < 1)
goto fail;
Stream_Read_UINT8(s, glyph->cacheIndex);
if (!update_read_2byte_signed(s, &glyph->x) || !update_read_2byte_signed(s, &glyph->y) ||
!update_read_2byte_unsigned(s, &glyph->cx) ||
!update_read_2byte_unsigned(s, &glyph->cy))
{
goto fail;
}
glyph->cb = ((glyph->cx + 7) / 8) * glyph->cy;
glyph->cb += ((glyph->cb % 4) > 0) ? 4 - (glyph->cb % 4) : 0;
if (Stream_GetRemainingLength(s) < glyph->cb)
goto fail;
glyph->aj = (BYTE*)malloc(glyph->cb);
if (!glyph->aj)
goto fail;
Stream_Read(s, glyph->aj, glyph->cb);
}
if ((flags & CG_GLYPH_UNICODE_PRESENT) && (cache_glyph_v2->cGlyphs > 0))
{
cache_glyph_v2->unicodeCharacters = calloc(cache_glyph_v2->cGlyphs, sizeof(WCHAR));
if (!cache_glyph_v2->unicodeCharacters)
goto fail;
if (Stream_GetRemainingLength(s) < sizeof(WCHAR) * cache_glyph_v2->cGlyphs)
goto fail;
Stream_Read_UTF16_String(s, cache_glyph_v2->unicodeCharacters, cache_glyph_v2->cGlyphs);
}
return cache_glyph_v2;
fail:
free_cache_glyph_v2_order(update->context, cache_glyph_v2);
return NULL;
}
int update_approximate_cache_glyph_v2_order(const CACHE_GLYPH_V2_ORDER* cache_glyph_v2,
UINT16* flags)
{
return 8 + cache_glyph_v2->cGlyphs * 32;
}
BOOL update_write_cache_glyph_v2_order(wStream* s, const CACHE_GLYPH_V2_ORDER* cache_glyph_v2,
UINT16* flags)
{
UINT32 i, inf;
inf = update_approximate_cache_glyph_v2_order(cache_glyph_v2, flags);
if (!Stream_EnsureRemainingCapacity(s, inf))
return FALSE;
*flags = (cache_glyph_v2->cacheId & 0x000F) | ((cache_glyph_v2->flags & 0x000F) << 4) |
((cache_glyph_v2->cGlyphs & 0x00FF) << 8);
for (i = 0; i < cache_glyph_v2->cGlyphs; i++)
{
UINT32 cb;
const GLYPH_DATA_V2* glyph = &cache_glyph_v2->glyphData[i];
Stream_Write_UINT8(s, glyph->cacheIndex);
if (!update_write_2byte_signed(s, glyph->x) || !update_write_2byte_signed(s, glyph->y) ||
!update_write_2byte_unsigned(s, glyph->cx) ||
!update_write_2byte_unsigned(s, glyph->cy))
{
return FALSE;
}
cb = ((glyph->cx + 7) / 8) * glyph->cy;
cb += ((cb % 4) > 0) ? 4 - (cb % 4) : 0;
Stream_Write(s, glyph->aj, cb);
}
if (*flags & CG_GLYPH_UNICODE_PRESENT)
{
Stream_Zero(s, cache_glyph_v2->cGlyphs * 2);
}
return TRUE;
}
static BOOL update_decompress_brush(wStream* s, BYTE* output, size_t outSize, BYTE bpp)
{
INT32 x, y, k;
BYTE byte = 0;
const BYTE* palette = Stream_Pointer(s) + 16;
const INT32 bytesPerPixel = ((bpp + 1) / 8);
if (!Stream_SafeSeek(s, 16ULL + 7ULL * bytesPerPixel)) // 64 / 4
return FALSE;
for (y = 7; y >= 0; y--)
{
for (x = 0; x < 8; x++)
{
UINT32 index;
if ((x % 4) == 0)
Stream_Read_UINT8(s, byte);
index = ((byte >> ((3 - (x % 4)) * 2)) & 0x03);
for (k = 0; k < bytesPerPixel; k++)
{
const size_t dstIndex = ((y * 8 + x) * bytesPerPixel) + k;
const size_t srcIndex = (index * bytesPerPixel) + k;
if (dstIndex >= outSize)
return FALSE;
output[dstIndex] = palette[srcIndex];
}
}
}
return TRUE;
}
static BOOL update_compress_brush(wStream* s, const BYTE* input, BYTE bpp)
{
return FALSE;
}
static CACHE_BRUSH_ORDER* update_read_cache_brush_order(rdpUpdate* update, wStream* s, UINT16 flags)
{
int i;
BYTE iBitmapFormat;
BOOL compressed = FALSE;
CACHE_BRUSH_ORDER* cache_brush = calloc(1, sizeof(CACHE_BRUSH_ORDER));
if (!cache_brush)
goto fail;
if (Stream_GetRemainingLength(s) < 6)
goto fail;
Stream_Read_UINT8(s, cache_brush->index); /* cacheEntry (1 byte) */
Stream_Read_UINT8(s, iBitmapFormat); /* iBitmapFormat (1 byte) */
if (iBitmapFormat >= ARRAYSIZE(BMF_BPP))
goto fail;
cache_brush->bpp = BMF_BPP[iBitmapFormat];
Stream_Read_UINT8(s, cache_brush->cx); /* cx (1 byte) */
Stream_Read_UINT8(s, cache_brush->cy); /* cy (1 byte) */
Stream_Read_UINT8(s, cache_brush->style); /* style (1 byte) */
Stream_Read_UINT8(s, cache_brush->length); /* iBytes (1 byte) */
if ((cache_brush->cx == 8) && (cache_brush->cy == 8))
{
if (cache_brush->bpp == 1)
{
if (cache_brush->length != 8)
{
WLog_Print(update->log, WLOG_ERROR, "incompatible 1bpp brush of length:%" PRIu32 "",
cache_brush->length);
goto fail;
}
/* rows are encoded in reverse order */
if (Stream_GetRemainingLength(s) < 8)
goto fail;
for (i = 7; i >= 0; i--)
{
Stream_Read_UINT8(s, cache_brush->data[i]);
}
}
else
{
if ((iBitmapFormat == BMF_8BPP) && (cache_brush->length == 20))
compressed = TRUE;
else if ((iBitmapFormat == BMF_16BPP) && (cache_brush->length == 24))
compressed = TRUE;
else if ((iBitmapFormat == BMF_32BPP) && (cache_brush->length == 32))
compressed = TRUE;
if (compressed != FALSE)
{
/* compressed brush */
if (!update_decompress_brush(s, cache_brush->data, sizeof(cache_brush->data),
cache_brush->bpp))
goto fail;
}
else
{
/* uncompressed brush */
UINT32 scanline = (cache_brush->bpp / 8) * 8;
if (Stream_GetRemainingLength(s) < scanline * 8)
goto fail;
for (i = 7; i >= 0; i--)
{
Stream_Read(s, &cache_brush->data[i * scanline], scanline);
}
}
}
}
return cache_brush;
fail:
free_cache_brush_order(update->context, cache_brush);
return NULL;
}
int update_approximate_cache_brush_order(const CACHE_BRUSH_ORDER* cache_brush, UINT16* flags)
{
return 64;
}
BOOL update_write_cache_brush_order(wStream* s, const CACHE_BRUSH_ORDER* cache_brush, UINT16* flags)
{
int i;
BYTE iBitmapFormat;
BOOL compressed = FALSE;
if (!Stream_EnsureRemainingCapacity(s,
update_approximate_cache_brush_order(cache_brush, flags)))
return FALSE;
iBitmapFormat = BPP_BMF[cache_brush->bpp];
Stream_Write_UINT8(s, cache_brush->index); /* cacheEntry (1 byte) */
Stream_Write_UINT8(s, iBitmapFormat); /* iBitmapFormat (1 byte) */
Stream_Write_UINT8(s, cache_brush->cx); /* cx (1 byte) */
Stream_Write_UINT8(s, cache_brush->cy); /* cy (1 byte) */
Stream_Write_UINT8(s, cache_brush->style); /* style (1 byte) */
Stream_Write_UINT8(s, cache_brush->length); /* iBytes (1 byte) */
if ((cache_brush->cx == 8) && (cache_brush->cy == 8))
{
if (cache_brush->bpp == 1)
{
if (cache_brush->length != 8)
{
WLog_ERR(TAG, "incompatible 1bpp brush of length:%" PRIu32 "", cache_brush->length);
return FALSE;
}
for (i = 7; i >= 0; i--)
{
Stream_Write_UINT8(s, cache_brush->data[i]);
}
}
else
{
if ((iBitmapFormat == BMF_8BPP) && (cache_brush->length == 20))
compressed = TRUE;
else if ((iBitmapFormat == BMF_16BPP) && (cache_brush->length == 24))
compressed = TRUE;
else if ((iBitmapFormat == BMF_32BPP) && (cache_brush->length == 32))
compressed = TRUE;
if (compressed != FALSE)
{
/* compressed brush */
if (!update_compress_brush(s, cache_brush->data, cache_brush->bpp))
return FALSE;
}
else
{
/* uncompressed brush */
int scanline = (cache_brush->bpp / 8) * 8;
for (i = 7; i >= 0; i--)
{
Stream_Write(s, &cache_brush->data[i * scanline], scanline);
}
}
}
}
return TRUE;
}
/* Alternate Secondary Drawing Orders */
static BOOL
update_read_create_offscreen_bitmap_order(wStream* s,
CREATE_OFFSCREEN_BITMAP_ORDER* create_offscreen_bitmap)
{
UINT16 flags;
BOOL deleteListPresent;
OFFSCREEN_DELETE_LIST* deleteList;
if (Stream_GetRemainingLength(s) < 6)
return FALSE;
Stream_Read_UINT16(s, flags); /* flags (2 bytes) */
create_offscreen_bitmap->id = flags & 0x7FFF;
deleteListPresent = (flags & 0x8000) ? TRUE : FALSE;
Stream_Read_UINT16(s, create_offscreen_bitmap->cx); /* cx (2 bytes) */
Stream_Read_UINT16(s, create_offscreen_bitmap->cy); /* cy (2 bytes) */
deleteList = &(create_offscreen_bitmap->deleteList);
if (deleteListPresent)
{
UINT32 i;
if (Stream_GetRemainingLength(s) < 2)
return FALSE;
Stream_Read_UINT16(s, deleteList->cIndices);
if (deleteList->cIndices > deleteList->sIndices)
{
UINT16* new_indices;
new_indices = (UINT16*)realloc(deleteList->indices, deleteList->cIndices * 2);
if (!new_indices)
return FALSE;
deleteList->sIndices = deleteList->cIndices;
deleteList->indices = new_indices;
}
if (Stream_GetRemainingLength(s) < 2 * deleteList->cIndices)
return FALSE;
for (i = 0; i < deleteList->cIndices; i++)
{
Stream_Read_UINT16(s, deleteList->indices[i]);
}
}
else
{
deleteList->cIndices = 0;
}
return TRUE;
}
int update_approximate_create_offscreen_bitmap_order(
const CREATE_OFFSCREEN_BITMAP_ORDER* create_offscreen_bitmap)
{
const OFFSCREEN_DELETE_LIST* deleteList = &(create_offscreen_bitmap->deleteList);
return 32 + deleteList->cIndices * 2;
}
BOOL update_write_create_offscreen_bitmap_order(
wStream* s, const CREATE_OFFSCREEN_BITMAP_ORDER* create_offscreen_bitmap)
{
UINT16 flags;
BOOL deleteListPresent;
const OFFSCREEN_DELETE_LIST* deleteList;
if (!Stream_EnsureRemainingCapacity(
s, update_approximate_create_offscreen_bitmap_order(create_offscreen_bitmap)))
return FALSE;
deleteList = &(create_offscreen_bitmap->deleteList);
flags = create_offscreen_bitmap->id & 0x7FFF;
deleteListPresent = (deleteList->cIndices > 0) ? TRUE : FALSE;
if (deleteListPresent)
flags |= 0x8000;
Stream_Write_UINT16(s, flags); /* flags (2 bytes) */
Stream_Write_UINT16(s, create_offscreen_bitmap->cx); /* cx (2 bytes) */
Stream_Write_UINT16(s, create_offscreen_bitmap->cy); /* cy (2 bytes) */
if (deleteListPresent)
{
int i;
Stream_Write_UINT16(s, deleteList->cIndices);
for (i = 0; i < (int)deleteList->cIndices; i++)
{
Stream_Write_UINT16(s, deleteList->indices[i]);
}
}
return TRUE;
}
static BOOL update_read_switch_surface_order(wStream* s, SWITCH_SURFACE_ORDER* switch_surface)
{
if (Stream_GetRemainingLength(s) < 2)
return FALSE;
Stream_Read_UINT16(s, switch_surface->bitmapId); /* bitmapId (2 bytes) */
return TRUE;
}
int update_approximate_switch_surface_order(const SWITCH_SURFACE_ORDER* switch_surface)
{
return 2;
}
BOOL update_write_switch_surface_order(wStream* s, const SWITCH_SURFACE_ORDER* switch_surface)
{
int inf = update_approximate_switch_surface_order(switch_surface);
if (!Stream_EnsureRemainingCapacity(s, inf))
return FALSE;
Stream_Write_UINT16(s, switch_surface->bitmapId); /* bitmapId (2 bytes) */
return TRUE;
}
static BOOL
update_read_create_nine_grid_bitmap_order(wStream* s,
CREATE_NINE_GRID_BITMAP_ORDER* create_nine_grid_bitmap)
{
NINE_GRID_BITMAP_INFO* nineGridInfo;
if (Stream_GetRemainingLength(s) < 19)
return FALSE;
Stream_Read_UINT8(s, create_nine_grid_bitmap->bitmapBpp); /* bitmapBpp (1 byte) */
if ((create_nine_grid_bitmap->bitmapBpp < 1) || (create_nine_grid_bitmap->bitmapBpp > 32))
{
WLog_ERR(TAG, "invalid bpp value %" PRIu32 "", create_nine_grid_bitmap->bitmapBpp);
return FALSE;
}
Stream_Read_UINT16(s, create_nine_grid_bitmap->bitmapId); /* bitmapId (2 bytes) */
nineGridInfo = &(create_nine_grid_bitmap->nineGridInfo);
Stream_Read_UINT32(s, nineGridInfo->flFlags); /* flFlags (4 bytes) */
Stream_Read_UINT16(s, nineGridInfo->ulLeftWidth); /* ulLeftWidth (2 bytes) */
Stream_Read_UINT16(s, nineGridInfo->ulRightWidth); /* ulRightWidth (2 bytes) */
Stream_Read_UINT16(s, nineGridInfo->ulTopHeight); /* ulTopHeight (2 bytes) */
Stream_Read_UINT16(s, nineGridInfo->ulBottomHeight); /* ulBottomHeight (2 bytes) */
update_read_colorref(s, &nineGridInfo->crTransparent); /* crTransparent (4 bytes) */
return TRUE;
}
static BOOL update_read_frame_marker_order(wStream* s, FRAME_MARKER_ORDER* frame_marker)
{
if (Stream_GetRemainingLength(s) < 4)
return FALSE;
Stream_Read_UINT32(s, frame_marker->action); /* action (4 bytes) */
return TRUE;
}
static BOOL update_read_stream_bitmap_first_order(wStream* s,
STREAM_BITMAP_FIRST_ORDER* stream_bitmap_first)
{
if (Stream_GetRemainingLength(s) < 10) // 8 + 2 at least
return FALSE;
Stream_Read_UINT8(s, stream_bitmap_first->bitmapFlags); /* bitmapFlags (1 byte) */
Stream_Read_UINT8(s, stream_bitmap_first->bitmapBpp); /* bitmapBpp (1 byte) */
if ((stream_bitmap_first->bitmapBpp < 1) || (stream_bitmap_first->bitmapBpp > 32))
{
WLog_ERR(TAG, "invalid bpp value %" PRIu32 "", stream_bitmap_first->bitmapBpp);
return FALSE;
}
Stream_Read_UINT16(s, stream_bitmap_first->bitmapType); /* bitmapType (2 bytes) */
Stream_Read_UINT16(s, stream_bitmap_first->bitmapWidth); /* bitmapWidth (2 bytes) */
Stream_Read_UINT16(s, stream_bitmap_first->bitmapHeight); /* bitmapHeigth (2 bytes) */
if (stream_bitmap_first->bitmapFlags & STREAM_BITMAP_V2)
{
if (Stream_GetRemainingLength(s) < 4)
return FALSE;
Stream_Read_UINT32(s, stream_bitmap_first->bitmapSize); /* bitmapSize (4 bytes) */
}
else
{
if (Stream_GetRemainingLength(s) < 2)
return FALSE;
Stream_Read_UINT16(s, stream_bitmap_first->bitmapSize); /* bitmapSize (2 bytes) */
}
FIELD_SKIP_BUFFER16(
s, stream_bitmap_first->bitmapBlockSize); /* bitmapBlockSize(2 bytes) + bitmapBlock */
return TRUE;
}
static BOOL update_read_stream_bitmap_next_order(wStream* s,
STREAM_BITMAP_NEXT_ORDER* stream_bitmap_next)
{
if (Stream_GetRemainingLength(s) < 5)
return FALSE;
Stream_Read_UINT8(s, stream_bitmap_next->bitmapFlags); /* bitmapFlags (1 byte) */
Stream_Read_UINT16(s, stream_bitmap_next->bitmapType); /* bitmapType (2 bytes) */
FIELD_SKIP_BUFFER16(
s, stream_bitmap_next->bitmapBlockSize); /* bitmapBlockSize(2 bytes) + bitmapBlock */
return TRUE;
}
static BOOL update_read_draw_gdiplus_first_order(wStream* s,
DRAW_GDIPLUS_FIRST_ORDER* draw_gdiplus_first)
{
if (Stream_GetRemainingLength(s) < 11)
return FALSE;
Stream_Seek_UINT8(s); /* pad1Octet (1 byte) */
Stream_Read_UINT16(s, draw_gdiplus_first->cbSize); /* cbSize (2 bytes) */
Stream_Read_UINT32(s, draw_gdiplus_first->cbTotalSize); /* cbTotalSize (4 bytes) */
Stream_Read_UINT32(s, draw_gdiplus_first->cbTotalEmfSize); /* cbTotalEmfSize (4 bytes) */
return Stream_SafeSeek(s, draw_gdiplus_first->cbSize); /* emfRecords */
}
static BOOL update_read_draw_gdiplus_next_order(wStream* s,
DRAW_GDIPLUS_NEXT_ORDER* draw_gdiplus_next)
{
if (Stream_GetRemainingLength(s) < 3)
return FALSE;
Stream_Seek_UINT8(s); /* pad1Octet (1 byte) */
FIELD_SKIP_BUFFER16(s, draw_gdiplus_next->cbSize); /* cbSize(2 bytes) + emfRecords */
return TRUE;
}
static BOOL update_read_draw_gdiplus_end_order(wStream* s, DRAW_GDIPLUS_END_ORDER* draw_gdiplus_end)
{
if (Stream_GetRemainingLength(s) < 11)
return FALSE;
Stream_Seek_UINT8(s); /* pad1Octet (1 byte) */
Stream_Read_UINT16(s, draw_gdiplus_end->cbSize); /* cbSize (2 bytes) */
Stream_Read_UINT32(s, draw_gdiplus_end->cbTotalSize); /* cbTotalSize (4 bytes) */
Stream_Read_UINT32(s, draw_gdiplus_end->cbTotalEmfSize); /* cbTotalEmfSize (4 bytes) */
return Stream_SafeSeek(s, draw_gdiplus_end->cbSize); /* emfRecords */
}
static BOOL
update_read_draw_gdiplus_cache_first_order(wStream* s,
DRAW_GDIPLUS_CACHE_FIRST_ORDER* draw_gdiplus_cache_first)
{
if (Stream_GetRemainingLength(s) < 11)
return FALSE;
Stream_Read_UINT8(s, draw_gdiplus_cache_first->flags); /* flags (1 byte) */
Stream_Read_UINT16(s, draw_gdiplus_cache_first->cacheType); /* cacheType (2 bytes) */
Stream_Read_UINT16(s, draw_gdiplus_cache_first->cacheIndex); /* cacheIndex (2 bytes) */
Stream_Read_UINT16(s, draw_gdiplus_cache_first->cbSize); /* cbSize (2 bytes) */
Stream_Read_UINT32(s, draw_gdiplus_cache_first->cbTotalSize); /* cbTotalSize (4 bytes) */
return Stream_SafeSeek(s, draw_gdiplus_cache_first->cbSize); /* emfRecords */
}
static BOOL
update_read_draw_gdiplus_cache_next_order(wStream* s,
DRAW_GDIPLUS_CACHE_NEXT_ORDER* draw_gdiplus_cache_next)
{
if (Stream_GetRemainingLength(s) < 7)
return FALSE;
Stream_Read_UINT8(s, draw_gdiplus_cache_next->flags); /* flags (1 byte) */
Stream_Read_UINT16(s, draw_gdiplus_cache_next->cacheType); /* cacheType (2 bytes) */
Stream_Read_UINT16(s, draw_gdiplus_cache_next->cacheIndex); /* cacheIndex (2 bytes) */
FIELD_SKIP_BUFFER16(s, draw_gdiplus_cache_next->cbSize); /* cbSize(2 bytes) + emfRecords */
return TRUE;
}
static BOOL
update_read_draw_gdiplus_cache_end_order(wStream* s,
DRAW_GDIPLUS_CACHE_END_ORDER* draw_gdiplus_cache_end)
{
if (Stream_GetRemainingLength(s) < 11)
return FALSE;
Stream_Read_UINT8(s, draw_gdiplus_cache_end->flags); /* flags (1 byte) */
Stream_Read_UINT16(s, draw_gdiplus_cache_end->cacheType); /* cacheType (2 bytes) */
Stream_Read_UINT16(s, draw_gdiplus_cache_end->cacheIndex); /* cacheIndex (2 bytes) */
Stream_Read_UINT16(s, draw_gdiplus_cache_end->cbSize); /* cbSize (2 bytes) */
Stream_Read_UINT32(s, draw_gdiplus_cache_end->cbTotalSize); /* cbTotalSize (4 bytes) */
return Stream_SafeSeek(s, draw_gdiplus_cache_end->cbSize); /* emfRecords */
}
static BOOL update_read_field_flags(wStream* s, UINT32* fieldFlags, BYTE flags, BYTE fieldBytes)
{
int i;
BYTE byte;
if (flags & ORDER_ZERO_FIELD_BYTE_BIT0)
fieldBytes--;
if (flags & ORDER_ZERO_FIELD_BYTE_BIT1)
{
if (fieldBytes > 1)
fieldBytes -= 2;
else
fieldBytes = 0;
}
if (Stream_GetRemainingLength(s) < fieldBytes)
return FALSE;
*fieldFlags = 0;
for (i = 0; i < fieldBytes; i++)
{
Stream_Read_UINT8(s, byte);
*fieldFlags |= byte << (i * 8);
}
return TRUE;
}
BOOL update_write_field_flags(wStream* s, UINT32 fieldFlags, BYTE flags, BYTE fieldBytes)
{
BYTE byte;
if (fieldBytes == 1)
{
byte = fieldFlags & 0xFF;
Stream_Write_UINT8(s, byte);
}
else if (fieldBytes == 2)
{
byte = fieldFlags & 0xFF;
Stream_Write_UINT8(s, byte);
byte = (fieldFlags >> 8) & 0xFF;
Stream_Write_UINT8(s, byte);
}
else if (fieldBytes == 3)
{
byte = fieldFlags & 0xFF;
Stream_Write_UINT8(s, byte);
byte = (fieldFlags >> 8) & 0xFF;
Stream_Write_UINT8(s, byte);
byte = (fieldFlags >> 16) & 0xFF;
Stream_Write_UINT8(s, byte);
}
else
{
return FALSE;
}
return TRUE;
}
static BOOL update_read_bounds(wStream* s, rdpBounds* bounds)
{
BYTE flags;
if (Stream_GetRemainingLength(s) < 1)
return FALSE;
Stream_Read_UINT8(s, flags); /* field flags */
if (flags & BOUND_LEFT)
{
if (!update_read_coord(s, &bounds->left, FALSE))
return FALSE;
}
else if (flags & BOUND_DELTA_LEFT)
{
if (!update_read_coord(s, &bounds->left, TRUE))
return FALSE;
}
if (flags & BOUND_TOP)
{
if (!update_read_coord(s, &bounds->top, FALSE))
return FALSE;
}
else if (flags & BOUND_DELTA_TOP)
{
if (!update_read_coord(s, &bounds->top, TRUE))
return FALSE;
}
if (flags & BOUND_RIGHT)
{
if (!update_read_coord(s, &bounds->right, FALSE))
return FALSE;
}
else if (flags & BOUND_DELTA_RIGHT)
{
if (!update_read_coord(s, &bounds->right, TRUE))
return FALSE;
}
if (flags & BOUND_BOTTOM)
{
if (!update_read_coord(s, &bounds->bottom, FALSE))
return FALSE;
}
else if (flags & BOUND_DELTA_BOTTOM)
{
if (!update_read_coord(s, &bounds->bottom, TRUE))
return FALSE;
}
return TRUE;
}
BOOL update_write_bounds(wStream* s, ORDER_INFO* orderInfo)
{
if (!(orderInfo->controlFlags & ORDER_BOUNDS))
return TRUE;
if (orderInfo->controlFlags & ORDER_ZERO_BOUNDS_DELTAS)
return TRUE;
Stream_Write_UINT8(s, orderInfo->boundsFlags); /* field flags */
if (orderInfo->boundsFlags & BOUND_LEFT)
{
if (!update_write_coord(s, orderInfo->bounds.left))
return FALSE;
}
else if (orderInfo->boundsFlags & BOUND_DELTA_LEFT)
{
}
if (orderInfo->boundsFlags & BOUND_TOP)
{
if (!update_write_coord(s, orderInfo->bounds.top))
return FALSE;
}
else if (orderInfo->boundsFlags & BOUND_DELTA_TOP)
{
}
if (orderInfo->boundsFlags & BOUND_RIGHT)
{
if (!update_write_coord(s, orderInfo->bounds.right))
return FALSE;
}
else if (orderInfo->boundsFlags & BOUND_DELTA_RIGHT)
{
}
if (orderInfo->boundsFlags & BOUND_BOTTOM)
{
if (!update_write_coord(s, orderInfo->bounds.bottom))
return FALSE;
}
else if (orderInfo->boundsFlags & BOUND_DELTA_BOTTOM)
{
}
return TRUE;
}
static BOOL read_primary_order(wLog* log, const char* orderName, wStream* s,
const ORDER_INFO* orderInfo, rdpPrimaryUpdate* primary)
{
BOOL rc = FALSE;
if (!s || !orderInfo || !primary || !orderName)
return FALSE;
switch (orderInfo->orderType)
{
case ORDER_TYPE_DSTBLT:
rc = update_read_dstblt_order(s, orderInfo, &(primary->dstblt));
break;
case ORDER_TYPE_PATBLT:
rc = update_read_patblt_order(s, orderInfo, &(primary->patblt));
break;
case ORDER_TYPE_SCRBLT:
rc = update_read_scrblt_order(s, orderInfo, &(primary->scrblt));
break;
case ORDER_TYPE_OPAQUE_RECT:
rc = update_read_opaque_rect_order(s, orderInfo, &(primary->opaque_rect));
break;
case ORDER_TYPE_DRAW_NINE_GRID:
rc = update_read_draw_nine_grid_order(s, orderInfo, &(primary->draw_nine_grid));
break;
case ORDER_TYPE_MULTI_DSTBLT:
rc = update_read_multi_dstblt_order(s, orderInfo, &(primary->multi_dstblt));
break;
case ORDER_TYPE_MULTI_PATBLT:
rc = update_read_multi_patblt_order(s, orderInfo, &(primary->multi_patblt));
break;
case ORDER_TYPE_MULTI_SCRBLT:
rc = update_read_multi_scrblt_order(s, orderInfo, &(primary->multi_scrblt));
break;
case ORDER_TYPE_MULTI_OPAQUE_RECT:
rc = update_read_multi_opaque_rect_order(s, orderInfo, &(primary->multi_opaque_rect));
break;
case ORDER_TYPE_MULTI_DRAW_NINE_GRID:
rc = update_read_multi_draw_nine_grid_order(s, orderInfo,
&(primary->multi_draw_nine_grid));
break;
case ORDER_TYPE_LINE_TO:
rc = update_read_line_to_order(s, orderInfo, &(primary->line_to));
break;
case ORDER_TYPE_POLYLINE:
rc = update_read_polyline_order(s, orderInfo, &(primary->polyline));
break;
case ORDER_TYPE_MEMBLT:
rc = update_read_memblt_order(s, orderInfo, &(primary->memblt));
break;
case ORDER_TYPE_MEM3BLT:
rc = update_read_mem3blt_order(s, orderInfo, &(primary->mem3blt));
break;
case ORDER_TYPE_SAVE_BITMAP:
rc = update_read_save_bitmap_order(s, orderInfo, &(primary->save_bitmap));
break;
case ORDER_TYPE_GLYPH_INDEX:
rc = update_read_glyph_index_order(s, orderInfo, &(primary->glyph_index));
break;
case ORDER_TYPE_FAST_INDEX:
rc = update_read_fast_index_order(s, orderInfo, &(primary->fast_index));
break;
case ORDER_TYPE_FAST_GLYPH:
rc = update_read_fast_glyph_order(s, orderInfo, &(primary->fast_glyph));
break;
case ORDER_TYPE_POLYGON_SC:
rc = update_read_polygon_sc_order(s, orderInfo, &(primary->polygon_sc));
break;
case ORDER_TYPE_POLYGON_CB:
rc = update_read_polygon_cb_order(s, orderInfo, &(primary->polygon_cb));
break;
case ORDER_TYPE_ELLIPSE_SC:
rc = update_read_ellipse_sc_order(s, orderInfo, &(primary->ellipse_sc));
break;
case ORDER_TYPE_ELLIPSE_CB:
rc = update_read_ellipse_cb_order(s, orderInfo, &(primary->ellipse_cb));
break;
default:
WLog_Print(log, WLOG_WARN, "Primary Drawing Order %s not supported, ignoring",
orderName);
rc = TRUE;
break;
}
if (!rc)
{
WLog_Print(log, WLOG_ERROR, "%s - update_read_dstblt_order() failed", orderName);
return FALSE;
}
return TRUE;
}
static BOOL update_recv_primary_order(rdpUpdate* update, wStream* s, BYTE flags)
{
BOOL rc = FALSE;
rdpContext* context = update->context;
rdpPrimaryUpdate* primary = update->primary;
ORDER_INFO* orderInfo = &(primary->order_info);
rdpSettings* settings = context->settings;
const char* orderName;
if (flags & ORDER_TYPE_CHANGE)
{
if (Stream_GetRemainingLength(s) < 1)
{
WLog_Print(update->log, WLOG_ERROR, "Stream_GetRemainingLength(s) < 1");
return FALSE;
}
Stream_Read_UINT8(s, orderInfo->orderType); /* orderType (1 byte) */
}
orderName = primary_order_string(orderInfo->orderType);
if (!check_primary_order_supported(update->log, settings, orderInfo->orderType, orderName))
return FALSE;
if (!update_read_field_flags(s, &(orderInfo->fieldFlags), flags,
PRIMARY_DRAWING_ORDER_FIELD_BYTES[orderInfo->orderType]))
{
WLog_Print(update->log, WLOG_ERROR, "update_read_field_flags() failed");
return FALSE;
}
if (flags & ORDER_BOUNDS)
{
if (!(flags & ORDER_ZERO_BOUNDS_DELTAS))
{
if (!update_read_bounds(s, &orderInfo->bounds))
{
WLog_Print(update->log, WLOG_ERROR, "update_read_bounds() failed");
return FALSE;
}
}
rc = IFCALLRESULT(FALSE, update->SetBounds, context, &orderInfo->bounds);
if (!rc)
return FALSE;
}
orderInfo->deltaCoordinates = (flags & ORDER_DELTA_COORDINATES) ? TRUE : FALSE;
if (!read_primary_order(update->log, orderName, s, orderInfo, primary))
return FALSE;
switch (orderInfo->orderType)
{
case ORDER_TYPE_DSTBLT:
{
WLog_Print(update->log, WLOG_DEBUG, "Primary Drawing Order %s rop=%s [0x%08" PRIx32 "]",
orderName, gdi_rop3_code_string(primary->dstblt.bRop),
gdi_rop3_code(primary->dstblt.bRop));
rc = IFCALLRESULT(FALSE, primary->DstBlt, context, &primary->dstblt);
}
break;
case ORDER_TYPE_PATBLT:
{
WLog_Print(update->log, WLOG_DEBUG, "Primary Drawing Order %s rop=%s [0x%08" PRIx32 "]",
orderName, gdi_rop3_code_string(primary->patblt.bRop),
gdi_rop3_code(primary->patblt.bRop));
rc = IFCALLRESULT(FALSE, primary->PatBlt, context, &primary->patblt);
}
break;
case ORDER_TYPE_SCRBLT:
{
WLog_Print(update->log, WLOG_DEBUG, "Primary Drawing Order %s rop=%s [0x%08" PRIx32 "]",
orderName, gdi_rop3_code_string(primary->scrblt.bRop),
gdi_rop3_code(primary->scrblt.bRop));
rc = IFCALLRESULT(FALSE, primary->ScrBlt, context, &primary->scrblt);
}
break;
case ORDER_TYPE_OPAQUE_RECT:
{
WLog_Print(update->log, WLOG_DEBUG, "Primary Drawing Order %s", orderName);
rc = IFCALLRESULT(FALSE, primary->OpaqueRect, context, &primary->opaque_rect);
}
break;
case ORDER_TYPE_DRAW_NINE_GRID:
{
WLog_Print(update->log, WLOG_DEBUG, "Primary Drawing Order %s", orderName);
rc = IFCALLRESULT(FALSE, primary->DrawNineGrid, context, &primary->draw_nine_grid);
}
break;
case ORDER_TYPE_MULTI_DSTBLT:
{
WLog_Print(update->log, WLOG_DEBUG, "Primary Drawing Order %s rop=%s [0x%08" PRIx32 "]",
orderName, gdi_rop3_code_string(primary->multi_dstblt.bRop),
gdi_rop3_code(primary->multi_dstblt.bRop));
rc = IFCALLRESULT(FALSE, primary->MultiDstBlt, context, &primary->multi_dstblt);
}
break;
case ORDER_TYPE_MULTI_PATBLT:
{
WLog_Print(update->log, WLOG_DEBUG, "Primary Drawing Order %s rop=%s [0x%08" PRIx32 "]",
orderName, gdi_rop3_code_string(primary->multi_patblt.bRop),
gdi_rop3_code(primary->multi_patblt.bRop));
rc = IFCALLRESULT(FALSE, primary->MultiPatBlt, context, &primary->multi_patblt);
}
break;
case ORDER_TYPE_MULTI_SCRBLT:
{
WLog_Print(update->log, WLOG_DEBUG, "Primary Drawing Order %s rop=%s [0x%08" PRIx32 "]",
orderName, gdi_rop3_code_string(primary->multi_scrblt.bRop),
gdi_rop3_code(primary->multi_scrblt.bRop));
rc = IFCALLRESULT(FALSE, primary->MultiScrBlt, context, &primary->multi_scrblt);
}
break;
case ORDER_TYPE_MULTI_OPAQUE_RECT:
{
WLog_Print(update->log, WLOG_DEBUG, "Primary Drawing Order %s", orderName);
rc =
IFCALLRESULT(FALSE, primary->MultiOpaqueRect, context, &primary->multi_opaque_rect);
}
break;
case ORDER_TYPE_MULTI_DRAW_NINE_GRID:
{
WLog_Print(update->log, WLOG_DEBUG, "Primary Drawing Order %s", orderName);
rc = IFCALLRESULT(FALSE, primary->MultiDrawNineGrid, context,
&primary->multi_draw_nine_grid);
}
break;
case ORDER_TYPE_LINE_TO:
{
WLog_Print(update->log, WLOG_DEBUG, "Primary Drawing Order %s", orderName);
rc = IFCALLRESULT(FALSE, primary->LineTo, context, &primary->line_to);
}
break;
case ORDER_TYPE_POLYLINE:
{
WLog_Print(update->log, WLOG_DEBUG, "Primary Drawing Order %s", orderName);
rc = IFCALLRESULT(FALSE, primary->Polyline, context, &primary->polyline);
}
break;
case ORDER_TYPE_MEMBLT:
{
WLog_Print(update->log, WLOG_DEBUG, "Primary Drawing Order %s rop=%s [0x%08" PRIx32 "]",
orderName, gdi_rop3_code_string(primary->memblt.bRop),
gdi_rop3_code(primary->memblt.bRop));
rc = IFCALLRESULT(FALSE, primary->MemBlt, context, &primary->memblt);
}
break;
case ORDER_TYPE_MEM3BLT:
{
WLog_Print(update->log, WLOG_DEBUG, "Primary Drawing Order %s rop=%s [0x%08" PRIx32 "]",
orderName, gdi_rop3_code_string(primary->mem3blt.bRop),
gdi_rop3_code(primary->mem3blt.bRop));
rc = IFCALLRESULT(FALSE, primary->Mem3Blt, context, &primary->mem3blt);
}
break;
case ORDER_TYPE_SAVE_BITMAP:
{
WLog_Print(update->log, WLOG_DEBUG, "Primary Drawing Order %s", orderName);
rc = IFCALLRESULT(FALSE, primary->SaveBitmap, context, &primary->save_bitmap);
}
break;
case ORDER_TYPE_GLYPH_INDEX:
{
WLog_Print(update->log, WLOG_DEBUG, "Primary Drawing Order %s", orderName);
rc = IFCALLRESULT(FALSE, primary->GlyphIndex, context, &primary->glyph_index);
}
break;
case ORDER_TYPE_FAST_INDEX:
{
WLog_Print(update->log, WLOG_DEBUG, "Primary Drawing Order %s", orderName);
rc = IFCALLRESULT(FALSE, primary->FastIndex, context, &primary->fast_index);
}
break;
case ORDER_TYPE_FAST_GLYPH:
{
WLog_Print(update->log, WLOG_DEBUG, "Primary Drawing Order %s", orderName);
rc = IFCALLRESULT(FALSE, primary->FastGlyph, context, &primary->fast_glyph);
}
break;
case ORDER_TYPE_POLYGON_SC:
{
WLog_Print(update->log, WLOG_DEBUG, "Primary Drawing Order %s", orderName);
rc = IFCALLRESULT(FALSE, primary->PolygonSC, context, &primary->polygon_sc);
}
break;
case ORDER_TYPE_POLYGON_CB:
{
WLog_Print(update->log, WLOG_DEBUG, "Primary Drawing Order %s", orderName);
rc = IFCALLRESULT(FALSE, primary->PolygonCB, context, &primary->polygon_cb);
}
break;
case ORDER_TYPE_ELLIPSE_SC:
{
WLog_Print(update->log, WLOG_DEBUG, "Primary Drawing Order %s", orderName);
rc = IFCALLRESULT(FALSE, primary->EllipseSC, context, &primary->ellipse_sc);
}
break;
case ORDER_TYPE_ELLIPSE_CB:
{
WLog_Print(update->log, WLOG_DEBUG, "Primary Drawing Order %s", orderName);
rc = IFCALLRESULT(FALSE, primary->EllipseCB, context, &primary->ellipse_cb);
}
break;
default:
WLog_Print(update->log, WLOG_WARN, "Primary Drawing Order %s not supported", orderName);
break;
}
if (!rc)
{
WLog_Print(update->log, WLOG_WARN, "Primary Drawing Order %s failed", orderName);
return FALSE;
}
if (flags & ORDER_BOUNDS)
{
rc = IFCALLRESULT(FALSE, update->SetBounds, context, NULL);
}
return rc;
}
static BOOL update_recv_secondary_order(rdpUpdate* update, wStream* s, BYTE flags)
{
BOOL rc = FALSE;
size_t start, end, diff;
BYTE orderType;
UINT16 extraFlags;
UINT16 orderLength;
rdpContext* context = update->context;
rdpSettings* settings = context->settings;
rdpSecondaryUpdate* secondary = update->secondary;
const char* name;
if (Stream_GetRemainingLength(s) < 5)
{
WLog_Print(update->log, WLOG_ERROR, "Stream_GetRemainingLength(s) < 5");
return FALSE;
}
Stream_Read_UINT16(s, orderLength); /* orderLength (2 bytes) */
Stream_Read_UINT16(s, extraFlags); /* extraFlags (2 bytes) */
Stream_Read_UINT8(s, orderType); /* orderType (1 byte) */
if (Stream_GetRemainingLength(s) < orderLength + 7U)
{
WLog_Print(update->log, WLOG_ERROR, "Stream_GetRemainingLength(s) %" PRIuz " < %" PRIu16,
Stream_GetRemainingLength(s), orderLength + 7);
return FALSE;
}
start = Stream_GetPosition(s);
name = secondary_order_string(orderType);
WLog_Print(update->log, WLOG_DEBUG, "Secondary Drawing Order %s", name);
if (!check_secondary_order_supported(update->log, settings, orderType, name))
return FALSE;
switch (orderType)
{
case ORDER_TYPE_BITMAP_UNCOMPRESSED:
case ORDER_TYPE_CACHE_BITMAP_COMPRESSED:
{
const BOOL compressed = (orderType == ORDER_TYPE_CACHE_BITMAP_COMPRESSED);
CACHE_BITMAP_ORDER* order =
update_read_cache_bitmap_order(update, s, compressed, extraFlags);
if (order)
{
rc = IFCALLRESULT(FALSE, secondary->CacheBitmap, context, order);
free_cache_bitmap_order(context, order);
}
}
break;
case ORDER_TYPE_BITMAP_UNCOMPRESSED_V2:
case ORDER_TYPE_BITMAP_COMPRESSED_V2:
{
const BOOL compressed = (orderType == ORDER_TYPE_BITMAP_COMPRESSED_V2);
CACHE_BITMAP_V2_ORDER* order =
update_read_cache_bitmap_v2_order(update, s, compressed, extraFlags);
if (order)
{
rc = IFCALLRESULT(FALSE, secondary->CacheBitmapV2, context, order);
free_cache_bitmap_v2_order(context, order);
}
}
break;
case ORDER_TYPE_BITMAP_COMPRESSED_V3:
{
CACHE_BITMAP_V3_ORDER* order = update_read_cache_bitmap_v3_order(update, s, extraFlags);
if (order)
{
rc = IFCALLRESULT(FALSE, secondary->CacheBitmapV3, context, order);
free_cache_bitmap_v3_order(context, order);
}
}
break;
case ORDER_TYPE_CACHE_COLOR_TABLE:
{
CACHE_COLOR_TABLE_ORDER* order =
update_read_cache_color_table_order(update, s, extraFlags);
if (order)
{
rc = IFCALLRESULT(FALSE, secondary->CacheColorTable, context, order);
free_cache_color_table_order(context, order);
}
}
break;
case ORDER_TYPE_CACHE_GLYPH:
{
switch (settings->GlyphSupportLevel)
{
case GLYPH_SUPPORT_PARTIAL:
case GLYPH_SUPPORT_FULL:
{
CACHE_GLYPH_ORDER* order = update_read_cache_glyph_order(update, s, extraFlags);
if (order)
{
rc = IFCALLRESULT(FALSE, secondary->CacheGlyph, context, order);
free_cache_glyph_order(context, order);
}
}
break;
case GLYPH_SUPPORT_ENCODE:
{
CACHE_GLYPH_V2_ORDER* order =
update_read_cache_glyph_v2_order(update, s, extraFlags);
if (order)
{
rc = IFCALLRESULT(FALSE, secondary->CacheGlyphV2, context, order);
free_cache_glyph_v2_order(context, order);
}
}
break;
case GLYPH_SUPPORT_NONE:
default:
break;
}
}
break;
case ORDER_TYPE_CACHE_BRUSH:
/* [MS-RDPEGDI] 2.2.2.2.1.2.7 Cache Brush (CACHE_BRUSH_ORDER) */
{
CACHE_BRUSH_ORDER* order = update_read_cache_brush_order(update, s, extraFlags);
if (order)
{
rc = IFCALLRESULT(FALSE, secondary->CacheBrush, context, order);
free_cache_brush_order(context, order);
}
}
break;
default:
WLog_Print(update->log, WLOG_WARN, "SECONDARY ORDER %s not supported", name);
break;
}
if (!rc)
{
WLog_Print(update->log, WLOG_ERROR, "SECONDARY ORDER %s failed", name);
}
start += orderLength + 7;
end = Stream_GetPosition(s);
if (start > end)
{
WLog_Print(update->log, WLOG_WARN, "SECONDARY_ORDER %s: read %" PRIuz "bytes too much",
name, end - start);
return FALSE;
}
diff = start - end;
if (diff > 0)
{
WLog_Print(update->log, WLOG_DEBUG,
"SECONDARY_ORDER %s: read %" PRIuz "bytes short, skipping", name, diff);
Stream_Seek(s, diff);
}
return rc;
}
static BOOL read_altsec_order(wStream* s, BYTE orderType, rdpAltSecUpdate* altsec)
{
BOOL rc = FALSE;
switch (orderType)
{
case ORDER_TYPE_CREATE_OFFSCREEN_BITMAP:
rc = update_read_create_offscreen_bitmap_order(s, &(altsec->create_offscreen_bitmap));
break;
case ORDER_TYPE_SWITCH_SURFACE:
rc = update_read_switch_surface_order(s, &(altsec->switch_surface));
break;
case ORDER_TYPE_CREATE_NINE_GRID_BITMAP:
rc = update_read_create_nine_grid_bitmap_order(s, &(altsec->create_nine_grid_bitmap));
break;
case ORDER_TYPE_FRAME_MARKER:
rc = update_read_frame_marker_order(s, &(altsec->frame_marker));
break;
case ORDER_TYPE_STREAM_BITMAP_FIRST:
rc = update_read_stream_bitmap_first_order(s, &(altsec->stream_bitmap_first));
break;
case ORDER_TYPE_STREAM_BITMAP_NEXT:
rc = update_read_stream_bitmap_next_order(s, &(altsec->stream_bitmap_next));
break;
case ORDER_TYPE_GDIPLUS_FIRST:
rc = update_read_draw_gdiplus_first_order(s, &(altsec->draw_gdiplus_first));
break;
case ORDER_TYPE_GDIPLUS_NEXT:
rc = update_read_draw_gdiplus_next_order(s, &(altsec->draw_gdiplus_next));
break;
case ORDER_TYPE_GDIPLUS_END:
rc = update_read_draw_gdiplus_end_order(s, &(altsec->draw_gdiplus_end));
break;
case ORDER_TYPE_GDIPLUS_CACHE_FIRST:
rc = update_read_draw_gdiplus_cache_first_order(s, &(altsec->draw_gdiplus_cache_first));
break;
case ORDER_TYPE_GDIPLUS_CACHE_NEXT:
rc = update_read_draw_gdiplus_cache_next_order(s, &(altsec->draw_gdiplus_cache_next));
break;
case ORDER_TYPE_GDIPLUS_CACHE_END:
rc = update_read_draw_gdiplus_cache_end_order(s, &(altsec->draw_gdiplus_cache_end));
break;
case ORDER_TYPE_WINDOW:
/* This order is handled elsewhere. */
rc = TRUE;
break;
case ORDER_TYPE_COMPDESK_FIRST:
rc = TRUE;
break;
default:
break;
}
return rc;
}
static BOOL update_recv_altsec_order(rdpUpdate* update, wStream* s, BYTE flags)
{
BYTE orderType = flags >>= 2; /* orderType is in higher 6 bits of flags field */
BOOL rc = FALSE;
rdpContext* context = update->context;
rdpSettings* settings = context->settings;
rdpAltSecUpdate* altsec = update->altsec;
const char* orderName = altsec_order_string(orderType);
WLog_Print(update->log, WLOG_DEBUG, "Alternate Secondary Drawing Order %s", orderName);
if (!check_alt_order_supported(update->log, settings, orderType, orderName))
return FALSE;
if (!read_altsec_order(s, orderType, altsec))
return FALSE;
switch (orderType)
{
case ORDER_TYPE_CREATE_OFFSCREEN_BITMAP:
IFCALLRET(altsec->CreateOffscreenBitmap, rc, context,
&(altsec->create_offscreen_bitmap));
break;
case ORDER_TYPE_SWITCH_SURFACE:
IFCALLRET(altsec->SwitchSurface, rc, context, &(altsec->switch_surface));
break;
case ORDER_TYPE_CREATE_NINE_GRID_BITMAP:
IFCALLRET(altsec->CreateNineGridBitmap, rc, context,
&(altsec->create_nine_grid_bitmap));
break;
case ORDER_TYPE_FRAME_MARKER:
IFCALLRET(altsec->FrameMarker, rc, context, &(altsec->frame_marker));
break;
case ORDER_TYPE_STREAM_BITMAP_FIRST:
IFCALLRET(altsec->StreamBitmapFirst, rc, context, &(altsec->stream_bitmap_first));
break;
case ORDER_TYPE_STREAM_BITMAP_NEXT:
IFCALLRET(altsec->StreamBitmapNext, rc, context, &(altsec->stream_bitmap_next));
break;
case ORDER_TYPE_GDIPLUS_FIRST:
IFCALLRET(altsec->DrawGdiPlusFirst, rc, context, &(altsec->draw_gdiplus_first));
break;
case ORDER_TYPE_GDIPLUS_NEXT:
IFCALLRET(altsec->DrawGdiPlusNext, rc, context, &(altsec->draw_gdiplus_next));
break;
case ORDER_TYPE_GDIPLUS_END:
IFCALLRET(altsec->DrawGdiPlusEnd, rc, context, &(altsec->draw_gdiplus_end));
break;
case ORDER_TYPE_GDIPLUS_CACHE_FIRST:
IFCALLRET(altsec->DrawGdiPlusCacheFirst, rc, context,
&(altsec->draw_gdiplus_cache_first));
break;
case ORDER_TYPE_GDIPLUS_CACHE_NEXT:
IFCALLRET(altsec->DrawGdiPlusCacheNext, rc, context,
&(altsec->draw_gdiplus_cache_next));
break;
case ORDER_TYPE_GDIPLUS_CACHE_END:
IFCALLRET(altsec->DrawGdiPlusCacheEnd, rc, context, &(altsec->draw_gdiplus_cache_end));
break;
case ORDER_TYPE_WINDOW:
rc = update_recv_altsec_window_order(update, s);
break;
case ORDER_TYPE_COMPDESK_FIRST:
rc = TRUE;
break;
default:
break;
}
if (!rc)
{
WLog_Print(update->log, WLOG_WARN, "Alternate Secondary Drawing Order %s failed",
orderName);
}
return rc;
}
BOOL update_recv_order(rdpUpdate* update, wStream* s)
{
BOOL rc;
BYTE controlFlags;
if (Stream_GetRemainingLength(s) < 1)
{
WLog_Print(update->log, WLOG_ERROR, "Stream_GetRemainingLength(s) < 1");
return FALSE;
}
Stream_Read_UINT8(s, controlFlags); /* controlFlags (1 byte) */
if (!(controlFlags & ORDER_STANDARD))
rc = update_recv_altsec_order(update, s, controlFlags);
else if (controlFlags & ORDER_SECONDARY)
rc = update_recv_secondary_order(update, s, controlFlags);
else
rc = update_recv_primary_order(update, s, controlFlags);
if (!rc)
WLog_Print(update->log, WLOG_ERROR, "order flags %02" PRIx8 " failed", controlFlags);
return rc;
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_3951_0 |
crossvul-cpp_data_bad_5201_0 | #ifdef HAVE_CONFIG_H
#include "config.h"
#endif /* HAVE_CONFIG_H */
#include <stdio.h>
#include <stddef.h>
#include <stdlib.h>
#include <string.h>
#include "gd_tga.h"
#include "gd.h"
#include "gd_errors.h"
#include "gdhelpers.h"
/*! \brief Creates a gdImage from a TGA file
* Creates a gdImage from a TGA binary file via a gdIOCtx.
* \param infile Pointer to TGA binary file
* \return gdImagePtr
*/
BGD_DECLARE(gdImagePtr) gdImageCreateFromTga(FILE *fp)
{
gdImagePtr image;
gdIOCtx* in = gdNewFileCtx(fp);
if (in == NULL) return NULL;
image = gdImageCreateFromTgaCtx(in);
in->gd_free( in );
return image;
}
BGD_DECLARE(gdImagePtr) gdImageCreateFromTgaPtr(int size, void *data)
{
gdImagePtr im;
gdIOCtx *in = gdNewDynamicCtxEx (size, data, 0);
if (in == NULL) return NULL;
im = gdImageCreateFromTgaCtx(in);
in->gd_free(in);
return im;
}
/*! \brief Creates a gdImage from a gdIOCtx
* Creates a gdImage from a gdIOCtx referencing a TGA binary file.
* \param ctx Pointer to a gdIOCtx structure
* \return gdImagePtr
*/
BGD_DECLARE(gdImagePtr) gdImageCreateFromTgaCtx(gdIOCtx* ctx)
{
int bitmap_caret = 0;
oTga *tga = NULL;
/* int pixel_block_size = 0;
int image_block_size = 0; */
volatile gdImagePtr image = NULL;
int x = 0;
int y = 0;
tga = (oTga *) gdMalloc(sizeof(oTga));
if (!tga) {
return NULL;
}
tga->bitmap = NULL;
tga->ident = NULL;
if (read_header_tga(ctx, tga) < 0) {
free_tga(tga);
return NULL;
}
/*TODO: Will this be used?
pixel_block_size = tga->bits / 8;
image_block_size = (tga->width * tga->height) * pixel_block_size;
*/
if (read_image_tga(ctx, tga) < 0) {
free_tga(tga);
return NULL;
}
image = gdImageCreateTrueColor((int)tga->width, (int)tga->height );
if (image == 0) {
free_tga( tga );
return NULL;
}
/*! \brief Populate GD image object
* Copy the pixel data from our tga bitmap buffer into the GD image
* Disable blending and save the alpha channel per default
*/
if (tga->alphabits) {
gdImageAlphaBlending(image, 0);
gdImageSaveAlpha(image, 1);
}
/* TODO: use alphabits as soon as we support 24bit and other alpha bps (ie != 8bits) */
for (y = 0; y < tga->height; y++) {
register int *tpix = image->tpixels[y];
for ( x = 0; x < tga->width; x++, tpix++) {
if (tga->bits == TGA_BPP_24) {
*tpix = gdTrueColor(tga->bitmap[bitmap_caret + 2], tga->bitmap[bitmap_caret + 1], tga->bitmap[bitmap_caret]);
bitmap_caret += 3;
} else if (tga->bits == TGA_BPP_32 || tga->alphabits) {
register int a = tga->bitmap[bitmap_caret + 3];
*tpix = gdTrueColorAlpha(tga->bitmap[bitmap_caret + 2], tga->bitmap[bitmap_caret + 1], tga->bitmap[bitmap_caret], gdAlphaMax - (a >> 1));
bitmap_caret += 4;
}
}
}
if (tga->flipv && tga->fliph) {
gdImageFlipBoth(image);
} else if (tga->flipv) {
gdImageFlipVertical(image);
} else if (tga->fliph) {
gdImageFlipHorizontal(image);
}
free_tga(tga);
return image;
}
/*! \brief Reads a TGA header.
* Reads the header block from a binary TGA file populating the referenced TGA structure.
* \param ctx Pointer to TGA binary file
* \param tga Pointer to TGA structure
* \return int 1 on sucess, -1 on failure
*/
int read_header_tga(gdIOCtx *ctx, oTga *tga)
{
unsigned char header[18];
if (gdGetBuf(header, sizeof(header), ctx) < 18) {
gd_error("fail to read header");
return -1;
}
tga->identsize = header[0];
tga->colormaptype = header[1];
tga->imagetype = header[2];
tga->colormapstart = header[3] + (header[4] << 8);
tga->colormaplength = header[5] + (header[6] << 8);
tga->colormapbits = header[7];
tga->xstart = header[8] + (header[9] << 8);
tga->ystart = header[10] + (header[11] << 8);
tga->width = header[12] + (header[13] << 8);
tga->height = header[14] + (header[15] << 8);
tga->bits = header[16];
tga->alphabits = header[17] & 0x0f;
tga->fliph = (header[17] & 0x10) ? 1 : 0;
tga->flipv = (header[17] & 0x20) ? 0 : 1;
#if DEBUG
printf("format bps: %i\n", tga->bits);
printf("flip h/v: %i / %i\n", tga->fliph, tga->flipv);
printf("alpha: %i\n", tga->alphabits);
printf("wxh: %i %i\n", tga->width, tga->height);
#endif
switch(tga->bits) {
case 8:
case 16:
case 24:
case 32:
break;
default:
gd_error("bps %i not supported", tga->bits);
return -1;
break;
}
tga->ident = NULL;
if (tga->identsize > 0) {
tga->ident = (char *) gdMalloc(tga->identsize * sizeof(char));
if(tga->ident == NULL) {
return -1;
}
gdGetBuf(tga->ident, tga->identsize, ctx);
}
return 1;
}
/*! \brief Reads a TGA image data into buffer.
* Reads the image data block from a binary TGA file populating the referenced TGA structure.
* \param ctx Pointer to TGA binary file
* \param tga Pointer to TGA structure
* \return int 0 on sucess, -1 on failure
*/
int read_image_tga( gdIOCtx *ctx, oTga *tga )
{
int pixel_block_size = (tga->bits / 8);
int image_block_size = (tga->width * tga->height) * pixel_block_size;
uint8_t* decompression_buffer = NULL;
unsigned char* conversion_buffer = NULL;
int buffer_caret = 0;
int bitmap_caret = 0;
int i = 0;
int j = 0;
uint8_t encoded_pixels;
if(overflow2(tga->width, tga->height)) {
return -1;
}
if(overflow2(tga->width * tga->height, pixel_block_size)) {
return -1;
}
if(overflow2(image_block_size, sizeof(int))) {
return -1;
}
/*! \todo Add more image type support.
*/
if (tga->imagetype != TGA_TYPE_RGB && tga->imagetype != TGA_TYPE_RGB_RLE)
return -1;
/*! \brief Allocate memmory for image block
* Allocate a chunk of memory for the image block to be passed into.
*/
tga->bitmap = (int *) gdMalloc(image_block_size * sizeof(int));
if (tga->bitmap == NULL)
return -1;
switch (tga->imagetype) {
case TGA_TYPE_RGB:
/*! \brief Read in uncompressed RGB TGA
* Chunk load the pixel data from an uncompressed RGB type TGA.
*/
conversion_buffer = (unsigned char *) gdMalloc(image_block_size * sizeof(unsigned char));
if (conversion_buffer == NULL) {
return -1;
}
if (gdGetBuf(conversion_buffer, image_block_size, ctx) != image_block_size) {
gd_error("gd-tga: premature end of image data\n");
gdFree(conversion_buffer);
return -1;
}
while (buffer_caret < image_block_size) {
tga->bitmap[buffer_caret] = (int) conversion_buffer[buffer_caret];
buffer_caret++;
}
gdFree(conversion_buffer);
break;
case TGA_TYPE_RGB_RLE:
/*! \brief Read in RLE compressed RGB TGA
* Chunk load the pixel data from an RLE compressed RGB type TGA.
*/
decompression_buffer = (uint8_t*) gdMalloc(image_block_size * sizeof(uint8_t));
if (decompression_buffer == NULL) {
return -1;
}
conversion_buffer = (unsigned char *) gdMalloc(image_block_size * sizeof(unsigned char));
if (conversion_buffer == NULL) {
gd_error("gd-tga: premature end of image data\n");
gdFree( decompression_buffer );
return -1;
}
if (gdGetBuf(conversion_buffer, image_block_size, ctx) != image_block_size) {
gdFree(conversion_buffer);
gdFree(decompression_buffer);
return -1;
}
buffer_caret = 0;
while( buffer_caret < image_block_size) {
decompression_buffer[buffer_caret] = (int)conversion_buffer[buffer_caret];
buffer_caret++;
}
buffer_caret = 0;
while( bitmap_caret < image_block_size ) {
if ((decompression_buffer[buffer_caret] & TGA_RLE_FLAG) == TGA_RLE_FLAG) {
encoded_pixels = ( ( decompression_buffer[ buffer_caret ] & 127 ) + 1 );
buffer_caret++;
for (i = 0; i < encoded_pixels; i++) {
for (j = 0; j < pixel_block_size; j++, bitmap_caret++) {
tga->bitmap[ bitmap_caret ] = decompression_buffer[ buffer_caret + j ];
}
}
buffer_caret += pixel_block_size;
} else {
encoded_pixels = decompression_buffer[ buffer_caret ] + 1;
buffer_caret++;
for (i = 0; i < encoded_pixels; i++) {
for( j = 0; j < pixel_block_size; j++, bitmap_caret++ ) {
tga->bitmap[ bitmap_caret ] = decompression_buffer[ buffer_caret + j ];
}
buffer_caret += pixel_block_size;
}
}
}
gdFree( decompression_buffer );
gdFree( conversion_buffer );
break;
}
return 1;
}
/*! \brief Cleans up a TGA structure.
* Dereferences the bitmap referenced in a TGA structure, then the structure itself
* \param tga Pointer to TGA structure
*/
void free_tga(oTga * tga)
{
if (tga) {
if (tga->ident)
gdFree(tga->ident);
if (tga->bitmap)
gdFree(tga->bitmap);
gdFree(tga);
}
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_5201_0 |
crossvul-cpp_data_good_3907_0 | /**
* FreeRDP: A Remote Desktop Protocol Implementation
* Update Data PDUs
*
* Copyright 2011 Marc-Andre Moreau <marcandre.moreau@gmail.com>
* Copyright 2016 Armin Novak <armin.novak@thincast.com>
* Copyright 2016 Thincast Technologies GmbH
*
* 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 HAVE_CONFIG_H
#include "config.h"
#endif
#include <winpr/crt.h>
#include <winpr/print.h>
#include <winpr/synch.h>
#include <winpr/thread.h>
#include <winpr/collections.h>
#include "update.h"
#include "surface.h"
#include "message.h"
#include "info.h"
#include "window.h"
#include <freerdp/log.h>
#include <freerdp/peer.h>
#include <freerdp/codec/bitmap.h>
#include "../cache/pointer.h"
#include "../cache/palette.h"
#include "../cache/bitmap.h"
#define TAG FREERDP_TAG("core.update")
static const char* const UPDATE_TYPE_STRINGS[] = { "Orders", "Bitmap", "Palette", "Synchronize" };
static const char* update_type_to_string(UINT16 updateType)
{
if (updateType >= ARRAYSIZE(UPDATE_TYPE_STRINGS))
return "UNKNOWN";
return UPDATE_TYPE_STRINGS[updateType];
}
static BOOL update_recv_orders(rdpUpdate* update, wStream* s)
{
UINT16 numberOrders;
if (Stream_GetRemainingLength(s) < 6)
{
WLog_ERR(TAG, "Stream_GetRemainingLength(s) < 6");
return FALSE;
}
Stream_Seek_UINT16(s); /* pad2OctetsA (2 bytes) */
Stream_Read_UINT16(s, numberOrders); /* numberOrders (2 bytes) */
Stream_Seek_UINT16(s); /* pad2OctetsB (2 bytes) */
while (numberOrders > 0)
{
if (!update_recv_order(update, s))
{
WLog_ERR(TAG, "update_recv_order() failed");
return FALSE;
}
numberOrders--;
}
return TRUE;
}
static BOOL update_read_bitmap_data(rdpUpdate* update, wStream* s, BITMAP_DATA* bitmapData)
{
WINPR_UNUSED(update);
if (Stream_GetRemainingLength(s) < 18)
return FALSE;
Stream_Read_UINT16(s, bitmapData->destLeft);
Stream_Read_UINT16(s, bitmapData->destTop);
Stream_Read_UINT16(s, bitmapData->destRight);
Stream_Read_UINT16(s, bitmapData->destBottom);
Stream_Read_UINT16(s, bitmapData->width);
Stream_Read_UINT16(s, bitmapData->height);
Stream_Read_UINT16(s, bitmapData->bitsPerPixel);
Stream_Read_UINT16(s, bitmapData->flags);
Stream_Read_UINT16(s, bitmapData->bitmapLength);
if (bitmapData->flags & BITMAP_COMPRESSION)
{
if (!(bitmapData->flags & NO_BITMAP_COMPRESSION_HDR))
{
if (Stream_GetRemainingLength(s) < 8)
return FALSE;
Stream_Read_UINT16(s,
bitmapData->cbCompFirstRowSize); /* cbCompFirstRowSize (2 bytes) */
Stream_Read_UINT16(s,
bitmapData->cbCompMainBodySize); /* cbCompMainBodySize (2 bytes) */
Stream_Read_UINT16(s, bitmapData->cbScanWidth); /* cbScanWidth (2 bytes) */
Stream_Read_UINT16(s,
bitmapData->cbUncompressedSize); /* cbUncompressedSize (2 bytes) */
bitmapData->bitmapLength = bitmapData->cbCompMainBodySize;
}
bitmapData->compressed = TRUE;
}
else
bitmapData->compressed = FALSE;
if (Stream_GetRemainingLength(s) < bitmapData->bitmapLength)
return FALSE;
if (bitmapData->bitmapLength > 0)
{
bitmapData->bitmapDataStream = malloc(bitmapData->bitmapLength);
if (!bitmapData->bitmapDataStream)
return FALSE;
memcpy(bitmapData->bitmapDataStream, Stream_Pointer(s), bitmapData->bitmapLength);
Stream_Seek(s, bitmapData->bitmapLength);
}
return TRUE;
}
static BOOL update_write_bitmap_data(rdpUpdate* update, wStream* s, BITMAP_DATA* bitmapData)
{
if (!Stream_EnsureRemainingCapacity(s, 64 + bitmapData->bitmapLength))
return FALSE;
if (update->autoCalculateBitmapData)
{
bitmapData->flags = 0;
bitmapData->cbCompFirstRowSize = 0;
if (bitmapData->compressed)
bitmapData->flags |= BITMAP_COMPRESSION;
if (update->context->settings->NoBitmapCompressionHeader)
{
bitmapData->flags |= NO_BITMAP_COMPRESSION_HDR;
bitmapData->cbCompMainBodySize = bitmapData->bitmapLength;
}
}
Stream_Write_UINT16(s, bitmapData->destLeft);
Stream_Write_UINT16(s, bitmapData->destTop);
Stream_Write_UINT16(s, bitmapData->destRight);
Stream_Write_UINT16(s, bitmapData->destBottom);
Stream_Write_UINT16(s, bitmapData->width);
Stream_Write_UINT16(s, bitmapData->height);
Stream_Write_UINT16(s, bitmapData->bitsPerPixel);
Stream_Write_UINT16(s, bitmapData->flags);
Stream_Write_UINT16(s, bitmapData->bitmapLength);
if (bitmapData->flags & BITMAP_COMPRESSION)
{
if (!(bitmapData->flags & NO_BITMAP_COMPRESSION_HDR))
{
Stream_Write_UINT16(s,
bitmapData->cbCompFirstRowSize); /* cbCompFirstRowSize (2 bytes) */
Stream_Write_UINT16(s,
bitmapData->cbCompMainBodySize); /* cbCompMainBodySize (2 bytes) */
Stream_Write_UINT16(s, bitmapData->cbScanWidth); /* cbScanWidth (2 bytes) */
Stream_Write_UINT16(s,
bitmapData->cbUncompressedSize); /* cbUncompressedSize (2 bytes) */
}
Stream_Write(s, bitmapData->bitmapDataStream, bitmapData->bitmapLength);
}
else
{
Stream_Write(s, bitmapData->bitmapDataStream, bitmapData->bitmapLength);
}
return TRUE;
}
BITMAP_UPDATE* update_read_bitmap_update(rdpUpdate* update, wStream* s)
{
UINT32 i;
BITMAP_UPDATE* bitmapUpdate = calloc(1, sizeof(BITMAP_UPDATE));
if (!bitmapUpdate)
goto fail;
if (Stream_GetRemainingLength(s) < 2)
goto fail;
Stream_Read_UINT16(s, bitmapUpdate->number); /* numberRectangles (2 bytes) */
WLog_Print(update->log, WLOG_TRACE, "BitmapUpdate: %" PRIu32 "", bitmapUpdate->number);
if (bitmapUpdate->number > bitmapUpdate->count)
{
UINT32 count = bitmapUpdate->number * 2;
BITMAP_DATA* newdata =
(BITMAP_DATA*)realloc(bitmapUpdate->rectangles, sizeof(BITMAP_DATA) * count);
if (!newdata)
goto fail;
bitmapUpdate->rectangles = newdata;
ZeroMemory(&bitmapUpdate->rectangles[bitmapUpdate->count],
sizeof(BITMAP_DATA) * (count - bitmapUpdate->count));
bitmapUpdate->count = count;
}
/* rectangles */
for (i = 0; i < bitmapUpdate->number; i++)
{
if (!update_read_bitmap_data(update, s, &bitmapUpdate->rectangles[i]))
goto fail;
}
return bitmapUpdate;
fail:
free_bitmap_update(update->context, bitmapUpdate);
return NULL;
}
static BOOL update_write_bitmap_update(rdpUpdate* update, wStream* s,
const BITMAP_UPDATE* bitmapUpdate)
{
int i;
if (!Stream_EnsureRemainingCapacity(s, 32))
return FALSE;
Stream_Write_UINT16(s, UPDATE_TYPE_BITMAP); /* updateType */
Stream_Write_UINT16(s, bitmapUpdate->number); /* numberRectangles (2 bytes) */
/* rectangles */
for (i = 0; i < (int)bitmapUpdate->number; i++)
{
if (!update_write_bitmap_data(update, s, &bitmapUpdate->rectangles[i]))
return FALSE;
}
return TRUE;
}
PALETTE_UPDATE* update_read_palette(rdpUpdate* update, wStream* s)
{
int i;
PALETTE_ENTRY* entry;
PALETTE_UPDATE* palette_update = calloc(1, sizeof(PALETTE_UPDATE));
if (!palette_update)
goto fail;
if (Stream_GetRemainingLength(s) < 6)
goto fail;
Stream_Seek_UINT16(s); /* pad2Octets (2 bytes) */
Stream_Read_UINT32(s, palette_update->number); /* numberColors (4 bytes), must be set to 256 */
if (palette_update->number > 256)
palette_update->number = 256;
if (Stream_GetRemainingLength(s) < palette_update->number * 3)
goto fail;
/* paletteEntries */
for (i = 0; i < (int)palette_update->number; i++)
{
entry = &palette_update->entries[i];
Stream_Read_UINT8(s, entry->red);
Stream_Read_UINT8(s, entry->green);
Stream_Read_UINT8(s, entry->blue);
}
return palette_update;
fail:
free_palette_update(update->context, palette_update);
return NULL;
}
static BOOL update_read_synchronize(rdpUpdate* update, wStream* s)
{
WINPR_UNUSED(update);
return Stream_SafeSeek(s, 2); /* pad2Octets (2 bytes) */
/**
* The Synchronize Update is an artifact from the
* T.128 protocol and should be ignored.
*/
}
static BOOL update_read_play_sound(wStream* s, PLAY_SOUND_UPDATE* play_sound)
{
if (Stream_GetRemainingLength(s) < 8)
return FALSE;
Stream_Read_UINT32(s, play_sound->duration); /* duration (4 bytes) */
Stream_Read_UINT32(s, play_sound->frequency); /* frequency (4 bytes) */
return TRUE;
}
BOOL update_recv_play_sound(rdpUpdate* update, wStream* s)
{
PLAY_SOUND_UPDATE play_sound;
if (!update_read_play_sound(s, &play_sound))
return FALSE;
return IFCALLRESULT(FALSE, update->PlaySound, update->context, &play_sound);
}
POINTER_POSITION_UPDATE* update_read_pointer_position(rdpUpdate* update, wStream* s)
{
POINTER_POSITION_UPDATE* pointer_position = calloc(1, sizeof(POINTER_POSITION_UPDATE));
if (!pointer_position)
goto fail;
if (Stream_GetRemainingLength(s) < 4)
goto fail;
Stream_Read_UINT16(s, pointer_position->xPos); /* xPos (2 bytes) */
Stream_Read_UINT16(s, pointer_position->yPos); /* yPos (2 bytes) */
return pointer_position;
fail:
free_pointer_position_update(update->context, pointer_position);
return NULL;
}
POINTER_SYSTEM_UPDATE* update_read_pointer_system(rdpUpdate* update, wStream* s)
{
POINTER_SYSTEM_UPDATE* pointer_system = calloc(1, sizeof(POINTER_SYSTEM_UPDATE));
if (!pointer_system)
goto fail;
if (Stream_GetRemainingLength(s) < 4)
goto fail;
Stream_Read_UINT32(s, pointer_system->type); /* systemPointerType (4 bytes) */
return pointer_system;
fail:
free_pointer_system_update(update->context, pointer_system);
return NULL;
}
static BOOL _update_read_pointer_color(wStream* s, POINTER_COLOR_UPDATE* pointer_color, BYTE xorBpp)
{
BYTE* newMask;
UINT32 scanlineSize;
if (!pointer_color)
goto fail;
if (Stream_GetRemainingLength(s) < 14)
goto fail;
Stream_Read_UINT16(s, pointer_color->cacheIndex); /* cacheIndex (2 bytes) */
Stream_Read_UINT16(s, pointer_color->xPos); /* xPos (2 bytes) */
Stream_Read_UINT16(s, pointer_color->yPos); /* yPos (2 bytes) */
/**
* As stated in 2.2.9.1.1.4.4 Color Pointer Update:
* The maximum allowed pointer width/height is 96 pixels if the client indicated support
* for large pointers by setting the LARGE_POINTER_FLAG (0x00000001) in the Large
* Pointer Capability Set (section 2.2.7.2.7). If the LARGE_POINTER_FLAG was not
* set, the maximum allowed pointer width/height is 32 pixels.
*
* So we check for a maximum of 96 for CVE-2014-0250.
*/
Stream_Read_UINT16(s, pointer_color->width); /* width (2 bytes) */
Stream_Read_UINT16(s, pointer_color->height); /* height (2 bytes) */
if ((pointer_color->width > 96) || (pointer_color->height > 96))
goto fail;
Stream_Read_UINT16(s, pointer_color->lengthAndMask); /* lengthAndMask (2 bytes) */
Stream_Read_UINT16(s, pointer_color->lengthXorMask); /* lengthXorMask (2 bytes) */
/**
* There does not seem to be any documentation on why
* xPos / yPos can be larger than width / height
* so it is missing in documentation or a bug in implementation
* 2.2.9.1.1.4.4 Color Pointer Update (TS_COLORPOINTERATTRIBUTE)
*/
if (pointer_color->xPos >= pointer_color->width)
pointer_color->xPos = 0;
if (pointer_color->yPos >= pointer_color->height)
pointer_color->yPos = 0;
if (pointer_color->lengthXorMask > 0)
{
/**
* Spec states that:
*
* xorMaskData (variable): A variable-length array of bytes. Contains the 24-bpp, bottom-up
* XOR mask scan-line data. The XOR mask is padded to a 2-byte boundary for each encoded
* scan-line. For example, if a 3x3 pixel cursor is being sent, then each scan-line will
* consume 10 bytes (3 pixels per scan-line multiplied by 3 bytes per pixel, rounded up to
* the next even number of bytes).
*
* In fact instead of 24-bpp, the bpp parameter is given by the containing packet.
*/
if (Stream_GetRemainingLength(s) < pointer_color->lengthXorMask)
goto fail;
scanlineSize = (7 + xorBpp * pointer_color->width) / 8;
scanlineSize = ((scanlineSize + 1) / 2) * 2;
if (scanlineSize * pointer_color->height != pointer_color->lengthXorMask)
{
WLog_ERR(TAG,
"invalid lengthXorMask: width=%" PRIu32 " height=%" PRIu32 ", %" PRIu32
" instead of %" PRIu32 "",
pointer_color->width, pointer_color->height, pointer_color->lengthXorMask,
scanlineSize * pointer_color->height);
goto fail;
}
newMask = realloc(pointer_color->xorMaskData, pointer_color->lengthXorMask);
if (!newMask)
goto fail;
pointer_color->xorMaskData = newMask;
Stream_Read(s, pointer_color->xorMaskData, pointer_color->lengthXorMask);
}
if (pointer_color->lengthAndMask > 0)
{
/**
* andMaskData (variable): A variable-length array of bytes. Contains the 1-bpp, bottom-up
* AND mask scan-line data. The AND mask is padded to a 2-byte boundary for each encoded
* scan-line. For example, if a 7x7 pixel cursor is being sent, then each scan-line will
* consume 2 bytes (7 pixels per scan-line multiplied by 1 bpp, rounded up to the next even
* number of bytes).
*/
if (Stream_GetRemainingLength(s) < pointer_color->lengthAndMask)
goto fail;
scanlineSize = ((7 + pointer_color->width) / 8);
scanlineSize = ((1 + scanlineSize) / 2) * 2;
if (scanlineSize * pointer_color->height != pointer_color->lengthAndMask)
{
WLog_ERR(TAG, "invalid lengthAndMask: %" PRIu32 " instead of %" PRIu32 "",
pointer_color->lengthAndMask, scanlineSize * pointer_color->height);
goto fail;
}
newMask = realloc(pointer_color->andMaskData, pointer_color->lengthAndMask);
if (!newMask)
goto fail;
pointer_color->andMaskData = newMask;
Stream_Read(s, pointer_color->andMaskData, pointer_color->lengthAndMask);
}
if (Stream_GetRemainingLength(s) > 0)
Stream_Seek_UINT8(s); /* pad (1 byte) */
return TRUE;
fail:
return FALSE;
}
POINTER_COLOR_UPDATE* update_read_pointer_color(rdpUpdate* update, wStream* s, BYTE xorBpp)
{
POINTER_COLOR_UPDATE* pointer_color = calloc(1, sizeof(POINTER_COLOR_UPDATE));
if (!pointer_color)
goto fail;
if (!_update_read_pointer_color(s, pointer_color, xorBpp))
goto fail;
return pointer_color;
fail:
free_pointer_color_update(update->context, pointer_color);
return NULL;
}
static BOOL _update_read_pointer_large(wStream* s, POINTER_LARGE_UPDATE* pointer)
{
BYTE* newMask;
UINT32 scanlineSize;
if (!pointer)
goto fail;
if (Stream_GetRemainingLength(s) < 14)
goto fail;
Stream_Read_UINT16(s, pointer->xorBpp);
Stream_Read_UINT16(s, pointer->cacheIndex); /* cacheIndex (2 bytes) */
Stream_Read_UINT16(s, pointer->hotSpotX); /* xPos (2 bytes) */
Stream_Read_UINT16(s, pointer->hotSpotY); /* yPos (2 bytes) */
Stream_Read_UINT16(s, pointer->width); /* width (2 bytes) */
Stream_Read_UINT16(s, pointer->height); /* height (2 bytes) */
if ((pointer->width > 384) || (pointer->height > 384))
goto fail;
Stream_Read_UINT16(s, pointer->lengthAndMask); /* lengthAndMask (2 bytes) */
Stream_Read_UINT16(s, pointer->lengthXorMask); /* lengthXorMask (2 bytes) */
if (pointer->hotSpotX >= pointer->width)
pointer->hotSpotX = 0;
if (pointer->hotSpotY >= pointer->height)
pointer->hotSpotY = 0;
if (pointer->lengthXorMask > 0)
{
/**
* Spec states that:
*
* xorMaskData (variable): A variable-length array of bytes. Contains the 24-bpp, bottom-up
* XOR mask scan-line data. The XOR mask is padded to a 2-byte boundary for each encoded
* scan-line. For example, if a 3x3 pixel cursor is being sent, then each scan-line will
* consume 10 bytes (3 pixels per scan-line multiplied by 3 bytes per pixel, rounded up to
* the next even number of bytes).
*
* In fact instead of 24-bpp, the bpp parameter is given by the containing packet.
*/
if (Stream_GetRemainingLength(s) < pointer->lengthXorMask)
goto fail;
scanlineSize = (7 + pointer->xorBpp * pointer->width) / 8;
scanlineSize = ((scanlineSize + 1) / 2) * 2;
if (scanlineSize * pointer->height != pointer->lengthXorMask)
{
WLog_ERR(TAG,
"invalid lengthXorMask: width=%" PRIu32 " height=%" PRIu32 ", %" PRIu32
" instead of %" PRIu32 "",
pointer->width, pointer->height, pointer->lengthXorMask,
scanlineSize * pointer->height);
goto fail;
}
newMask = realloc(pointer->xorMaskData, pointer->lengthXorMask);
if (!newMask)
goto fail;
pointer->xorMaskData = newMask;
Stream_Read(s, pointer->xorMaskData, pointer->lengthXorMask);
}
if (pointer->lengthAndMask > 0)
{
/**
* andMaskData (variable): A variable-length array of bytes. Contains the 1-bpp, bottom-up
* AND mask scan-line data. The AND mask is padded to a 2-byte boundary for each encoded
* scan-line. For example, if a 7x7 pixel cursor is being sent, then each scan-line will
* consume 2 bytes (7 pixels per scan-line multiplied by 1 bpp, rounded up to the next even
* number of bytes).
*/
if (Stream_GetRemainingLength(s) < pointer->lengthAndMask)
goto fail;
scanlineSize = ((7 + pointer->width) / 8);
scanlineSize = ((1 + scanlineSize) / 2) * 2;
if (scanlineSize * pointer->height != pointer->lengthAndMask)
{
WLog_ERR(TAG, "invalid lengthAndMask: %" PRIu32 " instead of %" PRIu32 "",
pointer->lengthAndMask, scanlineSize * pointer->height);
goto fail;
}
newMask = realloc(pointer->andMaskData, pointer->lengthAndMask);
if (!newMask)
goto fail;
pointer->andMaskData = newMask;
Stream_Read(s, pointer->andMaskData, pointer->lengthAndMask);
}
if (Stream_GetRemainingLength(s) > 0)
Stream_Seek_UINT8(s); /* pad (1 byte) */
return TRUE;
fail:
return FALSE;
}
POINTER_LARGE_UPDATE* update_read_pointer_large(rdpUpdate* update, wStream* s)
{
POINTER_LARGE_UPDATE* pointer = calloc(1, sizeof(POINTER_LARGE_UPDATE));
if (!pointer)
goto fail;
if (!_update_read_pointer_large(s, pointer))
goto fail;
return pointer;
fail:
free_pointer_large_update(update->context, pointer);
return NULL;
}
POINTER_NEW_UPDATE* update_read_pointer_new(rdpUpdate* update, wStream* s)
{
POINTER_NEW_UPDATE* pointer_new = calloc(1, sizeof(POINTER_NEW_UPDATE));
if (!pointer_new)
goto fail;
if (Stream_GetRemainingLength(s) < 2)
goto fail;
Stream_Read_UINT16(s, pointer_new->xorBpp); /* xorBpp (2 bytes) */
if ((pointer_new->xorBpp < 1) || (pointer_new->xorBpp > 32))
{
WLog_ERR(TAG, "invalid xorBpp %" PRIu32 "", pointer_new->xorBpp);
goto fail;
}
if (!_update_read_pointer_color(s, &pointer_new->colorPtrAttr,
pointer_new->xorBpp)) /* colorPtrAttr */
goto fail;
return pointer_new;
fail:
free_pointer_new_update(update->context, pointer_new);
return NULL;
}
POINTER_CACHED_UPDATE* update_read_pointer_cached(rdpUpdate* update, wStream* s)
{
POINTER_CACHED_UPDATE* pointer = calloc(1, sizeof(POINTER_CACHED_UPDATE));
if (!pointer)
goto fail;
if (Stream_GetRemainingLength(s) < 2)
goto fail;
Stream_Read_UINT16(s, pointer->cacheIndex); /* cacheIndex (2 bytes) */
return pointer;
fail:
free_pointer_cached_update(update->context, pointer);
return NULL;
}
BOOL update_recv_pointer(rdpUpdate* update, wStream* s)
{
BOOL rc = FALSE;
UINT16 messageType;
rdpContext* context = update->context;
rdpPointerUpdate* pointer = update->pointer;
if (Stream_GetRemainingLength(s) < 2 + 2)
return FALSE;
Stream_Read_UINT16(s, messageType); /* messageType (2 bytes) */
Stream_Seek_UINT16(s); /* pad2Octets (2 bytes) */
switch (messageType)
{
case PTR_MSG_TYPE_POSITION:
{
POINTER_POSITION_UPDATE* pointer_position = update_read_pointer_position(update, s);
if (pointer_position)
{
rc = IFCALLRESULT(FALSE, pointer->PointerPosition, context, pointer_position);
free_pointer_position_update(context, pointer_position);
}
}
break;
case PTR_MSG_TYPE_SYSTEM:
{
POINTER_SYSTEM_UPDATE* pointer_system = update_read_pointer_system(update, s);
if (pointer_system)
{
rc = IFCALLRESULT(FALSE, pointer->PointerSystem, context, pointer_system);
free_pointer_system_update(context, pointer_system);
}
}
break;
case PTR_MSG_TYPE_COLOR:
{
POINTER_COLOR_UPDATE* pointer_color = update_read_pointer_color(update, s, 24);
if (pointer_color)
{
rc = IFCALLRESULT(FALSE, pointer->PointerColor, context, pointer_color);
free_pointer_color_update(context, pointer_color);
}
}
break;
case PTR_MSG_TYPE_POINTER_LARGE:
{
POINTER_LARGE_UPDATE* pointer_large = update_read_pointer_large(update, s);
if (pointer_large)
{
rc = IFCALLRESULT(FALSE, pointer->PointerLarge, context, pointer_large);
free_pointer_large_update(context, pointer_large);
}
}
break;
case PTR_MSG_TYPE_POINTER:
{
POINTER_NEW_UPDATE* pointer_new = update_read_pointer_new(update, s);
if (pointer_new)
{
rc = IFCALLRESULT(FALSE, pointer->PointerNew, context, pointer_new);
free_pointer_new_update(context, pointer_new);
}
}
break;
case PTR_MSG_TYPE_CACHED:
{
POINTER_CACHED_UPDATE* pointer_cached = update_read_pointer_cached(update, s);
if (pointer_cached)
{
rc = IFCALLRESULT(FALSE, pointer->PointerCached, context, pointer_cached);
free_pointer_cached_update(context, pointer_cached);
}
}
break;
default:
break;
}
return rc;
}
BOOL update_recv(rdpUpdate* update, wStream* s)
{
BOOL rc = FALSE;
UINT16 updateType;
rdpContext* context = update->context;
if (Stream_GetRemainingLength(s) < 2)
{
WLog_ERR(TAG, "Stream_GetRemainingLength(s) < 2");
return FALSE;
}
Stream_Read_UINT16(s, updateType); /* updateType (2 bytes) */
WLog_Print(update->log, WLOG_TRACE, "%s Update Data PDU", UPDATE_TYPE_STRINGS[updateType]);
if (!update_begin_paint(update))
goto fail;
switch (updateType)
{
case UPDATE_TYPE_ORDERS:
rc = update_recv_orders(update, s);
break;
case UPDATE_TYPE_BITMAP:
{
BITMAP_UPDATE* bitmap_update = update_read_bitmap_update(update, s);
if (!bitmap_update)
{
WLog_ERR(TAG, "UPDATE_TYPE_BITMAP - update_read_bitmap_update() failed");
goto fail;
}
rc = IFCALLRESULT(FALSE, update->BitmapUpdate, context, bitmap_update);
free_bitmap_update(update->context, bitmap_update);
}
break;
case UPDATE_TYPE_PALETTE:
{
PALETTE_UPDATE* palette_update = update_read_palette(update, s);
if (!palette_update)
{
WLog_ERR(TAG, "UPDATE_TYPE_PALETTE - update_read_palette() failed");
goto fail;
}
rc = IFCALLRESULT(FALSE, update->Palette, context, palette_update);
free_palette_update(context, palette_update);
}
break;
case UPDATE_TYPE_SYNCHRONIZE:
if (!update_read_synchronize(update, s))
goto fail;
rc = IFCALLRESULT(TRUE, update->Synchronize, context);
break;
default:
break;
}
fail:
if (!update_end_paint(update))
rc = FALSE;
if (!rc)
{
WLog_ERR(TAG, "UPDATE_TYPE %s [%" PRIu16 "] failed", update_type_to_string(updateType),
updateType);
return FALSE;
}
return TRUE;
}
void update_reset_state(rdpUpdate* update)
{
rdpPrimaryUpdate* primary = update->primary;
rdpAltSecUpdate* altsec = update->altsec;
if (primary->fast_glyph.glyphData.aj)
{
free(primary->fast_glyph.glyphData.aj);
primary->fast_glyph.glyphData.aj = NULL;
}
ZeroMemory(&primary->order_info, sizeof(ORDER_INFO));
ZeroMemory(&primary->dstblt, sizeof(DSTBLT_ORDER));
ZeroMemory(&primary->patblt, sizeof(PATBLT_ORDER));
ZeroMemory(&primary->scrblt, sizeof(SCRBLT_ORDER));
ZeroMemory(&primary->opaque_rect, sizeof(OPAQUE_RECT_ORDER));
ZeroMemory(&primary->draw_nine_grid, sizeof(DRAW_NINE_GRID_ORDER));
ZeroMemory(&primary->multi_dstblt, sizeof(MULTI_DSTBLT_ORDER));
ZeroMemory(&primary->multi_patblt, sizeof(MULTI_PATBLT_ORDER));
ZeroMemory(&primary->multi_scrblt, sizeof(MULTI_SCRBLT_ORDER));
ZeroMemory(&primary->multi_opaque_rect, sizeof(MULTI_OPAQUE_RECT_ORDER));
ZeroMemory(&primary->multi_draw_nine_grid, sizeof(MULTI_DRAW_NINE_GRID_ORDER));
ZeroMemory(&primary->line_to, sizeof(LINE_TO_ORDER));
ZeroMemory(&primary->polyline, sizeof(POLYLINE_ORDER));
ZeroMemory(&primary->memblt, sizeof(MEMBLT_ORDER));
ZeroMemory(&primary->mem3blt, sizeof(MEM3BLT_ORDER));
ZeroMemory(&primary->save_bitmap, sizeof(SAVE_BITMAP_ORDER));
ZeroMemory(&primary->glyph_index, sizeof(GLYPH_INDEX_ORDER));
ZeroMemory(&primary->fast_index, sizeof(FAST_INDEX_ORDER));
ZeroMemory(&primary->fast_glyph, sizeof(FAST_GLYPH_ORDER));
ZeroMemory(&primary->polygon_sc, sizeof(POLYGON_SC_ORDER));
ZeroMemory(&primary->polygon_cb, sizeof(POLYGON_CB_ORDER));
ZeroMemory(&primary->ellipse_sc, sizeof(ELLIPSE_SC_ORDER));
ZeroMemory(&primary->ellipse_cb, sizeof(ELLIPSE_CB_ORDER));
primary->order_info.orderType = ORDER_TYPE_PATBLT;
if (!update->initialState)
{
altsec->switch_surface.bitmapId = SCREEN_BITMAP_SURFACE;
IFCALL(altsec->SwitchSurface, update->context, &(altsec->switch_surface));
}
}
BOOL update_post_connect(rdpUpdate* update)
{
update->asynchronous = update->context->settings->AsyncUpdate;
if (update->asynchronous)
if (!(update->proxy = update_message_proxy_new(update)))
return FALSE;
update->altsec->switch_surface.bitmapId = SCREEN_BITMAP_SURFACE;
IFCALL(update->altsec->SwitchSurface, update->context, &(update->altsec->switch_surface));
update->initialState = FALSE;
return TRUE;
}
void update_post_disconnect(rdpUpdate* update)
{
update->asynchronous = update->context->settings->AsyncUpdate;
if (update->asynchronous)
update_message_proxy_free(update->proxy);
update->initialState = TRUE;
}
static BOOL _update_begin_paint(rdpContext* context)
{
wStream* s;
rdpUpdate* update = context->update;
if (update->us)
{
if (!update_end_paint(update))
return FALSE;
}
s = fastpath_update_pdu_init_new(context->rdp->fastpath);
if (!s)
return FALSE;
Stream_SealLength(s);
Stream_Seek(s, 2); /* numberOrders (2 bytes) */
update->combineUpdates = TRUE;
update->numberOrders = 0;
update->us = s;
return TRUE;
}
static BOOL _update_end_paint(rdpContext* context)
{
wStream* s;
int headerLength;
rdpUpdate* update = context->update;
if (!update->us)
return FALSE;
s = update->us;
headerLength = Stream_Length(s);
Stream_SealLength(s);
Stream_SetPosition(s, headerLength);
Stream_Write_UINT16(s, update->numberOrders); /* numberOrders (2 bytes) */
Stream_SetPosition(s, Stream_Length(s));
if (update->numberOrders > 0)
{
WLog_DBG(TAG, "sending %" PRIu16 " orders", update->numberOrders);
fastpath_send_update_pdu(context->rdp->fastpath, FASTPATH_UPDATETYPE_ORDERS, s, FALSE);
}
update->combineUpdates = FALSE;
update->numberOrders = 0;
update->us = NULL;
Stream_Free(s, TRUE);
return TRUE;
}
static void update_flush(rdpContext* context)
{
rdpUpdate* update = context->update;
if (update->numberOrders > 0)
{
update_end_paint(update);
update_begin_paint(update);
}
}
static void update_force_flush(rdpContext* context)
{
update_flush(context);
}
static BOOL update_check_flush(rdpContext* context, int size)
{
wStream* s;
rdpUpdate* update = context->update;
s = update->us;
if (!update->us)
{
update_begin_paint(update);
return FALSE;
}
if (Stream_GetPosition(s) + size + 64 >= 0x3FFF)
{
update_flush(context);
return TRUE;
}
return FALSE;
}
static BOOL update_set_bounds(rdpContext* context, const rdpBounds* bounds)
{
rdpUpdate* update = context->update;
CopyMemory(&update->previousBounds, &update->currentBounds, sizeof(rdpBounds));
if (!bounds)
ZeroMemory(&update->currentBounds, sizeof(rdpBounds));
else
CopyMemory(&update->currentBounds, bounds, sizeof(rdpBounds));
return TRUE;
}
static BOOL update_bounds_is_null(rdpBounds* bounds)
{
if ((bounds->left == 0) && (bounds->top == 0) && (bounds->right == 0) && (bounds->bottom == 0))
return TRUE;
return FALSE;
}
static BOOL update_bounds_equals(rdpBounds* bounds1, rdpBounds* bounds2)
{
if ((bounds1->left == bounds2->left) && (bounds1->top == bounds2->top) &&
(bounds1->right == bounds2->right) && (bounds1->bottom == bounds2->bottom))
return TRUE;
return FALSE;
}
static int update_prepare_bounds(rdpContext* context, ORDER_INFO* orderInfo)
{
int length = 0;
rdpUpdate* update = context->update;
orderInfo->boundsFlags = 0;
if (update_bounds_is_null(&update->currentBounds))
return 0;
orderInfo->controlFlags |= ORDER_BOUNDS;
if (update_bounds_equals(&update->previousBounds, &update->currentBounds))
{
orderInfo->controlFlags |= ORDER_ZERO_BOUNDS_DELTAS;
return 0;
}
else
{
length += 1;
if (update->previousBounds.left != update->currentBounds.left)
{
orderInfo->bounds.left = update->currentBounds.left;
orderInfo->boundsFlags |= BOUND_LEFT;
length += 2;
}
if (update->previousBounds.top != update->currentBounds.top)
{
orderInfo->bounds.top = update->currentBounds.top;
orderInfo->boundsFlags |= BOUND_TOP;
length += 2;
}
if (update->previousBounds.right != update->currentBounds.right)
{
orderInfo->bounds.right = update->currentBounds.right;
orderInfo->boundsFlags |= BOUND_RIGHT;
length += 2;
}
if (update->previousBounds.bottom != update->currentBounds.bottom)
{
orderInfo->bounds.bottom = update->currentBounds.bottom;
orderInfo->boundsFlags |= BOUND_BOTTOM;
length += 2;
}
}
return length;
}
static int update_prepare_order_info(rdpContext* context, ORDER_INFO* orderInfo, UINT32 orderType)
{
int length = 1;
orderInfo->fieldFlags = 0;
orderInfo->orderType = orderType;
orderInfo->controlFlags = ORDER_STANDARD;
orderInfo->controlFlags |= ORDER_TYPE_CHANGE;
length += 1;
length += PRIMARY_DRAWING_ORDER_FIELD_BYTES[orderInfo->orderType];
length += update_prepare_bounds(context, orderInfo);
return length;
}
static int update_write_order_info(rdpContext* context, wStream* s, ORDER_INFO* orderInfo,
size_t offset)
{
size_t position;
WINPR_UNUSED(context);
position = Stream_GetPosition(s);
Stream_SetPosition(s, offset);
Stream_Write_UINT8(s, orderInfo->controlFlags); /* controlFlags (1 byte) */
if (orderInfo->controlFlags & ORDER_TYPE_CHANGE)
Stream_Write_UINT8(s, orderInfo->orderType); /* orderType (1 byte) */
update_write_field_flags(s, orderInfo->fieldFlags, orderInfo->controlFlags,
PRIMARY_DRAWING_ORDER_FIELD_BYTES[orderInfo->orderType]);
update_write_bounds(s, orderInfo);
Stream_SetPosition(s, position);
return 0;
}
static void update_write_refresh_rect(wStream* s, BYTE count, const RECTANGLE_16* areas)
{
int i;
Stream_Write_UINT8(s, count); /* numberOfAreas (1 byte) */
Stream_Seek(s, 3); /* pad3Octets (3 bytes) */
for (i = 0; i < count; i++)
{
Stream_Write_UINT16(s, areas[i].left); /* left (2 bytes) */
Stream_Write_UINT16(s, areas[i].top); /* top (2 bytes) */
Stream_Write_UINT16(s, areas[i].right); /* right (2 bytes) */
Stream_Write_UINT16(s, areas[i].bottom); /* bottom (2 bytes) */
}
}
static BOOL update_send_refresh_rect(rdpContext* context, BYTE count, const RECTANGLE_16* areas)
{
rdpRdp* rdp = context->rdp;
if (rdp->settings->RefreshRect)
{
wStream* s = rdp_data_pdu_init(rdp);
if (!s)
return FALSE;
update_write_refresh_rect(s, count, areas);
return rdp_send_data_pdu(rdp, s, DATA_PDU_TYPE_REFRESH_RECT, rdp->mcs->userId);
}
return TRUE;
}
static void update_write_suppress_output(wStream* s, BYTE allow, const RECTANGLE_16* area)
{
Stream_Write_UINT8(s, allow); /* allowDisplayUpdates (1 byte) */
/* Use zeros for padding (like mstsc) for compatibility with legacy servers */
Stream_Zero(s, 3); /* pad3Octets (3 bytes) */
if (allow > 0)
{
Stream_Write_UINT16(s, area->left); /* left (2 bytes) */
Stream_Write_UINT16(s, area->top); /* top (2 bytes) */
Stream_Write_UINT16(s, area->right); /* right (2 bytes) */
Stream_Write_UINT16(s, area->bottom); /* bottom (2 bytes) */
}
}
static BOOL update_send_suppress_output(rdpContext* context, BYTE allow, const RECTANGLE_16* area)
{
rdpRdp* rdp = context->rdp;
if (rdp->settings->SuppressOutput)
{
wStream* s = rdp_data_pdu_init(rdp);
if (!s)
return FALSE;
update_write_suppress_output(s, allow, area);
return rdp_send_data_pdu(rdp, s, DATA_PDU_TYPE_SUPPRESS_OUTPUT, rdp->mcs->userId);
}
return TRUE;
}
static BOOL update_send_surface_command(rdpContext* context, wStream* s)
{
wStream* update;
rdpRdp* rdp = context->rdp;
BOOL ret;
update = fastpath_update_pdu_init(rdp->fastpath);
if (!update)
return FALSE;
if (!Stream_EnsureRemainingCapacity(update, Stream_GetPosition(s)))
{
ret = FALSE;
goto out;
}
Stream_Write(update, Stream_Buffer(s), Stream_GetPosition(s));
ret = fastpath_send_update_pdu(rdp->fastpath, FASTPATH_UPDATETYPE_SURFCMDS, update, FALSE);
out:
Stream_Release(update);
return ret;
}
static BOOL update_send_surface_bits(rdpContext* context,
const SURFACE_BITS_COMMAND* surfaceBitsCommand)
{
wStream* s;
rdpRdp* rdp = context->rdp;
BOOL ret = FALSE;
update_force_flush(context);
s = fastpath_update_pdu_init(rdp->fastpath);
if (!s)
return FALSE;
if (!update_write_surfcmd_surface_bits(s, surfaceBitsCommand))
goto out_fail;
if (!fastpath_send_update_pdu(rdp->fastpath, FASTPATH_UPDATETYPE_SURFCMDS, s,
surfaceBitsCommand->skipCompression))
goto out_fail;
update_force_flush(context);
ret = TRUE;
out_fail:
Stream_Release(s);
return ret;
}
static BOOL update_send_surface_frame_marker(rdpContext* context,
const SURFACE_FRAME_MARKER* surfaceFrameMarker)
{
wStream* s;
rdpRdp* rdp = context->rdp;
BOOL ret = FALSE;
update_force_flush(context);
s = fastpath_update_pdu_init(rdp->fastpath);
if (!s)
return FALSE;
if (!update_write_surfcmd_frame_marker(s, surfaceFrameMarker->frameAction,
surfaceFrameMarker->frameId) ||
!fastpath_send_update_pdu(rdp->fastpath, FASTPATH_UPDATETYPE_SURFCMDS, s, FALSE))
goto out_fail;
update_force_flush(context);
ret = TRUE;
out_fail:
Stream_Release(s);
return ret;
}
static BOOL update_send_surface_frame_bits(rdpContext* context, const SURFACE_BITS_COMMAND* cmd,
BOOL first, BOOL last, UINT32 frameId)
{
wStream* s;
rdpRdp* rdp = context->rdp;
BOOL ret = FALSE;
update_force_flush(context);
s = fastpath_update_pdu_init(rdp->fastpath);
if (!s)
return FALSE;
if (first)
{
if (!update_write_surfcmd_frame_marker(s, SURFACECMD_FRAMEACTION_BEGIN, frameId))
goto out_fail;
}
if (!update_write_surfcmd_surface_bits(s, cmd))
goto out_fail;
if (last)
{
if (!update_write_surfcmd_frame_marker(s, SURFACECMD_FRAMEACTION_END, frameId))
goto out_fail;
}
ret = fastpath_send_update_pdu(rdp->fastpath, FASTPATH_UPDATETYPE_SURFCMDS, s,
cmd->skipCompression);
update_force_flush(context);
out_fail:
Stream_Release(s);
return ret;
}
static BOOL update_send_frame_acknowledge(rdpContext* context, UINT32 frameId)
{
rdpRdp* rdp = context->rdp;
if (rdp->settings->ReceivedCapabilities[CAPSET_TYPE_FRAME_ACKNOWLEDGE])
{
wStream* s = rdp_data_pdu_init(rdp);
if (!s)
return FALSE;
Stream_Write_UINT32(s, frameId);
return rdp_send_data_pdu(rdp, s, DATA_PDU_TYPE_FRAME_ACKNOWLEDGE, rdp->mcs->userId);
}
return TRUE;
}
static BOOL update_send_synchronize(rdpContext* context)
{
wStream* s;
rdpRdp* rdp = context->rdp;
BOOL ret;
s = fastpath_update_pdu_init(rdp->fastpath);
if (!s)
return FALSE;
Stream_Zero(s, 2); /* pad2Octets (2 bytes) */
ret = fastpath_send_update_pdu(rdp->fastpath, FASTPATH_UPDATETYPE_SYNCHRONIZE, s, FALSE);
Stream_Release(s);
return ret;
}
static BOOL update_send_desktop_resize(rdpContext* context)
{
return rdp_server_reactivate(context->rdp);
}
static BOOL update_send_bitmap_update(rdpContext* context, const BITMAP_UPDATE* bitmapUpdate)
{
wStream* s;
rdpRdp* rdp = context->rdp;
rdpUpdate* update = context->update;
BOOL ret = TRUE;
update_force_flush(context);
s = fastpath_update_pdu_init(rdp->fastpath);
if (!s)
return FALSE;
if (!update_write_bitmap_update(update, s, bitmapUpdate) ||
!fastpath_send_update_pdu(rdp->fastpath, FASTPATH_UPDATETYPE_BITMAP, s,
bitmapUpdate->skipCompression))
{
ret = FALSE;
goto out_fail;
}
update_force_flush(context);
out_fail:
Stream_Release(s);
return ret;
}
static BOOL update_send_play_sound(rdpContext* context, const PLAY_SOUND_UPDATE* play_sound)
{
wStream* s;
rdpRdp* rdp = context->rdp;
if (!rdp->settings->ReceivedCapabilities[CAPSET_TYPE_SOUND])
{
return TRUE;
}
s = rdp_data_pdu_init(rdp);
if (!s)
return FALSE;
Stream_Write_UINT32(s, play_sound->duration);
Stream_Write_UINT32(s, play_sound->frequency);
return rdp_send_data_pdu(rdp, s, DATA_PDU_TYPE_PLAY_SOUND, rdp->mcs->userId);
}
/**
* Primary Drawing Orders
*/
static BOOL update_send_dstblt(rdpContext* context, const DSTBLT_ORDER* dstblt)
{
wStream* s;
UINT32 offset;
UINT32 headerLength;
ORDER_INFO orderInfo;
int inf;
rdpUpdate* update = context->update;
headerLength = update_prepare_order_info(context, &orderInfo, ORDER_TYPE_DSTBLT);
inf = update_approximate_dstblt_order(&orderInfo, dstblt);
update_check_flush(context, headerLength + inf);
s = update->us;
if (!s)
return FALSE;
offset = Stream_GetPosition(s);
if (!Stream_EnsureRemainingCapacity(s, headerLength))
return FALSE;
Stream_Seek(s, headerLength);
if (!update_write_dstblt_order(s, &orderInfo, dstblt))
return FALSE;
update_write_order_info(context, s, &orderInfo, offset);
update->numberOrders++;
return TRUE;
}
static BOOL update_send_patblt(rdpContext* context, PATBLT_ORDER* patblt)
{
wStream* s;
size_t offset;
int headerLength;
ORDER_INFO orderInfo;
rdpUpdate* update = context->update;
headerLength = update_prepare_order_info(context, &orderInfo, ORDER_TYPE_PATBLT);
update_check_flush(context, headerLength + update_approximate_patblt_order(&orderInfo, patblt));
s = update->us;
if (!s)
return FALSE;
offset = Stream_GetPosition(s);
if (!Stream_EnsureRemainingCapacity(s, headerLength))
return FALSE;
Stream_Seek(s, headerLength);
update_write_patblt_order(s, &orderInfo, patblt);
update_write_order_info(context, s, &orderInfo, offset);
update->numberOrders++;
return TRUE;
}
static BOOL update_send_scrblt(rdpContext* context, const SCRBLT_ORDER* scrblt)
{
wStream* s;
UINT32 offset;
UINT32 headerLength;
ORDER_INFO orderInfo;
int inf;
rdpUpdate* update = context->update;
headerLength = update_prepare_order_info(context, &orderInfo, ORDER_TYPE_SCRBLT);
inf = update_approximate_scrblt_order(&orderInfo, scrblt);
update_check_flush(context, headerLength + inf);
s = update->us;
if (!s)
return TRUE;
offset = Stream_GetPosition(s);
if (!Stream_EnsureRemainingCapacity(s, headerLength))
return FALSE;
Stream_Seek(s, headerLength);
update_write_scrblt_order(s, &orderInfo, scrblt);
update_write_order_info(context, s, &orderInfo, offset);
update->numberOrders++;
return TRUE;
}
static BOOL update_send_opaque_rect(rdpContext* context, const OPAQUE_RECT_ORDER* opaque_rect)
{
wStream* s;
size_t offset;
int headerLength;
ORDER_INFO orderInfo;
rdpUpdate* update = context->update;
headerLength = update_prepare_order_info(context, &orderInfo, ORDER_TYPE_OPAQUE_RECT);
update_check_flush(context, headerLength +
update_approximate_opaque_rect_order(&orderInfo, opaque_rect));
s = update->us;
if (!s)
return FALSE;
offset = Stream_GetPosition(s);
if (!Stream_EnsureRemainingCapacity(s, headerLength))
return FALSE;
Stream_Seek(s, headerLength);
update_write_opaque_rect_order(s, &orderInfo, opaque_rect);
update_write_order_info(context, s, &orderInfo, offset);
update->numberOrders++;
return TRUE;
}
static BOOL update_send_line_to(rdpContext* context, const LINE_TO_ORDER* line_to)
{
wStream* s;
int offset;
int headerLength;
ORDER_INFO orderInfo;
int inf;
rdpUpdate* update = context->update;
headerLength = update_prepare_order_info(context, &orderInfo, ORDER_TYPE_LINE_TO);
inf = update_approximate_line_to_order(&orderInfo, line_to);
update_check_flush(context, headerLength + inf);
s = update->us;
if (!s)
return FALSE;
offset = Stream_GetPosition(s);
if (!Stream_EnsureRemainingCapacity(s, headerLength))
return FALSE;
Stream_Seek(s, headerLength);
update_write_line_to_order(s, &orderInfo, line_to);
update_write_order_info(context, s, &orderInfo, offset);
update->numberOrders++;
return TRUE;
}
static BOOL update_send_memblt(rdpContext* context, MEMBLT_ORDER* memblt)
{
wStream* s;
size_t offset;
int headerLength;
ORDER_INFO orderInfo;
rdpUpdate* update = context->update;
headerLength = update_prepare_order_info(context, &orderInfo, ORDER_TYPE_MEMBLT);
update_check_flush(context, headerLength + update_approximate_memblt_order(&orderInfo, memblt));
s = update->us;
if (!s)
return FALSE;
offset = Stream_GetPosition(s);
if (!Stream_EnsureRemainingCapacity(s, headerLength))
return FALSE;
Stream_Seek(s, headerLength);
update_write_memblt_order(s, &orderInfo, memblt);
update_write_order_info(context, s, &orderInfo, offset);
update->numberOrders++;
return TRUE;
}
static BOOL update_send_glyph_index(rdpContext* context, GLYPH_INDEX_ORDER* glyph_index)
{
wStream* s;
size_t offset;
int headerLength;
int inf;
ORDER_INFO orderInfo;
rdpUpdate* update = context->update;
headerLength = update_prepare_order_info(context, &orderInfo, ORDER_TYPE_GLYPH_INDEX);
inf = update_approximate_glyph_index_order(&orderInfo, glyph_index);
update_check_flush(context, headerLength + inf);
s = update->us;
if (!s)
return FALSE;
offset = Stream_GetPosition(s);
if (!Stream_EnsureRemainingCapacity(s, headerLength))
return FALSE;
Stream_Seek(s, headerLength);
update_write_glyph_index_order(s, &orderInfo, glyph_index);
update_write_order_info(context, s, &orderInfo, offset);
update->numberOrders++;
return TRUE;
}
/*
* Secondary Drawing Orders
*/
static BOOL update_send_cache_bitmap(rdpContext* context, const CACHE_BITMAP_ORDER* cache_bitmap)
{
wStream* s;
size_t bm, em;
BYTE orderType;
int headerLength;
int inf;
UINT16 extraFlags;
INT16 orderLength;
rdpUpdate* update = context->update;
extraFlags = 0;
headerLength = 6;
orderType = cache_bitmap->compressed ? ORDER_TYPE_CACHE_BITMAP_COMPRESSED
: ORDER_TYPE_BITMAP_UNCOMPRESSED;
inf =
update_approximate_cache_bitmap_order(cache_bitmap, cache_bitmap->compressed, &extraFlags);
update_check_flush(context, headerLength + inf);
s = update->us;
if (!s)
return FALSE;
bm = Stream_GetPosition(s);
if (!Stream_EnsureRemainingCapacity(s, headerLength))
return FALSE;
Stream_Seek(s, headerLength);
if (!update_write_cache_bitmap_order(s, cache_bitmap, cache_bitmap->compressed, &extraFlags))
return FALSE;
em = Stream_GetPosition(s);
orderLength = (em - bm) - 13;
Stream_SetPosition(s, bm);
Stream_Write_UINT8(s, ORDER_STANDARD | ORDER_SECONDARY); /* controlFlags (1 byte) */
Stream_Write_UINT16(s, orderLength); /* orderLength (2 bytes) */
Stream_Write_UINT16(s, extraFlags); /* extraFlags (2 bytes) */
Stream_Write_UINT8(s, orderType); /* orderType (1 byte) */
Stream_SetPosition(s, em);
update->numberOrders++;
return TRUE;
}
static BOOL update_send_cache_bitmap_v2(rdpContext* context, CACHE_BITMAP_V2_ORDER* cache_bitmap_v2)
{
wStream* s;
size_t bm, em;
BYTE orderType;
int headerLength;
UINT16 extraFlags;
INT16 orderLength;
rdpUpdate* update = context->update;
extraFlags = 0;
headerLength = 6;
orderType = cache_bitmap_v2->compressed ? ORDER_TYPE_BITMAP_COMPRESSED_V2
: ORDER_TYPE_BITMAP_UNCOMPRESSED_V2;
if (context->settings->NoBitmapCompressionHeader)
cache_bitmap_v2->flags |= CBR2_NO_BITMAP_COMPRESSION_HDR;
update_check_flush(context, headerLength +
update_approximate_cache_bitmap_v2_order(
cache_bitmap_v2, cache_bitmap_v2->compressed, &extraFlags));
s = update->us;
if (!s)
return FALSE;
bm = Stream_GetPosition(s);
if (!Stream_EnsureRemainingCapacity(s, headerLength))
return FALSE;
Stream_Seek(s, headerLength);
if (!update_write_cache_bitmap_v2_order(s, cache_bitmap_v2, cache_bitmap_v2->compressed,
&extraFlags))
return FALSE;
em = Stream_GetPosition(s);
orderLength = (em - bm) - 13;
Stream_SetPosition(s, bm);
Stream_Write_UINT8(s, ORDER_STANDARD | ORDER_SECONDARY); /* controlFlags (1 byte) */
Stream_Write_UINT16(s, orderLength); /* orderLength (2 bytes) */
Stream_Write_UINT16(s, extraFlags); /* extraFlags (2 bytes) */
Stream_Write_UINT8(s, orderType); /* orderType (1 byte) */
Stream_SetPosition(s, em);
update->numberOrders++;
return TRUE;
}
static BOOL update_send_cache_bitmap_v3(rdpContext* context, CACHE_BITMAP_V3_ORDER* cache_bitmap_v3)
{
wStream* s;
size_t bm, em;
BYTE orderType;
int headerLength;
UINT16 extraFlags;
INT16 orderLength;
rdpUpdate* update = context->update;
extraFlags = 0;
headerLength = 6;
orderType = ORDER_TYPE_BITMAP_COMPRESSED_V3;
update_check_flush(context, headerLength + update_approximate_cache_bitmap_v3_order(
cache_bitmap_v3, &extraFlags));
s = update->us;
if (!s)
return FALSE;
bm = Stream_GetPosition(s);
if (!Stream_EnsureRemainingCapacity(s, headerLength))
return FALSE;
Stream_Seek(s, headerLength);
if (!update_write_cache_bitmap_v3_order(s, cache_bitmap_v3, &extraFlags))
return FALSE;
em = Stream_GetPosition(s);
orderLength = (em - bm) - 13;
Stream_SetPosition(s, bm);
Stream_Write_UINT8(s, ORDER_STANDARD | ORDER_SECONDARY); /* controlFlags (1 byte) */
Stream_Write_UINT16(s, orderLength); /* orderLength (2 bytes) */
Stream_Write_UINT16(s, extraFlags); /* extraFlags (2 bytes) */
Stream_Write_UINT8(s, orderType); /* orderType (1 byte) */
Stream_SetPosition(s, em);
update->numberOrders++;
return TRUE;
}
static BOOL update_send_cache_color_table(rdpContext* context,
const CACHE_COLOR_TABLE_ORDER* cache_color_table)
{
wStream* s;
UINT16 flags;
size_t bm, em, inf;
int headerLength;
INT16 orderLength;
rdpUpdate* update = context->update;
flags = 0;
headerLength = 6;
inf = update_approximate_cache_color_table_order(cache_color_table, &flags);
update_check_flush(context, headerLength + inf);
s = update->us;
if (!s)
return FALSE;
bm = Stream_GetPosition(s);
if (!Stream_EnsureRemainingCapacity(s, headerLength))
return FALSE;
Stream_Seek(s, headerLength);
if (!update_write_cache_color_table_order(s, cache_color_table, &flags))
return FALSE;
em = Stream_GetPosition(s);
orderLength = (em - bm) - 13;
Stream_SetPosition(s, bm);
Stream_Write_UINT8(s, ORDER_STANDARD | ORDER_SECONDARY); /* controlFlags (1 byte) */
Stream_Write_UINT16(s, orderLength); /* orderLength (2 bytes) */
Stream_Write_UINT16(s, flags); /* extraFlags (2 bytes) */
Stream_Write_UINT8(s, ORDER_TYPE_CACHE_COLOR_TABLE); /* orderType (1 byte) */
Stream_SetPosition(s, em);
update->numberOrders++;
return TRUE;
}
static BOOL update_send_cache_glyph(rdpContext* context, const CACHE_GLYPH_ORDER* cache_glyph)
{
wStream* s;
UINT16 flags;
size_t bm, em, inf;
int headerLength;
INT16 orderLength;
rdpUpdate* update = context->update;
flags = 0;
headerLength = 6;
inf = update_approximate_cache_glyph_order(cache_glyph, &flags);
update_check_flush(context, headerLength + inf);
s = update->us;
if (!s)
return FALSE;
bm = Stream_GetPosition(s);
if (!Stream_EnsureRemainingCapacity(s, headerLength))
return FALSE;
Stream_Seek(s, headerLength);
if (!update_write_cache_glyph_order(s, cache_glyph, &flags))
return FALSE;
em = Stream_GetPosition(s);
orderLength = (em - bm) - 13;
Stream_SetPosition(s, bm);
Stream_Write_UINT8(s, ORDER_STANDARD | ORDER_SECONDARY); /* controlFlags (1 byte) */
Stream_Write_UINT16(s, orderLength); /* orderLength (2 bytes) */
Stream_Write_UINT16(s, flags); /* extraFlags (2 bytes) */
Stream_Write_UINT8(s, ORDER_TYPE_CACHE_GLYPH); /* orderType (1 byte) */
Stream_SetPosition(s, em);
update->numberOrders++;
return TRUE;
}
static BOOL update_send_cache_glyph_v2(rdpContext* context,
const CACHE_GLYPH_V2_ORDER* cache_glyph_v2)
{
wStream* s;
UINT16 flags;
size_t bm, em, inf;
int headerLength;
INT16 orderLength;
rdpUpdate* update = context->update;
flags = 0;
headerLength = 6;
inf = update_approximate_cache_glyph_v2_order(cache_glyph_v2, &flags);
update_check_flush(context, headerLength + inf);
s = update->us;
if (!s)
return FALSE;
bm = Stream_GetPosition(s);
if (!Stream_EnsureRemainingCapacity(s, headerLength))
return FALSE;
Stream_Seek(s, headerLength);
if (!update_write_cache_glyph_v2_order(s, cache_glyph_v2, &flags))
return FALSE;
em = Stream_GetPosition(s);
orderLength = (em - bm) - 13;
Stream_SetPosition(s, bm);
Stream_Write_UINT8(s, ORDER_STANDARD | ORDER_SECONDARY); /* controlFlags (1 byte) */
Stream_Write_UINT16(s, orderLength); /* orderLength (2 bytes) */
Stream_Write_UINT16(s, flags); /* extraFlags (2 bytes) */
Stream_Write_UINT8(s, ORDER_TYPE_CACHE_GLYPH); /* orderType (1 byte) */
Stream_SetPosition(s, em);
update->numberOrders++;
return TRUE;
}
static BOOL update_send_cache_brush(rdpContext* context, const CACHE_BRUSH_ORDER* cache_brush)
{
wStream* s;
UINT16 flags;
size_t bm, em, inf;
int headerLength;
INT16 orderLength;
rdpUpdate* update = context->update;
flags = 0;
headerLength = 6;
inf = update_approximate_cache_brush_order(cache_brush, &flags);
update_check_flush(context, headerLength + inf);
s = update->us;
if (!s)
return FALSE;
bm = Stream_GetPosition(s);
if (!Stream_EnsureRemainingCapacity(s, headerLength))
return FALSE;
Stream_Seek(s, headerLength);
if (!update_write_cache_brush_order(s, cache_brush, &flags))
return FALSE;
em = Stream_GetPosition(s);
orderLength = (em - bm) - 13;
Stream_SetPosition(s, bm);
Stream_Write_UINT8(s, ORDER_STANDARD | ORDER_SECONDARY); /* controlFlags (1 byte) */
Stream_Write_UINT16(s, orderLength); /* orderLength (2 bytes) */
Stream_Write_UINT16(s, flags); /* extraFlags (2 bytes) */
Stream_Write_UINT8(s, ORDER_TYPE_CACHE_BRUSH); /* orderType (1 byte) */
Stream_SetPosition(s, em);
update->numberOrders++;
return TRUE;
}
/**
* Alternate Secondary Drawing Orders
*/
static BOOL update_send_create_offscreen_bitmap_order(
rdpContext* context, const CREATE_OFFSCREEN_BITMAP_ORDER* create_offscreen_bitmap)
{
wStream* s;
size_t bm, em, inf;
BYTE orderType;
BYTE controlFlags;
int headerLength;
rdpUpdate* update = context->update;
headerLength = 1;
orderType = ORDER_TYPE_CREATE_OFFSCREEN_BITMAP;
controlFlags = ORDER_SECONDARY | (orderType << 2);
inf = update_approximate_create_offscreen_bitmap_order(create_offscreen_bitmap);
update_check_flush(context, headerLength + inf);
s = update->us;
if (!s)
return FALSE;
bm = Stream_GetPosition(s);
if (!Stream_EnsureRemainingCapacity(s, headerLength))
return FALSE;
Stream_Seek(s, headerLength);
if (!update_write_create_offscreen_bitmap_order(s, create_offscreen_bitmap))
return FALSE;
em = Stream_GetPosition(s);
Stream_SetPosition(s, bm);
Stream_Write_UINT8(s, controlFlags); /* controlFlags (1 byte) */
Stream_SetPosition(s, em);
update->numberOrders++;
return TRUE;
}
static BOOL update_send_switch_surface_order(rdpContext* context,
const SWITCH_SURFACE_ORDER* switch_surface)
{
wStream* s;
size_t bm, em, inf;
BYTE orderType;
BYTE controlFlags;
int headerLength;
rdpUpdate* update;
if (!context || !switch_surface || !context->update)
return FALSE;
update = context->update;
headerLength = 1;
orderType = ORDER_TYPE_SWITCH_SURFACE;
controlFlags = ORDER_SECONDARY | (orderType << 2);
inf = update_approximate_switch_surface_order(switch_surface);
update_check_flush(context, headerLength + inf);
s = update->us;
if (!s)
return FALSE;
bm = Stream_GetPosition(s);
if (!Stream_EnsureRemainingCapacity(s, headerLength))
return FALSE;
Stream_Seek(s, headerLength);
if (!update_write_switch_surface_order(s, switch_surface))
return FALSE;
em = Stream_GetPosition(s);
Stream_SetPosition(s, bm);
Stream_Write_UINT8(s, controlFlags); /* controlFlags (1 byte) */
Stream_SetPosition(s, em);
update->numberOrders++;
return TRUE;
}
static BOOL update_send_pointer_system(rdpContext* context,
const POINTER_SYSTEM_UPDATE* pointer_system)
{
wStream* s;
BYTE updateCode;
rdpRdp* rdp = context->rdp;
BOOL ret;
s = fastpath_update_pdu_init(rdp->fastpath);
if (!s)
return FALSE;
if (pointer_system->type == SYSPTR_NULL)
updateCode = FASTPATH_UPDATETYPE_PTR_NULL;
else
updateCode = FASTPATH_UPDATETYPE_PTR_DEFAULT;
ret = fastpath_send_update_pdu(rdp->fastpath, updateCode, s, FALSE);
Stream_Release(s);
return ret;
}
static BOOL update_send_pointer_position(rdpContext* context,
const POINTER_POSITION_UPDATE* pointerPosition)
{
wStream* s;
rdpRdp* rdp = context->rdp;
BOOL ret = FALSE;
s = fastpath_update_pdu_init(rdp->fastpath);
if (!s)
return FALSE;
if (!Stream_EnsureRemainingCapacity(s, 16))
goto out_fail;
Stream_Write_UINT16(s, pointerPosition->xPos); /* xPos (2 bytes) */
Stream_Write_UINT16(s, pointerPosition->yPos); /* yPos (2 bytes) */
ret = fastpath_send_update_pdu(rdp->fastpath, FASTPATH_UPDATETYPE_PTR_POSITION, s, FALSE);
out_fail:
Stream_Release(s);
return ret;
}
static BOOL update_write_pointer_color(wStream* s, const POINTER_COLOR_UPDATE* pointer_color)
{
if (!Stream_EnsureRemainingCapacity(s, 32 + pointer_color->lengthAndMask +
pointer_color->lengthXorMask))
return FALSE;
Stream_Write_UINT16(s, pointer_color->cacheIndex);
Stream_Write_UINT16(s, pointer_color->xPos);
Stream_Write_UINT16(s, pointer_color->yPos);
Stream_Write_UINT16(s, pointer_color->width);
Stream_Write_UINT16(s, pointer_color->height);
Stream_Write_UINT16(s, pointer_color->lengthAndMask);
Stream_Write_UINT16(s, pointer_color->lengthXorMask);
if (pointer_color->lengthXorMask > 0)
Stream_Write(s, pointer_color->xorMaskData, pointer_color->lengthXorMask);
if (pointer_color->lengthAndMask > 0)
Stream_Write(s, pointer_color->andMaskData, pointer_color->lengthAndMask);
Stream_Write_UINT8(s, 0); /* pad (1 byte) */
return TRUE;
}
static BOOL update_send_pointer_color(rdpContext* context,
const POINTER_COLOR_UPDATE* pointer_color)
{
wStream* s;
rdpRdp* rdp = context->rdp;
BOOL ret = FALSE;
s = fastpath_update_pdu_init(rdp->fastpath);
if (!s)
return FALSE;
if (!update_write_pointer_color(s, pointer_color))
goto out_fail;
ret = fastpath_send_update_pdu(rdp->fastpath, FASTPATH_UPDATETYPE_COLOR, s, FALSE);
out_fail:
Stream_Release(s);
return ret;
}
static BOOL update_write_pointer_large(wStream* s, const POINTER_LARGE_UPDATE* pointer)
{
if (!Stream_EnsureRemainingCapacity(s, 32 + pointer->lengthAndMask + pointer->lengthXorMask))
return FALSE;
Stream_Write_UINT16(s, pointer->xorBpp);
Stream_Write_UINT16(s, pointer->cacheIndex);
Stream_Write_UINT16(s, pointer->hotSpotX);
Stream_Write_UINT16(s, pointer->hotSpotY);
Stream_Write_UINT16(s, pointer->width);
Stream_Write_UINT16(s, pointer->height);
Stream_Write_UINT32(s, pointer->lengthAndMask);
Stream_Write_UINT32(s, pointer->lengthXorMask);
Stream_Write(s, pointer->xorMaskData, pointer->lengthXorMask);
Stream_Write(s, pointer->andMaskData, pointer->lengthAndMask);
Stream_Write_UINT8(s, 0); /* pad (1 byte) */
return TRUE;
}
static BOOL update_send_pointer_large(rdpContext* context, const POINTER_LARGE_UPDATE* pointer)
{
wStream* s;
rdpRdp* rdp = context->rdp;
BOOL ret = FALSE;
s = fastpath_update_pdu_init(rdp->fastpath);
if (!s)
return FALSE;
if (!update_write_pointer_large(s, pointer))
goto out_fail;
ret = fastpath_send_update_pdu(rdp->fastpath, FASTPATH_UPDATETYPE_LARGE_POINTER, s, FALSE);
out_fail:
Stream_Release(s);
return ret;
}
static BOOL update_send_pointer_new(rdpContext* context, const POINTER_NEW_UPDATE* pointer_new)
{
wStream* s;
rdpRdp* rdp = context->rdp;
BOOL ret = FALSE;
s = fastpath_update_pdu_init(rdp->fastpath);
if (!s)
return FALSE;
if (!Stream_EnsureRemainingCapacity(s, 16))
goto out_fail;
Stream_Write_UINT16(s, pointer_new->xorBpp); /* xorBpp (2 bytes) */
update_write_pointer_color(s, &pointer_new->colorPtrAttr);
ret = fastpath_send_update_pdu(rdp->fastpath, FASTPATH_UPDATETYPE_POINTER, s, FALSE);
out_fail:
Stream_Release(s);
return ret;
}
static BOOL update_send_pointer_cached(rdpContext* context,
const POINTER_CACHED_UPDATE* pointer_cached)
{
wStream* s;
rdpRdp* rdp = context->rdp;
BOOL ret;
s = fastpath_update_pdu_init(rdp->fastpath);
if (!s)
return FALSE;
Stream_Write_UINT16(s, pointer_cached->cacheIndex); /* cacheIndex (2 bytes) */
ret = fastpath_send_update_pdu(rdp->fastpath, FASTPATH_UPDATETYPE_CACHED, s, FALSE);
Stream_Release(s);
return ret;
}
BOOL update_read_refresh_rect(rdpUpdate* update, wStream* s)
{
int index;
BYTE numberOfAreas;
RECTANGLE_16* areas;
if (Stream_GetRemainingLength(s) < 4)
return FALSE;
Stream_Read_UINT8(s, numberOfAreas);
Stream_Seek(s, 3); /* pad3Octects */
if (Stream_GetRemainingLength(s) < ((size_t)numberOfAreas * 4 * 2))
return FALSE;
areas = (RECTANGLE_16*)calloc(numberOfAreas, sizeof(RECTANGLE_16));
if (!areas)
return FALSE;
for (index = 0; index < numberOfAreas; index++)
{
Stream_Read_UINT16(s, areas[index].left);
Stream_Read_UINT16(s, areas[index].top);
Stream_Read_UINT16(s, areas[index].right);
Stream_Read_UINT16(s, areas[index].bottom);
}
if (update->context->settings->RefreshRect)
IFCALL(update->RefreshRect, update->context, numberOfAreas, areas);
else
WLog_Print(update->log, WLOG_WARN, "ignoring refresh rect request from client");
free(areas);
return TRUE;
}
BOOL update_read_suppress_output(rdpUpdate* update, wStream* s)
{
RECTANGLE_16* prect = NULL;
RECTANGLE_16 rect = { 0 };
BYTE allowDisplayUpdates;
if (Stream_GetRemainingLength(s) < 4)
return FALSE;
Stream_Read_UINT8(s, allowDisplayUpdates);
Stream_Seek(s, 3); /* pad3Octects */
if (allowDisplayUpdates > 0)
{
if (Stream_GetRemainingLength(s) < sizeof(RECTANGLE_16))
return FALSE;
Stream_Read_UINT16(s, rect.left);
Stream_Read_UINT16(s, rect.top);
Stream_Read_UINT16(s, rect.right);
Stream_Read_UINT16(s, rect.bottom);
prect = ▭
}
if (update->context->settings->SuppressOutput)
IFCALL(update->SuppressOutput, update->context, allowDisplayUpdates, prect);
else
WLog_Print(update->log, WLOG_WARN, "ignoring suppress output request from client");
return TRUE;
}
static BOOL update_send_set_keyboard_indicators(rdpContext* context, UINT16 led_flags)
{
wStream* s;
rdpRdp* rdp = context->rdp;
s = rdp_data_pdu_init(rdp);
if (!s)
return FALSE;
Stream_Write_UINT16(s, 0); /* unitId should be 0 according to MS-RDPBCGR 2.2.8.2.1.1 */
Stream_Write_UINT16(s, led_flags); /* ledFlags (2 bytes) */
return rdp_send_data_pdu(rdp, s, DATA_PDU_TYPE_SET_KEYBOARD_INDICATORS, rdp->mcs->userId);
}
static BOOL update_send_set_keyboard_ime_status(rdpContext* context, UINT16 imeId, UINT32 imeState,
UINT32 imeConvMode)
{
wStream* s;
rdpRdp* rdp = context->rdp;
s = rdp_data_pdu_init(rdp);
if (!s)
return FALSE;
/* unitId should be 0 according to MS-RDPBCGR 2.2.8.2.2.1 */
Stream_Write_UINT16(s, imeId);
Stream_Write_UINT32(s, imeState);
Stream_Write_UINT32(s, imeConvMode);
return rdp_send_data_pdu(rdp, s, DATA_PDU_TYPE_SET_KEYBOARD_IME_STATUS, rdp->mcs->userId);
}
static UINT16 update_calculate_new_or_existing_window(const WINDOW_ORDER_INFO* orderInfo,
const WINDOW_STATE_ORDER* stateOrder)
{
UINT16 orderSize = 11;
if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_OWNER) != 0)
orderSize += 4;
if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_STYLE) != 0)
orderSize += 8;
if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_SHOW) != 0)
orderSize += 1;
if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_TITLE) != 0)
orderSize += 2 + stateOrder->titleInfo.length;
if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_CLIENT_AREA_OFFSET) != 0)
orderSize += 8;
if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_CLIENT_AREA_SIZE) != 0)
orderSize += 8;
if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_RESIZE_MARGIN_X) != 0)
orderSize += 8;
if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_RESIZE_MARGIN_Y) != 0)
orderSize += 8;
if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_RP_CONTENT) != 0)
orderSize += 1;
if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_ROOT_PARENT) != 0)
orderSize += 4;
if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_WND_OFFSET) != 0)
orderSize += 8;
if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_WND_CLIENT_DELTA) != 0)
orderSize += 8;
if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_WND_SIZE) != 0)
orderSize += 8;
if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_WND_RECTS) != 0)
orderSize += 2 + stateOrder->numWindowRects * sizeof(RECTANGLE_16);
if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_VIS_OFFSET) != 0)
orderSize += 8;
if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_VISIBILITY) != 0)
orderSize += 2 + stateOrder->numVisibilityRects * sizeof(RECTANGLE_16);
if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_OVERLAY_DESCRIPTION) != 0)
orderSize += 2 + stateOrder->OverlayDescription.length;
if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_TASKBAR_BUTTON) != 0)
orderSize += 1;
if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_ENFORCE_SERVER_ZORDER) != 0)
orderSize += 1;
if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_APPBAR_STATE) != 0)
orderSize += 1;
if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_APPBAR_EDGE) != 0)
orderSize += 1;
return orderSize;
}
static BOOL update_send_new_or_existing_window(rdpContext* context,
const WINDOW_ORDER_INFO* orderInfo,
const WINDOW_STATE_ORDER* stateOrder)
{
wStream* s;
rdpUpdate* update = context->update;
BYTE controlFlags = ORDER_SECONDARY | (ORDER_TYPE_WINDOW << 2);
UINT16 orderSize = update_calculate_new_or_existing_window(orderInfo, stateOrder);
update_check_flush(context, orderSize);
s = update->us;
if (!s)
return FALSE;
if (!Stream_EnsureRemainingCapacity(s, orderSize))
return FALSE;
Stream_Write_UINT8(s, controlFlags); /* Header (1 byte) */
Stream_Write_UINT16(s, orderSize); /* OrderSize (2 bytes) */
Stream_Write_UINT32(s, orderInfo->fieldFlags); /* FieldsPresentFlags (4 bytes) */
Stream_Write_UINT32(s, orderInfo->windowId); /* WindowID (4 bytes) */
if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_OWNER) != 0)
Stream_Write_UINT32(s, stateOrder->ownerWindowId);
if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_STYLE) != 0)
{
Stream_Write_UINT32(s, stateOrder->style);
Stream_Write_UINT32(s, stateOrder->extendedStyle);
}
if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_SHOW) != 0)
{
Stream_Write_UINT8(s, stateOrder->showState);
}
if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_TITLE) != 0)
{
Stream_Write_UINT16(s, stateOrder->titleInfo.length);
Stream_Write(s, stateOrder->titleInfo.string, stateOrder->titleInfo.length);
}
if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_CLIENT_AREA_OFFSET) != 0)
{
Stream_Write_INT32(s, stateOrder->clientOffsetX);
Stream_Write_INT32(s, stateOrder->clientOffsetY);
}
if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_CLIENT_AREA_SIZE) != 0)
{
Stream_Write_UINT32(s, stateOrder->clientAreaWidth);
Stream_Write_UINT32(s, stateOrder->clientAreaHeight);
}
if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_RESIZE_MARGIN_X) != 0)
{
Stream_Write_UINT32(s, stateOrder->resizeMarginLeft);
Stream_Write_UINT32(s, stateOrder->resizeMarginRight);
}
if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_RESIZE_MARGIN_Y) != 0)
{
Stream_Write_UINT32(s, stateOrder->resizeMarginTop);
Stream_Write_UINT32(s, stateOrder->resizeMarginBottom);
}
if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_RP_CONTENT) != 0)
{
Stream_Write_UINT8(s, stateOrder->RPContent);
}
if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_ROOT_PARENT) != 0)
{
Stream_Write_UINT32(s, stateOrder->rootParentHandle);
}
if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_WND_OFFSET) != 0)
{
Stream_Write_INT32(s, stateOrder->windowOffsetX);
Stream_Write_INT32(s, stateOrder->windowOffsetY);
}
if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_WND_CLIENT_DELTA) != 0)
{
Stream_Write_INT32(s, stateOrder->windowClientDeltaX);
Stream_Write_INT32(s, stateOrder->windowClientDeltaY);
}
if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_WND_SIZE) != 0)
{
Stream_Write_UINT32(s, stateOrder->windowWidth);
Stream_Write_UINT32(s, stateOrder->windowHeight);
}
if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_WND_RECTS) != 0)
{
Stream_Write_UINT16(s, stateOrder->numWindowRects);
Stream_Write(s, stateOrder->windowRects, stateOrder->numWindowRects * sizeof(RECTANGLE_16));
}
if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_VIS_OFFSET) != 0)
{
Stream_Write_UINT32(s, stateOrder->visibleOffsetX);
Stream_Write_UINT32(s, stateOrder->visibleOffsetY);
}
if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_VISIBILITY) != 0)
{
Stream_Write_UINT16(s, stateOrder->numVisibilityRects);
Stream_Write(s, stateOrder->visibilityRects,
stateOrder->numVisibilityRects * sizeof(RECTANGLE_16));
}
if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_OVERLAY_DESCRIPTION) != 0)
{
Stream_Write_UINT16(s, stateOrder->OverlayDescription.length);
Stream_Write(s, stateOrder->OverlayDescription.string,
stateOrder->OverlayDescription.length);
}
if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_TASKBAR_BUTTON) != 0)
{
Stream_Write_UINT8(s, stateOrder->TaskbarButton);
}
if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_ENFORCE_SERVER_ZORDER) != 0)
{
Stream_Write_UINT8(s, stateOrder->EnforceServerZOrder);
}
if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_APPBAR_STATE) != 0)
{
Stream_Write_UINT8(s, stateOrder->AppBarState);
}
if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_APPBAR_EDGE) != 0)
{
Stream_Write_UINT8(s, stateOrder->AppBarEdge);
}
update->numberOrders++;
return TRUE;
}
static BOOL update_send_window_create(rdpContext* context, const WINDOW_ORDER_INFO* orderInfo,
const WINDOW_STATE_ORDER* stateOrder)
{
return update_send_new_or_existing_window(context, orderInfo, stateOrder);
}
static BOOL update_send_window_update(rdpContext* context, const WINDOW_ORDER_INFO* orderInfo,
const WINDOW_STATE_ORDER* stateOrder)
{
return update_send_new_or_existing_window(context, orderInfo, stateOrder);
}
static UINT16 update_calculate_window_icon_order(const WINDOW_ORDER_INFO* orderInfo,
const WINDOW_ICON_ORDER* iconOrder)
{
UINT16 orderSize = 23;
ICON_INFO* iconInfo = iconOrder->iconInfo;
orderSize += iconInfo->cbBitsColor + iconInfo->cbBitsMask;
if (iconInfo->bpp <= 8)
orderSize += 2 + iconInfo->cbColorTable;
return orderSize;
}
static BOOL update_send_window_icon(rdpContext* context, const WINDOW_ORDER_INFO* orderInfo,
const WINDOW_ICON_ORDER* iconOrder)
{
wStream* s;
rdpUpdate* update = context->update;
BYTE controlFlags = ORDER_SECONDARY | (ORDER_TYPE_WINDOW << 2);
ICON_INFO* iconInfo = iconOrder->iconInfo;
UINT16 orderSize = update_calculate_window_icon_order(orderInfo, iconOrder);
update_check_flush(context, orderSize);
s = update->us;
if (!s || !iconInfo)
return FALSE;
if (!Stream_EnsureRemainingCapacity(s, orderSize))
return FALSE;
/* Write Hdr */
Stream_Write_UINT8(s, controlFlags); /* Header (1 byte) */
Stream_Write_UINT16(s, orderSize); /* OrderSize (2 bytes) */
Stream_Write_UINT32(s, orderInfo->fieldFlags); /* FieldsPresentFlags (4 bytes) */
Stream_Write_UINT32(s, orderInfo->windowId); /* WindowID (4 bytes) */
/* Write body */
Stream_Write_UINT16(s, iconInfo->cacheEntry); /* CacheEntry (2 bytes) */
Stream_Write_UINT8(s, iconInfo->cacheId); /* CacheId (1 byte) */
Stream_Write_UINT8(s, iconInfo->bpp); /* Bpp (1 byte) */
Stream_Write_UINT16(s, iconInfo->width); /* Width (2 bytes) */
Stream_Write_UINT16(s, iconInfo->height); /* Height (2 bytes) */
if (iconInfo->bpp <= 8)
{
Stream_Write_UINT16(s, iconInfo->cbColorTable); /* CbColorTable (2 bytes) */
}
Stream_Write_UINT16(s, iconInfo->cbBitsMask); /* CbBitsMask (2 bytes) */
Stream_Write_UINT16(s, iconInfo->cbBitsColor); /* CbBitsColor (2 bytes) */
Stream_Write(s, iconInfo->bitsMask, iconInfo->cbBitsMask); /* BitsMask (variable) */
if (iconInfo->bpp <= 8)
{
Stream_Write(s, iconInfo->colorTable, iconInfo->cbColorTable); /* ColorTable (variable) */
}
Stream_Write(s, iconInfo->bitsColor, iconInfo->cbBitsColor); /* BitsColor (variable) */
update->numberOrders++;
return TRUE;
}
static BOOL update_send_window_cached_icon(rdpContext* context, const WINDOW_ORDER_INFO* orderInfo,
const WINDOW_CACHED_ICON_ORDER* cachedIconOrder)
{
wStream* s;
rdpUpdate* update = context->update;
BYTE controlFlags = ORDER_SECONDARY | (ORDER_TYPE_WINDOW << 2);
UINT16 orderSize = 14;
CACHED_ICON_INFO cachedIcon = cachedIconOrder->cachedIcon;
update_check_flush(context, orderSize);
s = update->us;
if (!s)
return FALSE;
if (!Stream_EnsureRemainingCapacity(s, orderSize))
return FALSE;
/* Write Hdr */
Stream_Write_UINT8(s, controlFlags); /* Header (1 byte) */
Stream_Write_UINT16(s, orderSize); /* OrderSize (2 bytes) */
Stream_Write_UINT32(s, orderInfo->fieldFlags); /* FieldsPresentFlags (4 bytes) */
Stream_Write_UINT32(s, orderInfo->windowId); /* WindowID (4 bytes) */
/* Write body */
Stream_Write_UINT16(s, cachedIcon.cacheEntry); /* CacheEntry (2 bytes) */
Stream_Write_UINT8(s, cachedIcon.cacheId); /* CacheId (1 byte) */
update->numberOrders++;
return TRUE;
}
static BOOL update_send_window_delete(rdpContext* context, const WINDOW_ORDER_INFO* orderInfo)
{
wStream* s;
rdpUpdate* update = context->update;
BYTE controlFlags = ORDER_SECONDARY | (ORDER_TYPE_WINDOW << 2);
UINT16 orderSize = 11;
update_check_flush(context, orderSize);
s = update->us;
if (!s)
return FALSE;
if (!Stream_EnsureRemainingCapacity(s, orderSize))
return FALSE;
/* Write Hdr */
Stream_Write_UINT8(s, controlFlags); /* Header (1 byte) */
Stream_Write_UINT16(s, orderSize); /* OrderSize (2 bytes) */
Stream_Write_UINT32(s, orderInfo->fieldFlags); /* FieldsPresentFlags (4 bytes) */
Stream_Write_UINT32(s, orderInfo->windowId); /* WindowID (4 bytes) */
update->numberOrders++;
return TRUE;
}
static UINT16 update_calculate_new_or_existing_notification_icons_order(
const WINDOW_ORDER_INFO* orderInfo, const NOTIFY_ICON_STATE_ORDER* iconStateOrder)
{
UINT16 orderSize = 15;
if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_NOTIFY_VERSION) != 0)
orderSize += 4;
if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_NOTIFY_TIP) != 0)
{
orderSize += 2 + iconStateOrder->toolTip.length;
}
if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_NOTIFY_INFO_TIP) != 0)
{
NOTIFY_ICON_INFOTIP infoTip = iconStateOrder->infoTip;
orderSize += 12 + infoTip.text.length + infoTip.title.length;
}
if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_NOTIFY_STATE) != 0)
{
orderSize += 4;
}
if ((orderInfo->fieldFlags & WINDOW_ORDER_ICON) != 0)
{
ICON_INFO iconInfo = iconStateOrder->icon;
orderSize += 12;
if (iconInfo.bpp <= 8)
orderSize += 2 + iconInfo.cbColorTable;
orderSize += iconInfo.cbBitsMask + iconInfo.cbBitsColor;
}
else if ((orderInfo->fieldFlags & WINDOW_ORDER_CACHED_ICON) != 0)
{
orderSize += 3;
}
return orderSize;
}
static BOOL
update_send_new_or_existing_notification_icons(rdpContext* context,
const WINDOW_ORDER_INFO* orderInfo,
const NOTIFY_ICON_STATE_ORDER* iconStateOrder)
{
wStream* s;
rdpUpdate* update = context->update;
BYTE controlFlags = ORDER_SECONDARY | (ORDER_TYPE_WINDOW << 2);
BOOL versionFieldPresent = FALSE;
UINT16 orderSize =
update_calculate_new_or_existing_notification_icons_order(orderInfo, iconStateOrder);
update_check_flush(context, orderSize);
s = update->us;
if (!s)
return FALSE;
if (!Stream_EnsureRemainingCapacity(s, orderSize))
return FALSE;
/* Write Hdr */
Stream_Write_UINT8(s, controlFlags); /* Header (1 byte) */
Stream_Write_INT16(s, orderSize); /* OrderSize (2 bytes) */
Stream_Write_UINT32(s, orderInfo->fieldFlags); /* FieldsPresentFlags (4 bytes) */
Stream_Write_UINT32(s, orderInfo->windowId); /* WindowID (4 bytes) */
Stream_Write_UINT32(s, orderInfo->notifyIconId); /* NotifyIconId (4 bytes) */
/* Write body */
if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_NOTIFY_VERSION) != 0)
{
versionFieldPresent = TRUE;
Stream_Write_UINT32(s, iconStateOrder->version);
}
if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_NOTIFY_TIP) != 0)
{
Stream_Write_UINT16(s, iconStateOrder->toolTip.length);
Stream_Write(s, iconStateOrder->toolTip.string, iconStateOrder->toolTip.length);
}
if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_NOTIFY_INFO_TIP) != 0)
{
NOTIFY_ICON_INFOTIP infoTip = iconStateOrder->infoTip;
/* info tip should not be sent when version is 0 */
if (versionFieldPresent && iconStateOrder->version == 0)
return FALSE;
Stream_Write_UINT32(s, infoTip.timeout); /* Timeout (4 bytes) */
Stream_Write_UINT32(s, infoTip.flags); /* InfoFlags (4 bytes) */
Stream_Write_UINT16(s, infoTip.text.length); /* InfoTipText (variable) */
Stream_Write(s, infoTip.text.string, infoTip.text.length);
Stream_Write_UINT16(s, infoTip.title.length); /* Title (variable) */
Stream_Write(s, infoTip.title.string, infoTip.title.length);
}
if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_NOTIFY_STATE) != 0)
{
/* notify state should not be sent when version is 0 */
if (versionFieldPresent && iconStateOrder->version == 0)
return FALSE;
Stream_Write_UINT32(s, iconStateOrder->state);
}
if ((orderInfo->fieldFlags & WINDOW_ORDER_ICON) != 0)
{
ICON_INFO iconInfo = iconStateOrder->icon;
Stream_Write_UINT16(s, iconInfo.cacheEntry); /* CacheEntry (2 bytes) */
Stream_Write_UINT8(s, iconInfo.cacheId); /* CacheId (1 byte) */
Stream_Write_UINT8(s, iconInfo.bpp); /* Bpp (1 byte) */
Stream_Write_UINT16(s, iconInfo.width); /* Width (2 bytes) */
Stream_Write_UINT16(s, iconInfo.height); /* Height (2 bytes) */
if (iconInfo.bpp <= 8)
{
Stream_Write_UINT16(s, iconInfo.cbColorTable); /* CbColorTable (2 bytes) */
}
Stream_Write_UINT16(s, iconInfo.cbBitsMask); /* CbBitsMask (2 bytes) */
Stream_Write_UINT16(s, iconInfo.cbBitsColor); /* CbBitsColor (2 bytes) */
Stream_Write(s, iconInfo.bitsMask, iconInfo.cbBitsMask); /* BitsMask (variable) */
orderSize += iconInfo.cbBitsMask;
if (iconInfo.bpp <= 8)
{
Stream_Write(s, iconInfo.colorTable, iconInfo.cbColorTable); /* ColorTable (variable) */
}
Stream_Write(s, iconInfo.bitsColor, iconInfo.cbBitsColor); /* BitsColor (variable) */
}
else if ((orderInfo->fieldFlags & WINDOW_ORDER_CACHED_ICON) != 0)
{
CACHED_ICON_INFO cachedIcon = iconStateOrder->cachedIcon;
Stream_Write_UINT16(s, cachedIcon.cacheEntry); /* CacheEntry (2 bytes) */
Stream_Write_UINT8(s, cachedIcon.cacheId); /* CacheId (1 byte) */
}
update->numberOrders++;
return TRUE;
}
static BOOL update_send_notify_icon_create(rdpContext* context, const WINDOW_ORDER_INFO* orderInfo,
const NOTIFY_ICON_STATE_ORDER* iconStateOrder)
{
return update_send_new_or_existing_notification_icons(context, orderInfo, iconStateOrder);
}
static BOOL update_send_notify_icon_update(rdpContext* context, const WINDOW_ORDER_INFO* orderInfo,
const NOTIFY_ICON_STATE_ORDER* iconStateOrder)
{
return update_send_new_or_existing_notification_icons(context, orderInfo, iconStateOrder);
}
static BOOL update_send_notify_icon_delete(rdpContext* context, const WINDOW_ORDER_INFO* orderInfo)
{
wStream* s;
rdpUpdate* update = context->update;
BYTE controlFlags = ORDER_SECONDARY | (ORDER_TYPE_WINDOW << 2);
UINT16 orderSize = 15;
update_check_flush(context, orderSize);
s = update->us;
if (!s)
return FALSE;
/* Write Hdr */
Stream_Write_UINT8(s, controlFlags); /* Header (1 byte) */
Stream_Write_UINT16(s, orderSize); /* OrderSize (2 bytes) */
Stream_Write_UINT32(s, orderInfo->fieldFlags); /* FieldsPresentFlags (4 bytes) */
Stream_Write_UINT32(s, orderInfo->windowId); /* WindowID (4 bytes) */
Stream_Write_UINT32(s, orderInfo->notifyIconId); /* NotifyIconId (4 bytes) */
update->numberOrders++;
return TRUE;
}
static UINT16 update_calculate_monitored_desktop(const WINDOW_ORDER_INFO* orderInfo,
const MONITORED_DESKTOP_ORDER* monitoredDesktop)
{
UINT16 orderSize = 7;
if (orderInfo->fieldFlags & WINDOW_ORDER_FIELD_DESKTOP_ACTIVE_WND)
{
orderSize += 4;
}
if (orderInfo->fieldFlags & WINDOW_ORDER_FIELD_DESKTOP_ZORDER)
{
orderSize += 1 + (4 * monitoredDesktop->numWindowIds);
}
return orderSize;
}
static BOOL update_send_monitored_desktop(rdpContext* context, const WINDOW_ORDER_INFO* orderInfo,
const MONITORED_DESKTOP_ORDER* monitoredDesktop)
{
UINT32 i;
wStream* s;
rdpUpdate* update = context->update;
BYTE controlFlags = ORDER_SECONDARY | (ORDER_TYPE_WINDOW << 2);
UINT16 orderSize = update_calculate_monitored_desktop(orderInfo, monitoredDesktop);
update_check_flush(context, orderSize);
s = update->us;
if (!s)
return FALSE;
Stream_Write_UINT8(s, controlFlags); /* Header (1 byte) */
Stream_Write_UINT16(s, orderSize); /* OrderSize (2 bytes) */
Stream_Write_UINT32(s, orderInfo->fieldFlags); /* FieldsPresentFlags (4 bytes) */
if (orderInfo->fieldFlags & WINDOW_ORDER_FIELD_DESKTOP_ACTIVE_WND)
{
Stream_Write_UINT32(s, monitoredDesktop->activeWindowId); /* activeWindowId (4 bytes) */
}
if (orderInfo->fieldFlags & WINDOW_ORDER_FIELD_DESKTOP_ZORDER)
{
Stream_Write_UINT8(s, monitoredDesktop->numWindowIds); /* numWindowIds (1 byte) */
/* windowIds */
for (i = 0; i < monitoredDesktop->numWindowIds; i++)
{
Stream_Write_UINT32(s, monitoredDesktop->windowIds[i]);
}
}
update->numberOrders++;
return TRUE;
}
static BOOL update_send_non_monitored_desktop(rdpContext* context,
const WINDOW_ORDER_INFO* orderInfo)
{
wStream* s;
rdpUpdate* update = context->update;
BYTE controlFlags = ORDER_SECONDARY | (ORDER_TYPE_WINDOW << 2);
UINT16 orderSize = 7;
update_check_flush(context, orderSize);
s = update->us;
if (!s)
return FALSE;
Stream_Write_UINT8(s, controlFlags); /* Header (1 byte) */
Stream_Write_UINT16(s, orderSize); /* OrderSize (2 bytes) */
Stream_Write_UINT32(s, orderInfo->fieldFlags); /* FieldsPresentFlags (4 bytes) */
update->numberOrders++;
return TRUE;
}
void update_register_server_callbacks(rdpUpdate* update)
{
update->BeginPaint = _update_begin_paint;
update->EndPaint = _update_end_paint;
update->SetBounds = update_set_bounds;
update->Synchronize = update_send_synchronize;
update->DesktopResize = update_send_desktop_resize;
update->BitmapUpdate = update_send_bitmap_update;
update->SurfaceBits = update_send_surface_bits;
update->SurfaceFrameMarker = update_send_surface_frame_marker;
update->SurfaceCommand = update_send_surface_command;
update->SurfaceFrameBits = update_send_surface_frame_bits;
update->PlaySound = update_send_play_sound;
update->SetKeyboardIndicators = update_send_set_keyboard_indicators;
update->SetKeyboardImeStatus = update_send_set_keyboard_ime_status;
update->SaveSessionInfo = rdp_send_save_session_info;
update->ServerStatusInfo = rdp_send_server_status_info;
update->primary->DstBlt = update_send_dstblt;
update->primary->PatBlt = update_send_patblt;
update->primary->ScrBlt = update_send_scrblt;
update->primary->OpaqueRect = update_send_opaque_rect;
update->primary->LineTo = update_send_line_to;
update->primary->MemBlt = update_send_memblt;
update->primary->GlyphIndex = update_send_glyph_index;
update->secondary->CacheBitmap = update_send_cache_bitmap;
update->secondary->CacheBitmapV2 = update_send_cache_bitmap_v2;
update->secondary->CacheBitmapV3 = update_send_cache_bitmap_v3;
update->secondary->CacheColorTable = update_send_cache_color_table;
update->secondary->CacheGlyph = update_send_cache_glyph;
update->secondary->CacheGlyphV2 = update_send_cache_glyph_v2;
update->secondary->CacheBrush = update_send_cache_brush;
update->altsec->CreateOffscreenBitmap = update_send_create_offscreen_bitmap_order;
update->altsec->SwitchSurface = update_send_switch_surface_order;
update->pointer->PointerSystem = update_send_pointer_system;
update->pointer->PointerPosition = update_send_pointer_position;
update->pointer->PointerColor = update_send_pointer_color;
update->pointer->PointerLarge = update_send_pointer_large;
update->pointer->PointerNew = update_send_pointer_new;
update->pointer->PointerCached = update_send_pointer_cached;
update->window->WindowCreate = update_send_window_create;
update->window->WindowUpdate = update_send_window_update;
update->window->WindowIcon = update_send_window_icon;
update->window->WindowCachedIcon = update_send_window_cached_icon;
update->window->WindowDelete = update_send_window_delete;
update->window->NotifyIconCreate = update_send_notify_icon_create;
update->window->NotifyIconUpdate = update_send_notify_icon_update;
update->window->NotifyIconDelete = update_send_notify_icon_delete;
update->window->MonitoredDesktop = update_send_monitored_desktop;
update->window->NonMonitoredDesktop = update_send_non_monitored_desktop;
}
void update_register_client_callbacks(rdpUpdate* update)
{
update->RefreshRect = update_send_refresh_rect;
update->SuppressOutput = update_send_suppress_output;
update->SurfaceFrameAcknowledge = update_send_frame_acknowledge;
}
int update_process_messages(rdpUpdate* update)
{
return update_message_queue_process_pending_messages(update);
}
static void update_free_queued_message(void* obj)
{
wMessage* msg = (wMessage*)obj;
update_message_queue_free_message(msg);
}
void update_free_window_state(WINDOW_STATE_ORDER* window_state)
{
if (!window_state)
return;
free(window_state->OverlayDescription.string);
free(window_state->titleInfo.string);
free(window_state->windowRects);
free(window_state->visibilityRects);
memset(window_state, 0, sizeof(WINDOW_STATE_ORDER));
}
rdpUpdate* update_new(rdpRdp* rdp)
{
const wObject cb = { NULL, NULL, NULL, update_free_queued_message, NULL };
rdpUpdate* update;
OFFSCREEN_DELETE_LIST* deleteList;
WINPR_UNUSED(rdp);
update = (rdpUpdate*)calloc(1, sizeof(rdpUpdate));
if (!update)
return NULL;
update->log = WLog_Get("com.freerdp.core.update");
InitializeCriticalSection(&(update->mux));
update->pointer = (rdpPointerUpdate*)calloc(1, sizeof(rdpPointerUpdate));
if (!update->pointer)
goto fail;
update->primary = (rdpPrimaryUpdate*)calloc(1, sizeof(rdpPrimaryUpdate));
if (!update->primary)
goto fail;
update->secondary = (rdpSecondaryUpdate*)calloc(1, sizeof(rdpSecondaryUpdate));
if (!update->secondary)
goto fail;
update->altsec = (rdpAltSecUpdate*)calloc(1, sizeof(rdpAltSecUpdate));
if (!update->altsec)
goto fail;
update->window = (rdpWindowUpdate*)calloc(1, sizeof(rdpWindowUpdate));
if (!update->window)
goto fail;
deleteList = &(update->altsec->create_offscreen_bitmap.deleteList);
deleteList->sIndices = 64;
deleteList->indices = calloc(deleteList->sIndices, 2);
if (!deleteList->indices)
goto fail;
deleteList->cIndices = 0;
update->SuppressOutput = update_send_suppress_output;
update->initialState = TRUE;
update->autoCalculateBitmapData = TRUE;
update->queue = MessageQueue_New(&cb);
if (!update->queue)
goto fail;
return update;
fail:
update_free(update);
return NULL;
}
void update_free(rdpUpdate* update)
{
if (update != NULL)
{
OFFSCREEN_DELETE_LIST* deleteList = &(update->altsec->create_offscreen_bitmap.deleteList);
if (deleteList)
free(deleteList->indices);
free(update->pointer);
if (update->primary)
{
free(update->primary->polyline.points);
free(update->primary->polygon_sc.points);
free(update->primary->fast_glyph.glyphData.aj);
free(update->primary);
}
free(update->secondary);
free(update->altsec);
if (update->window)
{
free(update->window);
}
MessageQueue_Free(update->queue);
DeleteCriticalSection(&update->mux);
free(update);
}
}
BOOL update_begin_paint(rdpUpdate* update)
{
if (!update)
return FALSE;
EnterCriticalSection(&update->mux);
if (!update->BeginPaint)
return TRUE;
return update->BeginPaint(update->context);
}
BOOL update_end_paint(rdpUpdate* update)
{
BOOL rc = FALSE;
if (!update)
return FALSE;
if (update->EndPaint)
rc = update->EndPaint(update->context);
LeaveCriticalSection(&update->mux);
return rc;
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/good_3907_0 |
crossvul-cpp_data_bad_2730_0 | /*
* Copyright (c) 1998-2007 The TCPDUMP project
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that: (1) source code
* distributions retain the above copyright notice and this paragraph
* in its entirety, and (2) distributions including binary code include
* the above copyright notice and this paragraph in its entirety in
* the documentation or other materials provided with the distribution.
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND
* WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, WITHOUT
* LIMITATION, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE.
*
* Original code by Hannes Gredler (hannes@gredler.at)
* IEEE and TIA extensions by Carles Kishimoto <carles.kishimoto@gmail.com>
* DCBX extensions by Kaladhar Musunuru <kaladharm@sourceforge.net>
*/
/* \summary: IEEE 802.1ab Link Layer Discovery Protocol (LLDP) printer */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <netdissect-stdinc.h>
#include <stdio.h>
#include "netdissect.h"
#include "extract.h"
#include "addrtoname.h"
#include "af.h"
#include "oui.h"
#define LLDP_EXTRACT_TYPE(x) (((x)&0xfe00)>>9)
#define LLDP_EXTRACT_LEN(x) ((x)&0x01ff)
/*
* TLV type codes
*/
#define LLDP_END_TLV 0
#define LLDP_CHASSIS_ID_TLV 1
#define LLDP_PORT_ID_TLV 2
#define LLDP_TTL_TLV 3
#define LLDP_PORT_DESCR_TLV 4
#define LLDP_SYSTEM_NAME_TLV 5
#define LLDP_SYSTEM_DESCR_TLV 6
#define LLDP_SYSTEM_CAP_TLV 7
#define LLDP_MGMT_ADDR_TLV 8
#define LLDP_PRIVATE_TLV 127
static const struct tok lldp_tlv_values[] = {
{ LLDP_END_TLV, "End" },
{ LLDP_CHASSIS_ID_TLV, "Chassis ID" },
{ LLDP_PORT_ID_TLV, "Port ID" },
{ LLDP_TTL_TLV, "Time to Live" },
{ LLDP_PORT_DESCR_TLV, "Port Description" },
{ LLDP_SYSTEM_NAME_TLV, "System Name" },
{ LLDP_SYSTEM_DESCR_TLV, "System Description" },
{ LLDP_SYSTEM_CAP_TLV, "System Capabilities" },
{ LLDP_MGMT_ADDR_TLV, "Management Address" },
{ LLDP_PRIVATE_TLV, "Organization specific" },
{ 0, NULL}
};
/*
* Chassis ID subtypes
*/
#define LLDP_CHASSIS_CHASSIS_COMP_SUBTYPE 1
#define LLDP_CHASSIS_INTF_ALIAS_SUBTYPE 2
#define LLDP_CHASSIS_PORT_COMP_SUBTYPE 3
#define LLDP_CHASSIS_MAC_ADDR_SUBTYPE 4
#define LLDP_CHASSIS_NETWORK_ADDR_SUBTYPE 5
#define LLDP_CHASSIS_INTF_NAME_SUBTYPE 6
#define LLDP_CHASSIS_LOCAL_SUBTYPE 7
static const struct tok lldp_chassis_subtype_values[] = {
{ LLDP_CHASSIS_CHASSIS_COMP_SUBTYPE, "Chassis component"},
{ LLDP_CHASSIS_INTF_ALIAS_SUBTYPE, "Interface alias"},
{ LLDP_CHASSIS_PORT_COMP_SUBTYPE, "Port component"},
{ LLDP_CHASSIS_MAC_ADDR_SUBTYPE, "MAC address"},
{ LLDP_CHASSIS_NETWORK_ADDR_SUBTYPE, "Network address"},
{ LLDP_CHASSIS_INTF_NAME_SUBTYPE, "Interface name"},
{ LLDP_CHASSIS_LOCAL_SUBTYPE, "Local"},
{ 0, NULL}
};
/*
* Port ID subtypes
*/
#define LLDP_PORT_INTF_ALIAS_SUBTYPE 1
#define LLDP_PORT_PORT_COMP_SUBTYPE 2
#define LLDP_PORT_MAC_ADDR_SUBTYPE 3
#define LLDP_PORT_NETWORK_ADDR_SUBTYPE 4
#define LLDP_PORT_INTF_NAME_SUBTYPE 5
#define LLDP_PORT_AGENT_CIRC_ID_SUBTYPE 6
#define LLDP_PORT_LOCAL_SUBTYPE 7
static const struct tok lldp_port_subtype_values[] = {
{ LLDP_PORT_INTF_ALIAS_SUBTYPE, "Interface alias"},
{ LLDP_PORT_PORT_COMP_SUBTYPE, "Port component"},
{ LLDP_PORT_MAC_ADDR_SUBTYPE, "MAC address"},
{ LLDP_PORT_NETWORK_ADDR_SUBTYPE, "Network Address"},
{ LLDP_PORT_INTF_NAME_SUBTYPE, "Interface Name"},
{ LLDP_PORT_AGENT_CIRC_ID_SUBTYPE, "Agent circuit ID"},
{ LLDP_PORT_LOCAL_SUBTYPE, "Local"},
{ 0, NULL}
};
/*
* System Capabilities
*/
#define LLDP_CAP_OTHER (1 << 0)
#define LLDP_CAP_REPEATER (1 << 1)
#define LLDP_CAP_BRIDGE (1 << 2)
#define LLDP_CAP_WLAN_AP (1 << 3)
#define LLDP_CAP_ROUTER (1 << 4)
#define LLDP_CAP_PHONE (1 << 5)
#define LLDP_CAP_DOCSIS (1 << 6)
#define LLDP_CAP_STATION_ONLY (1 << 7)
static const struct tok lldp_cap_values[] = {
{ LLDP_CAP_OTHER, "Other"},
{ LLDP_CAP_REPEATER, "Repeater"},
{ LLDP_CAP_BRIDGE, "Bridge"},
{ LLDP_CAP_WLAN_AP, "WLAN AP"},
{ LLDP_CAP_ROUTER, "Router"},
{ LLDP_CAP_PHONE, "Telephone"},
{ LLDP_CAP_DOCSIS, "Docsis"},
{ LLDP_CAP_STATION_ONLY, "Station Only"},
{ 0, NULL}
};
#define LLDP_PRIVATE_8021_SUBTYPE_PORT_VLAN_ID 1
#define LLDP_PRIVATE_8021_SUBTYPE_PROTOCOL_VLAN_ID 2
#define LLDP_PRIVATE_8021_SUBTYPE_VLAN_NAME 3
#define LLDP_PRIVATE_8021_SUBTYPE_PROTOCOL_IDENTITY 4
#define LLDP_PRIVATE_8021_SUBTYPE_CONGESTION_NOTIFICATION 8
#define LLDP_PRIVATE_8021_SUBTYPE_ETS_CONFIGURATION 9
#define LLDP_PRIVATE_8021_SUBTYPE_ETS_RECOMMENDATION 10
#define LLDP_PRIVATE_8021_SUBTYPE_PFC_CONFIGURATION 11
#define LLDP_PRIVATE_8021_SUBTYPE_APPLICATION_PRIORITY 12
#define LLDP_PRIVATE_8021_SUBTYPE_EVB 13
#define LLDP_PRIVATE_8021_SUBTYPE_CDCP 14
static const struct tok lldp_8021_subtype_values[] = {
{ LLDP_PRIVATE_8021_SUBTYPE_PORT_VLAN_ID, "Port VLAN Id"},
{ LLDP_PRIVATE_8021_SUBTYPE_PROTOCOL_VLAN_ID, "Port and Protocol VLAN ID"},
{ LLDP_PRIVATE_8021_SUBTYPE_VLAN_NAME, "VLAN name"},
{ LLDP_PRIVATE_8021_SUBTYPE_PROTOCOL_IDENTITY, "Protocol Identity"},
{ LLDP_PRIVATE_8021_SUBTYPE_CONGESTION_NOTIFICATION, "Congestion Notification"},
{ LLDP_PRIVATE_8021_SUBTYPE_ETS_CONFIGURATION, "ETS Configuration"},
{ LLDP_PRIVATE_8021_SUBTYPE_ETS_RECOMMENDATION, "ETS Recommendation"},
{ LLDP_PRIVATE_8021_SUBTYPE_PFC_CONFIGURATION, "Priority Flow Control Configuration"},
{ LLDP_PRIVATE_8021_SUBTYPE_APPLICATION_PRIORITY, "Application Priority"},
{ LLDP_PRIVATE_8021_SUBTYPE_EVB, "EVB"},
{ LLDP_PRIVATE_8021_SUBTYPE_CDCP,"CDCP"},
{ 0, NULL}
};
#define LLDP_8021_PORT_PROTOCOL_VLAN_SUPPORT (1 << 1)
#define LLDP_8021_PORT_PROTOCOL_VLAN_STATUS (1 << 2)
static const struct tok lldp_8021_port_protocol_id_values[] = {
{ LLDP_8021_PORT_PROTOCOL_VLAN_SUPPORT, "supported"},
{ LLDP_8021_PORT_PROTOCOL_VLAN_STATUS, "enabled"},
{ 0, NULL}
};
#define LLDP_PRIVATE_8023_SUBTYPE_MACPHY 1
#define LLDP_PRIVATE_8023_SUBTYPE_MDIPOWER 2
#define LLDP_PRIVATE_8023_SUBTYPE_LINKAGGR 3
#define LLDP_PRIVATE_8023_SUBTYPE_MTU 4
static const struct tok lldp_8023_subtype_values[] = {
{ LLDP_PRIVATE_8023_SUBTYPE_MACPHY, "MAC/PHY configuration/status"},
{ LLDP_PRIVATE_8023_SUBTYPE_MDIPOWER, "Power via MDI"},
{ LLDP_PRIVATE_8023_SUBTYPE_LINKAGGR, "Link aggregation"},
{ LLDP_PRIVATE_8023_SUBTYPE_MTU, "Max frame size"},
{ 0, NULL}
};
#define LLDP_PRIVATE_TIA_SUBTYPE_CAPABILITIES 1
#define LLDP_PRIVATE_TIA_SUBTYPE_NETWORK_POLICY 2
#define LLDP_PRIVATE_TIA_SUBTYPE_LOCAL_ID 3
#define LLDP_PRIVATE_TIA_SUBTYPE_EXTENDED_POWER_MDI 4
#define LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_HARDWARE_REV 5
#define LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_FIRMWARE_REV 6
#define LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_SOFTWARE_REV 7
#define LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_SERIAL_NUMBER 8
#define LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_MANUFACTURER_NAME 9
#define LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_MODEL_NAME 10
#define LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_ASSET_ID 11
static const struct tok lldp_tia_subtype_values[] = {
{ LLDP_PRIVATE_TIA_SUBTYPE_CAPABILITIES, "LLDP-MED Capabilities" },
{ LLDP_PRIVATE_TIA_SUBTYPE_NETWORK_POLICY, "Network policy" },
{ LLDP_PRIVATE_TIA_SUBTYPE_LOCAL_ID, "Location identification" },
{ LLDP_PRIVATE_TIA_SUBTYPE_EXTENDED_POWER_MDI, "Extended power-via-MDI" },
{ LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_HARDWARE_REV, "Inventory - hardware revision" },
{ LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_FIRMWARE_REV, "Inventory - firmware revision" },
{ LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_SOFTWARE_REV, "Inventory - software revision" },
{ LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_SERIAL_NUMBER, "Inventory - serial number" },
{ LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_MANUFACTURER_NAME, "Inventory - manufacturer name" },
{ LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_MODEL_NAME, "Inventory - model name" },
{ LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_ASSET_ID, "Inventory - asset ID" },
{ 0, NULL}
};
#define LLDP_PRIVATE_TIA_LOCATION_ALTITUDE_METERS 1
#define LLDP_PRIVATE_TIA_LOCATION_ALTITUDE_FLOORS 2
static const struct tok lldp_tia_location_altitude_type_values[] = {
{ LLDP_PRIVATE_TIA_LOCATION_ALTITUDE_METERS, "meters"},
{ LLDP_PRIVATE_TIA_LOCATION_ALTITUDE_FLOORS, "floors"},
{ 0, NULL}
};
/* ANSI/TIA-1057 - Annex B */
#define LLDP_PRIVATE_TIA_LOCATION_LCI_CATYPE_A1 1
#define LLDP_PRIVATE_TIA_LOCATION_LCI_CATYPE_A2 2
#define LLDP_PRIVATE_TIA_LOCATION_LCI_CATYPE_A3 3
#define LLDP_PRIVATE_TIA_LOCATION_LCI_CATYPE_A4 4
#define LLDP_PRIVATE_TIA_LOCATION_LCI_CATYPE_A5 5
#define LLDP_PRIVATE_TIA_LOCATION_LCI_CATYPE_A6 6
static const struct tok lldp_tia_location_lci_catype_values[] = {
{ LLDP_PRIVATE_TIA_LOCATION_LCI_CATYPE_A1, "national subdivisions (state,canton,region,province,prefecture)"},
{ LLDP_PRIVATE_TIA_LOCATION_LCI_CATYPE_A2, "county, parish, gun, district"},
{ LLDP_PRIVATE_TIA_LOCATION_LCI_CATYPE_A3, "city, township, shi"},
{ LLDP_PRIVATE_TIA_LOCATION_LCI_CATYPE_A4, "city division, borough, city district, ward chou"},
{ LLDP_PRIVATE_TIA_LOCATION_LCI_CATYPE_A5, "neighborhood, block"},
{ LLDP_PRIVATE_TIA_LOCATION_LCI_CATYPE_A6, "street"},
{ 0, NULL}
};
static const struct tok lldp_tia_location_lci_what_values[] = {
{ 0, "location of DHCP server"},
{ 1, "location of the network element believed to be closest to the client"},
{ 2, "location of the client"},
{ 0, NULL}
};
/*
* From RFC 3636 - dot3MauType
*/
#define LLDP_MAU_TYPE_UNKNOWN 0
#define LLDP_MAU_TYPE_AUI 1
#define LLDP_MAU_TYPE_10BASE_5 2
#define LLDP_MAU_TYPE_FOIRL 3
#define LLDP_MAU_TYPE_10BASE_2 4
#define LLDP_MAU_TYPE_10BASE_T 5
#define LLDP_MAU_TYPE_10BASE_FP 6
#define LLDP_MAU_TYPE_10BASE_FB 7
#define LLDP_MAU_TYPE_10BASE_FL 8
#define LLDP_MAU_TYPE_10BROAD36 9
#define LLDP_MAU_TYPE_10BASE_T_HD 10
#define LLDP_MAU_TYPE_10BASE_T_FD 11
#define LLDP_MAU_TYPE_10BASE_FL_HD 12
#define LLDP_MAU_TYPE_10BASE_FL_FD 13
#define LLDP_MAU_TYPE_100BASE_T4 14
#define LLDP_MAU_TYPE_100BASE_TX_HD 15
#define LLDP_MAU_TYPE_100BASE_TX_FD 16
#define LLDP_MAU_TYPE_100BASE_FX_HD 17
#define LLDP_MAU_TYPE_100BASE_FX_FD 18
#define LLDP_MAU_TYPE_100BASE_T2_HD 19
#define LLDP_MAU_TYPE_100BASE_T2_FD 20
#define LLDP_MAU_TYPE_1000BASE_X_HD 21
#define LLDP_MAU_TYPE_1000BASE_X_FD 22
#define LLDP_MAU_TYPE_1000BASE_LX_HD 23
#define LLDP_MAU_TYPE_1000BASE_LX_FD 24
#define LLDP_MAU_TYPE_1000BASE_SX_HD 25
#define LLDP_MAU_TYPE_1000BASE_SX_FD 26
#define LLDP_MAU_TYPE_1000BASE_CX_HD 27
#define LLDP_MAU_TYPE_1000BASE_CX_FD 28
#define LLDP_MAU_TYPE_1000BASE_T_HD 29
#define LLDP_MAU_TYPE_1000BASE_T_FD 30
#define LLDP_MAU_TYPE_10GBASE_X 31
#define LLDP_MAU_TYPE_10GBASE_LX4 32
#define LLDP_MAU_TYPE_10GBASE_R 33
#define LLDP_MAU_TYPE_10GBASE_ER 34
#define LLDP_MAU_TYPE_10GBASE_LR 35
#define LLDP_MAU_TYPE_10GBASE_SR 36
#define LLDP_MAU_TYPE_10GBASE_W 37
#define LLDP_MAU_TYPE_10GBASE_EW 38
#define LLDP_MAU_TYPE_10GBASE_LW 39
#define LLDP_MAU_TYPE_10GBASE_SW 40
static const struct tok lldp_mau_types_values[] = {
{ LLDP_MAU_TYPE_UNKNOWN, "Unknown"},
{ LLDP_MAU_TYPE_AUI, "AUI"},
{ LLDP_MAU_TYPE_10BASE_5, "10BASE_5"},
{ LLDP_MAU_TYPE_FOIRL, "FOIRL"},
{ LLDP_MAU_TYPE_10BASE_2, "10BASE2"},
{ LLDP_MAU_TYPE_10BASE_T, "10BASET duplex mode unknown"},
{ LLDP_MAU_TYPE_10BASE_FP, "10BASEFP"},
{ LLDP_MAU_TYPE_10BASE_FB, "10BASEFB"},
{ LLDP_MAU_TYPE_10BASE_FL, "10BASEFL duplex mode unknown"},
{ LLDP_MAU_TYPE_10BROAD36, "10BROAD36"},
{ LLDP_MAU_TYPE_10BASE_T_HD, "10BASET hdx"},
{ LLDP_MAU_TYPE_10BASE_T_FD, "10BASET fdx"},
{ LLDP_MAU_TYPE_10BASE_FL_HD, "10BASEFL hdx"},
{ LLDP_MAU_TYPE_10BASE_FL_FD, "10BASEFL fdx"},
{ LLDP_MAU_TYPE_100BASE_T4, "100BASET4"},
{ LLDP_MAU_TYPE_100BASE_TX_HD, "100BASETX hdx"},
{ LLDP_MAU_TYPE_100BASE_TX_FD, "100BASETX fdx"},
{ LLDP_MAU_TYPE_100BASE_FX_HD, "100BASEFX hdx"},
{ LLDP_MAU_TYPE_100BASE_FX_FD, "100BASEFX fdx"},
{ LLDP_MAU_TYPE_100BASE_T2_HD, "100BASET2 hdx"},
{ LLDP_MAU_TYPE_100BASE_T2_FD, "100BASET2 fdx"},
{ LLDP_MAU_TYPE_1000BASE_X_HD, "1000BASEX hdx"},
{ LLDP_MAU_TYPE_1000BASE_X_FD, "1000BASEX fdx"},
{ LLDP_MAU_TYPE_1000BASE_LX_HD, "1000BASELX hdx"},
{ LLDP_MAU_TYPE_1000BASE_LX_FD, "1000BASELX fdx"},
{ LLDP_MAU_TYPE_1000BASE_SX_HD, "1000BASESX hdx"},
{ LLDP_MAU_TYPE_1000BASE_SX_FD, "1000BASESX fdx"},
{ LLDP_MAU_TYPE_1000BASE_CX_HD, "1000BASECX hdx"},
{ LLDP_MAU_TYPE_1000BASE_CX_FD, "1000BASECX fdx"},
{ LLDP_MAU_TYPE_1000BASE_T_HD, "1000BASET hdx"},
{ LLDP_MAU_TYPE_1000BASE_T_FD, "1000BASET fdx"},
{ LLDP_MAU_TYPE_10GBASE_X, "10GBASEX"},
{ LLDP_MAU_TYPE_10GBASE_LX4, "10GBASELX4"},
{ LLDP_MAU_TYPE_10GBASE_R, "10GBASER"},
{ LLDP_MAU_TYPE_10GBASE_ER, "10GBASEER"},
{ LLDP_MAU_TYPE_10GBASE_LR, "10GBASELR"},
{ LLDP_MAU_TYPE_10GBASE_SR, "10GBASESR"},
{ LLDP_MAU_TYPE_10GBASE_W, "10GBASEW"},
{ LLDP_MAU_TYPE_10GBASE_EW, "10GBASEEW"},
{ LLDP_MAU_TYPE_10GBASE_LW, "10GBASELW"},
{ LLDP_MAU_TYPE_10GBASE_SW, "10GBASESW"},
{ 0, NULL}
};
#define LLDP_8023_AUTONEGOTIATION_SUPPORT (1 << 0)
#define LLDP_8023_AUTONEGOTIATION_STATUS (1 << 1)
static const struct tok lldp_8023_autonegotiation_values[] = {
{ LLDP_8023_AUTONEGOTIATION_SUPPORT, "supported"},
{ LLDP_8023_AUTONEGOTIATION_STATUS, "enabled"},
{ 0, NULL}
};
#define LLDP_TIA_CAPABILITY_MED (1 << 0)
#define LLDP_TIA_CAPABILITY_NETWORK_POLICY (1 << 1)
#define LLDP_TIA_CAPABILITY_LOCATION_IDENTIFICATION (1 << 2)
#define LLDP_TIA_CAPABILITY_EXTENDED_POWER_MDI_PSE (1 << 3)
#define LLDP_TIA_CAPABILITY_EXTENDED_POWER_MDI_PD (1 << 4)
#define LLDP_TIA_CAPABILITY_INVENTORY (1 << 5)
static const struct tok lldp_tia_capabilities_values[] = {
{ LLDP_TIA_CAPABILITY_MED, "LLDP-MED capabilities"},
{ LLDP_TIA_CAPABILITY_NETWORK_POLICY, "network policy"},
{ LLDP_TIA_CAPABILITY_LOCATION_IDENTIFICATION, "location identification"},
{ LLDP_TIA_CAPABILITY_EXTENDED_POWER_MDI_PSE, "extended power via MDI-PSE"},
{ LLDP_TIA_CAPABILITY_EXTENDED_POWER_MDI_PD, "extended power via MDI-PD"},
{ LLDP_TIA_CAPABILITY_INVENTORY, "Inventory"},
{ 0, NULL}
};
#define LLDP_TIA_DEVICE_TYPE_ENDPOINT_CLASS_1 1
#define LLDP_TIA_DEVICE_TYPE_ENDPOINT_CLASS_2 2
#define LLDP_TIA_DEVICE_TYPE_ENDPOINT_CLASS_3 3
#define LLDP_TIA_DEVICE_TYPE_NETWORK_CONNECTIVITY 4
static const struct tok lldp_tia_device_type_values[] = {
{ LLDP_TIA_DEVICE_TYPE_ENDPOINT_CLASS_1, "endpoint class 1"},
{ LLDP_TIA_DEVICE_TYPE_ENDPOINT_CLASS_2, "endpoint class 2"},
{ LLDP_TIA_DEVICE_TYPE_ENDPOINT_CLASS_3, "endpoint class 3"},
{ LLDP_TIA_DEVICE_TYPE_NETWORK_CONNECTIVITY, "network connectivity"},
{ 0, NULL}
};
#define LLDP_TIA_APPLICATION_TYPE_VOICE 1
#define LLDP_TIA_APPLICATION_TYPE_VOICE_SIGNALING 2
#define LLDP_TIA_APPLICATION_TYPE_GUEST_VOICE 3
#define LLDP_TIA_APPLICATION_TYPE_GUEST_VOICE_SIGNALING 4
#define LLDP_TIA_APPLICATION_TYPE_SOFTPHONE_VOICE 5
#define LLDP_TIA_APPLICATION_TYPE_VIDEO_CONFERENCING 6
#define LLDP_TIA_APPLICATION_TYPE_STREAMING_VIDEO 7
#define LLDP_TIA_APPLICATION_TYPE_VIDEO_SIGNALING 8
static const struct tok lldp_tia_application_type_values[] = {
{ LLDP_TIA_APPLICATION_TYPE_VOICE, "voice"},
{ LLDP_TIA_APPLICATION_TYPE_VOICE_SIGNALING, "voice signaling"},
{ LLDP_TIA_APPLICATION_TYPE_GUEST_VOICE, "guest voice"},
{ LLDP_TIA_APPLICATION_TYPE_GUEST_VOICE_SIGNALING, "guest voice signaling"},
{ LLDP_TIA_APPLICATION_TYPE_SOFTPHONE_VOICE, "softphone voice"},
{ LLDP_TIA_APPLICATION_TYPE_VIDEO_CONFERENCING, "video conferencing"},
{ LLDP_TIA_APPLICATION_TYPE_STREAMING_VIDEO, "streaming video"},
{ LLDP_TIA_APPLICATION_TYPE_VIDEO_SIGNALING, "video signaling"},
{ 0, NULL}
};
#define LLDP_TIA_NETWORK_POLICY_X_BIT (1 << 5)
#define LLDP_TIA_NETWORK_POLICY_T_BIT (1 << 6)
#define LLDP_TIA_NETWORK_POLICY_U_BIT (1 << 7)
static const struct tok lldp_tia_network_policy_bits_values[] = {
{ LLDP_TIA_NETWORK_POLICY_U_BIT, "Unknown"},
{ LLDP_TIA_NETWORK_POLICY_T_BIT, "Tagged"},
{ LLDP_TIA_NETWORK_POLICY_X_BIT, "reserved"},
{ 0, NULL}
};
#define LLDP_EXTRACT_NETWORK_POLICY_VLAN(x) (((x)&0x1ffe)>>1)
#define LLDP_EXTRACT_NETWORK_POLICY_L2_PRIORITY(x) (((x)&0x01ff)>>6)
#define LLDP_EXTRACT_NETWORK_POLICY_DSCP(x) ((x)&0x003f)
#define LLDP_TIA_LOCATION_DATA_FORMAT_COORDINATE_BASED 1
#define LLDP_TIA_LOCATION_DATA_FORMAT_CIVIC_ADDRESS 2
#define LLDP_TIA_LOCATION_DATA_FORMAT_ECS_ELIN 3
static const struct tok lldp_tia_location_data_format_values[] = {
{ LLDP_TIA_LOCATION_DATA_FORMAT_COORDINATE_BASED, "coordinate-based LCI"},
{ LLDP_TIA_LOCATION_DATA_FORMAT_CIVIC_ADDRESS, "civic address LCI"},
{ LLDP_TIA_LOCATION_DATA_FORMAT_ECS_ELIN, "ECS ELIN"},
{ 0, NULL}
};
#define LLDP_TIA_LOCATION_DATUM_WGS_84 1
#define LLDP_TIA_LOCATION_DATUM_NAD_83_NAVD_88 2
#define LLDP_TIA_LOCATION_DATUM_NAD_83_MLLW 3
static const struct tok lldp_tia_location_datum_type_values[] = {
{ LLDP_TIA_LOCATION_DATUM_WGS_84, "World Geodesic System 1984"},
{ LLDP_TIA_LOCATION_DATUM_NAD_83_NAVD_88, "North American Datum 1983 (NAVD88)"},
{ LLDP_TIA_LOCATION_DATUM_NAD_83_MLLW, "North American Datum 1983 (MLLW)"},
{ 0, NULL}
};
#define LLDP_TIA_POWER_SOURCE_PSE 1
#define LLDP_TIA_POWER_SOURCE_LOCAL 2
#define LLDP_TIA_POWER_SOURCE_PSE_AND_LOCAL 3
static const struct tok lldp_tia_power_source_values[] = {
{ LLDP_TIA_POWER_SOURCE_PSE, "PSE - primary power source"},
{ LLDP_TIA_POWER_SOURCE_LOCAL, "local - backup power source"},
{ LLDP_TIA_POWER_SOURCE_PSE_AND_LOCAL, "PSE+local - reserved"},
{ 0, NULL}
};
#define LLDP_TIA_POWER_PRIORITY_CRITICAL 1
#define LLDP_TIA_POWER_PRIORITY_HIGH 2
#define LLDP_TIA_POWER_PRIORITY_LOW 3
static const struct tok lldp_tia_power_priority_values[] = {
{ LLDP_TIA_POWER_PRIORITY_CRITICAL, "critical"},
{ LLDP_TIA_POWER_PRIORITY_HIGH, "high"},
{ LLDP_TIA_POWER_PRIORITY_LOW, "low"},
{ 0, NULL}
};
#define LLDP_TIA_POWER_VAL_MAX 1024
static const struct tok lldp_tia_inventory_values[] = {
{ LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_HARDWARE_REV, "Hardware revision" },
{ LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_FIRMWARE_REV, "Firmware revision" },
{ LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_SOFTWARE_REV, "Software revision" },
{ LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_SERIAL_NUMBER, "Serial number" },
{ LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_MANUFACTURER_NAME, "Manufacturer name" },
{ LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_MODEL_NAME, "Model name" },
{ LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_ASSET_ID, "Asset ID" },
{ 0, NULL}
};
/*
* From RFC 3636 - ifMauAutoNegCapAdvertisedBits
*/
#define LLDP_MAU_PMD_OTHER (1 << 15)
#define LLDP_MAU_PMD_10BASE_T (1 << 14)
#define LLDP_MAU_PMD_10BASE_T_FD (1 << 13)
#define LLDP_MAU_PMD_100BASE_T4 (1 << 12)
#define LLDP_MAU_PMD_100BASE_TX (1 << 11)
#define LLDP_MAU_PMD_100BASE_TX_FD (1 << 10)
#define LLDP_MAU_PMD_100BASE_T2 (1 << 9)
#define LLDP_MAU_PMD_100BASE_T2_FD (1 << 8)
#define LLDP_MAU_PMD_FDXPAUSE (1 << 7)
#define LLDP_MAU_PMD_FDXAPAUSE (1 << 6)
#define LLDP_MAU_PMD_FDXSPAUSE (1 << 5)
#define LLDP_MAU_PMD_FDXBPAUSE (1 << 4)
#define LLDP_MAU_PMD_1000BASE_X (1 << 3)
#define LLDP_MAU_PMD_1000BASE_X_FD (1 << 2)
#define LLDP_MAU_PMD_1000BASE_T (1 << 1)
#define LLDP_MAU_PMD_1000BASE_T_FD (1 << 0)
static const struct tok lldp_pmd_capability_values[] = {
{ LLDP_MAU_PMD_10BASE_T, "10BASE-T hdx"},
{ LLDP_MAU_PMD_10BASE_T_FD, "10BASE-T fdx"},
{ LLDP_MAU_PMD_100BASE_T4, "100BASE-T4"},
{ LLDP_MAU_PMD_100BASE_TX, "100BASE-TX hdx"},
{ LLDP_MAU_PMD_100BASE_TX_FD, "100BASE-TX fdx"},
{ LLDP_MAU_PMD_100BASE_T2, "100BASE-T2 hdx"},
{ LLDP_MAU_PMD_100BASE_T2_FD, "100BASE-T2 fdx"},
{ LLDP_MAU_PMD_FDXPAUSE, "Pause for fdx links"},
{ LLDP_MAU_PMD_FDXAPAUSE, "Asym PAUSE for fdx"},
{ LLDP_MAU_PMD_FDXSPAUSE, "Sym PAUSE for fdx"},
{ LLDP_MAU_PMD_FDXBPAUSE, "Asym and Sym PAUSE for fdx"},
{ LLDP_MAU_PMD_1000BASE_X, "1000BASE-{X LX SX CX} hdx"},
{ LLDP_MAU_PMD_1000BASE_X_FD, "1000BASE-{X LX SX CX} fdx"},
{ LLDP_MAU_PMD_1000BASE_T, "1000BASE-T hdx"},
{ LLDP_MAU_PMD_1000BASE_T_FD, "1000BASE-T fdx"},
{ 0, NULL}
};
#define LLDP_MDI_PORT_CLASS (1 << 0)
#define LLDP_MDI_POWER_SUPPORT (1 << 1)
#define LLDP_MDI_POWER_STATE (1 << 2)
#define LLDP_MDI_PAIR_CONTROL_ABILITY (1 << 3)
static const struct tok lldp_mdi_values[] = {
{ LLDP_MDI_PORT_CLASS, "PSE"},
{ LLDP_MDI_POWER_SUPPORT, "supported"},
{ LLDP_MDI_POWER_STATE, "enabled"},
{ LLDP_MDI_PAIR_CONTROL_ABILITY, "can be controlled"},
{ 0, NULL}
};
#define LLDP_MDI_PSE_PORT_POWER_PAIRS_SIGNAL 1
#define LLDP_MDI_PSE_PORT_POWER_PAIRS_SPARE 2
static const struct tok lldp_mdi_power_pairs_values[] = {
{ LLDP_MDI_PSE_PORT_POWER_PAIRS_SIGNAL, "signal"},
{ LLDP_MDI_PSE_PORT_POWER_PAIRS_SPARE, "spare"},
{ 0, NULL}
};
#define LLDP_MDI_POWER_CLASS0 1
#define LLDP_MDI_POWER_CLASS1 2
#define LLDP_MDI_POWER_CLASS2 3
#define LLDP_MDI_POWER_CLASS3 4
#define LLDP_MDI_POWER_CLASS4 5
static const struct tok lldp_mdi_power_class_values[] = {
{ LLDP_MDI_POWER_CLASS0, "class0"},
{ LLDP_MDI_POWER_CLASS1, "class1"},
{ LLDP_MDI_POWER_CLASS2, "class2"},
{ LLDP_MDI_POWER_CLASS3, "class3"},
{ LLDP_MDI_POWER_CLASS4, "class4"},
{ 0, NULL}
};
#define LLDP_AGGREGATION_CAPABILTIY (1 << 0)
#define LLDP_AGGREGATION_STATUS (1 << 1)
static const struct tok lldp_aggregation_values[] = {
{ LLDP_AGGREGATION_CAPABILTIY, "supported"},
{ LLDP_AGGREGATION_STATUS, "enabled"},
{ 0, NULL}
};
/*
* DCBX protocol subtypes.
*/
#define LLDP_DCBX_SUBTYPE_1 1
#define LLDP_DCBX_SUBTYPE_2 2
static const struct tok lldp_dcbx_subtype_values[] = {
{ LLDP_DCBX_SUBTYPE_1, "DCB Capability Exchange Protocol Rev 1" },
{ LLDP_DCBX_SUBTYPE_2, "DCB Capability Exchange Protocol Rev 1.01" },
{ 0, NULL}
};
#define LLDP_DCBX_CONTROL_TLV 1
#define LLDP_DCBX_PRIORITY_GROUPS_TLV 2
#define LLDP_DCBX_PRIORITY_FLOW_CONTROL_TLV 3
#define LLDP_DCBX_APPLICATION_TLV 4
/*
* Interface numbering subtypes.
*/
#define LLDP_INTF_NUMB_IFX_SUBTYPE 2
#define LLDP_INTF_NUMB_SYSPORT_SUBTYPE 3
static const struct tok lldp_intf_numb_subtype_values[] = {
{ LLDP_INTF_NUMB_IFX_SUBTYPE, "Interface Index" },
{ LLDP_INTF_NUMB_SYSPORT_SUBTYPE, "System Port Number" },
{ 0, NULL}
};
#define LLDP_INTF_NUM_LEN 5
#define LLDP_EVB_MODE_NOT_SUPPORTED 0
#define LLDP_EVB_MODE_EVB_BRIDGE 1
#define LLDP_EVB_MODE_EVB_STATION 2
#define LLDP_EVB_MODE_RESERVED 3
static const struct tok lldp_evb_mode_values[]={
{ LLDP_EVB_MODE_NOT_SUPPORTED, "Not Supported"},
{ LLDP_EVB_MODE_EVB_BRIDGE, "EVB Bridge"},
{ LLDP_EVB_MODE_EVB_STATION, "EVB Staion"},
{ LLDP_EVB_MODE_RESERVED, "Reserved for future Standardization"},
{ 0, NULL},
};
#define NO_OF_BITS 8
#define LLDP_PRIVATE_8021_SUBTYPE_CONGESTION_NOTIFICATION_LENGTH 6
#define LLDP_PRIVATE_8021_SUBTYPE_ETS_CONFIGURATION_LENGTH 25
#define LLDP_PRIVATE_8021_SUBTYPE_ETS_RECOMMENDATION_LENGTH 25
#define LLDP_PRIVATE_8021_SUBTYPE_PFC_CONFIGURATION_LENGTH 6
#define LLDP_PRIVATE_8021_SUBTYPE_APPLICATION_PRIORITY_MIN_LENGTH 5
#define LLDP_PRIVATE_8021_SUBTYPE_EVB_LENGTH 9
#define LLDP_PRIVATE_8021_SUBTYPE_CDCP_MIN_LENGTH 8
#define LLDP_IANA_SUBTYPE_MUDURL 1
static const struct tok lldp_iana_subtype_values[] = {
{ LLDP_IANA_SUBTYPE_MUDURL, "MUD-URL" },
{ 0, NULL }
};
static void
print_ets_priority_assignment_table(netdissect_options *ndo,
const u_char *ptr)
{
ND_PRINT((ndo, "\n\t Priority Assignment Table"));
ND_PRINT((ndo, "\n\t Priority : 0 1 2 3 4 5 6 7"));
ND_PRINT((ndo, "\n\t Value : %-3d %-3d %-3d %-3d %-3d %-3d %-3d %-3d",
ptr[0]>>4,ptr[0]&0x0f,ptr[1]>>4,ptr[1]&0x0f,ptr[2]>>4,
ptr[2] & 0x0f, ptr[3] >> 4, ptr[3] & 0x0f));
}
static void
print_tc_bandwidth_table(netdissect_options *ndo,
const u_char *ptr)
{
ND_PRINT((ndo, "\n\t TC Bandwidth Table"));
ND_PRINT((ndo, "\n\t TC%% : 0 1 2 3 4 5 6 7"));
ND_PRINT((ndo, "\n\t Value : %-3d %-3d %-3d %-3d %-3d %-3d %-3d %-3d",
ptr[0], ptr[1], ptr[2], ptr[3], ptr[4], ptr[5], ptr[6], ptr[7]));
}
static void
print_tsa_assignment_table(netdissect_options *ndo,
const u_char *ptr)
{
ND_PRINT((ndo, "\n\t TSA Assignment Table"));
ND_PRINT((ndo, "\n\t Traffic Class: 0 1 2 3 4 5 6 7"));
ND_PRINT((ndo, "\n\t Value : %-3d %-3d %-3d %-3d %-3d %-3d %-3d %-3d",
ptr[0], ptr[1], ptr[2], ptr[3], ptr[4], ptr[5], ptr[6], ptr[7]));
}
/*
* Print IEEE 802.1 private extensions. (802.1AB annex E)
*/
static int
lldp_private_8021_print(netdissect_options *ndo,
const u_char *tptr, u_int tlv_len)
{
int subtype, hexdump = FALSE;
u_int sublen;
u_int tval;
u_int i;
if (tlv_len < 4) {
return hexdump;
}
subtype = *(tptr+3);
ND_PRINT((ndo, "\n\t %s Subtype (%u)",
tok2str(lldp_8021_subtype_values, "unknown", subtype),
subtype));
switch (subtype) {
case LLDP_PRIVATE_8021_SUBTYPE_PORT_VLAN_ID:
if (tlv_len < 6) {
return hexdump;
}
ND_PRINT((ndo, "\n\t port vlan id (PVID): %u",
EXTRACT_16BITS(tptr + 4)));
break;
case LLDP_PRIVATE_8021_SUBTYPE_PROTOCOL_VLAN_ID:
if (tlv_len < 7) {
return hexdump;
}
ND_PRINT((ndo, "\n\t port and protocol vlan id (PPVID): %u, flags [%s] (0x%02x)",
EXTRACT_16BITS(tptr+5),
bittok2str(lldp_8021_port_protocol_id_values, "none", *(tptr+4)),
*(tptr + 4)));
break;
case LLDP_PRIVATE_8021_SUBTYPE_VLAN_NAME:
if (tlv_len < 6) {
return hexdump;
}
ND_PRINT((ndo, "\n\t vlan id (VID): %u", EXTRACT_16BITS(tptr + 4)));
if (tlv_len < 7) {
return hexdump;
}
sublen = *(tptr+6);
if (tlv_len < 7+sublen) {
return hexdump;
}
ND_PRINT((ndo, "\n\t vlan name: "));
safeputs(ndo, tptr + 7, sublen);
break;
case LLDP_PRIVATE_8021_SUBTYPE_PROTOCOL_IDENTITY:
if (tlv_len < 5) {
return hexdump;
}
sublen = *(tptr+4);
if (tlv_len < 5+sublen) {
return hexdump;
}
ND_PRINT((ndo, "\n\t protocol identity: "));
safeputs(ndo, tptr + 5, sublen);
break;
case LLDP_PRIVATE_8021_SUBTYPE_CONGESTION_NOTIFICATION:
if(tlv_len<LLDP_PRIVATE_8021_SUBTYPE_CONGESTION_NOTIFICATION_LENGTH){
return hexdump;
}
tval=*(tptr+4);
ND_PRINT((ndo, "\n\t Pre-Priority CNPV Indicator"));
ND_PRINT((ndo, "\n\t Priority : 0 1 2 3 4 5 6 7"));
ND_PRINT((ndo, "\n\t Value : "));
for(i=0;i<NO_OF_BITS;i++)
ND_PRINT((ndo, "%-2d ", (tval >> i) & 0x01));
tval=*(tptr+5);
ND_PRINT((ndo, "\n\t Pre-Priority Ready Indicator"));
ND_PRINT((ndo, "\n\t Priority : 0 1 2 3 4 5 6 7"));
ND_PRINT((ndo, "\n\t Value : "));
for(i=0;i<NO_OF_BITS;i++)
ND_PRINT((ndo, "%-2d ", (tval >> i) & 0x01));
break;
case LLDP_PRIVATE_8021_SUBTYPE_ETS_CONFIGURATION:
if(tlv_len<LLDP_PRIVATE_8021_SUBTYPE_ETS_CONFIGURATION_LENGTH) {
return hexdump;
}
tval=*(tptr+4);
ND_PRINT((ndo, "\n\t Willing:%d, CBS:%d, RES:%d, Max TCs:%d",
tval >> 7, (tval >> 6) & 0x02, (tval >> 3) & 0x07, tval & 0x07));
/*Print Priority Assignment Table*/
print_ets_priority_assignment_table(ndo, tptr + 5);
/*Print TC Bandwidth Table*/
print_tc_bandwidth_table(ndo, tptr + 9);
/* Print TSA Assignment Table */
print_tsa_assignment_table(ndo, tptr + 17);
break;
case LLDP_PRIVATE_8021_SUBTYPE_ETS_RECOMMENDATION:
if(tlv_len<LLDP_PRIVATE_8021_SUBTYPE_ETS_RECOMMENDATION_LENGTH) {
return hexdump;
}
ND_PRINT((ndo, "\n\t RES: %d", *(tptr + 4)));
/*Print Priority Assignment Table */
print_ets_priority_assignment_table(ndo, tptr + 5);
/*Print TC Bandwidth Table */
print_tc_bandwidth_table(ndo, tptr + 9);
/* Print TSA Assignment Table */
print_tsa_assignment_table(ndo, tptr + 17);
break;
case LLDP_PRIVATE_8021_SUBTYPE_PFC_CONFIGURATION:
if(tlv_len<LLDP_PRIVATE_8021_SUBTYPE_PFC_CONFIGURATION_LENGTH) {
return hexdump;
}
tval=*(tptr+4);
ND_PRINT((ndo, "\n\t Willing: %d, MBC: %d, RES: %d, PFC cap:%d ",
tval >> 7, (tval >> 6) & 0x01, (tval >> 4) & 0x03, (tval & 0x0f)));
ND_PRINT((ndo, "\n\t PFC Enable"));
tval=*(tptr+5);
ND_PRINT((ndo, "\n\t Priority : 0 1 2 3 4 5 6 7"));
ND_PRINT((ndo, "\n\t Value : "));
for(i=0;i<NO_OF_BITS;i++)
ND_PRINT((ndo, "%-2d ", (tval >> i) & 0x01));
break;
case LLDP_PRIVATE_8021_SUBTYPE_APPLICATION_PRIORITY:
if(tlv_len<LLDP_PRIVATE_8021_SUBTYPE_APPLICATION_PRIORITY_MIN_LENGTH) {
return hexdump;
}
ND_PRINT((ndo, "\n\t RES: %d", *(tptr + 4)));
if(tlv_len<=LLDP_PRIVATE_8021_SUBTYPE_APPLICATION_PRIORITY_MIN_LENGTH){
return hexdump;
}
/* Length of Application Priority Table */
sublen=tlv_len-5;
if(sublen%3!=0){
return hexdump;
}
i=0;
ND_PRINT((ndo, "\n\t Application Priority Table"));
while(i<sublen) {
tval=*(tptr+i+5);
ND_PRINT((ndo, "\n\t Priority: %u, RES: %u, Sel: %u, Protocol ID: %u",
tval >> 5, (tval >> 3) & 0x03, (tval & 0x07),
EXTRACT_16BITS(tptr + i + 5)));
i=i+3;
}
break;
case LLDP_PRIVATE_8021_SUBTYPE_EVB:
if(tlv_len<LLDP_PRIVATE_8021_SUBTYPE_EVB_LENGTH){
return hexdump;
}
ND_PRINT((ndo, "\n\t EVB Bridge Status"));
tval=*(tptr+4);
ND_PRINT((ndo, "\n\t RES: %d, BGID: %d, RRCAP: %d, RRCTR: %d",
tval >> 3, (tval >> 2) & 0x01, (tval >> 1) & 0x01, tval & 0x01));
ND_PRINT((ndo, "\n\t EVB Station Status"));
tval=*(tptr+5);
ND_PRINT((ndo, "\n\t RES: %d, SGID: %d, RRREQ: %d,RRSTAT: %d",
tval >> 4, (tval >> 3) & 0x01, (tval >> 2) & 0x01, tval & 0x03));
tval=*(tptr+6);
ND_PRINT((ndo, "\n\t R: %d, RTE: %d, ",tval >> 5, tval & 0x1f));
tval=*(tptr+7);
ND_PRINT((ndo, "EVB Mode: %s [%d]",
tok2str(lldp_evb_mode_values, "unknown", tval >> 6), tval >> 6));
ND_PRINT((ndo, "\n\t ROL: %d, RWD: %d, ", (tval >> 5) & 0x01, tval & 0x1f));
tval=*(tptr+8);
ND_PRINT((ndo, "RES: %d, ROL: %d, RKA: %d", tval >> 6, (tval >> 5) & 0x01, tval & 0x1f));
break;
case LLDP_PRIVATE_8021_SUBTYPE_CDCP:
if(tlv_len<LLDP_PRIVATE_8021_SUBTYPE_CDCP_MIN_LENGTH){
return hexdump;
}
tval=*(tptr+4);
ND_PRINT((ndo, "\n\t Role: %d, RES: %d, Scomp: %d ",
tval >> 7, (tval >> 4) & 0x07, (tval >> 3) & 0x01));
ND_PRINT((ndo, "ChnCap: %d", EXTRACT_16BITS(tptr + 6) & 0x0fff));
sublen=tlv_len-8;
if(sublen%3!=0) {
return hexdump;
}
i=0;
while(i<sublen) {
tval=EXTRACT_24BITS(tptr+i+8);
ND_PRINT((ndo, "\n\t SCID: %d, SVID: %d",
tval >> 12, tval & 0x000fff));
i=i+3;
}
break;
default:
hexdump = TRUE;
break;
}
return hexdump;
}
/*
* Print IEEE 802.3 private extensions. (802.3bc)
*/
static int
lldp_private_8023_print(netdissect_options *ndo,
const u_char *tptr, u_int tlv_len)
{
int subtype, hexdump = FALSE;
if (tlv_len < 4) {
return hexdump;
}
subtype = *(tptr+3);
ND_PRINT((ndo, "\n\t %s Subtype (%u)",
tok2str(lldp_8023_subtype_values, "unknown", subtype),
subtype));
switch (subtype) {
case LLDP_PRIVATE_8023_SUBTYPE_MACPHY:
if (tlv_len < 9) {
return hexdump;
}
ND_PRINT((ndo, "\n\t autonegotiation [%s] (0x%02x)",
bittok2str(lldp_8023_autonegotiation_values, "none", *(tptr+4)),
*(tptr + 4)));
ND_PRINT((ndo, "\n\t PMD autoneg capability [%s] (0x%04x)",
bittok2str(lldp_pmd_capability_values,"unknown", EXTRACT_16BITS(tptr+5)),
EXTRACT_16BITS(tptr + 5)));
ND_PRINT((ndo, "\n\t MAU type %s (0x%04x)",
tok2str(lldp_mau_types_values, "unknown", EXTRACT_16BITS(tptr+7)),
EXTRACT_16BITS(tptr + 7)));
break;
case LLDP_PRIVATE_8023_SUBTYPE_MDIPOWER:
if (tlv_len < 7) {
return hexdump;
}
ND_PRINT((ndo, "\n\t MDI power support [%s], power pair %s, power class %s",
bittok2str(lldp_mdi_values, "none", *(tptr+4)),
tok2str(lldp_mdi_power_pairs_values, "unknown", *(tptr+5)),
tok2str(lldp_mdi_power_class_values, "unknown", *(tptr + 6))));
break;
case LLDP_PRIVATE_8023_SUBTYPE_LINKAGGR:
if (tlv_len < 9) {
return hexdump;
}
ND_PRINT((ndo, "\n\t aggregation status [%s], aggregation port ID %u",
bittok2str(lldp_aggregation_values, "none", *(tptr+4)),
EXTRACT_32BITS(tptr + 5)));
break;
case LLDP_PRIVATE_8023_SUBTYPE_MTU:
ND_PRINT((ndo, "\n\t MTU size %u", EXTRACT_16BITS(tptr + 4)));
break;
default:
hexdump = TRUE;
break;
}
return hexdump;
}
/*
* Extract 34bits of latitude/longitude coordinates.
*/
static uint64_t
lldp_extract_latlon(const u_char *tptr)
{
uint64_t latlon;
latlon = *tptr & 0x3;
latlon = (latlon << 32) | EXTRACT_32BITS(tptr+1);
return latlon;
}
/* objects defined in IANA subtype 00 00 5e
* (right now there is only one)
*/
static int
lldp_private_iana_print(netdissect_options *ndo,
const u_char *tptr, u_int tlv_len)
{
int subtype, hexdump = FALSE;
if (tlv_len < 8) {
return hexdump;
}
subtype = *(tptr+3);
ND_PRINT((ndo, "\n\t %s Subtype (%u)",
tok2str(lldp_iana_subtype_values, "unknown", subtype),
subtype));
switch (subtype) {
case LLDP_IANA_SUBTYPE_MUDURL:
ND_PRINT((ndo, "\n\t MUD-URL="));
(void)fn_printn(ndo, tptr+4, tlv_len-4, NULL);
break;
default:
hexdump=TRUE;
}
return hexdump;
}
/*
* Print private TIA extensions.
*/
static int
lldp_private_tia_print(netdissect_options *ndo,
const u_char *tptr, u_int tlv_len)
{
int subtype, hexdump = FALSE;
uint8_t location_format;
uint16_t power_val;
u_int lci_len;
uint8_t ca_type, ca_len;
if (tlv_len < 4) {
return hexdump;
}
subtype = *(tptr+3);
ND_PRINT((ndo, "\n\t %s Subtype (%u)",
tok2str(lldp_tia_subtype_values, "unknown", subtype),
subtype));
switch (subtype) {
case LLDP_PRIVATE_TIA_SUBTYPE_CAPABILITIES:
if (tlv_len < 7) {
return hexdump;
}
ND_PRINT((ndo, "\n\t Media capabilities [%s] (0x%04x)",
bittok2str(lldp_tia_capabilities_values, "none",
EXTRACT_16BITS(tptr + 4)), EXTRACT_16BITS(tptr + 4)));
ND_PRINT((ndo, "\n\t Device type [%s] (0x%02x)",
tok2str(lldp_tia_device_type_values, "unknown", *(tptr+6)),
*(tptr + 6)));
break;
case LLDP_PRIVATE_TIA_SUBTYPE_NETWORK_POLICY:
if (tlv_len < 8) {
return hexdump;
}
ND_PRINT((ndo, "\n\t Application type [%s] (0x%02x)",
tok2str(lldp_tia_application_type_values, "none", *(tptr+4)),
*(tptr + 4)));
ND_PRINT((ndo, ", Flags [%s]", bittok2str(
lldp_tia_network_policy_bits_values, "none", *(tptr + 5))));
ND_PRINT((ndo, "\n\t Vlan id %u",
LLDP_EXTRACT_NETWORK_POLICY_VLAN(EXTRACT_16BITS(tptr + 5))));
ND_PRINT((ndo, ", L2 priority %u",
LLDP_EXTRACT_NETWORK_POLICY_L2_PRIORITY(EXTRACT_16BITS(tptr + 6))));
ND_PRINT((ndo, ", DSCP value %u",
LLDP_EXTRACT_NETWORK_POLICY_DSCP(EXTRACT_16BITS(tptr + 6))));
break;
case LLDP_PRIVATE_TIA_SUBTYPE_LOCAL_ID:
if (tlv_len < 5) {
return hexdump;
}
location_format = *(tptr+4);
ND_PRINT((ndo, "\n\t Location data format %s (0x%02x)",
tok2str(lldp_tia_location_data_format_values, "unknown", location_format),
location_format));
switch (location_format) {
case LLDP_TIA_LOCATION_DATA_FORMAT_COORDINATE_BASED:
if (tlv_len < 21) {
return hexdump;
}
ND_PRINT((ndo, "\n\t Latitude resolution %u, latitude value %" PRIu64,
(*(tptr + 5) >> 2), lldp_extract_latlon(tptr + 5)));
ND_PRINT((ndo, "\n\t Longitude resolution %u, longitude value %" PRIu64,
(*(tptr + 10) >> 2), lldp_extract_latlon(tptr + 10)));
ND_PRINT((ndo, "\n\t Altitude type %s (%u)",
tok2str(lldp_tia_location_altitude_type_values, "unknown",(*(tptr+15)>>4)),
(*(tptr + 15) >> 4)));
ND_PRINT((ndo, "\n\t Altitude resolution %u, altitude value 0x%x",
(EXTRACT_16BITS(tptr+15)>>6)&0x3f,
((EXTRACT_32BITS(tptr + 16) & 0x3fffffff))));
ND_PRINT((ndo, "\n\t Datum %s (0x%02x)",
tok2str(lldp_tia_location_datum_type_values, "unknown", *(tptr+20)),
*(tptr + 20)));
break;
case LLDP_TIA_LOCATION_DATA_FORMAT_CIVIC_ADDRESS:
if (tlv_len < 6) {
return hexdump;
}
lci_len = *(tptr+5);
if (lci_len < 3) {
return hexdump;
}
if (tlv_len < 7+lci_len) {
return hexdump;
}
ND_PRINT((ndo, "\n\t LCI length %u, LCI what %s (0x%02x), Country-code ",
lci_len,
tok2str(lldp_tia_location_lci_what_values, "unknown", *(tptr+6)),
*(tptr + 6)));
/* Country code */
safeputs(ndo, tptr + 7, 2);
lci_len = lci_len-3;
tptr = tptr + 9;
/* Decode each civic address element */
while (lci_len > 0) {
if (lci_len < 2) {
return hexdump;
}
ca_type = *(tptr);
ca_len = *(tptr+1);
tptr += 2;
lci_len -= 2;
ND_PRINT((ndo, "\n\t CA type \'%s\' (%u), length %u: ",
tok2str(lldp_tia_location_lci_catype_values, "unknown", ca_type),
ca_type, ca_len));
/* basic sanity check */
if ( ca_type == 0 || ca_len == 0) {
return hexdump;
}
if (lci_len < ca_len) {
return hexdump;
}
safeputs(ndo, tptr, ca_len);
tptr += ca_len;
lci_len -= ca_len;
}
break;
case LLDP_TIA_LOCATION_DATA_FORMAT_ECS_ELIN:
ND_PRINT((ndo, "\n\t ECS ELIN id "));
safeputs(ndo, tptr + 5, tlv_len - 5);
break;
default:
ND_PRINT((ndo, "\n\t Location ID "));
print_unknown_data(ndo, tptr + 5, "\n\t ", tlv_len - 5);
}
break;
case LLDP_PRIVATE_TIA_SUBTYPE_EXTENDED_POWER_MDI:
if (tlv_len < 7) {
return hexdump;
}
ND_PRINT((ndo, "\n\t Power type [%s]",
(*(tptr + 4) & 0xC0 >> 6) ? "PD device" : "PSE device"));
ND_PRINT((ndo, ", Power source [%s]",
tok2str(lldp_tia_power_source_values, "none", (*(tptr + 4) & 0x30) >> 4)));
ND_PRINT((ndo, "\n\t Power priority [%s] (0x%02x)",
tok2str(lldp_tia_power_priority_values, "none", *(tptr+4)&0x0f),
*(tptr + 4) & 0x0f));
power_val = EXTRACT_16BITS(tptr+5);
if (power_val < LLDP_TIA_POWER_VAL_MAX) {
ND_PRINT((ndo, ", Power %.1f Watts", ((float)power_val) / 10));
} else {
ND_PRINT((ndo, ", Power %u (Reserved)", power_val));
}
break;
case LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_HARDWARE_REV:
case LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_FIRMWARE_REV:
case LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_SOFTWARE_REV:
case LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_SERIAL_NUMBER:
case LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_MANUFACTURER_NAME:
case LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_MODEL_NAME:
case LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_ASSET_ID:
ND_PRINT((ndo, "\n\t %s ",
tok2str(lldp_tia_inventory_values, "unknown", subtype)));
safeputs(ndo, tptr + 4, tlv_len - 4);
break;
default:
hexdump = TRUE;
break;
}
return hexdump;
}
/*
* Print DCBX Protocol fields (V 1.01).
*/
static int
lldp_private_dcbx_print(netdissect_options *ndo,
const u_char *pptr, u_int len)
{
int subtype, hexdump = FALSE;
uint8_t tval;
uint16_t tlv;
uint32_t i, pgval, uval;
u_int tlen, tlv_type, tlv_len;
const u_char *tptr, *mptr;
if (len < 4) {
return hexdump;
}
subtype = *(pptr+3);
ND_PRINT((ndo, "\n\t %s Subtype (%u)",
tok2str(lldp_dcbx_subtype_values, "unknown", subtype),
subtype));
/* by passing old version */
if (subtype == LLDP_DCBX_SUBTYPE_1)
return TRUE;
tptr = pptr + 4;
tlen = len - 4;
while (tlen >= sizeof(tlv)) {
ND_TCHECK2(*tptr, sizeof(tlv));
tlv = EXTRACT_16BITS(tptr);
tlv_type = LLDP_EXTRACT_TYPE(tlv);
tlv_len = LLDP_EXTRACT_LEN(tlv);
hexdump = FALSE;
tlen -= sizeof(tlv);
tptr += sizeof(tlv);
/* loop check */
if (!tlv_type || !tlv_len) {
break;
}
ND_TCHECK2(*tptr, tlv_len);
if (tlen < tlv_len) {
goto trunc;
}
/* decode every tlv */
switch (tlv_type) {
case LLDP_DCBX_CONTROL_TLV:
if (tlv_len < 10) {
goto trunc;
}
ND_PRINT((ndo, "\n\t Control - Protocol Control (type 0x%x, length %d)",
LLDP_DCBX_CONTROL_TLV, tlv_len));
ND_PRINT((ndo, "\n\t Oper_Version: %d", *tptr));
ND_PRINT((ndo, "\n\t Max_Version: %d", *(tptr + 1)));
ND_PRINT((ndo, "\n\t Sequence Number: %d", EXTRACT_32BITS(tptr + 2)));
ND_PRINT((ndo, "\n\t Acknowledgement Number: %d",
EXTRACT_32BITS(tptr + 6)));
break;
case LLDP_DCBX_PRIORITY_GROUPS_TLV:
if (tlv_len < 17) {
goto trunc;
}
ND_PRINT((ndo, "\n\t Feature - Priority Group (type 0x%x, length %d)",
LLDP_DCBX_PRIORITY_GROUPS_TLV, tlv_len));
ND_PRINT((ndo, "\n\t Oper_Version: %d", *tptr));
ND_PRINT((ndo, "\n\t Max_Version: %d", *(tptr + 1)));
ND_PRINT((ndo, "\n\t Info block(0x%02X): ", *(tptr + 2)));
tval = *(tptr+2);
ND_PRINT((ndo, "Enable bit: %d, Willing bit: %d, Error Bit: %d",
(tval & 0x80) ? 1 : 0, (tval & 0x40) ? 1 : 0,
(tval & 0x20) ? 1 : 0));
ND_PRINT((ndo, "\n\t SubType: %d", *(tptr + 3)));
ND_PRINT((ndo, "\n\t Priority Allocation"));
/*
* Array of 8 4-bit priority group ID values; we fetch all
* 32 bits and extract each nibble.
*/
pgval = EXTRACT_32BITS(tptr+4);
for (i = 0; i <= 7; i++) {
ND_PRINT((ndo, "\n\t PgId_%d: %d",
i, (pgval >> (28 - 4 * i)) & 0xF));
}
ND_PRINT((ndo, "\n\t Priority Group Allocation"));
for (i = 0; i <= 7; i++)
ND_PRINT((ndo, "\n\t Pg percentage[%d]: %d", i, *(tptr + 8 + i)));
ND_PRINT((ndo, "\n\t NumTCsSupported: %d", *(tptr + 8 + 8)));
break;
case LLDP_DCBX_PRIORITY_FLOW_CONTROL_TLV:
if (tlv_len < 6) {
goto trunc;
}
ND_PRINT((ndo, "\n\t Feature - Priority Flow Control"));
ND_PRINT((ndo, " (type 0x%x, length %d)",
LLDP_DCBX_PRIORITY_FLOW_CONTROL_TLV, tlv_len));
ND_PRINT((ndo, "\n\t Oper_Version: %d", *tptr));
ND_PRINT((ndo, "\n\t Max_Version: %d", *(tptr + 1)));
ND_PRINT((ndo, "\n\t Info block(0x%02X): ", *(tptr + 2)));
tval = *(tptr+2);
ND_PRINT((ndo, "Enable bit: %d, Willing bit: %d, Error Bit: %d",
(tval & 0x80) ? 1 : 0, (tval & 0x40) ? 1 : 0,
(tval & 0x20) ? 1 : 0));
ND_PRINT((ndo, "\n\t SubType: %d", *(tptr + 3)));
tval = *(tptr+4);
ND_PRINT((ndo, "\n\t PFC Config (0x%02X)", *(tptr + 4)));
for (i = 0; i <= 7; i++)
ND_PRINT((ndo, "\n\t Priority Bit %d: %s",
i, (tval & (1 << i)) ? "Enabled" : "Disabled"));
ND_PRINT((ndo, "\n\t NumTCPFCSupported: %d", *(tptr + 5)));
break;
case LLDP_DCBX_APPLICATION_TLV:
if (tlv_len < 4) {
goto trunc;
}
ND_PRINT((ndo, "\n\t Feature - Application (type 0x%x, length %d)",
LLDP_DCBX_APPLICATION_TLV, tlv_len));
ND_PRINT((ndo, "\n\t Oper_Version: %d", *tptr));
ND_PRINT((ndo, "\n\t Max_Version: %d", *(tptr + 1)));
ND_PRINT((ndo, "\n\t Info block(0x%02X): ", *(tptr + 2)));
tval = *(tptr+2);
ND_PRINT((ndo, "Enable bit: %d, Willing bit: %d, Error Bit: %d",
(tval & 0x80) ? 1 : 0, (tval & 0x40) ? 1 : 0,
(tval & 0x20) ? 1 : 0));
ND_PRINT((ndo, "\n\t SubType: %d", *(tptr + 3)));
tval = tlv_len - 4;
mptr = tptr + 4;
while (tval >= 6) {
ND_PRINT((ndo, "\n\t Application Value"));
ND_PRINT((ndo, "\n\t Application Protocol ID: 0x%04x",
EXTRACT_16BITS(mptr)));
uval = EXTRACT_24BITS(mptr+2);
ND_PRINT((ndo, "\n\t SF (0x%x) Application Protocol ID is %s",
(uval >> 22),
(uval >> 22) ? "Socket Number" : "L2 EtherType"));
ND_PRINT((ndo, "\n\t OUI: 0x%06x", uval & 0x3fffff));
ND_PRINT((ndo, "\n\t User Priority Map: 0x%02x", *(mptr + 5)));
tval = tval - 6;
mptr = mptr + 6;
}
break;
default:
hexdump = TRUE;
break;
}
/* do we also want to see a hex dump ? */
if (ndo->ndo_vflag > 1 || (ndo->ndo_vflag && hexdump)) {
print_unknown_data(ndo, tptr, "\n\t ", tlv_len);
}
tlen -= tlv_len;
tptr += tlv_len;
}
trunc:
return hexdump;
}
static char *
lldp_network_addr_print(netdissect_options *ndo, const u_char *tptr, u_int len)
{
uint8_t af;
static char buf[BUFSIZE];
const char * (*pfunc)(netdissect_options *, const u_char *);
if (len < 1)
return NULL;
len--;
af = *tptr;
switch (af) {
case AFNUM_INET:
if (len < 4)
return NULL;
/* This cannot be assigned to ipaddr_string(), which is a macro. */
pfunc = getname;
break;
case AFNUM_INET6:
if (len < 16)
return NULL;
/* This cannot be assigned to ip6addr_string(), which is a macro. */
pfunc = getname6;
break;
case AFNUM_802:
if (len < 6)
return NULL;
pfunc = etheraddr_string;
break;
default:
pfunc = NULL;
break;
}
if (!pfunc) {
snprintf(buf, sizeof(buf), "AFI %s (%u), no AF printer !",
tok2str(af_values, "Unknown", af), af);
} else {
snprintf(buf, sizeof(buf), "AFI %s (%u): %s",
tok2str(af_values, "Unknown", af), af, (*pfunc)(ndo, tptr+1));
}
return buf;
}
static int
lldp_mgmt_addr_tlv_print(netdissect_options *ndo,
const u_char *pptr, u_int len)
{
uint8_t mgmt_addr_len, intf_num_subtype, oid_len;
const u_char *tptr;
u_int tlen;
char *mgmt_addr;
tlen = len;
tptr = pptr;
if (tlen < 1) {
return 0;
}
mgmt_addr_len = *tptr++;
tlen--;
if (tlen < mgmt_addr_len) {
return 0;
}
mgmt_addr = lldp_network_addr_print(ndo, tptr, mgmt_addr_len);
if (mgmt_addr == NULL) {
return 0;
}
ND_PRINT((ndo, "\n\t Management Address length %u, %s",
mgmt_addr_len, mgmt_addr));
tptr += mgmt_addr_len;
tlen -= mgmt_addr_len;
if (tlen < LLDP_INTF_NUM_LEN) {
return 0;
}
intf_num_subtype = *tptr;
ND_PRINT((ndo, "\n\t %s Interface Numbering (%u): %u",
tok2str(lldp_intf_numb_subtype_values, "Unknown", intf_num_subtype),
intf_num_subtype,
EXTRACT_32BITS(tptr + 1)));
tptr += LLDP_INTF_NUM_LEN;
tlen -= LLDP_INTF_NUM_LEN;
/*
* The OID is optional.
*/
if (tlen) {
oid_len = *tptr;
if (tlen < 1U + oid_len) {
return 0;
}
if (oid_len) {
ND_PRINT((ndo, "\n\t OID length %u", oid_len));
safeputs(ndo, tptr + 1, oid_len);
}
}
return 1;
}
void
lldp_print(netdissect_options *ndo,
register const u_char *pptr, register u_int len)
{
uint8_t subtype;
uint16_t tlv, cap, ena_cap;
u_int oui, tlen, hexdump, tlv_type, tlv_len;
const u_char *tptr;
char *network_addr;
tptr = pptr;
tlen = len;
ND_PRINT((ndo, "LLDP, length %u", len));
while (tlen >= sizeof(tlv)) {
ND_TCHECK2(*tptr, sizeof(tlv));
tlv = EXTRACT_16BITS(tptr);
tlv_type = LLDP_EXTRACT_TYPE(tlv);
tlv_len = LLDP_EXTRACT_LEN(tlv);
hexdump = FALSE;
tlen -= sizeof(tlv);
tptr += sizeof(tlv);
if (ndo->ndo_vflag) {
ND_PRINT((ndo, "\n\t%s TLV (%u), length %u",
tok2str(lldp_tlv_values, "Unknown", tlv_type),
tlv_type, tlv_len));
}
/* infinite loop check */
if (!tlv_type || !tlv_len) {
break;
}
ND_TCHECK2(*tptr, tlv_len);
if (tlen < tlv_len) {
goto trunc;
}
switch (tlv_type) {
case LLDP_CHASSIS_ID_TLV:
if (ndo->ndo_vflag) {
if (tlv_len < 2) {
goto trunc;
}
subtype = *tptr;
ND_PRINT((ndo, "\n\t Subtype %s (%u): ",
tok2str(lldp_chassis_subtype_values, "Unknown", subtype),
subtype));
switch (subtype) {
case LLDP_CHASSIS_MAC_ADDR_SUBTYPE:
if (tlv_len < 1+6) {
goto trunc;
}
ND_PRINT((ndo, "%s", etheraddr_string(ndo, tptr + 1)));
break;
case LLDP_CHASSIS_INTF_NAME_SUBTYPE: /* fall through */
case LLDP_CHASSIS_LOCAL_SUBTYPE:
case LLDP_CHASSIS_CHASSIS_COMP_SUBTYPE:
case LLDP_CHASSIS_INTF_ALIAS_SUBTYPE:
case LLDP_CHASSIS_PORT_COMP_SUBTYPE:
safeputs(ndo, tptr + 1, tlv_len - 1);
break;
case LLDP_CHASSIS_NETWORK_ADDR_SUBTYPE:
network_addr = lldp_network_addr_print(ndo, tptr+1, tlv_len-1);
if (network_addr == NULL) {
goto trunc;
}
ND_PRINT((ndo, "%s", network_addr));
break;
default:
hexdump = TRUE;
break;
}
}
break;
case LLDP_PORT_ID_TLV:
if (ndo->ndo_vflag) {
if (tlv_len < 2) {
goto trunc;
}
subtype = *tptr;
ND_PRINT((ndo, "\n\t Subtype %s (%u): ",
tok2str(lldp_port_subtype_values, "Unknown", subtype),
subtype));
switch (subtype) {
case LLDP_PORT_MAC_ADDR_SUBTYPE:
if (tlv_len < 1+6) {
goto trunc;
}
ND_PRINT((ndo, "%s", etheraddr_string(ndo, tptr + 1)));
break;
case LLDP_PORT_INTF_NAME_SUBTYPE: /* fall through */
case LLDP_PORT_LOCAL_SUBTYPE:
case LLDP_PORT_AGENT_CIRC_ID_SUBTYPE:
case LLDP_PORT_INTF_ALIAS_SUBTYPE:
case LLDP_PORT_PORT_COMP_SUBTYPE:
safeputs(ndo, tptr + 1, tlv_len - 1);
break;
case LLDP_PORT_NETWORK_ADDR_SUBTYPE:
network_addr = lldp_network_addr_print(ndo, tptr+1, tlv_len-1);
if (network_addr == NULL) {
goto trunc;
}
ND_PRINT((ndo, "%s", network_addr));
break;
default:
hexdump = TRUE;
break;
}
}
break;
case LLDP_TTL_TLV:
if (ndo->ndo_vflag) {
if (tlv_len < 2) {
goto trunc;
}
ND_PRINT((ndo, ": TTL %us", EXTRACT_16BITS(tptr)));
}
break;
case LLDP_PORT_DESCR_TLV:
if (ndo->ndo_vflag) {
ND_PRINT((ndo, ": "));
safeputs(ndo, tptr, tlv_len);
}
break;
case LLDP_SYSTEM_NAME_TLV:
/*
* The system name is also print in non-verbose mode
* similar to the CDP printer.
*/
ND_PRINT((ndo, ": "));
safeputs(ndo, tptr, tlv_len);
break;
case LLDP_SYSTEM_DESCR_TLV:
if (ndo->ndo_vflag) {
ND_PRINT((ndo, "\n\t "));
safeputs(ndo, tptr, tlv_len);
}
break;
case LLDP_SYSTEM_CAP_TLV:
if (ndo->ndo_vflag) {
/*
* XXX - IEEE Std 802.1AB-2009 says the first octet
* if a chassis ID subtype, with the system
* capabilities and enabled capabilities following
* it.
*/
if (tlv_len < 4) {
goto trunc;
}
cap = EXTRACT_16BITS(tptr);
ena_cap = EXTRACT_16BITS(tptr+2);
ND_PRINT((ndo, "\n\t System Capabilities [%s] (0x%04x)",
bittok2str(lldp_cap_values, "none", cap), cap));
ND_PRINT((ndo, "\n\t Enabled Capabilities [%s] (0x%04x)",
bittok2str(lldp_cap_values, "none", ena_cap), ena_cap));
}
break;
case LLDP_MGMT_ADDR_TLV:
if (ndo->ndo_vflag) {
if (!lldp_mgmt_addr_tlv_print(ndo, tptr, tlv_len)) {
goto trunc;
}
}
break;
case LLDP_PRIVATE_TLV:
if (ndo->ndo_vflag) {
if (tlv_len < 3) {
goto trunc;
}
oui = EXTRACT_24BITS(tptr);
ND_PRINT((ndo, ": OUI %s (0x%06x)", tok2str(oui_values, "Unknown", oui), oui));
switch (oui) {
case OUI_IEEE_8021_PRIVATE:
hexdump = lldp_private_8021_print(ndo, tptr, tlv_len);
break;
case OUI_IEEE_8023_PRIVATE:
hexdump = lldp_private_8023_print(ndo, tptr, tlv_len);
break;
case OUI_IANA:
hexdump = lldp_private_iana_print(ndo, tptr, tlv_len);
break;
case OUI_TIA:
hexdump = lldp_private_tia_print(ndo, tptr, tlv_len);
break;
case OUI_DCBX:
hexdump = lldp_private_dcbx_print(ndo, tptr, tlv_len);
break;
default:
hexdump = TRUE;
break;
}
}
break;
default:
hexdump = TRUE;
break;
}
/* do we also want to see a hex dump ? */
if (ndo->ndo_vflag > 1 || (ndo->ndo_vflag && hexdump)) {
print_unknown_data(ndo, tptr, "\n\t ", tlv_len);
}
tlen -= tlv_len;
tptr += tlv_len;
}
return;
trunc:
ND_PRINT((ndo, "\n\t[|LLDP]"));
}
/*
* Local Variables:
* c-style: whitesmith
* c-basic-offset: 4
* End:
*/
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_2730_0 |
crossvul-cpp_data_good_4250_0 | /* State machine for IKEv1
*
* Copyright (C) 1997 Angelos D. Keromytis.
* Copyright (C) 1998-2010,2013-2016 D. Hugh Redelmeier <hugh@mimosa.com>
* Copyright (C) 2003-2008 Michael Richardson <mcr@xelerance.com>
* Copyright (C) 2008-2009 David McCullough <david_mccullough@securecomputing.com>
* Copyright (C) 2008-2010 Paul Wouters <paul@xelerance.com>
* Copyright (C) 2011 Avesh Agarwal <avagarwa@redhat.com>
* Copyright (C) 2008 Hiren Joshi <joshihirenn@gmail.com>
* Copyright (C) 2009 Anthony Tong <atong@TrustedCS.com>
* Copyright (C) 2012-2019 Paul Wouters <pwouters@redhat.com>
* Copyright (C) 2013 Wolfgang Nothdurft <wolfgang@linogate.de>
* Copyright (C) 2019-2019 Andrew Cagney <cagney@gnu.org>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version. See <https://www.gnu.org/licenses/gpl2.txt>.
*
* 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.
*
*/
/* Ordering Constraints on Payloads
*
* rfc2409: The Internet Key Exchange (IKE)
*
* 5 Exchanges:
* "The SA payload MUST precede all other payloads in a phase 1 exchange."
*
* "Except where otherwise noted, there are no requirements for ISAKMP
* payloads in any message to be in any particular order."
*
* 5.3 Phase 1 Authenticated With a Revised Mode of Public Key Encryption:
*
* "If the HASH payload is sent it MUST be the first payload of the
* second message exchange and MUST be followed by the encrypted
* nonce. If the HASH payload is not sent, the first payload of the
* second message exchange MUST be the encrypted nonce."
*
* "Save the requirements on the location of the optional HASH payload
* and the mandatory nonce payload there are no further payload
* requirements. All payloads-- in whatever order-- following the
* encrypted nonce MUST be encrypted with Ke_i or Ke_r depending on the
* direction."
*
* 5.5 Phase 2 - Quick Mode
*
* "In Quick Mode, a HASH payload MUST immediately follow the ISAKMP
* header and a SA payload MUST immediately follow the HASH."
* [NOTE: there may be more than one SA payload, so this is not
* totally reasonable. Probably all SAs should be so constrained.]
*
* "If ISAKMP is acting as a client negotiator on behalf of another
* party, the identities of the parties MUST be passed as IDci and
* then IDcr."
*
* "With the exception of the HASH, SA, and the optional ID payloads,
* there are no payload ordering restrictions on Quick Mode."
*/
/* Unfolding of Identity -- a central mystery
*
* This concerns Phase 1 identities, those of the IKE hosts.
* These are the only ones that are authenticated. Phase 2
* identities are for IPsec SAs.
*
* There are three case of interest:
*
* (1) We initiate, based on a whack command specifying a Connection.
* We know the identity of the peer from the Connection.
*
* (2) (to be implemented) we initiate based on a flow from our client
* to some IP address.
* We immediately know one of the peer's client IP addresses from
* the flow. We must use this to figure out the peer's IP address
* and Id. To be solved.
*
* (3) We respond to an IKE negotiation.
* We immediately know the peer's IP address.
* We get an ID Payload in Main I2.
*
* Unfortunately, this is too late for a number of things:
* - the ISAKMP SA proposals have already been made (Main I1)
* AND one accepted (Main R1)
* - the SA includes a specification of the type of ID
* authentication so this is negotiated without being told the ID.
* - with Preshared Key authentication, Main I2 is encrypted
* using the key, so it cannot be decoded to reveal the ID
* without knowing (or guessing) which key to use.
*
* There are three reasonable choices here for the responder:
* + assume that the initiator is making wise offers since it
* knows the IDs involved. We can balk later (but not gracefully)
* when we find the actual initiator ID
* + attempt to infer identity by IP address. Again, we can balk
* when the true identity is revealed. Actually, it is enough
* to infer properties of the identity (eg. SA properties and
* PSK, if needed).
* + make all properties universal so discrimination based on
* identity isn't required. For example, always accept the same
* kinds of encryption. Accept Public Key Id authentication
* since the Initiator presumably has our public key and thinks
* we must have / can find his. This approach is weakest
* for preshared key since the actual key must be known to
* decrypt the Initiator's ID Payload.
* These choices can be blended. For example, a class of Identities
* can be inferred, sufficient to select a preshared key but not
* sufficient to infer a unique identity.
*/
#include <stdio.h>
#include <stdlib.h>
#include <stddef.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "sysdep.h"
#include "constants.h"
#include "lswlog.h"
#include "defs.h"
#include "ike_spi.h"
#include "id.h"
#include "x509.h"
#include "pluto_x509.h"
#include "certs.h"
#include "connections.h" /* needs id.h */
#include "state.h"
#include "ikev1_msgid.h"
#include "packet.h"
#include "crypto.h"
#include "ike_alg.h"
#include "log.h"
#include "demux.h" /* needs packet.h */
#include "ikev1.h"
#include "ipsec_doi.h" /* needs demux.h and state.h */
#include "ikev1_quick.h"
#include "timer.h"
#include "whack.h" /* requires connections.h */
#include "server.h"
#include "send.h"
#include "ikev1_send.h"
#include "ikev1_xauth.h"
#include "retransmit.h"
#include "nat_traversal.h"
#include "vendor.h"
#include "ikev1_dpd.h"
#include "hostpair.h"
#include "ip_address.h"
#include "ikev1_hash.h"
#include "ike_alg_encrypt_ops.h" /* XXX: oops */
#include "ikev1_states.h"
#include "initiate.h"
#include "iface.h"
#include "ip_selector.h"
#ifdef HAVE_NM
#include "kernel.h"
#endif
#include "pluto_stats.h"
/*
* state_v1_microcode is a tuple of information parameterizing certain
* centralized processing of a packet. For example, it roughly
* specifies what payloads are expected in this message. The
* microcode is selected primarily based on the state. In Phase 1,
* the payload structure often depends on the authentication
* technique, so that too plays a part in selecting the
* state_v1_microcode to use.
*/
struct state_v1_microcode {
enum state_kind state, next_state;
lset_t flags;
lset_t req_payloads; /* required payloads (allows just one) */
lset_t opt_payloads; /* optional payloads (any mumber) */
enum event_type timeout_event;
ikev1_state_transition_fn *processor;
const char *message;
enum v1_hash_type hash_type;
};
void jam_v1_transition(jambuf_t *buf, const struct state_v1_microcode *transition)
{
if (transition == NULL) {
jam(buf, "NULL");
} else {
jam(buf, "%s->%s",
finite_states[transition->state]->short_name,
finite_states[transition->next_state]->short_name);
}
}
/* State Microcode Flags, in several groups */
/* Oakley Auth values: to which auth values does this entry apply?
* Most entries will use SMF_ALL_AUTH because they apply to all.
* Note: SMF_ALL_AUTH matches 0 for those circumstances when no auth
* has been set.
*
* The IKEv1 state machine then uses the auth type (SMF_*_AUTH flags)
* to select the exact state transition. For states where auth
* (SMF_*_AUTH flags) don't apply (.e.g, child states)
* flags|=SMF_ALL_AUTH so the first transition always matches.
*
* Once a transition is selected, the containing payloads are checked
* against what is allowed. For instance, in STATE_MAIN_R2 ->
* STATE_MAIN_R3 with SMF_DS_AUTH requires P(SIG).
*
* In IKEv2, it is the message header and payload types that select
* the state. As for how the IKEv1 'from state' is slected, look for
* a big nasty magic switch.
*
* XXX: the state transition table is littered with STATE_UNDEFINED /
* SMF_ALL_AUTH / unexpected() entries. These are to catch things
* like unimplemented auth cases, and unexpected packets. For the
* latter, they seem to be place holders so that the table contains at
* least one entry for the state.
*
* XXX: Some of the SMF flags specify attributes of the current state
* (e.g., SMF_RETRANSMIT_ON_DUPLICATE), some apply to the state
* transition (e.g., SMF_REPLY), and some can be interpreted as either
* (.e.g., SMF_INPUT_ENCRYPTED).
*/
#define SMF_ALL_AUTH LRANGE(0, OAKLEY_AUTH_ROOF - 1)
#define SMF_PSK_AUTH LELEM(OAKLEY_PRESHARED_KEY)
#define SMF_DS_AUTH (LELEM(OAKLEY_DSS_SIG) | LELEM(OAKLEY_RSA_SIG))
#define SMF_PKE_AUTH LELEM(OAKLEY_RSA_ENC)
#define SMF_RPKE_AUTH LELEM(OAKLEY_RSA_REVISED_MODE)
/* misc flags */
#define SMF_INITIATOR LELEM(OAKLEY_AUTH_ROOF + 0)
#define SMF_FIRST_ENCRYPTED_INPUT LELEM(OAKLEY_AUTH_ROOF + 1)
#define SMF_INPUT_ENCRYPTED LELEM(OAKLEY_AUTH_ROOF + 2)
#define SMF_OUTPUT_ENCRYPTED LELEM(OAKLEY_AUTH_ROOF + 3)
#define SMF_RETRANSMIT_ON_DUPLICATE LELEM(OAKLEY_AUTH_ROOF + 4)
#define SMF_ENCRYPTED (SMF_INPUT_ENCRYPTED | SMF_OUTPUT_ENCRYPTED)
/* this state generates a reply message */
#define SMF_REPLY LELEM(OAKLEY_AUTH_ROOF + 5)
/* this state completes P1, so any pending P2 negotiations should start */
#define SMF_RELEASE_PENDING_P2 LELEM(OAKLEY_AUTH_ROOF + 6)
/* if we have canoncalized the authentication from XAUTH mode */
#define SMF_XAUTH_AUTH LELEM(OAKLEY_AUTH_ROOF + 7)
/* end of flags */
static ikev1_state_transition_fn unexpected; /* forward declaration */
static ikev1_state_transition_fn informational; /* forward declaration */
/*
* v1_state_microcode_table is a table of all state_v1_microcode
* tuples. It must be in order of state (the first element). After
* initialization, ike_microcode_index[s] points to the first entry in
* v1_state_microcode_table for state s. Remember that each state
* name in Main or Quick Mode describes what has happened in the past,
* not what this message is.
*/
static const struct state_v1_microcode v1_state_microcode_table[] = {
#define P(n) LELEM(ISAKMP_NEXT_ ##n)
#define FM(F) .processor = F, .message = #F
/***** Phase 1 Main Mode *****/
/* No state for main_outI1: --> HDR, SA */
/* STATE_MAIN_R0: I1 --> R1
* HDR, SA --> HDR, SA
*/
{ STATE_MAIN_R0, STATE_MAIN_R1,
SMF_ALL_AUTH | SMF_REPLY,
P(SA), P(VID) | P(CR),
EVENT_SO_DISCARD,
FM(main_inI1_outR1),
.hash_type = V1_HASH_NONE, },
/* STATE_MAIN_I1: R1 --> I2
* HDR, SA --> auth dependent
* SMF_PSK_AUTH, SMF_DS_AUTH: --> HDR, KE, Ni
* SMF_PKE_AUTH:
* --> HDR, KE, [ HASH(1), ] <IDi1_b>PubKey_r, <Ni_b>PubKey_r
* SMF_RPKE_AUTH:
* --> HDR, [ HASH(1), ] <Ni_b>Pubkey_r, <KE_b>Ke_i, <IDi1_b>Ke_i [,<<Cert-I_b>Ke_i]
* Note: since we don't know auth at start, we cannot differentiate
* microcode entries based on it.
*/
{ STATE_MAIN_I1, STATE_MAIN_I2,
SMF_ALL_AUTH | SMF_INITIATOR | SMF_REPLY,
P(SA), P(VID) | P(CR),
EVENT_RETRANSMIT,
FM(main_inR1_outI2),
.hash_type = V1_HASH_NONE, },
/* STATE_MAIN_R1: I2 --> R2
* SMF_PSK_AUTH, SMF_DS_AUTH: HDR, KE, Ni --> HDR, KE, Nr
* SMF_PKE_AUTH: HDR, KE, [ HASH(1), ] <IDi1_b>PubKey_r, <Ni_b>PubKey_r
* --> HDR, KE, <IDr1_b>PubKey_i, <Nr_b>PubKey_i
* SMF_RPKE_AUTH:
* HDR, [ HASH(1), ] <Ni_b>Pubkey_r, <KE_b>Ke_i, <IDi1_b>Ke_i [,<<Cert-I_b>Ke_i]
* --> HDR, <Nr_b>PubKey_i, <KE_b>Ke_r, <IDr1_b>Ke_r
*/
{ STATE_MAIN_R1, STATE_MAIN_R2,
SMF_PSK_AUTH | SMF_DS_AUTH | SMF_REPLY | SMF_RETRANSMIT_ON_DUPLICATE,
P(KE) | P(NONCE), P(VID) | P(CR) | P(NATD_RFC),
EVENT_RETRANSMIT,
FM(main_inI2_outR2),
.hash_type = V1_HASH_NONE, },
{ STATE_MAIN_R1, STATE_UNDEFINED,
SMF_PKE_AUTH | SMF_REPLY | SMF_RETRANSMIT_ON_DUPLICATE,
P(KE) | P(ID) | P(NONCE), P(VID) | P(CR) | P(HASH),
EVENT_RETRANSMIT,
FM(unexpected) /* ??? not yet implemented */,
.hash_type = V1_HASH_NONE, },
{ STATE_MAIN_R1, STATE_UNDEFINED,
SMF_RPKE_AUTH | SMF_REPLY | SMF_RETRANSMIT_ON_DUPLICATE,
P(NONCE) | P(KE) | P(ID), P(VID) | P(CR) | P(HASH) | P(CERT),
EVENT_RETRANSMIT,
FM(unexpected) /* ??? not yet implemented */,
.hash_type = V1_HASH_NONE, },
/* for states from here on, output message must be encrypted */
/* STATE_MAIN_I2: R2 --> I3
* SMF_PSK_AUTH: HDR, KE, Nr --> HDR*, IDi1, HASH_I
* SMF_DS_AUTH: HDR, KE, Nr --> HDR*, IDi1, [ CERT, ] SIG_I
* SMF_PKE_AUTH: HDR, KE, <IDr1_b>PubKey_i, <Nr_b>PubKey_i
* --> HDR*, HASH_I
* SMF_RPKE_AUTH: HDR, <Nr_b>PubKey_i, <KE_b>Ke_r, <IDr1_b>Ke_r
* --> HDR*, HASH_I
*/
{ STATE_MAIN_I2, STATE_MAIN_I3,
SMF_PSK_AUTH | SMF_DS_AUTH | SMF_INITIATOR | SMF_OUTPUT_ENCRYPTED | SMF_REPLY,
P(KE) | P(NONCE), P(VID) | P(CR) | P(NATD_RFC),
EVENT_RETRANSMIT,
FM(main_inR2_outI3),
/* calls main_mode_hash() after DH */
.hash_type = V1_HASH_NONE, },
{ STATE_MAIN_I2, STATE_UNDEFINED,
SMF_PKE_AUTH | SMF_INITIATOR | SMF_OUTPUT_ENCRYPTED | SMF_REPLY,
P(KE) | P(ID) | P(NONCE), P(VID) | P(CR),
EVENT_RETRANSMIT,
FM(unexpected) /* ??? not yet implemented */,
.hash_type = V1_HASH_NONE, },
{ STATE_MAIN_I2, STATE_UNDEFINED,
SMF_ALL_AUTH | SMF_INITIATOR | SMF_OUTPUT_ENCRYPTED | SMF_REPLY,
P(NONCE) | P(KE) | P(ID), P(VID) | P(CR),
EVENT_RETRANSMIT,
FM(unexpected) /* ??? not yet implemented */,
.hash_type = V1_HASH_NONE, },
/* for states from here on, input message must be encrypted */
/* STATE_MAIN_R2: I3 --> R3
* SMF_PSK_AUTH: HDR*, IDi1, HASH_I --> HDR*, IDr1, HASH_R
* SMF_DS_AUTH: HDR*, IDi1, [ CERT, ] SIG_I --> HDR*, IDr1, [ CERT, ] SIG_R
* SMF_PKE_AUTH, SMF_RPKE_AUTH: HDR*, HASH_I --> HDR*, HASH_R
*/
{ STATE_MAIN_R2, STATE_MAIN_R3,
SMF_PSK_AUTH | SMF_FIRST_ENCRYPTED_INPUT | SMF_ENCRYPTED |
SMF_REPLY | SMF_RELEASE_PENDING_P2,
P(ID) | P(HASH), P(VID) | P(CR),
EVENT_SA_REPLACE,
FM(main_inI3_outR3),
/* calls oakley_id_and_auth() which calls main_mode_hash() */
/* RFC 2409: 5. Exchanges & 5.2 Phase 1 Authenticated With Public Key Encryption
HASH_I = prf(SKEYID, g^xi | g^xr | CKY-I | CKY-R | SAi_b | IDii_b ) */
.hash_type = V1_HASH_NONE, },
{ STATE_MAIN_R2, STATE_MAIN_R3,
SMF_DS_AUTH | SMF_FIRST_ENCRYPTED_INPUT | SMF_ENCRYPTED |
SMF_REPLY | SMF_RELEASE_PENDING_P2,
P(ID) | P(SIG), P(VID) | P(CR) | P(CERT),
EVENT_SA_REPLACE,
FM(main_inI3_outR3),
/* calls oakley_id_and_auth() which calls main_mode_hash() */
/* RFC 2409: 5. Exchanges & 5.1 IKE Phase 1 Authenticated With Signatures
HASH_I = prf(SKEYID, g^xi | g^xr | CKY-I | CKY-R | SAi_b | IDii_b )
SIG_I = SIGN(HASH_I) *",
SIG_I = SIGN(HASH_I) */
.hash_type = V1_HASH_NONE, },
{ STATE_MAIN_R2, STATE_UNDEFINED,
SMF_PKE_AUTH | SMF_RPKE_AUTH | SMF_FIRST_ENCRYPTED_INPUT |
SMF_ENCRYPTED |
SMF_REPLY | SMF_RELEASE_PENDING_P2,
P(HASH), P(VID) | P(CR),
EVENT_SA_REPLACE,
FM(unexpected) /* ??? not yet implemented */,
.hash_type = V1_HASH_NONE, },
/* STATE_MAIN_I3: R3 --> done
* SMF_PSK_AUTH: HDR*, IDr1, HASH_R --> done
* SMF_DS_AUTH: HDR*, IDr1, [ CERT, ] SIG_R --> done
* SMF_PKE_AUTH, SMF_RPKE_AUTH: HDR*, HASH_R --> done
* May initiate quick mode by calling quick_outI1
*/
{ STATE_MAIN_I3, STATE_MAIN_I4,
SMF_PSK_AUTH | SMF_INITIATOR |
SMF_FIRST_ENCRYPTED_INPUT | SMF_ENCRYPTED | SMF_RELEASE_PENDING_P2,
P(ID) | P(HASH), P(VID) | P(CR),
EVENT_SA_REPLACE,
FM(main_inR3),
/* calls oakley_id_and_auth() which calls main_mode_hash() */
/* RFC 2409: 5. Exchanges & 5.2 Phase 1 Authenticated With Public Key Encryption
HASH_R = prf(SKEYID, g^xr | g^xi | CKY-R | CKY-I | SAi_b | IDir_b ) */
.hash_type = V1_HASH_NONE, },
{ STATE_MAIN_I3, STATE_MAIN_I4,
SMF_DS_AUTH | SMF_INITIATOR |
SMF_FIRST_ENCRYPTED_INPUT | SMF_ENCRYPTED | SMF_RELEASE_PENDING_P2,
P(ID) | P(SIG), P(VID) | P(CR) | P(CERT),
EVENT_SA_REPLACE,
FM(main_inR3),
/* calls oakley_id_and_auth() which calls main_mode_hash() */
/* RFC 2409: 5. Exchanges & 5.1 IKE Phase 1 Authenticated With Signatures
HASH_R = prf(SKEYID, g^xr | g^xi | CKY-R | CKY-I | SAi_b | IDir_b )
SIG_R = SIGN(HASH_R) */
.hash_type = V1_HASH_NONE, },
{ STATE_MAIN_I3, STATE_UNDEFINED,
SMF_PKE_AUTH | SMF_RPKE_AUTH | SMF_INITIATOR |
SMF_FIRST_ENCRYPTED_INPUT | SMF_ENCRYPTED | SMF_RELEASE_PENDING_P2,
P(HASH), P(VID) | P(CR),
EVENT_SA_REPLACE,
FM(unexpected) /* ??? not yet implemented */,
.hash_type = V1_HASH_NONE, },
/* STATE_MAIN_R3: can only get here due to packet loss */
{ STATE_MAIN_R3, STATE_UNDEFINED,
SMF_ALL_AUTH | SMF_ENCRYPTED | SMF_RETRANSMIT_ON_DUPLICATE,
LEMPTY, LEMPTY,
EVENT_NULL,
FM(unexpected),
.hash_type = V1_HASH_NONE, },
/* STATE_MAIN_I4: can only get here due to packet loss */
{ STATE_MAIN_I4, STATE_UNDEFINED,
SMF_ALL_AUTH | SMF_INITIATOR | SMF_ENCRYPTED,
LEMPTY, LEMPTY,
EVENT_NULL,
FM(unexpected),
.hash_type = V1_HASH_NONE, },
/***** Phase 1 Aggressive Mode *****/
/* No initial state for aggr_outI1:
* SMF_DS_AUTH (RFC 2409 5.1) and SMF_PSK_AUTH (RFC 2409 5.4):
* -->HDR, SA, KE, Ni, IDii
*
* Not implemented:
* RFC 2409 5.2: --> HDR, SA, [ HASH(1),] KE, <IDii_b>Pubkey_r, <Ni_b>Pubkey_r
* RFC 2409 5.3: --> HDR, SA, [ HASH(1),] <Ni_b>Pubkey_r, <KE_b>Ke_i, <IDii_b>Ke_i [, <Cert-I_b>Ke_i ]
*/
/* STATE_AGGR_R0:
* SMF_PSK_AUTH: HDR, SA, KE, Ni, IDii
* --> HDR, SA, KE, Nr, IDir, HASH_R
* SMF_DS_AUTH: HDR, SA, KE, Nr, IDii
* --> HDR, SA, KE, Nr, IDir, [CERT,] SIG_R
*/
{ STATE_AGGR_R0, STATE_AGGR_R1,
SMF_PSK_AUTH | SMF_DS_AUTH | SMF_REPLY,
P(SA) | P(KE) | P(NONCE) | P(ID), P(VID) | P(NATD_RFC),
EVENT_SO_DISCARD,
FM(aggr_inI1_outR1),
/* N/A */
.hash_type = V1_HASH_NONE, },
/* STATE_AGGR_I1:
* SMF_PSK_AUTH: HDR, SA, KE, Nr, IDir, HASH_R
* --> HDR*, HASH_I
* SMF_DS_AUTH: HDR, SA, KE, Nr, IDir, [CERT,] SIG_R
* --> HDR*, [CERT,] SIG_I
*/
{ STATE_AGGR_I1, STATE_AGGR_I2,
SMF_PSK_AUTH | SMF_INITIATOR | SMF_OUTPUT_ENCRYPTED | SMF_REPLY |
SMF_RELEASE_PENDING_P2,
P(SA) | P(KE) | P(NONCE) | P(ID) | P(HASH), P(VID) | P(NATD_RFC),
EVENT_SA_REPLACE,
FM(aggr_inR1_outI2),
/* after DH calls oakley_id_and_auth() which calls main_mode_hash() */
/* RFC 2409: 5. Exchanges & 5.2 Phase 1 Authenticated With Public Key Encryption
HASH_R = prf(SKEYID, g^xr | g^xi | CKY-R | CKY-I | SAi_b | IDir_b ) */
.hash_type = V1_HASH_NONE, },
{ STATE_AGGR_I1, STATE_AGGR_I2,
SMF_DS_AUTH | SMF_INITIATOR | SMF_OUTPUT_ENCRYPTED | SMF_REPLY |
SMF_RELEASE_PENDING_P2,
P(SA) | P(KE) | P(NONCE) | P(ID) | P(SIG), P(VID) | P(NATD_RFC),
EVENT_SA_REPLACE,
FM(aggr_inR1_outI2),
/* after DH calls oakley_id_and_auth() which calls main_mode_hash() */
/* RFC 2409: 5. Exchanges & 5.1 IKE Phase 1 Authenticated With Signatures
HASH_R = prf(SKEYID, g^xr | g^xi | CKY-R | CKY-I | SAi_b | IDir_b )
SIG_R = SIGN(HASH_R) */
.hash_type = V1_HASH_NONE, },
/* STATE_AGGR_R1:
* SMF_PSK_AUTH: HDR*, HASH_I --> done
* SMF_DS_AUTH: HDR*, SIG_I --> done
*/
{ STATE_AGGR_R1, STATE_AGGR_R2,
SMF_PSK_AUTH | SMF_FIRST_ENCRYPTED_INPUT |
SMF_OUTPUT_ENCRYPTED | SMF_RELEASE_PENDING_P2 |
SMF_RETRANSMIT_ON_DUPLICATE,
P(HASH), P(VID) | P(NATD_RFC),
EVENT_SA_REPLACE,
FM(aggr_inI2),
/* calls oakley_id_and_auth() which calls main_mode_hash() */
/* RFC 2409: 5. Exchanges & 5.2 Phase 1 Authenticated With Public Key Encryption
HASH_I = prf(SKEYID, g^xi | g^xr | CKY-I | CKY-R | SAi_b | IDii_b ) */
.hash_type = V1_HASH_NONE, },
{ STATE_AGGR_R1, STATE_AGGR_R2,
SMF_DS_AUTH | SMF_FIRST_ENCRYPTED_INPUT |
SMF_OUTPUT_ENCRYPTED | SMF_RELEASE_PENDING_P2 |
SMF_RETRANSMIT_ON_DUPLICATE,
P(SIG), P(VID) | P(NATD_RFC),
EVENT_SA_REPLACE,
FM(aggr_inI2),
/* calls oakley_id_and_auth() which calls main_mode_hash() */
/* RFC 2409: 5. Exchanges & 5.1 IKE Phase 1 Authenticated With Signatures
HASH_I = prf(SKEYID, g^xi | g^xr | CKY-I | CKY-R | SAi_b | IDii_b )
SIG_I = SIGN(HASH_I) */
.hash_type = V1_HASH_NONE, },
/* STATE_AGGR_I2: can only get here due to packet loss */
{ STATE_AGGR_I2, STATE_UNDEFINED,
SMF_ALL_AUTH | SMF_INITIATOR | SMF_RETRANSMIT_ON_DUPLICATE,
LEMPTY, LEMPTY, EVENT_NULL,
FM(unexpected),
.hash_type = V1_HASH_NONE, },
/* STATE_AGGR_R2: can only get here due to packet loss */
{ STATE_AGGR_R2, STATE_UNDEFINED,
SMF_ALL_AUTH,
LEMPTY, LEMPTY, EVENT_NULL,
FM(unexpected),
.hash_type = V1_HASH_NONE, },
/***** Phase 2 Quick Mode *****/
/* No state for quick_outI1:
* --> HDR*, HASH(1), SA, Nr [, KE ] [, IDci, IDcr ]
*/
/* STATE_QUICK_R0:
* HDR*, HASH(1), SA, Ni [, KE ] [, IDci, IDcr ] -->
* HDR*, HASH(2), SA, Nr [, KE ] [, IDci, IDcr ]
* Installs inbound IPsec SAs.
* Because it may suspend for asynchronous DNS, first_out_payload
* is set to NONE to suppress early emission of HDR*.
* ??? it is legal to have multiple SAs, but we don't support it yet.
*/
{ STATE_QUICK_R0, STATE_QUICK_R1,
SMF_ALL_AUTH | SMF_ENCRYPTED | SMF_REPLY,
P(HASH) | P(SA) | P(NONCE), /* P(SA) | */ P(KE) | P(ID) | P(NATOA_RFC),
EVENT_RETRANSMIT,
FM(quick_inI1_outR1),
/* RFC 2409: 5.5 Phase 2 - Quick Mode:
HASH(1) = prf(SKEYID_a, M-ID | <rest>) */
.hash_type = V1_HASH_1, },
/* STATE_QUICK_I1:
* HDR*, HASH(2), SA, Nr [, KE ] [, IDci, IDcr ] -->
* HDR*, HASH(3)
* Installs inbound and outbound IPsec SAs, routing, etc.
* ??? it is legal to have multiple SAs, but we don't support it yet.
*/
{ STATE_QUICK_I1, STATE_QUICK_I2,
SMF_ALL_AUTH | SMF_INITIATOR | SMF_ENCRYPTED | SMF_REPLY,
P(HASH) | P(SA) | P(NONCE), /* P(SA) | */ P(KE) | P(ID) | P(NATOA_RFC),
EVENT_SA_REPLACE,
FM(quick_inR1_outI2),
/* RFC 2409: 5.5 Phase 2 - Quick Mode:
HASH(2) = prf(SKEYID_a, M-ID | Ni_b | <rest>) */
.hash_type = V1_HASH_2, },
/* STATE_QUICK_R1: HDR*, HASH(3) --> done
* Installs outbound IPsec SAs, routing, etc.
*/
{ STATE_QUICK_R1, STATE_QUICK_R2,
SMF_ALL_AUTH | SMF_ENCRYPTED,
P(HASH), LEMPTY,
EVENT_SA_REPLACE,
FM(quick_inI2),
/* RFC 2409: 5.5 Phase 2 - Quick Mode:
HASH(3) = prf(SKEYID_a, 0 | M-ID | Ni_b | Nr_b) */
.hash_type = V1_HASH_3, },
/* STATE_QUICK_I2: can only happen due to lost packet */
{ STATE_QUICK_I2, STATE_UNDEFINED,
SMF_ALL_AUTH | SMF_INITIATOR | SMF_ENCRYPTED |
SMF_RETRANSMIT_ON_DUPLICATE,
LEMPTY, LEMPTY,
EVENT_NULL,
FM(unexpected),
.hash_type = V1_HASH_NONE, },
/* STATE_QUICK_R2: can only happen due to lost packet */
{ STATE_QUICK_R2, STATE_UNDEFINED,
SMF_ALL_AUTH | SMF_ENCRYPTED,
LEMPTY, LEMPTY,
EVENT_NULL,
FM(unexpected),
.hash_type = V1_HASH_NONE, },
/***** informational messages *****/
/* Informational Exchange (RFC 2408 4.8):
* HDR N/D
* Unencrypted: must not occur after ISAKMP Phase 1 exchange of keying material.
*/
/* STATE_INFO: */
{ STATE_INFO, STATE_UNDEFINED,
SMF_ALL_AUTH,
LEMPTY, LEMPTY,
EVENT_NULL,
FM(informational),
.hash_type = V1_HASH_NONE, },
/* Informational Exchange (RFC 2408 4.8):
* HDR* N/D
*/
/* STATE_INFO_PROTECTED: */
{ STATE_INFO_PROTECTED, STATE_UNDEFINED,
SMF_ALL_AUTH | SMF_ENCRYPTED,
P(HASH), LEMPTY,
EVENT_NULL,
FM(informational),
/* RFC 2409: 5.7 ISAKMP Informational Exchanges:
HASH(1) = prf(SKEYID_a, M-ID | N/D) */
.hash_type = V1_HASH_1, },
{ STATE_XAUTH_R0, STATE_XAUTH_R1,
SMF_ALL_AUTH | SMF_ENCRYPTED,
P(MCFG_ATTR) | P(HASH), P(VID),
EVENT_NULL,
FM(xauth_inR0),
/* RFC ????: */
.hash_type = V1_HASH_1, }, /* Re-transmit may be done by previous state */
{ STATE_XAUTH_R1, STATE_MAIN_R3,
SMF_ALL_AUTH | SMF_ENCRYPTED,
P(MCFG_ATTR) | P(HASH), P(VID),
EVENT_SA_REPLACE,
FM(xauth_inR1),
/* RFC ????: */
.hash_type = V1_HASH_1, },
#if 0
/* for situation where there is XAUTH + ModeCFG */
{ STATE_XAUTH_R2, STATE_XAUTH_R3,
SMF_ALL_AUTH | SMF_ENCRYPTED,
P(MCFG_ATTR) | P(HASH), P(VID),
EVENT_SA_REPLACE,
FM(xauth_inR2), },
{ STATE_XAUTH_R3, STATE_MAIN_R3,
SMF_ALL_AUTH | SMF_ENCRYPTED,
P(MCFG_ATTR) | P(HASH), P(VID),
EVENT_SA_REPLACE,
FM(xauth_inR3), },
#endif
/* MODE_CFG_x:
* Case R0: Responder -> Initiator
* <- Req(addr=0)
* Reply(ad=x) ->
*
* Case R1: Set(addr=x) ->
* <- Ack(ok)
*/
{ STATE_MODE_CFG_R0, STATE_MODE_CFG_R1,
SMF_ALL_AUTH | SMF_ENCRYPTED | SMF_REPLY,
P(MCFG_ATTR) | P(HASH), P(VID),
EVENT_SA_REPLACE,
FM(modecfg_inR0),
/* RFC ????: */
.hash_type = V1_HASH_1, },
{ STATE_MODE_CFG_R1, STATE_MODE_CFG_R2,
SMF_ALL_AUTH | SMF_ENCRYPTED,
P(MCFG_ATTR) | P(HASH), P(VID),
EVENT_SA_REPLACE,
FM(modecfg_inR1),
/* RFC ????: */
.hash_type = V1_HASH_1, },
{ STATE_MODE_CFG_R2, STATE_UNDEFINED,
SMF_ALL_AUTH | SMF_ENCRYPTED,
LEMPTY, LEMPTY,
EVENT_NULL,
FM(unexpected),
.hash_type = V1_HASH_NONE, },
{ STATE_MODE_CFG_I1, STATE_MAIN_I4,
SMF_ALL_AUTH | SMF_ENCRYPTED | SMF_RELEASE_PENDING_P2,
P(MCFG_ATTR) | P(HASH), P(VID),
EVENT_SA_REPLACE,
FM(modecfg_inR1),
/* RFC ????: */
.hash_type = V1_HASH_1, },
{ STATE_XAUTH_I0, STATE_XAUTH_I1,
SMF_ALL_AUTH | SMF_ENCRYPTED | SMF_REPLY | SMF_RELEASE_PENDING_P2,
P(MCFG_ATTR) | P(HASH), P(VID),
EVENT_RETRANSMIT,
FM(xauth_inI0),
/* RFC ????: */
.hash_type = V1_HASH_1, },
{ STATE_XAUTH_I1, STATE_MAIN_I4,
SMF_ALL_AUTH | SMF_ENCRYPTED | SMF_REPLY | SMF_RELEASE_PENDING_P2,
P(MCFG_ATTR) | P(HASH), P(VID),
EVENT_RETRANSMIT,
FM(xauth_inI1),
/* RFC ????: */
.hash_type = V1_HASH_1, },
{ STATE_IKEv1_ROOF, STATE_IKEv1_ROOF,
LEMPTY,
LEMPTY, LEMPTY,
EVENT_NULL, NULL,
.hash_type = V1_HASH_NONE, },
#undef FM
#undef P
};
void init_ikev1(void)
{
DBGF(DBG_CONTROL, "checking IKEv1 state table");
/*
* Fill in FINITE_STATES[].
*
* This is a hack until each finite-state is a separate object
* with corresponding edges (aka microcodes).
*
* XXX: Long term goal is to have a constant FINITE_STATES[]
* contain constant pointers and this static writeable array
* to just go away.
*/
for (enum state_kind kind = STATE_IKEv1_FLOOR; kind < STATE_IKEv1_ROOF; kind++) {
/* fill in using static struct */
const struct finite_state *fs = &v1_states[kind - STATE_IKEv1_FLOOR];
passert(fs->kind == kind);
passert(finite_states[kind] == NULL);
finite_states[kind] = fs;
}
/*
* Go through the state transition table filling in details
* and checking for inconsistencies.
*/
for (const struct state_v1_microcode *t = v1_state_microcode_table;
t->state < STATE_IKEv1_ROOF; t++) {
passert(t->state >= STATE_IKEv1_FLOOR);
passert(t->state < STATE_IKEv1_ROOF);
struct finite_state *from = &v1_states[t->state - STATE_IKEv1_FLOOR];
/*
* Deal with next_state == STATE_UNDEFINED.
*
* XXX: STATE_UNDEFINED is used when a state
* transitions back to the same state; such
* transitions should instead explicitly specify that
* same state.
*/
enum state_kind next_state = (t->next_state == STATE_UNDEFINED ?
t->state : t->next_state);
passert(STATE_IKEv1_FLOOR <= next_state &&
next_state < STATE_IKEv1_ROOF);
const struct finite_state *to = finite_states[next_state];
passert(to != NULL);
if (DBGP(DBG_BASE)) {
if (from->nr_transitions == 0) {
LSWLOG_DEBUG(buf) {
lswlogs(buf, " ");
lswlog_finite_state(buf, from);
lswlogs(buf, ":");
}
}
DBG_log(" -> %s %s (%s)", to->short_name,
enum_short_name(&timer_event_names,
t->timeout_event),
t->message);
}
/*
* Point .fs_v1_transitions at to the first entry in
* v1_state_microcode_table for that state. All other
* transitions for that state should follow
* immediately after (or to put it another way, the
* previous transition's state should be the same as
* this).
*/
if (from->v1_transitions == NULL) {
from->v1_transitions = t;
} else {
passert(t[-1].state == t->state);
}
from->nr_transitions++;
if (t->message == NULL) {
PEXPECT_LOG("transition %s -> %s missing .message",
from->short_name, to->short_name);
}
/*
* Copy (actually merge) the flags that apply to the
* state; and not the state transition.
*
* The original code used something like state
* .microcode .flags after the state transition had
* completed. I.e., use the flags from a
* not-yet-taken potential future state transition and
* not the previous one.
*
* This is just trying to extact extract them and
* check they are consistent.
*
* XXX: this is confusing
*
* Should fs_flags and SMF_RETRANSMIT_ON_DUPLICATE
* should be replaced by SMF_RESPONDING in the
* transition flags?
*
* Or is this more like .fs_timeout_event which is
* always true of a state?
*/
if ((t->flags & from->flags) != from->flags) {
DBGF(DBG_BASE, "transition %s -> %s (%s) missing flags 0x%"PRIxLSET,
from->short_name, to->short_name,
t->message, from->flags);
}
from->flags |= t->flags & SMF_RETRANSMIT_ON_DUPLICATE;
if (!(t->flags & SMF_FIRST_ENCRYPTED_INPUT) &&
(t->flags & SMF_INPUT_ENCRYPTED) &&
t->processor != unexpected) {
/*
* The first encrypted message carries
* authentication information so isn't
* applicable. Other encrypted messages
* require integrity via the HASH payload.
*/
if (!(t->req_payloads & LELEM(ISAKMP_NEXT_HASH))) {
PEXPECT_LOG("transition %s -> %s (%s) missing HASH payload",
from->short_name, to->short_name,
t->message);
}
if (t->hash_type == V1_HASH_NONE) {
PEXPECT_LOG("transition %s -> %s (%s) missing HASH protection",
from->short_name, to->short_name,
t->message);
}
}
}
}
static stf_status unexpected(struct state *st, struct msg_digest *md UNUSED)
{
loglog(RC_LOG_SERIOUS, "unexpected message received in state %s",
st->st_state->name);
return STF_IGNORE;
}
/*
* RFC 2408 Section 4.6
*
* # Initiator Direction Responder NOTE
* (1) HDR*; N/D => Error Notification or Deletion
*/
static stf_status informational(struct state *st, struct msg_digest *md)
{
/*
* XXX: Danger: ST is deleted midway through this function.
*/
pexpect(st == md->st);
st = md->st; /* may be NULL */
struct payload_digest *const n_pld = md->chain[ISAKMP_NEXT_N];
/* If the Notification Payload is not null... */
if (n_pld != NULL) {
pb_stream *const n_pbs = &n_pld->pbs;
struct isakmp_notification *const n =
&n_pld->payload.notification;
/* Switch on Notification Type (enum) */
/* note that we _can_ get notification payloads unencrypted
* once we are at least in R3/I4.
* and that the handler is expected to treat them suspiciously.
*/
dbg("processing informational %s (%d)",
enum_name(&ikev1_notify_names, n->isan_type),
n->isan_type);
pstats(ikev1_recv_notifies_e, n->isan_type);
switch (n->isan_type) {
/*
* We answer DPD probes even if they claimed not to support
* Dead Peer Detection.
* We would have to send some kind of reply anyway to prevent
* a retransmit, so rather then send an error, we might as
* well just send a DPD reply
*/
case R_U_THERE:
if (st == NULL) {
plog_md(md, "received bogus R_U_THERE informational message");
return STF_IGNORE;
}
return dpd_inI_outR(st, n, n_pbs);
case R_U_THERE_ACK:
if (st == NULL) {
plog_md(md, "received bogus R_U_THERE_ACK informational message");
return STF_IGNORE;
}
return dpd_inR(st, n, n_pbs);
case PAYLOAD_MALFORMED:
if (st != NULL) {
st->hidden_variables.st_malformed_received++;
log_state(RC_LOG, st, "received %u malformed payload notifies",
st->hidden_variables.st_malformed_received);
if (st->hidden_variables.st_malformed_sent >
MAXIMUM_MALFORMED_NOTIFY / 2 &&
((st->hidden_variables.st_malformed_sent +
st->hidden_variables.
st_malformed_received) >
MAXIMUM_MALFORMED_NOTIFY)) {
log_state(RC_LOG, st, "too many malformed payloads (we sent %u and received %u",
st->hidden_variables.st_malformed_sent,
st->hidden_variables.st_malformed_received);
delete_state(st);
md->st = st = NULL;
}
}
return STF_IGNORE;
case ISAKMP_N_CISCO_LOAD_BALANCE:
/*
* ??? what the heck is in the payload?
* We take the peer's new IP address from the last 4 octets.
* Is anything else possible? Expected? Documented?
*/
if (st == NULL || !IS_ISAKMP_SA_ESTABLISHED(st->st_state)) {
plog_md(md, "ignoring ISAKMP_N_CISCO_LOAD_BALANCE Informational Message with for unestablished state.");
} else if (pbs_left(n_pbs) < 4) {
log_state(RC_LOG_SERIOUS, st,
"ignoring ISAKMP_N_CISCO_LOAD_BALANCE Informational Message without IPv4 address");
} else {
/*
* Copy (not cast) the last 4 bytes
* (size of an IPv4) address from the
* end of the notification into IN
* (can't cast as can't assume that
* ->roof-4 is correctly aligned).
*/
struct in_addr in;
memcpy(&in, n_pbs->roof - sizeof(in), sizeof(in));
ip_address new_peer = address_from_in_addr(&in);
/* is all zeros? */
if (address_is_any(&new_peer)) {
ipstr_buf b;
log_state(RC_LOG_SERIOUS, st,
"ignoring ISAKMP_N_CISCO_LOAD_BALANCE Informational Message with invalid IPv4 address %s",
ipstr(&new_peer, &b));
return FALSE; /* XXX: STF_*? */
}
/* Saving connection name and whack sock id */
const char *tmp_name = st->st_connection->name;
struct fd *tmp_whack_sock = dup_any(st->st_whack_sock);
/* deleting ISAKMP SA with the current remote peer */
delete_state(st);
md->st = st = NULL;
/* to find and store the connection associated with tmp_name */
/* ??? how do we know that tmp_name hasn't been freed? */
struct connection *tmp_c = conn_by_name(tmp_name, false/*!strict*/);
if (DBGP(DBG_BASE)) {
address_buf npb;
DBG_log("new peer address: %s",
str_address(&new_peer, &npb));
/* Current remote peer info */
int count_spd = 1;
for (const struct spd_route *tmp_spd = &tmp_c->spd;
tmp_spd != NULL; tmp_spd = tmp_spd->spd_next) {
address_buf b;
endpoint_buf e;
DBG_log("spd route number: %d",
count_spd++);
/**that info**/
DBG_log("that id kind: %d",
tmp_spd->that.id.kind);
DBG_log("that id ipaddr: %s",
str_address(&tmp_spd->that.id.ip_addr, &b));
if (tmp_spd->that.id.name.ptr != NULL) {
DBG_dump_hunk("that id name",
tmp_spd->that.id. name);
}
DBG_log("that host_addr: %s",
str_endpoint(&tmp_spd->that.host_addr, &e));
DBG_log("that nexthop: %s",
str_address(&tmp_spd->that.host_nexthop, &b));
DBG_log("that srcip: %s",
str_address(&tmp_spd->that.host_srcip, &b));
selector_buf sb;
DBG_log("that client: %s",
str_selector(&tmp_spd->that.client, &sb));
DBG_log("that has_client: %d",
tmp_spd->that.has_client);
DBG_log("that has_client_wildcard: %d",
tmp_spd->that.has_client_wildcard);
DBG_log("that has_port_wildcard: %d",
tmp_spd->that.has_port_wildcard);
DBG_log("that has_id_wildcards: %d",
tmp_spd->that.has_id_wildcards);
}
if (tmp_c->interface != NULL) {
endpoint_buf b;
DBG_log("Current interface_addr: %s",
str_endpoint(&tmp_c->interface->local_endpoint, &b));
}
}
/* save peer's old address for comparison purposes */
ip_address old_addr = tmp_c->spd.that.host_addr;
/* update peer's address */
tmp_c->spd.that.host_addr = new_peer;
/* Modifying connection info to store the redirected remote peer info */
dbg("Old host_addr_name : %s", tmp_c->spd.that.host_addr_name);
tmp_c->spd.that.host_addr_name = NULL;
/* ??? do we know the id.kind has an ip_addr? */
tmp_c->spd.that.id.ip_addr = new_peer;
/* update things that were the old peer */
ipstr_buf b;
if (sameaddr(&tmp_c->spd.this.host_nexthop,
&old_addr)) {
if (DBGP(DBG_BASE)) {
DBG_log("this host's next hop %s was the same as the old remote addr",
ipstr(&old_addr, &b));
DBG_log("changing this host's next hop to %s",
ipstr(&new_peer, &b));
}
tmp_c->spd.this.host_nexthop = new_peer;
}
if (sameaddr(&tmp_c->spd.that.host_srcip,
&old_addr)) {
if (DBGP(DBG_BASE)) {
DBG_log("Old that host's srcip %s was the same as the old remote addr",
ipstr(&old_addr, &b));
DBG_log("changing that host's srcip to %s",
ipstr(&new_peer, &b));
}
tmp_c->spd.that.host_srcip = new_peer;
}
if (sameaddr(&tmp_c->spd.that.client.addr,
&old_addr)) {
if (DBGP(DBG_BASE)) {
DBG_log("Old that client ip %s was the same as the old remote address",
ipstr(&old_addr, &b));
DBG_log("changing that client's ip to %s",
ipstr(&new_peer, &b));
}
tmp_c->spd.that.client.addr = new_peer;
}
/*
* ??? is this wise? This may changes
* a lot of other connections.
*
* XXX:
*
* As for the old code, preserve the
* existing port. NEW_PEER, an
* address, doesn't have a port and
* presumably the port wasn't
* updated(?).
*/
tmp_c->host_pair->remote = endpoint(&new_peer,
endpoint_hport(&tmp_c->host_pair->remote));
/* Initiating connection to the redirected peer */
initiate_connections_by_name(tmp_name, NULL,
tmp_whack_sock,
tmp_whack_sock == NULL/*guess*/);
close_any(&tmp_whack_sock);
}
return STF_IGNORE;
default:
{
struct logger logger = st != NULL ? *(st->st_logger) : MESSAGE_LOGGER(md);
log_message(RC_LOG_SERIOUS, &logger,
"received and ignored notification payload: %s",
enum_name(&ikev1_notify_names, n->isan_type));
return STF_IGNORE;
}
}
} else {
/* warn if we didn't find any Delete or Notify payload in packet */
if (md->chain[ISAKMP_NEXT_D] == NULL) {
struct logger logger = st != NULL ? *(st->st_logger) : MESSAGE_LOGGER(md);
log_message(RC_LOG_SERIOUS, &logger,
"received and ignored empty informational notification payload");
}
return STF_IGNORE;
}
}
/*
* create output HDR as replica of input HDR - IKEv1 only; return the body
*/
void ikev1_init_out_pbs_echo_hdr(struct msg_digest *md, bool enc,
pb_stream *output_stream, uint8_t *output_buffer,
size_t sizeof_output_buffer,
pb_stream *rbody)
{
struct isakmp_hdr hdr = md->hdr; /* mostly same as incoming header */
/* make sure we start with a clean buffer */
init_out_pbs(output_stream, output_buffer, sizeof_output_buffer,
"reply packet");
hdr.isa_flags = 0; /* zero all flags */
if (enc)
hdr.isa_flags |= ISAKMP_FLAGS_v1_ENCRYPTION;
if (impair.send_bogus_isakmp_flag) {
hdr.isa_flags |= ISAKMP_FLAGS_RESERVED_BIT6;
}
/* there is only one IKEv1 version, and no new one will ever come - no need to set version */
hdr.isa_np = 0;
/* surely must have room and be well-formed */
passert(out_struct(&hdr, &isakmp_hdr_desc, output_stream, rbody));
}
/*
* Recognise and, if necesssary, respond to an IKEv1 duplicate.
*
* Use .st_state, which is the true current state, and not MD
* .FROM_STATE (which is derived from some convoluted magic) when
* determining if the duplicate should or should not get a response.
*/
static bool ikev1_duplicate(struct state *st, struct msg_digest *md)
{
passert(st != NULL);
if (st->st_v1_rpacket.ptr != NULL &&
st->st_v1_rpacket.len == pbs_room(&md->packet_pbs) &&
memeq(st->st_v1_rpacket.ptr, md->packet_pbs.start,
st->st_v1_rpacket.len)) {
/*
* Duplicate. Drop or retransmit?
*
* Only re-transmit when the last state transition
* (triggered by this packet the first time) included
* a reply.
*
* XXX: is SMF_RETRANSMIT_ON_DUPLICATE useful or
* correct?
*/
bool replied = (st->st_v1_last_transition != NULL &&
(st->st_v1_last_transition->flags & SMF_REPLY));
bool retransmit_on_duplicate =
(st->st_state->flags & SMF_RETRANSMIT_ON_DUPLICATE);
if (replied && retransmit_on_duplicate) {
/*
* Transitions with EVENT_SO_DISCARD should
* always respond to re-transmits (why?); else
* cap.
*/
if (st->st_v1_last_transition->timeout_event == EVENT_SO_DISCARD ||
count_duplicate(st, MAXIMUM_v1_ACCEPTED_DUPLICATES)) {
loglog(RC_RETRANSMISSION,
"retransmitting in response to duplicate packet; already %s",
st->st_state->name);
resend_recorded_v1_ike_msg(st, "retransmit in response to duplicate");
} else {
loglog(RC_LOG_SERIOUS,
"discarding duplicate packet -- exhausted retransmission; already %s",
st->st_state->name);
}
} else {
dbg("#%lu discarding duplicate packet; already %s; replied=%s retransmit_on_duplicate=%s",
st->st_serialno, st->st_state->name,
bool_str(replied), bool_str(retransmit_on_duplicate));
}
return true;
}
return false;
}
/* process an input packet, possibly generating a reply.
*
* If all goes well, this routine eventually calls a state-specific
* transition function.
*
* This routine will not release_any_md(mdp). It is expected that its
* caller will do this. In fact, it will zap *mdp to NULL if it thinks
* **mdp should not be freed. So the caller should be prepared for
* *mdp being set to NULL.
*/
void process_v1_packet(struct msg_digest *md)
{
const struct state_v1_microcode *smc;
bool new_iv_set = FALSE;
struct state *st = NULL;
enum state_kind from_state = STATE_UNDEFINED; /* state we started in */
#define SEND_NOTIFICATION(t) { \
pstats(ikev1_sent_notifies_e, t); \
if (st != NULL) \
send_notification_from_state(st, from_state, t); \
else \
send_notification_from_md(md, t); }
switch (md->hdr.isa_xchg) {
case ISAKMP_XCHG_AGGR:
case ISAKMP_XCHG_IDPROT: /* part of a Main Mode exchange */
if (md->hdr.isa_msgid != v1_MAINMODE_MSGID) {
plog_md(md, "Message ID was 0x%08" PRIx32 " but should be zero in phase 1",
md->hdr.isa_msgid);
SEND_NOTIFICATION(INVALID_MESSAGE_ID);
return;
}
if (ike_spi_is_zero(&md->hdr.isa_ike_initiator_spi)) {
plog_md(md, "Initiator Cookie must not be zero in phase 1 message");
SEND_NOTIFICATION(INVALID_COOKIE);
return;
}
if (ike_spi_is_zero(&md->hdr.isa_ike_responder_spi)) {
/*
* initial message from initiator
*/
if (md->hdr.isa_flags & ISAKMP_FLAGS_v1_ENCRYPTION) {
plog_md(md, "initial phase 1 message is invalid: its Encrypted Flag is on");
SEND_NOTIFICATION(INVALID_FLAGS);
return;
}
/*
* If there is already an existing state with
* this ICOOKIE, asssume it is some sort of
* re-transmit.
*/
st = find_state_ikev1_init(&md->hdr.isa_ike_initiator_spi,
md->hdr.isa_msgid);
if (st != NULL) {
so_serial_t old_state = push_cur_state(st);
if (!ikev1_duplicate(st, md)) {
/*
* Not a duplicate for the
* current state; assume that
* this a really old
* re-transmit for an earlier
* state that should be
* discarded.
*/
log_state(RC_LOG, st, "discarding initial packet; already %s",
st->st_state->name);
}
pop_cur_state(old_state);
return;
}
passert(st == NULL); /* new state needed */
/* don't build a state until the message looks tasty */
from_state = (md->hdr.isa_xchg == ISAKMP_XCHG_IDPROT ?
STATE_MAIN_R0 : STATE_AGGR_R0);
} else {
/* not an initial message */
st = find_state_ikev1(&md->hdr.isa_ike_spis,
md->hdr.isa_msgid);
if (st == NULL) {
/*
* perhaps this is a first message
* from the responder and contains a
* responder cookie that we've not yet
* seen.
*/
st = find_state_ikev1_init(&md->hdr.isa_ike_initiator_spi,
md->hdr.isa_msgid);
if (st == NULL) {
plog_md(md, "phase 1 message is part of an unknown exchange");
/* XXX Could send notification back */
return;
}
}
set_cur_state(st);
from_state = st->st_state->kind;
}
break;
case ISAKMP_XCHG_INFO: /* an informational exchange */
st = find_v1_info_state(&md->hdr.isa_ike_spis,
v1_MAINMODE_MSGID);
if (st == NULL) {
/*
* might be an informational response to our
* first message, in which case, we don't know
* the rcookie yet.
*/
st = find_state_ikev1_init(&md->hdr.isa_ike_initiator_spi,
v1_MAINMODE_MSGID);
}
if (st != NULL)
set_cur_state(st);
if (md->hdr.isa_flags & ISAKMP_FLAGS_v1_ENCRYPTION) {
bool quiet = (st == NULL);
if (st == NULL) {
if (DBGP(DBG_BASE)) {
DBG_log("Informational Exchange is for an unknown (expired?) SA with MSGID:0x%08" PRIx32,
md->hdr.isa_msgid);
DBG_dump_thing("- unknown SA's md->hdr.isa_ike_initiator_spi.bytes:",
md->hdr.isa_ike_initiator_spi);
DBG_dump_thing("- unknown SA's md->hdr.isa_ike_responder_spi.bytes:",
md->hdr.isa_ike_responder_spi);
}
/* XXX Could send notification back */
return;
}
if (!IS_ISAKMP_ENCRYPTED(st->st_state->kind)) {
if (!quiet) {
log_state(RC_LOG_SERIOUS, st,
"encrypted Informational Exchange message is invalid because no key is known");
}
/* XXX Could send notification back */
return;
}
if (md->hdr.isa_msgid == v1_MAINMODE_MSGID) {
if (!quiet) {
log_state(RC_LOG_SERIOUS, st,
"Informational Exchange message is invalid because it has a Message ID of 0");
}
/* XXX Could send notification back */
return;
}
if (!unique_msgid(st, md->hdr.isa_msgid)) {
if (!quiet) {
log_state(RC_LOG_SERIOUS, st,
"Informational Exchange message is invalid because it has a previously used Message ID (0x%08" PRIx32 " )",
md->hdr.isa_msgid);
}
/* XXX Could send notification back */
return;
}
st->st_v1_msgid.reserved = FALSE;
init_phase2_iv(st, &md->hdr.isa_msgid);
new_iv_set = TRUE;
from_state = STATE_INFO_PROTECTED;
} else {
if (st != NULL &&
IS_ISAKMP_AUTHENTICATED(st->st_state)) {
log_state(RC_LOG_SERIOUS, st,
"Informational Exchange message must be encrypted");
/* XXX Could send notification back */
return;
}
from_state = STATE_INFO;
}
break;
case ISAKMP_XCHG_QUICK: /* part of a Quick Mode exchange */
if (ike_spi_is_zero(&md->hdr.isa_ike_initiator_spi)) {
dbg("Quick Mode message is invalid because it has an Initiator Cookie of 0");
SEND_NOTIFICATION(INVALID_COOKIE);
return;
}
if (ike_spi_is_zero(&md->hdr.isa_ike_responder_spi)) {
dbg("Quick Mode message is invalid because it has a Responder Cookie of 0");
SEND_NOTIFICATION(INVALID_COOKIE);
return;
}
if (md->hdr.isa_msgid == v1_MAINMODE_MSGID) {
dbg("Quick Mode message is invalid because it has a Message ID of 0");
SEND_NOTIFICATION(INVALID_MESSAGE_ID);
return;
}
st = find_state_ikev1(&md->hdr.isa_ike_spis,
md->hdr.isa_msgid);
if (st == NULL) {
/* No appropriate Quick Mode state.
* See if we have a Main Mode state.
* ??? what if this is a duplicate of another message?
*/
st = find_state_ikev1(&md->hdr.isa_ike_spis,
v1_MAINMODE_MSGID);
if (st == NULL) {
dbg("Quick Mode message is for a non-existent (expired?) ISAKMP SA");
/* XXX Could send notification back */
return;
}
if (st->st_oakley.doing_xauth) {
dbg("Cannot do Quick Mode until XAUTH done.");
return;
}
/* Have we just given an IP address to peer? */
if (st->st_state->kind == STATE_MODE_CFG_R2) {
/* ISAKMP is up... */
change_state(st, STATE_MAIN_R3);
}
#ifdef SOFTREMOTE_CLIENT_WORKAROUND
/* See: http://popoludnica.pl/?id=10100110 */
if (st->st_state->kind == STATE_MODE_CFG_R1) {
log_state(RC_LOG, st,
"SoftRemote workaround: Cannot do Quick Mode until MODECFG done.");
return;
}
#endif
set_cur_state(st);
if (!IS_ISAKMP_SA_ESTABLISHED(st->st_state)) {
log_state(RC_LOG_SERIOUS, st,
"Quick Mode message is unacceptable because it is for an incomplete ISAKMP SA");
SEND_NOTIFICATION(PAYLOAD_MALFORMED /* XXX ? */);
return;
}
if (!unique_msgid(st, md->hdr.isa_msgid)) {
log_state(RC_LOG_SERIOUS, st,
"Quick Mode I1 message is unacceptable because it uses a previously used Message ID 0x%08" PRIx32 " (perhaps this is a duplicated packet)",
md->hdr.isa_msgid);
SEND_NOTIFICATION(INVALID_MESSAGE_ID);
return;
}
st->st_v1_msgid.reserved = FALSE;
/* Quick Mode Initial IV */
init_phase2_iv(st, &md->hdr.isa_msgid);
new_iv_set = TRUE;
from_state = STATE_QUICK_R0;
} else {
if (st->st_oakley.doing_xauth) {
log_state(RC_LOG, st, "Cannot do Quick Mode until XAUTH done.");
return;
}
set_cur_state(st);
from_state = st->st_state->kind;
}
break;
case ISAKMP_XCHG_MODE_CFG:
if (ike_spi_is_zero(&md->hdr.isa_ike_initiator_spi)) {
dbg("Mode Config message is invalid because it has an Initiator Cookie of 0");
/* XXX Could send notification back */
return;
}
if (ike_spi_is_zero(&md->hdr.isa_ike_responder_spi)) {
dbg("Mode Config message is invalid because it has a Responder Cookie of 0");
/* XXX Could send notification back */
return;
}
if (md->hdr.isa_msgid == 0) {
dbg("Mode Config message is invalid because it has a Message ID of 0");
/* XXX Could send notification back */
return;
}
st = find_v1_info_state(&md->hdr.isa_ike_spis, md->hdr.isa_msgid);
if (st == NULL) {
/* No appropriate Mode Config state.
* See if we have a Main Mode state.
* ??? what if this is a duplicate of another message?
*/
dbg("No appropriate Mode Config state yet. See if we have a Main Mode state");
st = find_v1_info_state(&md->hdr.isa_ike_spis, 0);
if (st == NULL) {
dbg("Mode Config message is for a non-existent (expired?) ISAKMP SA");
/* XXX Could send notification back */
/* ??? ought to log something (not just DBG)? */
return;
}
set_cur_state(st);
const struct end *this = &st->st_connection->spd.this;
dbg(" processing received isakmp_xchg_type %s; this is a%s%s%s%s",
enum_show(&ikev1_exchange_names, md->hdr.isa_xchg),
this->xauth_server ? " xauthserver" : "",
this->xauth_client ? " xauthclient" : "",
this->modecfg_server ? " modecfgserver" : "",
this->modecfg_client ? " modecfgclient" : "");
if (!IS_ISAKMP_SA_ESTABLISHED(st->st_state)) {
dbg("Mode Config message is unacceptable because it is for an incomplete ISAKMP SA (state=%s)",
st->st_state->name);
/* XXX Could send notification back */
return;
}
dbg(" call init_phase2_iv");
init_phase2_iv(st, &md->hdr.isa_msgid);
new_iv_set = TRUE;
/*
* okay, now we have to figure out if we are receiving a bogus
* new message in an outstanding XAUTH server conversation
* (i.e. a reply to our challenge)
* (this occurs with some broken other implementations).
*
* or if receiving for the first time, an XAUTH challenge.
*
* or if we are getting a MODECFG request.
*
* we distinguish these states because we cannot both be an
* XAUTH server and client, and our policy tells us which
* one we are.
*
* to complicate further, it is normal to start a new msgid
* when going from one state to another, or when restarting
* the challenge.
*
*/
if (this->xauth_server &&
st->st_state->kind == STATE_XAUTH_R1 &&
st->quirks.xauth_ack_msgid) {
from_state = STATE_XAUTH_R1;
dbg(" set from_state to %s state is STATE_XAUTH_R1 and quirks.xauth_ack_msgid is TRUE",
st->st_state->name);
} else if (this->xauth_client &&
IS_PHASE1(st->st_state->kind)) {
from_state = STATE_XAUTH_I0;
dbg(" set from_state to %s this is xauthclient and IS_PHASE1() is TRUE",
st->st_state->name);
} else if (this->xauth_client &&
st->st_state->kind == STATE_XAUTH_I1) {
/*
* in this case, we got a new MODECFG message after I0, maybe
* because it wants to start over again.
*/
from_state = STATE_XAUTH_I0;
dbg(" set from_state to %s this is xauthclient and state == STATE_XAUTH_I1",
st->st_state->name);
} else if (this->modecfg_server &&
IS_PHASE1(st->st_state->kind)) {
from_state = STATE_MODE_CFG_R0;
dbg(" set from_state to %s this is modecfgserver and IS_PHASE1() is TRUE",
st->st_state->name);
} else if (this->modecfg_client &&
IS_PHASE1(st->st_state->kind)) {
from_state = STATE_MODE_CFG_R1;
dbg(" set from_state to %s this is modecfgclient and IS_PHASE1() is TRUE",
st->st_state->name);
} else {
dbg("received isakmp_xchg_type %s; this is a%s%s%s%s in state %s. Reply with UNSUPPORTED_EXCHANGE_TYPE",
enum_show(&ikev1_exchange_names, md->hdr.isa_xchg),
st->st_connection ->spd.this.xauth_server ? " xauthserver" : "",
st->st_connection->spd.this.xauth_client ? " xauthclient" : "",
st->st_connection->spd.this.modecfg_server ? " modecfgserver" : "",
st->st_connection->spd.this.modecfg_client ? " modecfgclient" : "",
st->st_state->name);
return;
}
} else {
if (st->st_connection->spd.this.xauth_server &&
IS_PHASE1(st->st_state->kind)) {
/* Switch from Phase1 to Mode Config */
dbg("We were in phase 1, with no state, so we went to XAUTH_R0");
change_state(st, STATE_XAUTH_R0);
}
/* otherwise, this is fine, we continue in the state we are in */
set_cur_state(st);
from_state = st->st_state->kind;
}
break;
case ISAKMP_XCHG_NONE:
case ISAKMP_XCHG_BASE:
case ISAKMP_XCHG_AO:
case ISAKMP_XCHG_NGRP:
default:
dbg("unsupported exchange type %s in message",
enum_show(&ikev1_exchange_names, md->hdr.isa_xchg));
SEND_NOTIFICATION(UNSUPPORTED_EXCHANGE_TYPE);
return;
}
/* We have found a from_state, and perhaps a state object.
* If we need to build a new state object,
* we wait until the packet has been sanity checked.
*/
/* We don't support the Commit Flag. It is such a bad feature.
* It isn't protected -- neither encrypted nor authenticated.
* A man in the middle turns it on, leading to DoS.
* We just ignore it, with a warning.
*/
if (md->hdr.isa_flags & ISAKMP_FLAGS_v1_COMMIT)
dbg("IKE message has the Commit Flag set but Pluto doesn't implement this feature due to security concerns; ignoring flag");
/* Handle IKE fragmentation payloads */
if (md->hdr.isa_np == ISAKMP_NEXT_IKE_FRAGMENTATION) {
struct isakmp_ikefrag fraghdr;
int last_frag_index = 0; /* index of the last fragment */
pb_stream frag_pbs;
if (st == NULL) {
dbg("received IKE fragment, but have no state. Ignoring packet.");
return;
}
if ((st->st_connection->policy & POLICY_IKE_FRAG_ALLOW) == 0) {
dbg("discarding IKE fragment packet - fragmentation not allowed by local policy (ike_frag=no)");
return;
}
if (!in_struct(&fraghdr, &isakmp_ikefrag_desc,
&md->message_pbs, &frag_pbs) ||
pbs_room(&frag_pbs) != fraghdr.isafrag_length ||
fraghdr.isafrag_np != ISAKMP_NEXT_NONE ||
fraghdr.isafrag_number == 0 ||
fraghdr.isafrag_number > 16) {
SEND_NOTIFICATION(PAYLOAD_MALFORMED);
return;
}
dbg("received IKE fragment id '%d', number '%u'%s",
fraghdr.isafrag_id,
fraghdr.isafrag_number,
(fraghdr.isafrag_flags == 1) ? "(last)" : "");
struct v1_ike_rfrag *ike_frag = alloc_thing(struct v1_ike_rfrag, "ike_frag");
ike_frag->md = md_addref(md, HERE);
ike_frag->index = fraghdr.isafrag_number;
ike_frag->last = (fraghdr.isafrag_flags & 1);
ike_frag->size = pbs_left(&frag_pbs);
ike_frag->data = frag_pbs.cur;
/* Add the fragment to the state */
struct v1_ike_rfrag **i = &st->st_v1_rfrags;
for (;;) {
if (ike_frag != NULL) {
/* Still looking for a place to insert ike_frag */
if (*i == NULL ||
(*i)->index > ike_frag->index) {
ike_frag->next = *i;
*i = ike_frag;
ike_frag = NULL;
} else if ((*i)->index == ike_frag->index) {
/* Replace fragment with same index */
struct v1_ike_rfrag *old = *i;
ike_frag->next = old->next;
*i = ike_frag;
pexpect(old->md != NULL);
release_any_md(&old->md);
pfree(old);
ike_frag = NULL;
}
}
if (*i == NULL)
break;
if ((*i)->last)
last_frag_index = (*i)->index;
i = &(*i)->next;
}
/* We have the last fragment, reassemble if complete */
if (last_frag_index != 0) {
size_t size = 0;
int prev_index = 0;
for (struct v1_ike_rfrag *frag = st->st_v1_rfrags; frag; frag = frag->next) {
size += frag->size;
if (frag->index != ++prev_index) {
break; /* fragment list incomplete */
} else if (frag->index == last_frag_index) {
struct msg_digest *whole_md = alloc_md("msg_digest by ikev1 fragment handler");
uint8_t *buffer = alloc_bytes(size,
"IKE fragments buffer");
size_t offset = 0;
whole_md->iface = frag->md->iface;
whole_md->sender = frag->md->sender;
/* Reassemble fragments in buffer */
frag = st->st_v1_rfrags;
while (frag != NULL &&
frag->index <= last_frag_index)
{
passert(offset + frag->size <=
size);
memcpy(buffer + offset,
frag->data, frag->size);
offset += frag->size;
frag = frag->next;
}
init_pbs(&whole_md->packet_pbs, buffer, size,
"packet");
process_packet(&whole_md);
release_any_md(&whole_md);
free_v1_message_queues(st);
/* optimize: if receiving fragments, immediately respond with fragments too */
st->st_seen_fragments = TRUE;
dbg(" updated IKE fragment state to respond using fragments without waiting for re-transmits");
break;
}
}
}
return;
}
/* Set smc to describe this state's properties.
* Look up the appropriate microcode based on state and
* possibly Oakley Auth type.
*/
passert(STATE_IKEv1_FLOOR <= from_state && from_state < STATE_IKEv1_ROOF);
const struct finite_state *fs = finite_states[from_state];
passert(fs != NULL);
smc = fs->v1_transitions;
passert(smc != NULL);
/*
* Find the state's the state transitions that has matching
* authentication.
*
* For states where this makes no sense (eg, quick states
* creating a CHILD_SA), .flags|=SMF_ALL_AUTH so the first
* (only) one always matches.
*
* XXX: The code assums that when there is always a match (if
* there isn't the passert() triggers. If needed, bogus
* transitions that log/drop the packet are added to the
* table? Would simply dropping the packets be easier.
*/
if (st != NULL) {
oakley_auth_t baseauth =
xauth_calcbaseauth(st->st_oakley.auth);
while (!LHAS(smc->flags, baseauth)) {
smc++;
passert(smc->state == from_state);
}
}
/*
* XXX: do this earlier? */
if (verbose_state_busy(st))
return;
/*
* Detect and handle duplicated packets. This won't work for
* the initial packet of an exchange because we won't have a
* state object to remember it. If we are in a non-receiving
* state (terminal), and the preceding state did transmit,
* then the duplicate may indicate that that transmission
* wasn't received -- retransmit it. Otherwise, just discard
* it. ??? Notification packets are like exchanges -- I hope
* that they are idempotent!
*
* XXX: do this earlier?
*/
if (st != NULL && ikev1_duplicate(st, md)) {
return;
}
/* save values for use in resumption of processing below.
* (may be suspended due to crypto operation not yet complete)
*/
md->st = st;
md->v1_from_state = from_state;
md->smc = smc;
md->new_iv_set = new_iv_set;
/*
* look for encrypt packets. We cannot handle them if we have not
* yet calculated the skeyids. We will just store the packet in
* the suspended state, since the calculation is likely underway.
*
* note that this differs from above, because skeyid is calculated
* in between states. (or will be, once DH is async)
*
*/
if ((md->hdr.isa_flags & ISAKMP_FLAGS_v1_ENCRYPTION) &&
st != NULL &&
!st->hidden_variables.st_skeyid_calculated) {
endpoint_buf b;
dbg("received encrypted packet from %s but exponentiation still in progress",
str_endpoint(&md->sender, &b));
/*
* if there was a previous packet, let it go, and go
* with most recent one.
*/
if (st->st_suspended_md != NULL) {
dbg("releasing suspended operation before completion: %p",
st->st_suspended_md);
release_any_md(&st->st_suspended_md);
}
suspend_any_md(st, md);
return;
}
process_packet_tail(md);
/* our caller will release_any_md(mdp); */
}
/*
* This routine will not release_any_md(mdp). It is expected that its
* caller will do this. In fact, it will zap *mdp to NULL if it thinks
* **mdp should not be freed. So the caller should be prepared for
* *mdp being set to NULL.
*/
void process_packet_tail(struct msg_digest *md)
{
struct state *st = md->st;
enum state_kind from_state = md->v1_from_state;
const struct state_v1_microcode *smc = md->smc;
bool new_iv_set = md->new_iv_set;
bool self_delete = FALSE;
if (md->hdr.isa_flags & ISAKMP_FLAGS_v1_ENCRYPTION) {
endpoint_buf b;
dbg("received encrypted packet from %s", str_endpoint(&md->sender, &b));
if (st == NULL) {
libreswan_log(
"discarding encrypted message for an unknown ISAKMP SA");
return;
}
if (st->st_skeyid_e_nss == NULL) {
loglog(RC_LOG_SERIOUS,
"discarding encrypted message because we haven't yet negotiated keying material");
return;
}
/* Mark as encrypted */
md->encrypted = TRUE;
/* do the specified decryption
*
* IV is from st->st_iv or (if new_iv_set) st->st_new_iv.
* The new IV is placed in st->st_new_iv
*
* See RFC 2409 "IKE" Appendix B
*
* XXX The IV should only be updated really if the packet
* is successfully processed.
* We should keep this value, check for a success return
* value from the parsing routines and then replace.
*
* Each post phase 1 exchange generates IVs from
* the last phase 1 block, not the last block sent.
*/
const struct encrypt_desc *e = st->st_oakley.ta_encrypt;
if (pbs_left(&md->message_pbs) % e->enc_blocksize != 0) {
loglog(RC_LOG_SERIOUS, "malformed message: not a multiple of encryption blocksize");
return;
}
/* XXX Detect weak keys */
/* grab a copy of raw packet (for duplicate packet detection) */
md->raw_packet = clone_bytes_as_chunk(md->packet_pbs.start,
pbs_room(&md->packet_pbs),
"raw packet");
/* Decrypt everything after header */
if (!new_iv_set) {
if (st->st_v1_iv.len == 0) {
init_phase2_iv(st, &md->hdr.isa_msgid);
} else {
/* use old IV */
restore_new_iv(st, st->st_v1_iv);
}
}
passert(st->st_v1_new_iv.len >= e->enc_blocksize);
st->st_v1_new_iv.len = e->enc_blocksize; /* truncate */
if (DBGP(DBG_CRYPT)) {
DBG_log("decrypting %u bytes using algorithm %s",
(unsigned) pbs_left(&md->message_pbs),
st->st_oakley.ta_encrypt->common.fqn);
DBG_dump_hunk("IV before:", st->st_v1_new_iv);
}
e->encrypt_ops->do_crypt(e, md->message_pbs.cur,
pbs_left(&md->message_pbs),
st->st_enc_key_nss,
st->st_v1_new_iv.ptr, FALSE);
if (DBGP(DBG_CRYPT)) {
DBG_dump_hunk("IV after:", st->st_v1_new_iv);
DBG_log("decrypted payload (starts at offset %td):",
md->message_pbs.cur - md->message_pbs.roof);
DBG_dump(NULL, md->message_pbs.start,
md->message_pbs.roof - md->message_pbs.start);
}
} else {
/* packet was not encryped -- should it have been? */
if (smc->flags & SMF_INPUT_ENCRYPTED) {
loglog(RC_LOG_SERIOUS,
"packet rejected: should have been encrypted");
SEND_NOTIFICATION(INVALID_FLAGS);
return;
}
}
/* Digest the message.
* Padding must be removed to make hashing work.
* Padding comes from encryption (so this code must be after decryption).
* Padding rules are described before the definition of
* struct isakmp_hdr in packet.h.
*/
{
enum next_payload_types_ikev1 np = md->hdr.isa_np;
lset_t needed = smc->req_payloads;
const char *excuse =
LIN(SMF_PSK_AUTH | SMF_FIRST_ENCRYPTED_INPUT,
smc->flags) ?
"probable authentication failure (mismatch of preshared secrets?): "
:
"";
while (np != ISAKMP_NEXT_NONE) {
struct_desc *sd = v1_payload_desc(np);
if (md->digest_roof >= elemsof(md->digest)) {
loglog(RC_LOG_SERIOUS,
"more than %zu payloads in message; ignored",
elemsof(md->digest));
if (!md->encrypted) {
SEND_NOTIFICATION(PAYLOAD_MALFORMED);
}
return;
}
struct payload_digest *const pd = md->digest + md->digest_roof;
/*
* only do this in main mode. In aggressive mode, there
* is no negotiation of NAT-T method. Get it right.
*/
if (st != NULL && st->st_connection != NULL &&
(st->st_connection->policy & POLICY_AGGRESSIVE) == LEMPTY)
{
switch (np) {
case ISAKMP_NEXT_NATD_RFC:
case ISAKMP_NEXT_NATOA_RFC:
if ((st->hidden_variables.st_nat_traversal & NAT_T_WITH_RFC_VALUES) == LEMPTY) {
/*
* don't accept NAT-D/NAT-OA reloc directly in message,
* unless we're using NAT-T RFC
*/
DBG(DBG_NATT,
DBG_log("st_nat_traversal was: %s",
bitnamesof(natt_bit_names,
st->hidden_variables.st_nat_traversal)));
sd = NULL;
}
break;
default:
break;
}
}
if (sd == NULL) {
/* payload type is out of range or requires special handling */
switch (np) {
case ISAKMP_NEXT_ID:
/* ??? two kinds of ID payloads */
sd = (IS_PHASE1(from_state) ||
IS_PHASE15(from_state)) ?
&isakmp_identification_desc :
&isakmp_ipsec_identification_desc;
break;
case ISAKMP_NEXT_NATD_DRAFTS: /* out of range */
/*
* ISAKMP_NEXT_NATD_DRAFTS was a private use type before RFC-3947.
* Since it has the same format as ISAKMP_NEXT_NATD_RFC,
* just rewrite np and sd, and carry on.
*/
np = ISAKMP_NEXT_NATD_RFC;
sd = &isakmp_nat_d_drafts;
break;
case ISAKMP_NEXT_NATOA_DRAFTS: /* out of range */
/* NAT-OA was a private use type before RFC-3947 -- same format */
np = ISAKMP_NEXT_NATOA_RFC;
sd = &isakmp_nat_oa_drafts;
break;
case ISAKMP_NEXT_SAK: /* or ISAKMP_NEXT_NATD_BADDRAFTS */
/*
* Official standards say that this is ISAKMP_NEXT_SAK,
* a part of Group DOI, something we don't implement.
* Old non-updated Cisco gear abused this number in ancient NAT drafts.
* We ignore (rather than reject) this in support of people
* with crufty Cisco machines.
*/
loglog(RC_LOG_SERIOUS,
"%smessage with unsupported payload ISAKMP_NEXT_SAK (or ISAKMP_NEXT_NATD_BADDRAFTS) ignored",
excuse);
/*
* Hack to discard payload, whatever it was.
* Since we are skipping the rest of the loop
* body we must do some things ourself:
* - demarshall the payload
* - grab the next payload number (np)
* - don't keep payload (don't increment pd)
* - skip rest of loop body
*/
if (!in_struct(&pd->payload, &isakmp_ignore_desc, &md->message_pbs,
&pd->pbs)) {
loglog(RC_LOG_SERIOUS,
"%smalformed payload in packet",
excuse);
if (!md->encrypted) {
SEND_NOTIFICATION(PAYLOAD_MALFORMED);
}
return;
}
np = pd->payload.generic.isag_np;
/* NOTE: we do not increment pd! */
continue; /* skip rest of the loop */
default:
loglog(RC_LOG_SERIOUS,
"%smessage ignored because it contains an unknown or unexpected payload type (%s) at the outermost level",
excuse,
enum_show(&ikev1_payload_names, np));
if (!md->encrypted) {
SEND_NOTIFICATION(INVALID_PAYLOAD_TYPE);
}
return;
}
passert(sd != NULL);
}
passert(np < LELEM_ROOF);
{
lset_t s = LELEM(np);
if (LDISJOINT(s,
needed | smc->opt_payloads |
LELEM(ISAKMP_NEXT_VID) |
LELEM(ISAKMP_NEXT_N) |
LELEM(ISAKMP_NEXT_D) |
LELEM(ISAKMP_NEXT_CR) |
LELEM(ISAKMP_NEXT_CERT))) {
loglog(RC_LOG_SERIOUS,
"%smessage ignored because it contains a payload type (%s) unexpected by state %s",
excuse,
enum_show(&ikev1_payload_names, np),
finite_states[smc->state]->name);
if (!md->encrypted) {
SEND_NOTIFICATION(INVALID_PAYLOAD_TYPE);
}
return;
}
DBG(DBG_PARSING,
DBG_log("got payload 0x%" PRIxLSET" (%s) needed: 0x%" PRIxLSET " opt: 0x%" PRIxLSET,
s, enum_show(&ikev1_payload_names, np),
needed, smc->opt_payloads));
needed &= ~s;
}
/*
* Read in the payload recording what type it
* should be
*/
pd->payload_type = np;
if (!in_struct(&pd->payload, sd, &md->message_pbs,
&pd->pbs)) {
loglog(RC_LOG_SERIOUS,
"%smalformed payload in packet",
excuse);
if (!md->encrypted) {
SEND_NOTIFICATION(PAYLOAD_MALFORMED);
}
return;
}
/* do payload-type specific debugging */
switch (np) {
case ISAKMP_NEXT_ID:
case ISAKMP_NEXT_NATOA_RFC:
/* dump ID section */
DBG(DBG_PARSING,
DBG_dump(" obj: ", pd->pbs.cur,
pbs_left(&pd->pbs)));
break;
default:
break;
}
/*
* Place payload at the end of the chain for this type.
* This code appears in ikev1.c and ikev2.c.
*/
{
/* np is a proper subscript for chain[] */
passert(np < elemsof(md->chain));
struct payload_digest **p = &md->chain[np];
while (*p != NULL)
p = &(*p)->next;
*p = pd;
pd->next = NULL;
}
np = pd->payload.generic.isag_np;
md->digest_roof++;
/* since we've digested one payload happily, it is probably
* the case that any decryption worked. So we will not suggest
* encryption failure as an excuse for subsequent payload
* problems.
*/
excuse = "";
}
DBG(DBG_PARSING, {
if (pbs_left(&md->message_pbs) != 0)
DBG_log("removing %d bytes of padding",
(int) pbs_left(&md->message_pbs));
});
md->message_pbs.roof = md->message_pbs.cur;
/* check that all mandatory payloads appeared */
if (needed != 0) {
loglog(RC_LOG_SERIOUS,
"message for %s is missing payloads %s",
finite_states[from_state]->name,
bitnamesof(payload_name_ikev1, needed));
if (!md->encrypted) {
SEND_NOTIFICATION(PAYLOAD_MALFORMED);
}
return;
}
}
if (!check_v1_HASH(smc->hash_type, smc->message, st, md)) {
/*SEND_NOTIFICATION(INVALID_HASH_INFORMATION);*/
return;
}
/* more sanity checking: enforce most ordering constraints */
if (IS_PHASE1(from_state) || IS_PHASE15(from_state)) {
/* rfc2409: The Internet Key Exchange (IKE), 5 Exchanges:
* "The SA payload MUST precede all other payloads in a phase 1 exchange."
*/
if (md->chain[ISAKMP_NEXT_SA] != NULL &&
md->hdr.isa_np != ISAKMP_NEXT_SA) {
loglog(RC_LOG_SERIOUS,
"malformed Phase 1 message: does not start with an SA payload");
if (!md->encrypted) {
SEND_NOTIFICATION(PAYLOAD_MALFORMED);
}
return;
}
} else if (IS_QUICK(from_state)) {
/* rfc2409: The Internet Key Exchange (IKE), 5.5 Phase 2 - Quick Mode
*
* "In Quick Mode, a HASH payload MUST immediately follow the ISAKMP
* header and a SA payload MUST immediately follow the HASH."
* [NOTE: there may be more than one SA payload, so this is not
* totally reasonable. Probably all SAs should be so constrained.]
*
* "If ISAKMP is acting as a client negotiator on behalf of another
* party, the identities of the parties MUST be passed as IDci and
* then IDcr."
*
* "With the exception of the HASH, SA, and the optional ID payloads,
* there are no payload ordering restrictions on Quick Mode."
*/
if (md->hdr.isa_np != ISAKMP_NEXT_HASH) {
loglog(RC_LOG_SERIOUS,
"malformed Quick Mode message: does not start with a HASH payload");
if (!md->encrypted) {
SEND_NOTIFICATION(PAYLOAD_MALFORMED);
}
return;
}
{
struct payload_digest *p;
int i;
p = md->chain[ISAKMP_NEXT_SA];
i = 1;
while (p != NULL) {
if (p != &md->digest[i]) {
loglog(RC_LOG_SERIOUS,
"malformed Quick Mode message: SA payload is in wrong position");
if (!md->encrypted) {
SEND_NOTIFICATION(PAYLOAD_MALFORMED);
}
return;
}
p = p->next;
i++;
}
}
/* rfc2409: The Internet Key Exchange (IKE), 5.5 Phase 2 - Quick Mode:
* "If ISAKMP is acting as a client negotiator on behalf of another
* party, the identities of the parties MUST be passed as IDci and
* then IDcr."
*/
{
struct payload_digest *id = md->chain[ISAKMP_NEXT_ID];
if (id != NULL) {
if (id->next == NULL ||
id->next->next != NULL) {
loglog(RC_LOG_SERIOUS,
"malformed Quick Mode message: if any ID payload is present, there must be exactly two");
SEND_NOTIFICATION(PAYLOAD_MALFORMED);
return;
}
if (id + 1 != id->next) {
loglog(RC_LOG_SERIOUS,
"malformed Quick Mode message: the ID payloads are not adjacent");
SEND_NOTIFICATION(PAYLOAD_MALFORMED);
return;
}
}
}
}
/*
* Ignore payloads that we don't handle:
*/
/* XXX Handle Notifications */
{
struct payload_digest *p = md->chain[ISAKMP_NEXT_N];
while (p != NULL) {
switch (p->payload.notification.isan_type) {
case R_U_THERE:
case R_U_THERE_ACK:
case ISAKMP_N_CISCO_LOAD_BALANCE:
case PAYLOAD_MALFORMED:
case INVALID_MESSAGE_ID:
case IPSEC_RESPONDER_LIFETIME:
if (md->hdr.isa_xchg == ISAKMP_XCHG_INFO) {
/* these are handled later on in informational() */
break;
}
/* FALL THROUGH */
default:
if (st == NULL) {
DBG(DBG_CONTROL, DBG_log(
"ignoring informational payload %s, no corresponding state",
enum_show(& ikev1_notify_names,
p->payload.notification.isan_type)));
} else {
loglog(RC_LOG_SERIOUS,
"ignoring informational payload %s, msgid=%08" PRIx32 ", length=%d",
enum_show(&ikev1_notify_names,
p->payload.notification.isan_type),
st->st_v1_msgid.id,
p->payload.notification.isan_length);
DBG_dump_pbs(&p->pbs);
}
}
if (DBGP(DBG_BASE)) {
DBG_dump("info:", p->pbs.cur,
pbs_left(&p->pbs));
}
p = p->next;
}
p = md->chain[ISAKMP_NEXT_D];
while (p != NULL) {
self_delete |= accept_delete(md, p);
if (DBGP(DBG_BASE)) {
DBG_dump("del:", p->pbs.cur,
pbs_left(&p->pbs));
}
if (md->st != st) {
pexpect(md->st == NULL);
dbg("zapping ST as accept_delete() zapped MD.ST");
st = md->st;
}
p = p->next;
}
p = md->chain[ISAKMP_NEXT_VID];
while (p != NULL) {
handle_vendorid(md, (char *)p->pbs.cur,
pbs_left(&p->pbs), FALSE);
p = p->next;
}
}
if (self_delete) {
accept_self_delete(md);
st = md->st;
/* note: st ought to be NULL from here on */
}
pexpect(st == md->st);
statetime_t start = statetime_start(md->st);
/*
* XXX: danger - the .informational() processor deletes ST;
* and then tunnels this loss through MD.ST.
*/
complete_v1_state_transition(md, smc->processor(st, md));
statetime_stop(&start, "%s()", __func__);
/* our caller will release_any_md(mdp); */
}
/*
* replace previous receive packet with latest, to update
* our notion of a retransmitted packet. This is important
* to do, even for failing transitions, and suspended transitions
* because the sender may well retransmit their request.
* We had better be idempotent since we can be called
* multiple times in handling a packet due to crypto helper logic.
*/
static void remember_received_packet(struct state *st, struct msg_digest *md)
{
if (md->encrypted) {
/* if encrypted, duplication already done */
if (md->raw_packet.ptr != NULL) {
pfreeany(st->st_v1_rpacket.ptr);
st->st_v1_rpacket = md->raw_packet;
md->raw_packet = EMPTY_CHUNK;
}
} else {
/* this may be a repeat, but it will work */
free_chunk_content(&st->st_v1_rpacket);
st->st_v1_rpacket = clone_bytes_as_chunk(md->packet_pbs.start,
pbs_room(&md->packet_pbs),
"raw packet");
}
}
/* complete job started by the state-specific state transition function
*
* This routine will not release_any_md(mdp). It is expected that its
* caller will do this. In fact, it will zap *mdp to NULL if it thinks
* **mdp should not be freed. So the caller should be prepared for
* *mdp being set to NULL.
*
* md is used to:
* - find st
* - find from_state (st might be gone)
* - find note for STF_FAIL (might not be part of result (STF_FAIL+note))
* - find note for STF_INTERNAL_ERROR
* - record md->event_already_set
* - remember_received_packet(st, md);
* - nat_traversal_change_port_lookup(md, st);
* - smc for smc->next_state
* - smc for smc->flags & SMF_REPLY to trigger a reply
* - smc for smc->timeout_event
* - smc for !(smc->flags & SMF_INITIATOR) for Contivity mode
* - smc for smc->flags & SMF_RELEASE_PENDING_P2 to trigger unpend call
* - smc for smc->flags & SMF_INITIATOR to adjust retransmission
* - fragvid, dpd, nortel
*/
void complete_v1_state_transition(struct msg_digest *md, stf_status result)
{
passert(md != NULL);
/* handle oddball/meta results now */
/*
* statistics; lump all FAILs together
*
* Fun fact: using min() stupidly fails (at least in GCC 8.1.1 with -Werror=sign-compare)
* error: comparison of integer expressions of different signedness: `stf_status' {aka `enum <anonymous>'} and `int'
*/
pstats(ike_stf, PMIN(result, STF_FAIL));
DBG(DBG_CONTROL,
DBG_log("complete v1 state transition with %s",
result > STF_FAIL ?
enum_name(&ikev1_notify_names, result - STF_FAIL) :
enum_name(&stf_status_names, result)));
switch (result) {
case STF_SUSPEND:
set_cur_state(md->st); /* might have changed */
/*
* If this transition was triggered by an incoming
* packet, save it.
*
* XXX: some initiator code creates a fake MD (there
* isn't a real one); save that as well.
*/
suspend_any_md(md->st, md);
return;
case STF_IGNORE:
return;
default:
break;
}
/* safe to refer to *md */
enum state_kind from_state = md->v1_from_state;
struct state *st = md->st;
set_cur_state(st); /* might have changed */
passert(st != NULL);
pexpect(!state_is_busy(st));
if (result > STF_OK) {
linux_audit_conn(md->st, IS_IKE_SA_ESTABLISHED(md->st) ? LAK_CHILD_FAIL : LAK_PARENT_FAIL);
}
switch (result) {
case STF_OK:
{
/* advance the state */
const struct state_v1_microcode *smc = md->smc;
DBG(DBG_CONTROL, DBG_log("doing_xauth:%s, t_xauth_client_done:%s",
bool_str(st->st_oakley.doing_xauth),
bool_str(st->hidden_variables.st_xauth_client_done)));
/* accept info from VID because we accept this message */
/*
* Most of below VIDs only appear Main/Aggr mode, not Quick mode,
* so why are we checking them for each state transition?
*/
if (md->fragvid) {
dbg("peer supports fragmentation");
st->st_seen_fragvid = TRUE;
}
if (md->dpd) {
dbg("peer supports DPD");
st->hidden_variables.st_peer_supports_dpd = TRUE;
if (dpd_active_locally(st)) {
dbg("DPD is configured locally");
}
}
/* If state has VID_NORTEL, import it to activate workaround */
if (md->nortel) {
dbg("peer requires Nortel Contivity workaround");
st->st_seen_nortel_vid = TRUE;
}
if (!st->st_v1_msgid.reserved &&
IS_CHILD_SA(st) &&
st->st_v1_msgid.id != v1_MAINMODE_MSGID) {
struct state *p1st = state_with_serialno(
st->st_clonedfrom);
if (p1st != NULL) {
/* do message ID reservation */
reserve_msgid(p1st, st->st_v1_msgid.id);
}
st->st_v1_msgid.reserved = TRUE;
}
dbg("IKEv1: transition from state %s to state %s",
finite_states[from_state]->name,
finite_states[smc->next_state]->name);
change_state(st, smc->next_state);
/*
* XAUTH negotiation without ModeCFG cannot follow the regular
* state machine change as it cannot be determined if the CFG
* payload is "XAUTH OK, no ModeCFG" or "XAUTH OK, expect
* ModeCFG". To the smc, these two cases look identical. So we
* have an ad hoc state change here for the case where
* we have XAUTH but not ModeCFG. We move it to the established
* state, so the regular state machine picks up the Quick Mode.
*/
if (st->st_connection->spd.this.xauth_client &&
st->hidden_variables.st_xauth_client_done &&
!st->st_connection->spd.this.modecfg_client &&
st->st_state->kind == STATE_XAUTH_I1)
{
bool aggrmode = LHAS(st->st_connection->policy, POLICY_AGGRESSIVE_IX);
libreswan_log("XAUTH completed; ModeCFG skipped as per configuration");
change_state(st, aggrmode ? STATE_AGGR_I2 : STATE_MAIN_I4);
st->st_v1_msgid.phase15 = v1_MAINMODE_MSGID;
}
/* Schedule for whatever timeout is specified */
if (!md->event_already_set) {
/*
* This md variable is hardly ever set.
* Only deals with v1 <-> v2 switching
* which will be removed in the near future anyway
* (PW 2017 Oct 8)
*/
DBG(DBG_CONTROL, DBG_log("event_already_set, deleting event"));
/*
* Delete previous retransmission event.
* New event will be scheduled below.
*/
delete_event(st);
clear_retransmits(st);
}
/* Delete IKE fragments */
free_v1_message_queues(st);
/* scrub the previous packet exchange */
free_chunk_content(&st->st_v1_rpacket);
free_chunk_content(&st->st_v1_tpacket);
/* in aggressive mode, there will be no reply packet in transition
* from STATE_AGGR_R1 to STATE_AGGR_R2
*/
if (nat_traversal_enabled && st->st_connection->ikev1_natt != NATT_NONE) {
/* adjust our destination port if necessary */
nat_traversal_change_port_lookup(md, st);
v1_maybe_natify_initiator_endpoints(st, HERE);
}
/*
* Save both the received packet, and this
* state-transition.
*
* Only when the (last) state transition was a "reply"
* should a duplicate packet trigger a retransmit
* (else they get discarded).
*
* XXX: .st_state .fs_flags & SMF_REPLY can't
* be used because it contains flags for the new state
* not the old-to-new state transition.
*/
remember_received_packet(st, md);
st->st_v1_last_transition = md->smc;
/* if requested, send the new reply packet */
if (smc->flags & SMF_REPLY) {
endpoint_buf b;
endpoint_buf b2;
pexpect_st_local_endpoint(st);
dbg("sending reply packet to %s (from %s)",
str_endpoint(&st->st_remote_endpoint, &b),
str_endpoint(&st->st_interface->local_endpoint, &b2));
close_output_pbs(&reply_stream); /* good form, but actually a no-op */
if (st->st_state->kind == STATE_MAIN_R2 &&
impair.send_no_main_r2) {
/* record-only so we propely emulate packet drop */
record_outbound_v1_ike_msg(st, &reply_stream,
finite_states[from_state]->name);
libreswan_log("IMPAIR: Skipped sending STATE_MAIN_R2 response packet");
} else {
record_and_send_v1_ike_msg(st, &reply_stream,
finite_states[from_state]->name);
}
}
/* Schedule for whatever timeout is specified */
if (!md->event_already_set) {
DBG(DBG_CONTROL, DBG_log("!event_already_set at reschedule"));
intmax_t delay_ms; /* delay is in milliseconds here */
enum event_type kind = smc->timeout_event;
bool agreed_time = FALSE;
struct connection *c = st->st_connection;
/* fixup in case of state machine jump for xauth without modecfg */
if (c->spd.this.xauth_client &&
st->hidden_variables.st_xauth_client_done &&
!c->spd.this.modecfg_client &&
(st->st_state->kind == STATE_MAIN_I4 || st->st_state->kind == STATE_AGGR_I2))
{
DBG(DBG_CONTROL, DBG_log("fixup XAUTH without ModeCFG event from EVENT_RETRANSMIT to EVENT_SA_REPLACE"));
kind = EVENT_SA_REPLACE;
}
switch (kind) {
case EVENT_RETRANSMIT: /* Retransmit packet */
start_retransmits(st);
break;
case EVENT_SA_REPLACE: /* SA replacement event */
if (IS_PHASE1(st->st_state->kind) ||
IS_PHASE15(st->st_state->kind)) {
/* Note: we will defer to the "negotiated" (dictated)
* lifetime if we are POLICY_DONT_REKEY.
* This allows the other side to dictate
* a time we would not otherwise accept
* but it prevents us from having to initiate
* rekeying. The negative consequences seem
* minor.
*/
delay_ms = deltamillisecs(c->sa_ike_life_seconds);
if ((c->policy & POLICY_DONT_REKEY) ||
delay_ms >= deltamillisecs(st->st_oakley.life_seconds))
{
agreed_time = TRUE;
delay_ms = deltamillisecs(st->st_oakley.life_seconds);
}
} else {
/* Delay is min of up to four things:
* each can limit the lifetime.
*/
time_t delay = deltasecs(c->sa_ipsec_life_seconds);
#define clamp_delay(trans) { \
if (st->trans.present && \
delay >= deltasecs(st->trans.attrs.life_seconds)) { \
agreed_time = TRUE; \
delay = deltasecs(st->trans.attrs.life_seconds); \
} \
}
clamp_delay(st_ah);
clamp_delay(st_esp);
clamp_delay(st_ipcomp);
delay_ms = delay * 1000;
#undef clamp_delay
}
/* By default, we plan to rekey.
*
* If there isn't enough time to rekey, plan to
* expire.
*
* If we are --dontrekey, a lot more rules apply.
* If we are the Initiator, use REPLACE_IF_USED.
* If we are the Responder, and the dictated time
* was unacceptable (too large), plan to REPLACE
* (the only way to ratchet down the time).
* If we are the Responder, and the dictated time
* is acceptable, plan to EXPIRE.
*
* Important policy lies buried here.
* For example, we favour the initiator over the
* responder by making the initiator start rekeying
* sooner. Also, fuzz is only added to the
* initiator's margin.
*
* Note: for ISAKMP SA, we let the negotiated
* time stand (implemented by earlier logic).
*/
if (agreed_time &&
(c->policy & POLICY_DONT_REKEY)) {
kind = (smc->flags & SMF_INITIATOR) ?
EVENT_v1_SA_REPLACE_IF_USED :
EVENT_SA_EXPIRE;
}
if (kind != EVENT_SA_EXPIRE) {
time_t marg =
deltasecs(c->sa_rekey_margin);
if (smc->flags & SMF_INITIATOR) {
marg += marg *
c->sa_rekey_fuzz /
100.E0 *
(rand() /
(RAND_MAX + 1.E0));
} else {
marg /= 2;
}
if (delay_ms > marg * 1000) {
delay_ms -= marg * 1000;
st->st_replace_margin = deltatime(marg);
} else {
kind = EVENT_SA_EXPIRE;
}
}
/* XXX: DELAY_MS should be a deltatime_t */
event_schedule(kind, deltatime_ms(delay_ms), st);
break;
case EVENT_SO_DISCARD:
event_schedule(EVENT_SO_DISCARD, c->r_timeout, st);
break;
default:
bad_case(kind);
}
}
/* tell whack and log of progress */
{
enum rc_type w;
void (*log_details)(struct lswlog *buf, struct state *st);
if (IS_IPSEC_SA_ESTABLISHED(st)) {
pstat_sa_established(st);
log_details = lswlog_child_sa_established;
w = RC_SUCCESS; /* log our success */
} else if (IS_ISAKMP_SA_ESTABLISHED(st->st_state)) {
pstat_sa_established(st);
log_details = lswlog_ike_sa_established;
w = RC_SUCCESS; /* log our success */
} else {
log_details = NULL;
w = RC_NEW_V1_STATE + st->st_state->kind;
}
passert(st->st_state->kind < STATE_IKEv1_ROOF);
/* tell whack and logs our progress */
LSWLOG_RC(w, buf) {
lswlogf(buf, "%s: %s", st->st_state->name,
st->st_state->story);
/* document SA details for admin's pleasure */
if (log_details != NULL) {
log_details(buf, st);
}
}
}
/*
* make sure that a DPD event gets created for a new phase 1
* SA.
* Why do we need a DPD event on an IKE SA???
*/
if (IS_ISAKMP_SA_ESTABLISHED(st->st_state)) {
if (dpd_init(st) != STF_OK) {
loglog(RC_LOG_SERIOUS, "DPD initialization failed - continuing without DPD");
}
}
/* Special case for XAUTH server */
if (st->st_connection->spd.this.xauth_server) {
if (st->st_oakley.doing_xauth &&
IS_ISAKMP_SA_ESTABLISHED(st->st_state)) {
DBG(DBG_CONTROLMORE|DBG_XAUTH,
DBG_log("XAUTH: Sending XAUTH Login/Password Request"));
event_schedule(EVENT_v1_SEND_XAUTH,
deltatime_ms(EVENT_v1_SEND_XAUTH_DELAY_MS),
st);
break;
}
}
/*
* for XAUTH client, we are also done, because we need to
* stay in this state, and let the server query us
*/
if (!IS_QUICK(st->st_state->kind) &&
st->st_connection->spd.this.xauth_client &&
!st->hidden_variables.st_xauth_client_done) {
DBG(DBG_CONTROL,
DBG_log("XAUTH client is not yet authenticated"));
break;
}
/*
* when talking to some vendors, we need to initiate a mode
* cfg request to get challenged, but there is also an
* override in the form of a policy bit.
*/
DBG(DBG_CONTROL,
DBG_log("modecfg pull: %s policy:%s %s",
(st->quirks.modecfg_pull_mode ?
"quirk-poll" : "noquirk"),
(st->st_connection->policy & POLICY_MODECFG_PULL) ?
"pull" : "push",
(st->st_connection->spd.this.modecfg_client ?
"modecfg-client" : "not-client")));
if (st->st_connection->spd.this.modecfg_client &&
IS_ISAKMP_SA_ESTABLISHED(st->st_state) &&
(st->quirks.modecfg_pull_mode ||
st->st_connection->policy & POLICY_MODECFG_PULL) &&
!st->hidden_variables.st_modecfg_started) {
DBG(DBG_CONTROL,
DBG_log("modecfg client is starting due to %s",
st->quirks.modecfg_pull_mode ? "quirk" :
"policy"));
modecfg_send_request(st);
break;
}
/* Should we set the peer's IP address regardless? */
if (st->st_connection->spd.this.modecfg_server &&
IS_ISAKMP_SA_ESTABLISHED(st->st_state) &&
!st->hidden_variables.st_modecfg_vars_set &&
!(st->st_connection->policy & POLICY_MODECFG_PULL)) {
change_state(st, STATE_MODE_CFG_R1);
set_cur_state(st);
libreswan_log("Sending MODE CONFIG set");
/*
* ??? we ignore the result of modecfg.
* But surely, if it fails, we ought to terminate this exchange.
* What do the RFCs say?
*/
modecfg_start_set(st);
break;
}
/*
* If we are the responder and the client is in "Contivity mode",
* we need to initiate Quick mode
*/
if (!(smc->flags & SMF_INITIATOR) &&
IS_MODE_CFG_ESTABLISHED(st->st_state) &&
(st->st_seen_nortel_vid)) {
libreswan_log("Nortel 'Contivity Mode' detected, starting Quick Mode");
change_state(st, STATE_MAIN_R3); /* ISAKMP is up... */
set_cur_state(st);
quick_outI1(st->st_whack_sock, st, st->st_connection,
st->st_connection->policy, 1, SOS_NOBODY,
NULL /* Setting NULL as this is responder and will not have sec ctx from a flow*/
);
break;
}
/* wait for modecfg_set */
if (st->st_connection->spd.this.modecfg_client &&
IS_ISAKMP_SA_ESTABLISHED(st->st_state) &&
!st->hidden_variables.st_modecfg_vars_set) {
DBG(DBG_CONTROL,
DBG_log("waiting for modecfg set from server"));
break;
}
DBG(DBG_CONTROL,
DBG_log("phase 1 is done, looking for phase 2 to unpend"));
if (smc->flags & SMF_RELEASE_PENDING_P2) {
/* Initiate any Quick Mode negotiations that
* were waiting to piggyback on this Keying Channel.
*
* ??? there is a potential race condition
* if we are the responder: the initial Phase 2
* message might outrun the final Phase 1 message.
*
* so, instead of actually sending the traffic now,
* we schedule an event to do so.
*
* but, in fact, quick_mode will enqueue a cryptographic operation
* anyway, which will get done "later" anyway, so maybe it is just fine
* as it is.
*
*/
unpend(pexpect_ike_sa(st), NULL);
}
if (IS_ISAKMP_SA_ESTABLISHED(st->st_state) ||
IS_IPSEC_SA_ESTABLISHED(st))
release_any_whack(st, HERE, "IKEv1 transitions finished");
if (IS_QUICK(st->st_state->kind))
break;
break;
}
case STF_INTERNAL_ERROR:
/* update the previous packet history */
remember_received_packet(st, md);
log_state(RC_INTERNALERR + md->v1_note, st,
"state transition function for %s had internal error",
st->st_state->name);
release_pending_whacks(st, "internal error");
break;
case STF_FATAL:
passert(st != NULL);
/* update the previous packet history */
remember_received_packet(st, md);
log_state(RC_FATAL, st, "encountered fatal error in state %s",
st->st_state->name);
#ifdef HAVE_NM
if (st->st_connection->remotepeertype == CISCO &&
st->st_connection->nmconfigured) {
if (!do_command(st->st_connection,
&st->st_connection->spd,
"disconnectNM", st))
DBG(DBG_CONTROL,
DBG_log("sending disconnect to NM failed, you may need to do it manually"));
}
#endif
release_pending_whacks(st, "fatal error");
delete_state(st);
md->st = st = NULL;
break;
default: /* a shortcut to STF_FAIL, setting md->note */
passert(result > STF_FAIL);
md->v1_note = result - STF_FAIL;
/* FALL THROUGH */
case STF_FAIL:
{
/* As it is, we act as if this message never happened:
* whatever retrying was in place, remains in place.
*/
/*
* Try to convert the notification into a non-NULL
* string. For NOTHING_WRONG, be vague (at the time
* of writing the enum_names didn't contain
* NOTHING_WRONG, and even if it did "nothing wrong"
* wouldn't exactly help here :-).
*/
const char *notify_name = (md->v1_note == NOTHING_WRONG ? "failed" :
enum_name(&ikev1_notify_names, md->v1_note));
if (notify_name == NULL) {
notify_name = "internal error";
}
/*
* ??? why no call of remember_received_packet?
* Perhaps because the message hasn't been authenticated?
* But then then any duplicate would lose too, I would think.
*/
if (md->v1_note != NOTHING_WRONG) {
/* this will log */
SEND_NOTIFICATION(md->v1_note);
} else {
/* XXX: why whack only? */
log_state(WHACK_STREAM | (RC_NOTIFICATION + md->v1_note), st,
"state transition failed: %s", notify_name);
}
dbg("state transition function for %s failed: %s",
st->st_state->name, notify_name);
#ifdef HAVE_NM
if (st->st_connection->remotepeertype == CISCO &&
st->st_connection->nmconfigured) {
if (!do_command(st->st_connection,
&st->st_connection->spd,
"disconnectNM", st))
DBG(DBG_CONTROL,
DBG_log("sending disconnect to NM failed, you may need to do it manually"));
}
#endif
if (IS_QUICK(st->st_state->kind)) {
delete_state(st);
/* wipe out dangling pointer to st */
md->st = NULL;
}
break;
}
}
}
/*
* note: may change which connection is referenced by md->st->st_connection.
* But only if we are a Main Mode Responder.
*/
bool ikev1_decode_peer_id(struct msg_digest *md, bool initiator, bool aggrmode)
{
struct state *const st = md->st;
struct connection *c = st->st_connection;
const struct payload_digest *const id_pld = md->chain[ISAKMP_NEXT_ID];
const struct isakmp_id *const id = &id_pld->payload.id;
/*
* I think that RFC2407 (IPSEC DOI) 4.6.2 is confused.
* It talks about the protocol ID and Port fields of the ID
* Payload, but they don't exist as such in Phase 1.
* We use more appropriate names.
* isaid_doi_specific_a is in place of Protocol ID.
* isaid_doi_specific_b is in place of Port.
* Besides, there is no good reason for allowing these to be
* other than 0 in Phase 1.
*/
if (st->hidden_variables.st_nat_traversal != LEMPTY &&
id->isaid_doi_specific_a == IPPROTO_UDP &&
(id->isaid_doi_specific_b == 0 ||
id->isaid_doi_specific_b == pluto_nat_port)) {
DBG_log("protocol/port in Phase 1 ID Payload is %d/%d. accepted with port_floating NAT-T",
id->isaid_doi_specific_a, id->isaid_doi_specific_b);
} else if (!(id->isaid_doi_specific_a == 0 &&
id->isaid_doi_specific_b == 0) &&
!(id->isaid_doi_specific_a == IPPROTO_UDP &&
id->isaid_doi_specific_b == pluto_port))
{
loglog(RC_LOG_SERIOUS,
"protocol/port in Phase 1 ID Payload MUST be 0/0 or %d/%d but are %d/%d (attempting to continue)",
IPPROTO_UDP, pluto_port,
id->isaid_doi_specific_a,
id->isaid_doi_specific_b);
/*
* We have turned this into a warning because of bugs in other
* vendors' products. Specifically CISCO VPN3000.
*/
/* return FALSE; */
}
struct id peer;
if (!extract_peer_id(id->isaid_idtype, &peer, &id_pld->pbs))
return FALSE;
if (c->spd.that.id.kind == ID_FROMCERT) {
/* breaks API, connection modified by %fromcert */
duplicate_id(&c->spd.that.id, &peer);
}
/*
* For interop with SoftRemote/aggressive mode we need to remember some
* things for checking the hash
*/
st->st_peeridentity_protocol = id->isaid_doi_specific_a;
st->st_peeridentity_port = ntohs(id->isaid_doi_specific_b);
{
id_buf buf;
libreswan_log("Peer ID is %s: '%s'",
enum_show(&ike_idtype_names, id->isaid_idtype),
str_id(&peer, &buf));
}
/* check for certificates */
if (!v1_verify_certs(md)) {
libreswan_log("X509: CERT payload does not match connection ID");
if (initiator || aggrmode) {
/* cannot switch connection so fail */
return false;
}
}
/* check for certificate requests */
ikev1_decode_cr(md);
/*
* Now that we've decoded the ID payload, let's see if we
* need to switch connections.
* Aggressive mode cannot switch connections.
* We must not switch horses if we initiated:
* - if the initiation was explicit, we'd be ignoring user's intent
* - if opportunistic, we'll lose our HOLD info
*/
if (initiator) {
if (!st->st_peer_alt_id &&
!same_id(&c->spd.that.id, &peer) &&
c->spd.that.id.kind != ID_FROMCERT) {
id_buf expect;
id_buf found;
loglog(RC_LOG_SERIOUS,
"we require IKEv1 peer to have ID '%s', but peer declares '%s'",
str_id(&c->spd.that.id, &expect),
str_id(&peer, &found));
return FALSE;
} else if (c->spd.that.id.kind == ID_FROMCERT) {
if (peer.kind != ID_DER_ASN1_DN) {
loglog(RC_LOG_SERIOUS,
"peer ID is not a certificate type");
return FALSE;
}
duplicate_id(&c->spd.that.id, &peer);
}
} else if (!aggrmode) {
/* Main Mode Responder */
uint16_t auth = xauth_calcbaseauth(st->st_oakley.auth);
lset_t auth_policy;
switch (auth) {
case OAKLEY_PRESHARED_KEY:
auth_policy = POLICY_PSK;
break;
case OAKLEY_RSA_SIG:
auth_policy = POLICY_RSASIG;
break;
/* Not implemented */
case OAKLEY_DSS_SIG:
case OAKLEY_RSA_ENC:
case OAKLEY_RSA_REVISED_MODE:
case OAKLEY_ECDSA_P256:
case OAKLEY_ECDSA_P384:
case OAKLEY_ECDSA_P521:
default:
DBG(DBG_CONTROL, DBG_log("ikev1 ike_decode_peer_id bad_case due to not supported policy"));
return FALSE;
}
bool fromcert;
struct connection *r =
refine_host_connection(st, &peer,
NULL, /* IKEv1 does not support 'you Tarzan, me Jane' */
FALSE, /* we are responder */
auth_policy,
AUTHBY_UNSET, /* ikev2 only */
&fromcert);
if (r == NULL) {
DBG(DBG_CONTROL, {
id_buf buf;
DBG_log("no more suitable connection for peer '%s'",
str_id(&peer, &buf));
});
/* can we continue with what we had? */
if (!md->st->st_peer_alt_id &&
!same_id(&c->spd.that.id, &peer) &&
c->spd.that.id.kind != ID_FROMCERT) {
libreswan_log("Peer mismatch on first found connection and no better connection found");
return FALSE;
} else {
DBG(DBG_CONTROL, DBG_log("Peer ID matches and no better connection found - continuing with existing connection"));
r = c;
}
}
if (DBGP(DBG_BASE)) {
dn_buf buf;
DBG_log("offered CA: '%s'",
str_dn_or_null(r->spd.this.ca, "%none", &buf));
}
if (r != c) {
/*
* We are changing st->st_connection!
* Our caller might be surprised!
*/
char b1[CONN_INST_BUF];
char b2[CONN_INST_BUF];
/* apparently, r is an improvement on c -- replace */
libreswan_log("switched from \"%s\"%s to \"%s\"%s",
c->name,
fmt_conn_instance(c, b1),
r->name,
fmt_conn_instance(r, b2));
if (r->kind == CK_TEMPLATE || r->kind == CK_GROUP) {
/* instantiate it, filling in peer's ID */
r = rw_instantiate(r, &c->spd.that.host_addr,
NULL,
&peer);
}
update_state_connection(st, r);
c = r; /* c not subsequently used */
/* redo from scratch so we read and check CERT payload */
DBG(DBG_CONTROL, DBG_log("retrying ike_decode_peer_id() with new conn"));
passert(!initiator && !aggrmode);
return ikev1_decode_peer_id(md, FALSE, FALSE);
} else if (c->spd.that.has_id_wildcards) {
duplicate_id(&c->spd.that.id, &peer);
c->spd.that.has_id_wildcards = FALSE;
} else if (fromcert) {
DBG(DBG_CONTROL, DBG_log("copying ID for fromcert"));
duplicate_id(&c->spd.that.id, &peer);
}
}
return TRUE;
}
bool ikev1_ship_chain(chunk_t *chain, int n, pb_stream *outs,
uint8_t type)
{
for (int i = 0; i < n; i++) {
if (!ikev1_ship_CERT(type, chain[i], outs))
return false;
}
return true;
}
void doi_log_cert_thinking(uint16_t auth,
enum ike_cert_type certtype,
enum certpolicy policy,
bool gotcertrequest,
bool send_cert,
bool send_chain)
{
DBG(DBG_CONTROL, {
DBG_log("thinking about whether to send my certificate:");
struct esb_buf oan;
struct esb_buf ictn;
DBG_log(" I have RSA key: %s cert.type: %s ",
enum_showb(&oakley_auth_names, auth, &oan),
enum_showb(&ike_cert_type_names, certtype, &ictn));
struct esb_buf cptn;
DBG_log(" sendcert: %s and I did%s get a certificate request ",
enum_showb(&certpolicy_type_names, policy, &cptn),
gotcertrequest ? "" : " not");
DBG_log(" so %ssend cert.", send_cert ? "" : "do not ");
if (!send_cert) {
if (auth == OAKLEY_PRESHARED_KEY) {
DBG_log("I did not send a certificate because digital signatures are not being used. (PSK)");
} else if (certtype == CERT_NONE) {
DBG_log("I did not send a certificate because I do not have one.");
} else if (policy == CERT_SENDIFASKED) {
DBG_log("I did not send my certificate because I was not asked to.");
} else {
DBG_log("INVALID AUTH SETTING: %d", auth);
}
}
if (send_chain)
DBG_log("Sending one or more authcerts");
});
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/good_4250_0 |
crossvul-cpp_data_good_146_0 | /* radare2 - LGPL - Copyright 2009-2018 - pancake, nibble, dso */
#include <r_bin.h>
// maybe too big sometimes? 2KB of stack eaten here..
#define R_STRING_SCAN_BUFFER_SIZE 2048
static void print_string(RBinString *string, RBinFile *bf) {
if (!string || !bf) {
return;
}
int mode = bf->strmode;
ut64 addr , vaddr;
RBin *bin = bf->rbin;
const char *section_name, *type_string;
RIO *io = bin->iob.io;
if (!io) {
return;
}
RBinSection *s = r_bin_get_section_at (bf->o, string->paddr, false);
if (s) {
string->vaddr = s->vaddr + (string->paddr - s->paddr);
}
section_name = s ? s->name : "";
type_string = r_bin_string_type (string->type);
vaddr = addr = r_bin_get_vaddr (bin, string->paddr, string->vaddr);
switch(mode) {
case MODE_SIMPLE :
io->cb_printf ("0x%08" PFMT64x " %s\n", addr, string->string);
break;
case MODE_RADARE :
{
char *f_name, *nstr;
f_name = strdup (string->string);
r_name_filter (f_name, 512);
if (bin->prefix) {
nstr = r_str_newf ("%s.str.%s", bin->prefix, f_name);
io->cb_printf ("f %s.str.%s %"PFMT64d" @ 0x%08"PFMT64x"\n"
"Cs %"PFMT64d" @ 0x%08"PFMT64x"\n",
bin->prefix, f_name, string->size, addr,
string->size, addr);
} else {
nstr = r_str_newf ("str.%s", f_name);
io->cb_printf ("f str.%s %"PFMT64d" @ 0x%08"PFMT64x"\n"
"Cs %"PFMT64d" @ 0x%08"PFMT64x"\n",
f_name, string->size, addr,
string->size, addr);
}
free (nstr);
free (f_name);
break;
}
case MODE_PRINT :
io->cb_printf ("%03u 0x%08"PFMT64x" 0x%08"
PFMT64x" %3u %3u "
"(%s) %5s %s\n",
string->ordinal, string->paddr, vaddr,
string->length, string->size,
section_name, type_string, string->string);
break;
}
}
static int string_scan_range(RList *list, RBinFile *bf, int min,
const ut64 from, const ut64 to, int type) {
ut8 tmp[R_STRING_SCAN_BUFFER_SIZE];
ut64 str_start, needle = from;
int count = 0, i, rc, runes;
int str_type = R_STRING_TYPE_DETECT;
if (type == -1) {
type = R_STRING_TYPE_DETECT;
}
if (from >= to) {
eprintf ("Invalid range to find strings 0x%llx .. 0x%llx\n", from, to);
return -1;
}
int len = to - from;
ut8 *buf = calloc (len, 1);
if (!buf || !min) {
return -1;
}
r_buf_read_at (bf->buf, from, buf, len);
// may oobread
while (needle < to) {
rc = r_utf8_decode (buf + needle - from, to - needle, NULL);
if (!rc) {
needle++;
continue;
}
if (type == R_STRING_TYPE_DETECT) {
char *w = (char *)buf + needle + rc - from;
if ((to - needle) > 5 + rc) {
bool is_wide32 = (needle + rc + 2 < to) && (!w[0] && !w[1] && !w[2] && w[3] && !w[4]);
if (is_wide32) {
str_type = R_STRING_TYPE_WIDE32;
} else {
bool is_wide = needle + rc + 2 < to && !w[0] && w[1] && !w[2];
str_type = is_wide? R_STRING_TYPE_WIDE: R_STRING_TYPE_ASCII;
}
} else {
str_type = R_STRING_TYPE_ASCII;
}
} else {
str_type = type;
}
runes = 0;
str_start = needle;
/* Eat a whole C string */
for (rc = i = 0; i < sizeof (tmp) - 3 && needle < to; i += rc) {
RRune r = {0};
if (str_type == R_STRING_TYPE_WIDE32) {
rc = r_utf32le_decode (buf + needle - from, to - needle, &r);
if (rc) {
rc = 4;
}
} else if (str_type == R_STRING_TYPE_WIDE) {
rc = r_utf16le_decode (buf + needle - from, to - needle, &r);
if (rc == 1) {
rc = 2;
}
} else {
rc = r_utf8_decode (buf + needle - from, to - needle, &r);
if (rc > 1) {
str_type = R_STRING_TYPE_UTF8;
}
}
/* Invalid sequence detected */
if (!rc) {
needle++;
break;
}
needle += rc;
if (r_isprint (r) && r != '\\') {
if (str_type == R_STRING_TYPE_WIDE32) {
if (r == 0xff) {
r = 0;
}
}
rc = r_utf8_encode (&tmp[i], r);
runes++;
/* Print the escape code */
} else if (r && r < 0x100 && strchr ("\b\v\f\n\r\t\a\033\\", (char)r)) {
if ((i + 32) < sizeof (tmp) && r < 93) {
tmp[i + 0] = '\\';
tmp[i + 1] = " abtnvfr e "
" "
" "
" \\"[r];
} else {
// string too long
break;
}
rc = 2;
runes++;
} else {
/* \0 marks the end of C-strings */
break;
}
}
tmp[i++] = '\0';
if (runes >= min) {
if (str_type == R_STRING_TYPE_ASCII) {
// reduce false positives
int j;
for (j = 0; j < i; j++) {
char ch = tmp[j];
if (ch != '\n' && ch != '\r' && ch != '\t') {
if (!IS_PRINTABLE (tmp[j])) {
continue;
}
}
}
}
RBinString *bs = R_NEW0 (RBinString);
if (!bs) {
break;
}
bs->type = str_type;
bs->length = runes;
bs->size = needle - str_start;
bs->ordinal = count++;
// TODO: move into adjust_offset
switch (str_type) {
case R_STRING_TYPE_WIDE:
if (str_start -from> 1) {
const ut8 *p = buf + str_start - 2 - from;
if (p[0] == 0xff && p[1] == 0xfe) {
str_start -= 2; // \xff\xfe
}
}
break;
case R_STRING_TYPE_WIDE32:
if (str_start -from> 3) {
const ut8 *p = buf + str_start - 4 - from;
if (p[0] == 0xff && p[1] == 0xfe) {
str_start -= 4; // \xff\xfe\x00\x00
}
}
break;
}
bs->paddr = bs->vaddr = str_start;
bs->string = r_str_ndup ((const char *)tmp, i);
if (list) {
r_list_append (list, bs);
} else {
print_string (bs, bf);
r_bin_string_free (bs);
}
}
}
free (buf);
return count;
}
static char *swiftField(const char *dn, const char *cn) {
char *p = strstr (dn, ".getter_");
if (!p) {
p = strstr (dn, ".setter_");
if (!p) {
p = strstr (dn, ".method_");
}
}
if (p) {
char *q = strstr (dn, cn);
if (q && q[strlen (cn)] == '.') {
q = strdup (q + strlen (cn) + 1);
char *r = strchr (q, '.');
if (r) {
*r = 0;
}
return q;
}
}
return NULL;
}
R_API RList *r_bin_classes_from_symbols (RBinFile *bf, RBinObject *o) {
RBinSymbol *sym;
RListIter *iter;
RList *symbols = o->symbols;
RList *classes = o->classes;
if (!classes) {
classes = r_list_newf ((RListFree)r_bin_class_free);
}
r_list_foreach (symbols, iter, sym) {
if (sym->name[0] != '_') {
continue;
}
const char *cn = sym->classname;
if (cn) {
RBinClass *c = r_bin_class_new (bf, sym->classname, NULL, 0);
if (!c) {
continue;
}
// swift specific
char *dn = sym->dname;
char *fn = swiftField (dn, cn);
if (fn) {
// eprintf ("FIELD %s %s\n", cn, fn);
RBinField *f = r_bin_field_new (sym->paddr, sym->vaddr, sym->size, fn, NULL, NULL);
r_list_append (c->fields, f);
free (fn);
} else {
char *mn = strstr (dn, "..");
if (mn) {
// eprintf ("META %s %s\n", sym->classname, mn);
} else {
char *mn = strstr (dn, cn);
if (mn && mn[strlen(cn)] == '.') {
mn += strlen (cn) + 1;
// eprintf ("METHOD %s %s\n", sym->classname, mn);
r_list_append (c->methods, sym);
}
}
}
}
}
if (r_list_empty (classes)) {
r_list_free (classes);
return NULL;
}
return classes;
}
R_API RBinFile *r_bin_file_new(RBin *bin, const char *file, const ut8 *bytes, ut64 sz, ut64 file_sz, int rawstr, int fd, const char *xtrname, Sdb *sdb, bool steal_ptr) {
RBinFile *binfile = R_NEW0 (RBinFile);
if (!binfile) {
return NULL;
}
if (!r_id_pool_grab_id (bin->file_ids, &binfile->id)) {
if (steal_ptr) { // we own the ptr, free on error
free ((void*) bytes);
}
free (binfile); //no id means no binfile
return NULL;
}
int res = r_bin_file_set_bytes (binfile, bytes, sz, steal_ptr);
if (!res && steal_ptr) { // we own the ptr, free on error
free((void*) bytes);
}
binfile->rbin = bin;
binfile->file = file? strdup (file): NULL;
binfile->rawstr = rawstr;
binfile->fd = fd;
binfile->curxtr = r_bin_get_xtrplugin_by_name (bin, xtrname);
binfile->sdb = sdb;
binfile->size = file_sz;
binfile->xtr_data = r_list_newf ((RListFree)r_bin_xtrdata_free);
binfile->objs = r_list_newf ((RListFree)r_bin_object_free);
binfile->xtr_obj = NULL;
if (!binfile->buf) {
//r_bin_file_free (binfile);
binfile->buf = r_buf_new ();
// return NULL;
}
if (sdb) {
binfile->sdb = sdb_ns (sdb, sdb_fmt ("fd.%d", fd), 1);
sdb_set (binfile->sdb, "archs", "0:0:x86:32", 0); // x86??
/* NOTE */
/* Those refs++ are necessary because sdb_ns() doesnt rerefs all
* sub-namespaces */
/* And if any namespace is referenced backwards it gets
* double-freed */
binfile->sdb_addrinfo = sdb_ns (binfile->sdb, "addrinfo", 1);
binfile->sdb_addrinfo->refs++;
sdb_ns_set (sdb, "cur", binfile->sdb);
binfile->sdb->refs++;
}
return binfile;
}
R_API bool r_bin_file_object_new_from_xtr_data(RBin *bin, RBinFile *bf, ut64 baseaddr, ut64 loadaddr, RBinXtrData *data) {
RBinObject *o = NULL;
RBinPlugin *plugin = NULL;
ut8* bytes;
ut64 offset = data? data->offset: 0;
ut64 sz = data ? data->size : 0;
if (!data || !bf) {
return false;
}
// for right now the bytes used will just be the offest into the binfile
// buffer
// if the extraction requires some sort of transformation then this will
// need to be fixed
// here.
bytes = data->buffer;
if (!bytes) {
return false;
}
plugin = r_bin_get_binplugin_by_bytes (bin, (const ut8*)bytes, sz);
if (!plugin) {
plugin = r_bin_get_binplugin_any (bin);
}
r_buf_free (bf->buf);
bf->buf = r_buf_new_with_bytes ((const ut8*)bytes, data->size);
//r_bin_object_new append the new object into binfile
o = r_bin_object_new (bf, plugin, baseaddr, loadaddr, offset, sz);
// size is set here because the reported size of the object depends on
// if loaded from xtr plugin or partially read
if (!o) {
return false;
}
if (o && !o->size) {
o->size = sz;
}
bf->narch = data->file_count;
if (!o->info) {
o->info = R_NEW0 (RBinInfo);
}
free (o->info->file);
free (o->info->arch);
free (o->info->machine);
free (o->info->type);
o->info->file = strdup (bf->file);
o->info->arch = strdup (data->metadata->arch);
o->info->machine = strdup (data->metadata->machine);
o->info->type = strdup (data->metadata->type);
o->info->bits = data->metadata->bits;
o->info->has_crypto = bf->o->info->has_crypto;
data->loaded = true;
return true;
}
R_API RBinFile *r_bin_file_new_from_fd(RBin *bin, int fd, RBinFileOptions *options) {
int file_sz = 0;
RBinPlugin *plugin = NULL;
RBinFile *bf = r_bin_file_create_append (bin, "-", NULL, 0, file_sz,
0, fd, NULL, false);
if (!bf) {
return NULL;
}
int loadaddr = options? options->laddr: 0;
int baseaddr = options? options->baddr: 0;
// int loadaddr = options? options->laddr: 0;
bool binfile_created = true;
r_buf_free (bf->buf);
bf->buf = r_buf_new_with_io (&bin->iob, fd);
if (bin->force) {
plugin = r_bin_get_binplugin_by_name (bin, bin->force);
}
if (!plugin) {
if (options && options->plugname) {
plugin = r_bin_get_binplugin_by_name (bin, options->plugname);
}
if (!plugin) {
ut8 bytes[1024];
int sz = 1024;
r_buf_read_at (bf->buf, 0, bytes, sz);
plugin = r_bin_get_binplugin_by_bytes (bin, bytes, sz);
if (!plugin) {
plugin = r_bin_get_binplugin_any (bin);
}
}
}
RBinObject *o = r_bin_object_new (bf, plugin, baseaddr, loadaddr, 0, r_buf_size (bf->buf));
// size is set here because the reported size of the object depends on
// if loaded from xtr plugin or partially read
if (o && !o->size) {
o->size = file_sz;
}
if (!o) {
if (bf && binfile_created) {
r_list_delete_data (bin->binfiles, bf);
}
return NULL;
}
#if 0
/* WTF */
if (strcmp (plugin->name, "any")) {
bf->narch = 1;
}
#endif
/* free unnecessary rbuffer (???) */
return bf;
}
R_API RBinFile *r_bin_file_new_from_bytes(RBin *bin, const char *file, const ut8 *bytes, ut64 sz, ut64 file_sz, int rawstr, ut64 baseaddr, ut64 loadaddr, int fd, const char *pluginname, const char *xtrname, ut64 offset, bool steal_ptr) {
ut8 binfile_created = false;
RBinPlugin *plugin = NULL;
RBinXtrPlugin *xtr = NULL;
RBinObject *o = NULL;
if (sz == UT64_MAX) {
return NULL;
}
if (xtrname) {
xtr = r_bin_get_xtrplugin_by_name (bin, xtrname);
}
if (xtr && xtr->check_bytes (bytes, sz)) {
return r_bin_file_xtr_load_bytes (bin, xtr, file,
bytes, sz, file_sz, baseaddr, loadaddr, 0,
fd, rawstr);
}
RBinFile *bf = r_bin_file_create_append (bin, file, bytes, sz, file_sz,
rawstr, fd, xtrname, steal_ptr);
if (!bf) {
if (!steal_ptr) { // we own the ptr, free on error
free ((void*) bytes);
}
return NULL;
}
binfile_created = true;
if (bin->force) {
plugin = r_bin_get_binplugin_by_name (bin, bin->force);
}
if (!plugin) {
if (pluginname) {
plugin = r_bin_get_binplugin_by_name (bin, pluginname);
}
if (!plugin) {
plugin = r_bin_get_binplugin_by_bytes (bin, bytes, sz);
if (!plugin) {
plugin = r_bin_get_binplugin_any (bin);
}
}
}
o = r_bin_object_new (bf, plugin, baseaddr, loadaddr, 0, r_buf_size (bf->buf));
// size is set here because the reported size of the object depends on
// if loaded from xtr plugin or partially read
if (o && !o->size) {
o->size = file_sz;
}
if (!o) {
if (bf && binfile_created) {
r_list_delete_data (bin->binfiles, bf);
}
return NULL;
}
#if 0
/* WTF */
if (strcmp (plugin->name, "any")) {
bf->narch = 1;
}
#endif
/* free unnecessary rbuffer (???) */
return bf;
}
R_API RBinFile *r_bin_file_find_by_arch_bits(RBin *bin, const char *arch, int bits, const char *name) {
RListIter *iter;
RBinFile *binfile = NULL;
RBinXtrData *xtr_data;
if (!name || !arch) {
return NULL;
}
r_list_foreach (bin->binfiles, iter, binfile) {
RListIter *iter_xtr;
if (!binfile->xtr_data) {
continue;
}
// look for sub-bins in Xtr Data and Load if we need to
r_list_foreach (binfile->xtr_data, iter_xtr, xtr_data) {
if (xtr_data->metadata && xtr_data->metadata->arch) {
char *iter_arch = xtr_data->metadata->arch;
int iter_bits = xtr_data->metadata->bits;
if (bits == iter_bits && !strcmp (iter_arch, arch)) {
if (!xtr_data->loaded) {
if (!r_bin_file_object_new_from_xtr_data (
bin, binfile, xtr_data->baddr,
xtr_data->laddr, xtr_data)) {
return NULL;
}
return binfile;
}
}
}
}
}
return binfile;
}
R_API RBinObject *r_bin_file_object_find_by_id(RBinFile *binfile, ut32 binobj_id) {
RBinObject *obj;
RListIter *iter;
if (binfile) {
r_list_foreach (binfile->objs, iter, obj) {
if (obj->id == binobj_id) {
return obj;
}
}
}
return NULL;
}
R_API RBinFile *r_bin_file_find_by_object_id(RBin *bin, ut32 binobj_id) {
RListIter *iter;
RBinFile *binfile;
r_list_foreach (bin->binfiles, iter, binfile) {
if (r_bin_file_object_find_by_id (binfile, binobj_id)) {
return binfile;
}
}
return NULL;
}
R_API RBinFile *r_bin_file_find_by_id(RBin *bin, ut32 binfile_id) {
RBinFile *binfile = NULL;
RListIter *iter = NULL;
r_list_foreach (bin->binfiles, iter, binfile) {
if (binfile->id == binfile_id) {
break;
}
binfile = NULL;
}
return binfile;
}
R_API int r_bin_file_object_add(RBinFile *binfile, RBinObject *o) {
if (!o) {
return false;
}
r_list_append (binfile->objs, o);
r_bin_file_set_cur_binfile_obj (binfile->rbin, binfile, o);
return true;
}
R_API int r_bin_file_delete_all(RBin *bin) {
int counter = 0;
if (bin) {
counter = r_list_length (bin->binfiles);
r_list_purge (bin->binfiles);
bin->cur = NULL;
}
return counter;
}
R_API int r_bin_file_delete(RBin *bin, ut32 bin_fd) {
RListIter *iter;
RBinFile *bf;
RBinFile *cur = r_bin_cur (bin);
if (bin && cur) {
r_list_foreach (bin->binfiles, iter, bf) {
if (bf && bf->fd == bin_fd) {
if (cur->fd == bin_fd) {
//avoiding UaF due to dead reference
bin->cur = NULL;
}
r_list_delete (bin->binfiles, iter);
return 1;
}
}
}
return 0;
}
R_API RBinFile *r_bin_file_find_by_fd(RBin *bin, ut32 bin_fd) {
RListIter *iter;
RBinFile *bf;
if (bin) {
r_list_foreach (bin->binfiles, iter, bf) {
if (bf && bf->fd == bin_fd) {
return bf;
}
}
}
return NULL;
}
R_API RBinFile *r_bin_file_find_by_name(RBin *bin, const char *name) {
RListIter *iter;
RBinFile *bf = NULL;
if (!bin || !name) {
return NULL;
}
r_list_foreach (bin->binfiles, iter, bf) {
if (bf && bf->file && !strcmp (bf->file, name)) {
break;
}
bf = NULL;
}
return bf;
}
R_API RBinFile *r_bin_file_find_by_name_n(RBin *bin, const char *name, int idx) {
RListIter *iter;
RBinFile *bf = NULL;
int i = 0;
if (!bin) {
return bf;
}
r_list_foreach (bin->binfiles, iter, bf) {
if (bf && bf->file && !strcmp (bf->file, name)) {
if (i == idx) {
break;
}
i++;
}
bf = NULL;
}
return bf;
}
R_API int r_bin_file_set_cur_by_fd(RBin *bin, ut32 bin_fd) {
RBinFile *bf = r_bin_file_find_by_fd (bin, bin_fd);
return r_bin_file_set_cur_binfile (bin, bf);
}
R_API bool r_bin_file_set_cur_binfile_obj(RBin *bin, RBinFile *bf, RBinObject *obj) {
RBinPlugin *plugin = NULL;
if (!bin || !bf || !obj) {
return false;
}
bin->file = bf->file;
bin->cur = bf;
bin->narch = bf->narch;
bf->o = obj;
plugin = r_bin_file_cur_plugin (bf);
if (bin->minstrlen < 1) {
bin->minstrlen = plugin? plugin->minstrlen: bin->minstrlen;
}
return true;
}
R_API int r_bin_file_set_cur_binfile(RBin *bin, RBinFile *bf) {
RBinObject *obj = bf? bf->o: NULL;
return r_bin_file_set_cur_binfile_obj (bin, bf, obj);
}
R_API int r_bin_file_set_cur_by_name(RBin *bin, const char *name) {
RBinFile *bf = r_bin_file_find_by_name (bin, name);
return r_bin_file_set_cur_binfile (bin, bf);
}
R_API RBinObject *r_bin_file_object_get_cur(RBinFile *binfile) {
return binfile? binfile->o: NULL;
}
R_API int r_bin_file_cur_set_plugin(RBinFile *binfile, RBinPlugin *plugin) {
if (binfile && binfile->o) {
binfile->o->plugin = plugin;
return true;
}
return false;
}
R_API int r_bin_file_deref_by_bind(RBinBind *binb) {
RBin *bin = binb? binb->bin: NULL;
RBinFile *a = r_bin_cur (bin);
return r_bin_file_deref (bin, a);
}
R_API int r_bin_file_deref(RBin *bin, RBinFile *a) {
RBinObject *o = r_bin_cur_object (bin);
int res = false;
if (a && !o) {
//r_list_delete_data (bin->binfiles, a);
res = true;
} else if (a && o->referenced - 1 < 1) {
//r_list_delete_data (bin->binfiles, a);
res = true;
// not thread safe
} else if (o) {
o->referenced--;
}
// it is possible for a file not
// to be bound to RBin and RBinFiles
// XXX - is this an ok assumption?
if (bin) {
bin->cur = NULL;
}
return res;
}
R_API int r_bin_file_ref_by_bind(RBinBind *binb) {
RBin *bin = binb? binb->bin: NULL;
RBinFile *a = r_bin_cur (bin);
return r_bin_file_ref (bin, a);
}
R_API int r_bin_file_ref(RBin *bin, RBinFile *a) {
RBinObject *o = r_bin_cur_object (bin);
if (a && o) {
o->referenced--;
return true;
}
return false;
}
R_API void r_bin_file_free(void /*RBinFile*/ *bf_) {
RBinFile *a = bf_;
RBinPlugin *plugin = r_bin_file_cur_plugin (a);
if (!a) {
return;
}
// Binary format objects are connected to the
// RBinObject, so the plugin must destroy the
// format data first
if (plugin && plugin->destroy) {
plugin->destroy (a);
}
if (a->curxtr && a->curxtr->destroy && a->xtr_obj) {
a->curxtr->free_xtr ((void *)(a->xtr_obj));
}
r_buf_free (a->buf);
// TODO: unset related sdb namespaces
if (a && a->sdb_addrinfo) {
sdb_free (a->sdb_addrinfo);
a->sdb_addrinfo = NULL;
}
R_FREE (a->file);
a->o = NULL;
r_list_free (a->objs);
r_list_free (a->xtr_data);
if (a->id != -1) {
r_id_pool_kick_id (a->rbin->file_ids, a->id);
}
memset (a, 0, sizeof (RBinFile));
free (a);
}
// This is an unnecessary piece of overengineering
R_API RBinFile *r_bin_file_create_append(RBin *bin, const char *file, const ut8 *bytes, ut64 sz, ut64 file_sz, int rawstr, int fd, const char *xtrname, bool steal_ptr) {
RBinFile *bf = r_bin_file_new (bin, file, bytes, sz, file_sz, rawstr,
fd, xtrname, bin->sdb, steal_ptr);
if (bf) {
r_list_append (bin->binfiles, bf);
}
return bf;
}
// This function populate RBinFile->xtr_data, that information is enough to
// create RBinObject when needed using r_bin_file_object_new_from_xtr_data
R_API RBinFile *r_bin_file_xtr_load_bytes(RBin *bin, RBinXtrPlugin *xtr, const char *filename, const ut8 *bytes, ut64 sz, ut64 file_sz, ut64 baseaddr, ut64 loadaddr, int idx, int fd, int rawstr) {
if (!bin || !bytes) {
return NULL;
}
RBinFile *bf = r_bin_file_find_by_name (bin, filename);
if (!bf) {
bf = r_bin_file_create_append (bin, filename, bytes, sz,
file_sz, rawstr, fd, xtr->name, false);
if (!bf) {
return NULL;
}
if (!bin->cur) {
bin->cur = bf;
}
}
if (bf->xtr_data) {
r_list_free (bf->xtr_data);
}
if (xtr && bytes) {
RList *xtr_data_list = xtr->extractall_from_bytes (bin, bytes, sz);
RListIter *iter;
RBinXtrData *xtr;
//populate xtr_data with baddr and laddr that will be used later on
//r_bin_file_object_new_from_xtr_data
r_list_foreach (xtr_data_list, iter, xtr) {
xtr->baddr = baseaddr? baseaddr : UT64_MAX;
xtr->laddr = loadaddr? loadaddr : UT64_MAX;
}
bf->loadaddr = loadaddr;
bf->xtr_data = xtr_data_list ? xtr_data_list : NULL;
}
return bf;
}
#define LIMIT_SIZE 0
R_API int r_bin_file_set_bytes(RBinFile *binfile, const ut8 *bytes, ut64 sz, bool steal_ptr) {
if (!binfile) {
return false;
}
if (!bytes) {
return false;
}
r_buf_free (binfile->buf);
binfile->buf = r_buf_new ();
#if LIMIT_SIZE
if (sz > 1024 * 1024) {
eprintf ("Too big\n");
// TODO: use r_buf_io instead of setbytes all the time to save memory
return NULL;
}
#else
if (steal_ptr) {
r_buf_set_bytes_steal (binfile->buf, bytes, sz);
} else {
r_buf_set_bytes (binfile->buf, bytes, sz);
}
#endif
return binfile->buf != NULL;
}
R_API RBinPlugin *r_bin_file_cur_plugin(RBinFile *binfile) {
return binfile && binfile->o? binfile->o->plugin: NULL;
}
static int is_data_section(RBinFile *a, RBinSection *s) {
if (s->has_strings || s->is_data) {
return true;
}
if (s->is_data) {
return true;
}
// Rust
return (strstr (s->name, "_const") != NULL);
}
R_API RList *r_bin_file_get_strings(RBinFile *a, int min, int dump) {
RListIter *iter;
RBinSection *section;
RBinObject *o = a? a->o: NULL;
RList *ret;
if (dump) {
/* dump to stdout, not stored in list */
ret = NULL;
} else {
ret = r_list_newf (r_bin_string_free);
if (!ret) {
return NULL;
}
}
if (o && o->sections && !r_list_empty (o->sections) && !a->rawstr) {
r_list_foreach (o->sections, iter, section) {
if (is_data_section (a, section)) {
r_bin_file_get_strings_range (a, ret, min, section->paddr,
section->paddr + section->size);
}
}
r_list_foreach (o->sections, iter, section) {
RBinString *s;
RListIter *iter2;
/* load objc/swift strings */
const int bits = (a->o && a->o->info) ? a->o->info->bits : 32;
const int cfstr_size = (bits == 64) ? 32 : 16;
const int cfstr_offs = (bits == 64) ? 16 : 8;
if (strstr (section->name, "__cfstring")) {
int i;
// XXX do not walk if bin.strings == 0
ut8 *p;
for (i = 0; i < section->size; i += cfstr_size) {
ut8 buf[32];
if (!r_buf_read_at (
a->buf, section->paddr + i + cfstr_offs,
buf, sizeof (buf))) {
break;
}
p = buf;
ut64 cfstr_vaddr = section->vaddr + i;
ut64 cstr_vaddr = (bits == 64)
? r_read_le64 (p)
: r_read_le32 (p);
r_list_foreach (ret, iter2, s) {
if (s->vaddr == cstr_vaddr) {
RBinString *bs = R_NEW0 (RBinString);
if (bs) {
bs->type = s->type;
bs->length = s->length;
bs->size = s->size;
bs->ordinal = s->ordinal;
bs->paddr = bs->vaddr = cfstr_vaddr;
bs->string = r_str_newf ("cstr.%s", s->string);
r_list_append (ret, bs);
}
break;
}
}
}
}
}
} else {
if (a) {
r_bin_file_get_strings_range (a, ret, min, 0, a->size);
}
}
return ret;
}
R_API void r_bin_file_get_strings_range(RBinFile *bf, RList *list, int min, ut64 from, ut64 to) {
RBinPlugin *plugin = r_bin_file_cur_plugin (bf);
RBinString *ptr;
RListIter *it;
if (!bf || !bf->buf) {
return;
}
if (!bf->rawstr) {
if (!plugin || !plugin->info) {
return;
}
}
if (!min) {
min = plugin? plugin->minstrlen: 4;
}
/* Some plugins return zero, fix it up */
if (!min) {
min = 4;
}
if (min < 0) {
return;
}
if (!to || to > bf->buf->length) {
to = r_buf_size (bf->buf);
}
if (!to) {
eprintf ("Empty file with fd %d?\n", bf->buf->fd);
return;
}
if (bf->rawstr != 2) {
ut64 size = to - from;
// in case of dump ignore here
if (bf->rbin->maxstrbuf && size && size > bf->rbin->maxstrbuf) {
if (bf->rbin->verbose) {
eprintf ("WARNING: bin_strings buffer is too big "
"(0x%08" PFMT64x
")."
" Use -zzz or set bin.maxstrbuf "
"(RABIN2_MAXSTRBUF) in r2 (rabin2)\n",
size);
}
return;
}
}
if (string_scan_range (list, bf, min, from, to, -1) < 0) {
return;
}
r_list_foreach (list, it, ptr) {
RBinSection *s = r_bin_get_section_at (bf->o, ptr->paddr, false);
if (s) {
ptr->vaddr = s->vaddr + (ptr->paddr - s->paddr);
}
}
}
R_API ut64 r_bin_file_get_baddr(RBinFile *binfile) {
return binfile? r_bin_object_get_baddr (binfile->o): UT64_MAX;
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/good_146_0 |
crossvul-cpp_data_good_2588_4 | /*
* mus_wm.c -- Midi Wavetable Processing library
*
* Copyright (C) WildMIDI Developers 2001-2016
*
* This file is part of WildMIDI.
*
* WildMIDI is free software: you can redistribute and/or modify the player
* under the terms of the GNU General Public License and you can redistribute
* and/or modify the library under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation, either version 3 of
* the licenses, or(at your option) any later version.
*
* WildMIDI 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 and
* the GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU General Public License and the
* GNU Lesser General Public License along with WildMIDI. If not, see
* <http://www.gnu.org/licenses/>.
*/
#include "config.h"
#include <stdint.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "common.h"
#include "wm_error.h"
#include "wildmidi_lib.h"
#include "internal_midi.h"
#include "reverb.h"
#include "f_mus.h"
#ifdef DEBUG_MUS
#define MUS_EVENT_DEBUG(dx,dy,dz) fprintf(stderr,"\r%s, 0x%.2x, 0x%.8x\n",dx,dy,dz)
#else
#define MUS_EVENT_DEBUG(dx,dy,dz)
#endif
/*
Turns hmp file data into an event stream
*/
struct _mdi *
_WM_ParseNewMus(uint8_t *mus_data, uint32_t mus_size) {
uint8_t mus_hdr[] = { 'M', 'U', 'S', 0x1A };
uint32_t mus_song_ofs = 0;
uint32_t mus_song_len = 0;
uint16_t mus_ch_cnt1 = 0;
uint16_t mus_ch_cnt2 = 0;
uint16_t mus_no_instr = 0;
uint32_t mus_data_ofs = 0;
uint16_t * mus_mid_instr = NULL;
uint16_t mus_instr_cnt = 0;
struct _mdi *mus_mdi;
uint32_t mus_divisions = 60;
float tempo_f = 0.0;
uint16_t mus_freq = 0;
float samples_per_tick_f = 0.0;
#define MUS_SZ 4
uint8_t mus_event[MUS_SZ] = { 0, 0, 0, 0 };
uint8_t mus_event_size = 0;
uint8_t mus_prev_vol[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
uint32_t setup_ret = 0;
uint32_t mus_ticks = 0;
uint32_t sample_count = 0;
float sample_count_f = 0.0;
float sample_remainder = 0.0;
uint16_t pitchbend_tmp = 0;
if (mus_size < 17) {
_WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_NOT_MUS, "File too short", 0);
return NULL;
}
if (memcmp(mus_data, mus_hdr, 4)) {
_WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_NOT_MUS, NULL, 0);
return NULL;
}
// Get Song Length
mus_song_len = (mus_data[5] << 8) | mus_data[4];
// Get Song Offset
mus_song_ofs = (mus_data[7] << 8) | mus_data[6];
// Have yet to determine what this actually is.
mus_ch_cnt1 = (mus_data[9] << 8) | mus_data[8];
mus_ch_cnt2 = (mus_data[11] << 8) | mus_data[10];
UNUSED(mus_ch_cnt1);
UNUSED(mus_ch_cnt2);
// Number of instruments defined
mus_no_instr = (mus_data[13] << 8) | mus_data[12];
// Skip next 2 data bytes
mus_data_ofs = 16;
// Check that we have enough data to check the rest
if (mus_size < (mus_data_ofs + (mus_no_instr << 1) + mus_song_len)) {
_WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_NOT_MUS, "File too short", 0);
return NULL;
}
// Instrument definition
mus_mid_instr = malloc(mus_no_instr * sizeof(uint16_t));
for (mus_instr_cnt = 0; mus_instr_cnt < mus_no_instr; mus_instr_cnt++) {
mus_mid_instr[mus_instr_cnt] = (mus_data[mus_data_ofs + 1] << 8) | mus_data[mus_data_ofs];
mus_data_ofs += 2;
}
// make sure we are at song offset
mus_data_ofs = mus_song_ofs;
// do some calculations so we know how many samples per mus tick
mus_freq = _cvt_get_option(WM_CO_FREQUENCY);
if (mus_freq == 0) mus_freq = 140;
if ((_WM_MixerOptions & WM_MO_ROUNDTEMPO)) {
tempo_f = (float) (60000000 / mus_freq) + 0.5f;
} else {
tempo_f = (float) (60000000 / mus_freq);
}
samples_per_tick_f = _WM_GetSamplesPerTick(mus_divisions, (uint32_t)tempo_f);
// initialise the mdi structure
mus_mdi = _WM_initMDI();
_WM_midi_setup_divisions(mus_mdi, mus_divisions);
_WM_midi_setup_tempo(mus_mdi, (uint32_t)tempo_f);
// lets do this
do {
// Build the event
_mus_build_event:
#if 1
// Mus drums happen on channel 15, swap channel 9 & 15
// DEBUG
MUS_EVENT_DEBUG("Before", mus_data[mus_data_ofs], 0);
if ((mus_data[mus_data_ofs] & 0x0f) == 0x0f) {
mus_data[mus_data_ofs] = (mus_data[mus_data_ofs] & 0xf0) | 0x09;
} else if ((mus_data[mus_data_ofs] & 0x0f) == 0x09) {
mus_data[mus_data_ofs] = (mus_data[mus_data_ofs] & 0xf0) | 0x0f;
}
// DEBUG
MUS_EVENT_DEBUG("After", mus_data[mus_data_ofs], 0);
#endif
switch ((mus_data[mus_data_ofs] >> 4) & 0x07) {
case 0: // Note Off
mus_event_size = 2;
mus_event[0] = 0x80 | (mus_data[mus_data_ofs] & 0x0f);
mus_event[1] = mus_data[mus_data_ofs + 1];
mus_event[2] = 0;
mus_event[3] = 0;
break;
case 1: // Note On
if (mus_data[mus_data_ofs + 1] & 0x80) {
mus_event_size = 3;
mus_event[0] = 0x90 | (mus_data[mus_data_ofs] & 0x0f);
mus_event[1] = mus_data[mus_data_ofs + 1] & 0x7f;
mus_event[2] = mus_data[mus_data_ofs + 2];
mus_event[3] = 0;
mus_prev_vol[mus_data[mus_data_ofs] & 0x0f] = mus_event[2];
} else {
mus_event_size = 2;
mus_event[0] = 0x90 | (mus_data[mus_data_ofs] & 0x0f);
mus_event[1] = mus_data[mus_data_ofs + 1];
mus_event[2] = mus_prev_vol[mus_data[mus_data_ofs] & 0x0f];
mus_event[3] = 0;
}
break;
case 2: // Pitch Bend
mus_event_size = 2;
mus_event[0] = 0xe0 | (mus_data[mus_data_ofs] & 0x0f);
pitchbend_tmp = mus_data[mus_data_ofs + 1] << 6;
mus_event[1] = pitchbend_tmp & 0x7f;
mus_event[2] = (pitchbend_tmp >> 7) & 0x7f;
mus_event[3] = 0;
break;
case 3:
mus_event_size = 2;
switch (mus_data[mus_data_ofs + 1]) {
case 10: // All Sounds Off
mus_event[0] = 0xb0 | (mus_data[mus_data_ofs] & 0x0f);
mus_event[1] = 120;
mus_event[2] = 0;
mus_event[3] = 0;
break;
case 11: // All Notes Off
mus_event[0] = 0xb0 | (mus_data[mus_data_ofs] & 0x0f);
mus_event[1] = 123;
mus_event[2] = 0;
mus_event[3] = 0;
break;
case 12: // Mono (Not supported by WildMIDI)
/*
**************************
FIXME: Add dummy mdi event
**************************
*/
mus_event[0] = 0xb0 | (mus_data[mus_data_ofs] & 0x0f);
mus_event[1] = 126;
mus_event[2] = 0;
mus_event[3] = 0;
break;
case 13: // Poly (Not supported by WildMIDI)
/*
**************************
FIXME: Add dummy mdi event
**************************
*/
mus_event[0] = 0xb0 | (mus_data[mus_data_ofs] & 0x0f);
mus_event[1] = 127;
mus_event[2] = 0;
mus_event[3] = 0;
break;
case 14: // Reset All Controllers
mus_event[0] = 0xb0 | (mus_data[mus_data_ofs] & 0x0f);
mus_event[1] = 121;
mus_event[2] = 0;
mus_event[3] = 0;
break;
default: // Unsupported
goto _mus_next_data;
}
break;
case 4:
mus_event_size = 3;
switch (mus_data[mus_data_ofs + 1]) {
case 0: // Patch
/*
*************************************************
FIXME: Check if setting is MIDI or MUS instrument
*************************************************
*/
mus_event[0] = 0xc0 | (mus_data[mus_data_ofs] & 0x0f);
mus_event[1] = mus_data[mus_data_ofs + 2];
mus_event[2] = 0;
mus_event[3] = 0;
break;
case 1: // Bank Select
mus_event[0] = 0xb0 | (mus_data[mus_data_ofs] & 0x0f);
mus_event[1] = 0;
mus_event[2] = mus_data[mus_data_ofs + 2];
mus_event[3] = 0;
break;
case 2: // Modulation (Not supported by WildMidi)
mus_event[0] = 0xb0 | (mus_data[mus_data_ofs] & 0x0f);
mus_event[1] = 1;
mus_event[2] = mus_data[mus_data_ofs + 2];
mus_event[3] = 0;
break;
case 3: // Volume
mus_event[0] = 0xb0 | (mus_data[mus_data_ofs] & 0x0f);
mus_event[1] = 7;
mus_event[2] = mus_data[mus_data_ofs + 2];
mus_event[3] = 0;
break;
case 4: // Pan
mus_event[0] = 0xb0 | (mus_data[mus_data_ofs] & 0x0f);
mus_event[1] = 10;
mus_event[2] = mus_data[mus_data_ofs + 2];
mus_event[3] = 0;
break;
case 5: // Expression
mus_event[0] = 0xb0 | (mus_data[mus_data_ofs] & 0x0f);
mus_event[1] = 11;
mus_event[2] = mus_data[mus_data_ofs + 2];
mus_event[3] = 0;
break;
case 6: // Reverb (Not supported by WildMidi)
mus_event[0] = 0xb0 | (mus_data[mus_data_ofs] & 0x0f);
mus_event[1] = 91;
mus_event[2] = mus_data[mus_data_ofs + 2];
mus_event[3] = 0;
break;
case 7: // Chorus (Not supported by WildMidi)
mus_event[0] = 0xb0 | (mus_data[mus_data_ofs] & 0x0f);
mus_event[1] = 93;
mus_event[2] = mus_data[mus_data_ofs + 2];
mus_event[3] = 0;
break;
case 8: // Sustain
mus_event[0] = 0xb0 | (mus_data[mus_data_ofs] & 0x0f);
mus_event[1] = 64;
mus_event[2] = mus_data[mus_data_ofs + 2];
mus_event[3] = 0;
break;
case 9: // Soft Peddle (Not supported by WildMidi)
mus_event[0] = 0xb0 | (mus_data[mus_data_ofs] & 0x0f);
mus_event[1] = 67;
mus_event[2] = mus_data[mus_data_ofs + 2];
mus_event[3] = 0;
break;
default: // Unsupported
goto _mus_next_data;
}
break;
case 5:
mus_event_size = 1;
goto _mus_next_data;
break;
case 6:
goto _mus_end_of_song;
break;
case 7:
mus_event_size = 1;
goto _mus_next_data;
break;
}
setup_ret = _WM_SetupMidiEvent(mus_mdi, (uint8_t *)mus_event, MUS_SZ, 0);
if (setup_ret == 0) {
goto _mus_end;
}
_mus_next_data:
if (!(mus_data[mus_data_ofs] & 0x80)) {
mus_data_ofs += mus_event_size;
goto _mus_build_event;
}
mus_data_ofs += mus_event_size;
mus_ticks = 0;
do {
mus_ticks = (mus_ticks << 7) | (mus_data[mus_data_ofs++] & 0x7f);
} while (mus_data[mus_data_ofs - 1] & 0x80);
sample_count_f = ((float)mus_ticks * samples_per_tick_f) + sample_remainder;
sample_count = (uint32_t)sample_count_f;
sample_remainder = sample_count_f - (float)sample_count;
mus_mdi->events[mus_mdi->event_count - 1].samples_to_next = sample_count;
mus_mdi->extra_info.approx_total_samples += sample_count;
} while (mus_data_ofs < mus_size);
_mus_end_of_song:
// Finalise mdi structure
if ((mus_mdi->reverb = _WM_init_reverb(_WM_SampleRate, _WM_reverb_room_width, _WM_reverb_room_length, _WM_reverb_listen_posx, _WM_reverb_listen_posy)) == NULL) {
_WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_MEM, "to init reverb", 0);
goto _mus_end;
}
_WM_midi_setup_endoftrack(mus_mdi);
mus_mdi->extra_info.current_sample = 0;
mus_mdi->current_event = &mus_mdi->events[0];
mus_mdi->samples_to_mix = 0;
mus_mdi->note = NULL;
_WM_ResetToStart(mus_mdi);
_mus_end:
free(mus_mid_instr);
if (mus_mdi->reverb) return (mus_mdi);
_WM_freeMDI(mus_mdi);
return NULL;
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/good_2588_4 |
crossvul-cpp_data_bad_5312_0 | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% PPPP SSSSS DDDD %
% P P SS D D %
% PPPP SSS D D %
% P SS D D %
% P SSSSS DDDD %
% %
% %
% Read/Write Adobe Photoshop Image Format %
% %
% Software Design %
% Cristy %
% Leonard Rosenthol %
% July 1992 %
% Dirk Lemstra %
% December 2013 %
% %
% %
% 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/artifact.h"
#include "MagickCore/attribute.h"
#include "MagickCore/blob.h"
#include "MagickCore/blob-private.h"
#include "MagickCore/cache.h"
#include "MagickCore/channel.h"
#include "MagickCore/colormap.h"
#include "MagickCore/colormap-private.h"
#include "MagickCore/colorspace.h"
#include "MagickCore/colorspace-private.h"
#include "MagickCore/constitute.h"
#include "MagickCore/enhance.h"
#include "MagickCore/exception.h"
#include "MagickCore/exception-private.h"
#include "MagickCore/image.h"
#include "MagickCore/image-private.h"
#include "MagickCore/list.h"
#include "MagickCore/log.h"
#include "MagickCore/magick.h"
#include "MagickCore/memory_.h"
#include "MagickCore/module.h"
#include "MagickCore/monitor-private.h"
#include "MagickCore/option.h"
#include "MagickCore/pixel.h"
#include "MagickCore/pixel-accessor.h"
#include "MagickCore/profile.h"
#include "MagickCore/property.h"
#include "MagickCore/quantum-private.h"
#include "MagickCore/static.h"
#include "MagickCore/string_.h"
#include "MagickCore/thread-private.h"
#ifdef MAGICKCORE_ZLIB_DELEGATE
#include <zlib.h>
#endif
#include "psd-private.h"
/*
Define declaractions.
*/
#define MaxPSDChannels 56
#define PSDQuantum(x) (((ssize_t) (x)+1) & -2)
/*
Enumerated declaractions.
*/
typedef enum
{
Raw = 0,
RLE = 1,
ZipWithoutPrediction = 2,
ZipWithPrediction = 3
} PSDCompressionType;
typedef enum
{
BitmapMode = 0,
GrayscaleMode = 1,
IndexedMode = 2,
RGBMode = 3,
CMYKMode = 4,
MultichannelMode = 7,
DuotoneMode = 8,
LabMode = 9
} PSDImageType;
/*
Typedef declaractions.
*/
typedef struct _ChannelInfo
{
short int
type;
size_t
size;
} ChannelInfo;
typedef struct _MaskInfo
{
Image
*image;
RectangleInfo
page;
unsigned char
background,
flags;
} MaskInfo;
typedef struct _LayerInfo
{
ChannelInfo
channel_info[MaxPSDChannels];
char
blendkey[4];
Image
*image;
MaskInfo
mask;
Quantum
opacity;
RectangleInfo
page;
size_t
offset_x,
offset_y;
unsigned char
clipping,
flags,
name[256],
visible;
unsigned short
channels;
} LayerInfo;
/*
Forward declarations.
*/
static MagickBooleanType
WritePSDImage(const ImageInfo *,Image *,ExceptionInfo *);
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% I s P S D %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% IsPSD()() returns MagickTrue if the image format type, identified by the
% magick string, is PSD.
%
% The format of the IsPSD method is:
%
% MagickBooleanType IsPSD(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 IsPSD(const unsigned char *magick,const size_t length)
{
if (length < 4)
return(MagickFalse);
if (LocaleNCompare((const char *) magick,"8BPS",4) == 0)
return(MagickTrue);
return(MagickFalse);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e a d P S D I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ReadPSDImage() reads an Adobe Photoshop 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 ReadPSDImage method is:
%
% Image *ReadPSDImage(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 const char *CompositeOperatorToPSDBlendMode(CompositeOperator op)
{
const char
*blend_mode;
switch (op)
{
case ColorBurnCompositeOp: blend_mode = "idiv"; break;
case ColorDodgeCompositeOp: blend_mode = "div "; break;
case ColorizeCompositeOp: blend_mode = "colr"; break;
case DarkenCompositeOp: blend_mode = "dark"; break;
case DifferenceCompositeOp: blend_mode = "diff"; break;
case DissolveCompositeOp: blend_mode = "diss"; break;
case ExclusionCompositeOp: blend_mode = "smud"; break;
case HardLightCompositeOp: blend_mode = "hLit"; break;
case HardMixCompositeOp: blend_mode = "hMix"; break;
case HueCompositeOp: blend_mode = "hue "; break;
case LightenCompositeOp: blend_mode = "lite"; break;
case LinearBurnCompositeOp: blend_mode = "lbrn"; break;
case LinearDodgeCompositeOp:blend_mode = "lddg"; break;
case LinearLightCompositeOp:blend_mode = "lLit"; break;
case LuminizeCompositeOp: blend_mode = "lum "; break;
case MultiplyCompositeOp: blend_mode = "mul "; break;
case OverCompositeOp: blend_mode = "norm"; break;
case OverlayCompositeOp: blend_mode = "over"; break;
case PinLightCompositeOp: blend_mode = "pLit"; break;
case SaturateCompositeOp: blend_mode = "sat "; break;
case ScreenCompositeOp: blend_mode = "scrn"; break;
case SoftLightCompositeOp: blend_mode = "sLit"; break;
case VividLightCompositeOp: blend_mode = "vLit"; break;
default: blend_mode = "norm";
}
return(blend_mode);
}
/*
For some reason Photoshop seems to blend semi-transparent pixels with white.
This method reverts the blending. This can be disabled by setting the
option 'psd:alpha-unblend' to off.
*/
static MagickBooleanType CorrectPSDAlphaBlend(const ImageInfo *image_info,
Image *image,ExceptionInfo* exception)
{
const char
*option;
MagickBooleanType
status;
ssize_t
y;
if (image->alpha_trait != BlendPixelTrait || image->colorspace != sRGBColorspace)
return(MagickTrue);
option=GetImageOption(image_info,"psd:alpha-unblend");
if (IsStringFalse(option) != MagickFalse)
return(MagickTrue);
status=MagickTrue;
#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=GetAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
double
gamma;
register ssize_t
i;
gamma=QuantumScale*GetPixelAlpha(image, q);
if (gamma != 0.0 && gamma != 1.0)
{
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
PixelChannel channel=GetPixelChannelChannel(image,i);
if (channel != AlphaPixelChannel)
q[i]=ClampToQuantum((q[i]-((1.0-gamma)*QuantumRange))/gamma);
}
}
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
status=MagickFalse;
}
return(status);
}
static inline CompressionType ConvertPSDCompression(
PSDCompressionType compression)
{
switch (compression)
{
case RLE:
return RLECompression;
case ZipWithPrediction:
case ZipWithoutPrediction:
return ZipCompression;
default:
return NoCompression;
}
}
static MagickBooleanType CorrectPSDOpacity(LayerInfo *layer_info,
ExceptionInfo *exception)
{
MagickBooleanType
status;
ssize_t
y;
if (layer_info->opacity == OpaqueAlpha)
return(MagickTrue);
layer_info->image->alpha_trait=BlendPixelTrait;
status=MagickTrue;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(status) \
magick_threads(layer_info->image,layer_info->image,layer_info->image->rows,1)
#endif
for (y=0; y < (ssize_t) layer_info->image->rows; y++)
{
register Quantum
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
q=GetAuthenticPixels(layer_info->image,0,y,layer_info->image->columns,1,
exception);
if (q == (Quantum *)NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) layer_info->image->columns; x++)
{
SetPixelAlpha(layer_info->image,(Quantum) (QuantumScale*(GetPixelAlpha(
layer_info->image,q))*layer_info->opacity),q);
q+=GetPixelChannels(layer_info->image);
}
if (SyncAuthenticPixels(layer_info->image,exception) == MagickFalse)
status=MagickFalse;
}
return(status);
}
static ssize_t DecodePSDPixels(const size_t number_compact_pixels,
const unsigned char *compact_pixels,const ssize_t depth,
const size_t number_pixels,unsigned char *pixels)
{
#define CheckNumberCompactPixels \
if (packets == 0) \
return(i); \
packets--
#define CheckNumberPixels(count) \
if (((ssize_t) i + count) > (ssize_t) number_pixels) \
return(i); \
i+=count
int
pixel;
register ssize_t
i,
j;
size_t
length;
ssize_t
packets;
packets=(ssize_t) number_compact_pixels;
for (i=0; (packets > 1) && (i < (ssize_t) number_pixels); )
{
packets--;
length=(size_t) (*compact_pixels++);
if (length == 128)
continue;
if (length > 128)
{
length=256-length+1;
CheckNumberCompactPixels;
pixel=(*compact_pixels++);
for (j=0; j < (ssize_t) length; j++)
{
switch (depth)
{
case 1:
{
CheckNumberPixels(8);
*pixels++=(pixel >> 7) & 0x01 ? 0U : 255U;
*pixels++=(pixel >> 6) & 0x01 ? 0U : 255U;
*pixels++=(pixel >> 5) & 0x01 ? 0U : 255U;
*pixels++=(pixel >> 4) & 0x01 ? 0U : 255U;
*pixels++=(pixel >> 3) & 0x01 ? 0U : 255U;
*pixels++=(pixel >> 2) & 0x01 ? 0U : 255U;
*pixels++=(pixel >> 1) & 0x01 ? 0U : 255U;
*pixels++=(pixel >> 0) & 0x01 ? 0U : 255U;
break;
}
case 2:
{
CheckNumberPixels(4);
*pixels++=(unsigned char) ((pixel >> 6) & 0x03);
*pixels++=(unsigned char) ((pixel >> 4) & 0x03);
*pixels++=(unsigned char) ((pixel >> 2) & 0x03);
*pixels++=(unsigned char) ((pixel & 0x03) & 0x03);
break;
}
case 4:
{
CheckNumberPixels(2);
*pixels++=(unsigned char) ((pixel >> 4) & 0xff);
*pixels++=(unsigned char) ((pixel & 0x0f) & 0xff);
break;
}
default:
{
CheckNumberPixels(1);
*pixels++=(unsigned char) pixel;
break;
}
}
}
continue;
}
length++;
for (j=0; j < (ssize_t) length; j++)
{
CheckNumberCompactPixels;
switch (depth)
{
case 1:
{
CheckNumberPixels(8);
*pixels++=(*compact_pixels >> 7) & 0x01 ? 0U : 255U;
*pixels++=(*compact_pixels >> 6) & 0x01 ? 0U : 255U;
*pixels++=(*compact_pixels >> 5) & 0x01 ? 0U : 255U;
*pixels++=(*compact_pixels >> 4) & 0x01 ? 0U : 255U;
*pixels++=(*compact_pixels >> 3) & 0x01 ? 0U : 255U;
*pixels++=(*compact_pixels >> 2) & 0x01 ? 0U : 255U;
*pixels++=(*compact_pixels >> 1) & 0x01 ? 0U : 255U;
*pixels++=(*compact_pixels >> 0) & 0x01 ? 0U : 255U;
break;
}
case 2:
{
CheckNumberPixels(4);
*pixels++=(*compact_pixels >> 6) & 0x03;
*pixels++=(*compact_pixels >> 4) & 0x03;
*pixels++=(*compact_pixels >> 2) & 0x03;
*pixels++=(*compact_pixels & 0x03) & 0x03;
break;
}
case 4:
{
CheckNumberPixels(2);
*pixels++=(*compact_pixels >> 4) & 0xff;
*pixels++=(*compact_pixels & 0x0f) & 0xff;
break;
}
default:
{
CheckNumberPixels(1);
*pixels++=(*compact_pixels);
break;
}
}
compact_pixels++;
}
}
return(i);
}
static inline LayerInfo *DestroyLayerInfo(LayerInfo *layer_info,
const ssize_t number_layers)
{
ssize_t
i;
for (i=0; i<number_layers; i++)
{
if (layer_info[i].image != (Image *) NULL)
layer_info[i].image=DestroyImage(layer_info[i].image);
if (layer_info[i].mask.image != (Image *) NULL)
layer_info[i].mask.image=DestroyImage(layer_info[i].mask.image);
}
return (LayerInfo *) RelinquishMagickMemory(layer_info);
}
static inline size_t GetPSDPacketSize(Image *image)
{
if (image->storage_class == PseudoClass)
{
if (image->colors > 256)
return(2);
else if (image->depth > 8)
return(2);
}
else
if (image->depth > 8)
return(2);
return(1);
}
static inline MagickSizeType GetPSDSize(const PSDInfo *psd_info,Image *image)
{
if (psd_info->version == 1)
return((MagickSizeType) ReadBlobLong(image));
return((MagickSizeType) ReadBlobLongLong(image));
}
static inline size_t GetPSDRowSize(Image *image)
{
if (image->depth == 1)
return((image->columns+7)/8);
else
return(image->columns*GetPSDPacketSize(image));
}
static const char *ModeToString(PSDImageType type)
{
switch (type)
{
case BitmapMode: return "Bitmap";
case GrayscaleMode: return "Grayscale";
case IndexedMode: return "Indexed";
case RGBMode: return "RGB";
case CMYKMode: return "CMYK";
case MultichannelMode: return "Multichannel";
case DuotoneMode: return "Duotone";
case LabMode: return "L*A*B";
default: return "unknown";
}
}
static MagickBooleanType NegateCMYK(Image *image,ExceptionInfo *exception)
{
ChannelType
channel_mask;
MagickBooleanType
status;
channel_mask=SetImageChannelMask(image,(ChannelType)(AllChannels &~
AlphaChannel));
status=NegateImage(image,MagickFalse,exception);
(void) SetImageChannelMask(image,channel_mask);
return(status);
}
static void ParseImageResourceBlocks(Image *image,
const unsigned char *blocks,size_t length,
MagickBooleanType *has_merged_image,ExceptionInfo *exception)
{
const unsigned char
*p;
StringInfo
*profile;
unsigned int
count,
long_sans;
unsigned short
id,
short_sans;
if (length < 16)
return;
profile=BlobToStringInfo((const unsigned char *) NULL,length);
SetStringInfoDatum(profile,blocks);
(void) SetImageProfile(image,"8bim",profile,exception);
profile=DestroyStringInfo(profile);
for (p=blocks; (p >= blocks) && (p < (blocks+length-16)); )
{
if (LocaleNCompare((const char *) p,"8BIM",4) != 0)
break;
p=PushLongPixel(MSBEndian,p,&long_sans);
p=PushShortPixel(MSBEndian,p,&id);
p=PushShortPixel(MSBEndian,p,&short_sans);
p=PushLongPixel(MSBEndian,p,&count);
if (p+count > blocks+length)
return;
switch (id)
{
case 0x03ed:
{
char
value[MagickPathExtent];
unsigned short
resolution;
/*
Resolution info.
*/
p=PushShortPixel(MSBEndian,p,&resolution);
image->resolution.x=(double) resolution;
(void) FormatLocaleString(value,MagickPathExtent,"%g",image->resolution.x);
(void) SetImageProperty(image,"tiff:XResolution",value,exception);
p=PushShortPixel(MSBEndian,p,&short_sans);
p=PushShortPixel(MSBEndian,p,&short_sans);
p=PushShortPixel(MSBEndian,p,&short_sans);
p=PushShortPixel(MSBEndian,p,&resolution);
image->resolution.y=(double) resolution;
(void) FormatLocaleString(value,MagickPathExtent,"%g",image->resolution.y);
(void) SetImageProperty(image,"tiff:YResolution",value,exception);
p=PushShortPixel(MSBEndian,p,&short_sans);
p=PushShortPixel(MSBEndian,p,&short_sans);
p=PushShortPixel(MSBEndian,p,&short_sans);
image->units=PixelsPerInchResolution;
break;
}
case 0x0421:
{
if (*(p+4) == 0)
*has_merged_image=MagickFalse;
p+=count;
break;
}
default:
{
p+=count;
break;
}
}
if ((count & 0x01) != 0)
p++;
}
return;
}
static CompositeOperator PSDBlendModeToCompositeOperator(const char *mode)
{
if (mode == (const char *) NULL)
return(OverCompositeOp);
if (LocaleNCompare(mode,"norm",4) == 0)
return(OverCompositeOp);
if (LocaleNCompare(mode,"mul ",4) == 0)
return(MultiplyCompositeOp);
if (LocaleNCompare(mode,"diss",4) == 0)
return(DissolveCompositeOp);
if (LocaleNCompare(mode,"diff",4) == 0)
return(DifferenceCompositeOp);
if (LocaleNCompare(mode,"dark",4) == 0)
return(DarkenCompositeOp);
if (LocaleNCompare(mode,"lite",4) == 0)
return(LightenCompositeOp);
if (LocaleNCompare(mode,"hue ",4) == 0)
return(HueCompositeOp);
if (LocaleNCompare(mode,"sat ",4) == 0)
return(SaturateCompositeOp);
if (LocaleNCompare(mode,"colr",4) == 0)
return(ColorizeCompositeOp);
if (LocaleNCompare(mode,"lum ",4) == 0)
return(LuminizeCompositeOp);
if (LocaleNCompare(mode,"scrn",4) == 0)
return(ScreenCompositeOp);
if (LocaleNCompare(mode,"over",4) == 0)
return(OverlayCompositeOp);
if (LocaleNCompare(mode,"hLit",4) == 0)
return(HardLightCompositeOp);
if (LocaleNCompare(mode,"sLit",4) == 0)
return(SoftLightCompositeOp);
if (LocaleNCompare(mode,"smud",4) == 0)
return(ExclusionCompositeOp);
if (LocaleNCompare(mode,"div ",4) == 0)
return(ColorDodgeCompositeOp);
if (LocaleNCompare(mode,"idiv",4) == 0)
return(ColorBurnCompositeOp);
if (LocaleNCompare(mode,"lbrn",4) == 0)
return(LinearBurnCompositeOp);
if (LocaleNCompare(mode,"lddg",4) == 0)
return(LinearDodgeCompositeOp);
if (LocaleNCompare(mode,"lLit",4) == 0)
return(LinearLightCompositeOp);
if (LocaleNCompare(mode,"vLit",4) == 0)
return(VividLightCompositeOp);
if (LocaleNCompare(mode,"pLit",4) == 0)
return(PinLightCompositeOp);
if (LocaleNCompare(mode,"hMix",4) == 0)
return(HardMixCompositeOp);
return(OverCompositeOp);
}
static inline void ReversePSDString(Image *image,char *p,size_t length)
{
char
*q;
if (image->endian == MSBEndian)
return;
q=p+length;
for(--q; p < q; ++p, --q)
{
*p = *p ^ *q,
*q = *p ^ *q,
*p = *p ^ *q;
}
}
static inline void SetPSDPixel(Image *image,const size_t channels,
const ssize_t type,const size_t packet_size,const Quantum pixel,Quantum *q,
ExceptionInfo *exception)
{
if (image->storage_class == PseudoClass)
{
if (packet_size == 1)
SetPixelIndex(image,ScaleQuantumToChar(pixel),q);
else
SetPixelIndex(image,ScaleQuantumToShort(pixel),q);
SetPixelViaPixelInfo(image,image->colormap+(ssize_t)
ConstrainColormapIndex(image,GetPixelIndex(image,q),exception),q);
return;
}
switch (type)
{
case -1:
{
SetPixelAlpha(image, pixel,q);
break;
}
case -2:
case 0:
{
SetPixelRed(image,pixel,q);
if (channels == 1 || type == -2)
SetPixelGray(image,pixel,q);
break;
}
case 1:
{
if (image->storage_class == PseudoClass)
SetPixelAlpha(image,pixel,q);
else
SetPixelGreen(image,pixel,q);
break;
}
case 2:
{
if (image->storage_class == PseudoClass)
SetPixelAlpha(image,pixel,q);
else
SetPixelBlue(image,pixel,q);
break;
}
case 3:
{
if (image->colorspace == CMYKColorspace)
SetPixelBlack(image,pixel,q);
else
if (image->alpha_trait != UndefinedPixelTrait)
SetPixelAlpha(image,pixel,q);
break;
}
case 4:
{
if ((IssRGBCompatibleColorspace(image->colorspace) != MagickFalse) &&
(channels > 3))
break;
if (image->alpha_trait != UndefinedPixelTrait)
SetPixelAlpha(image,pixel,q);
break;
}
}
}
static MagickBooleanType ReadPSDChannelPixels(Image *image,
const size_t channels,const size_t row,const ssize_t type,
const unsigned char *pixels,ExceptionInfo *exception)
{
Quantum
pixel;
register const unsigned char
*p;
register Quantum
*q;
register ssize_t
x;
size_t
packet_size;
unsigned short
nibble;
p=pixels;
q=GetAuthenticPixels(image,0,row,image->columns,1,exception);
if (q == (Quantum *) NULL)
return MagickFalse;
packet_size=GetPSDPacketSize(image);
for (x=0; x < (ssize_t) image->columns; x++)
{
if (packet_size == 1)
pixel=ScaleCharToQuantum(*p++);
else
{
p=PushShortPixel(MSBEndian,p,&nibble);
pixel=ScaleShortToQuantum(nibble);
}
if (image->depth > 1)
{
SetPSDPixel(image,channels,type,packet_size,pixel,q,exception);
q+=GetPixelChannels(image);
}
else
{
ssize_t
bit,
number_bits;
number_bits=image->columns-x;
if (number_bits > 8)
number_bits=8;
for (bit = 0; bit < number_bits; bit++)
{
SetPSDPixel(image,channels,type,packet_size,(((unsigned char) pixel)
& (0x01 << (7-bit))) != 0 ? 0 : 255,q,exception);
q+=GetPixelChannels(image);
x++;
}
if (x != (ssize_t) image->columns)
x--;
continue;
}
}
return(SyncAuthenticPixels(image,exception));
}
static MagickBooleanType ReadPSDChannelRaw(Image *image,const size_t channels,
const ssize_t type,ExceptionInfo *exception)
{
MagickBooleanType
status;
size_t
count,
row_size;
ssize_t
y;
unsigned char
*pixels;
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" layer data is RAW");
row_size=GetPSDRowSize(image);
pixels=(unsigned char *) AcquireQuantumMemory(row_size,sizeof(*pixels));
if (pixels == (unsigned char *) NULL)
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
status=MagickTrue;
for (y=0; y < (ssize_t) image->rows; y++)
{
status=MagickFalse;
count=ReadBlob(image,row_size,pixels);
if (count != row_size)
break;
status=ReadPSDChannelPixels(image,channels,y,type,pixels,exception);
if (status == MagickFalse)
break;
}
pixels=(unsigned char *) RelinquishMagickMemory(pixels);
return(status);
}
static inline MagickOffsetType *ReadPSDRLEOffsets(Image *image,
const PSDInfo *psd_info,const size_t size)
{
MagickOffsetType
*offsets;
ssize_t
y;
offsets=(MagickOffsetType *) AcquireQuantumMemory(size,sizeof(*offsets));
if(offsets != (MagickOffsetType *) NULL)
{
for (y=0; y < (ssize_t) size; y++)
{
if (psd_info->version == 1)
offsets[y]=(MagickOffsetType) ReadBlobShort(image);
else
offsets[y]=(MagickOffsetType) ReadBlobLong(image);
}
}
return offsets;
}
static MagickBooleanType ReadPSDChannelRLE(Image *image,const PSDInfo *psd_info,
const ssize_t type,MagickOffsetType *offsets,ExceptionInfo *exception)
{
MagickBooleanType
status;
size_t
length,
row_size;
ssize_t
count,
y;
unsigned char
*compact_pixels,
*pixels;
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" layer data is RLE compressed");
row_size=GetPSDRowSize(image);
pixels=(unsigned char *) AcquireQuantumMemory(row_size,sizeof(*pixels));
if (pixels == (unsigned char *) NULL)
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
length=0;
for (y=0; y < (ssize_t) image->rows; y++)
if ((MagickOffsetType) length < offsets[y])
length=(size_t) offsets[y];
if (length > row_size + 256) // arbitrary number
{
pixels=(unsigned char *) RelinquishMagickMemory(pixels);
ThrowBinaryException(ResourceLimitError,"InvalidLength",
image->filename);
}
compact_pixels=(unsigned char *) AcquireQuantumMemory(length,sizeof(*pixels));
if (compact_pixels == (unsigned char *) NULL)
{
pixels=(unsigned char *) RelinquishMagickMemory(pixels);
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
}
(void) ResetMagickMemory(compact_pixels,0,length*sizeof(*compact_pixels));
status=MagickTrue;
for (y=0; y < (ssize_t) image->rows; y++)
{
status=MagickFalse;
count=ReadBlob(image,(size_t) offsets[y],compact_pixels);
if (count != (ssize_t) offsets[y])
break;
count=DecodePSDPixels((size_t) offsets[y],compact_pixels,
(ssize_t) (image->depth == 1 ? 123456 : image->depth),row_size,pixels);
if (count != (ssize_t) row_size)
break;
status=ReadPSDChannelPixels(image,psd_info->channels,y,type,pixels,
exception);
if (status == MagickFalse)
break;
}
compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels);
pixels=(unsigned char *) RelinquishMagickMemory(pixels);
return(status);
}
#ifdef MAGICKCORE_ZLIB_DELEGATE
static MagickBooleanType ReadPSDChannelZip(Image *image,const size_t channels,
const ssize_t type,const PSDCompressionType compression,
const size_t compact_size,ExceptionInfo *exception)
{
MagickBooleanType
status;
register unsigned char
*p;
size_t
count,
length,
packet_size,
row_size;
ssize_t
y;
unsigned char
*compact_pixels,
*pixels;
z_stream
stream;
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" layer data is ZIP compressed");
compact_pixels=(unsigned char *) AcquireQuantumMemory(compact_size,
sizeof(*compact_pixels));
if (compact_pixels == (unsigned char *) NULL)
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
packet_size=GetPSDPacketSize(image);
row_size=image->columns*packet_size;
count=image->rows*row_size;
pixels=(unsigned char *) AcquireQuantumMemory(count,sizeof(*pixels));
if (pixels == (unsigned char *) NULL)
{
compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels);
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
}
ResetMagickMemory(&stream, 0, sizeof(z_stream));
stream.data_type=Z_BINARY;
(void) ReadBlob(image,compact_size,compact_pixels);
stream.next_in=(Bytef *)compact_pixels;
stream.avail_in=(unsigned int) compact_size;
stream.next_out=(Bytef *)pixels;
stream.avail_out=(unsigned int) count;
if(inflateInit(&stream) == Z_OK)
{
int
ret;
while (stream.avail_out > 0)
{
ret=inflate(&stream, Z_SYNC_FLUSH);
if (ret != Z_OK && ret != Z_STREAM_END)
{
compact_pixels=(unsigned char *) RelinquishMagickMemory(
compact_pixels);
pixels=(unsigned char *) RelinquishMagickMemory(pixels);
return(MagickFalse);
}
}
}
if (compression == ZipWithPrediction)
{
p=pixels;
while(count > 0)
{
length=image->columns;
while(--length)
{
if (packet_size == 2)
{
p[2]+=p[0]+((p[1]+p[3]) >> 8);
p[3]+=p[1];
}
else
*(p+1)+=*p;
p+=packet_size;
}
p+=packet_size;
count-=row_size;
}
}
status=MagickTrue;
p=pixels;
for (y=0; y < (ssize_t) image->rows; y++)
{
status=ReadPSDChannelPixels(image,channels,y,type,p,exception);
if (status == MagickFalse)
break;
p+=row_size;
}
compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels);
pixels=(unsigned char *) RelinquishMagickMemory(pixels);
return(status);
}
#endif
static MagickBooleanType ReadPSDChannel(Image *image,const PSDInfo *psd_info,
LayerInfo* layer_info,const size_t channel,
const PSDCompressionType compression,ExceptionInfo *exception)
{
Image
*channel_image,
*mask;
MagickOffsetType
offset;
MagickBooleanType
status;
channel_image=image;
mask=(Image *) NULL;
if (layer_info->channel_info[channel].type < -1)
{
/*
Ignore mask that is not a user supplied layer mask, if the mask is
disabled or if the flags have unsupported values.
*/
if (layer_info->channel_info[channel].type != -2 ||
(layer_info->mask.flags > 3) || (layer_info->mask.flags & 0x02))
{
SeekBlob(image,layer_info->channel_info[channel].size-2,SEEK_CUR);
return(MagickTrue);
}
mask=CloneImage(image,layer_info->mask.page.width,
layer_info->mask.page.height,MagickFalse,exception);
SetImageType(mask,GrayscaleType,exception);
channel_image=mask;
}
offset=TellBlob(channel_image);
status=MagickTrue;
switch(compression)
{
case Raw:
status=ReadPSDChannelRaw(channel_image,psd_info->channels,
layer_info->channel_info[channel].type,exception);
break;
case RLE:
{
MagickOffsetType
*offsets;
offsets=ReadPSDRLEOffsets(channel_image,psd_info,channel_image->rows);
if (offsets == (MagickOffsetType *) NULL)
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
status=ReadPSDChannelRLE(channel_image,psd_info,
layer_info->channel_info[channel].type,offsets,exception);
offsets=(MagickOffsetType *) RelinquishMagickMemory(offsets);
}
break;
case ZipWithPrediction:
case ZipWithoutPrediction:
#ifdef MAGICKCORE_ZLIB_DELEGATE
status=ReadPSDChannelZip(channel_image,layer_info->channels,
layer_info->channel_info[channel].type,compression,
layer_info->channel_info[channel].size-2,exception);
#else
SeekBlob(image,offset+layer_info->channel_info[channel].size-2,SEEK_SET);
(void) ThrowMagickException(exception,GetMagickModule(),
MissingDelegateWarning,"DelegateLibrarySupportNotBuiltIn",
"'%s' (ZLIB)",image->filename);
#endif
break;
default:
SeekBlob(image,offset+layer_info->channel_info[channel].size-2,SEEK_SET);
(void) ThrowMagickException(exception,GetMagickModule(),TypeWarning,
"CompressionNotSupported","'%.20g'",(double) compression);
break;
}
if (status == MagickFalse)
{
if (mask != (Image *) NULL)
DestroyImage(mask);
SeekBlob(image,offset+layer_info->channel_info[channel].size-2,SEEK_SET);
ThrowBinaryException(CoderError,"UnableToDecompressImage",
image->filename);
}
if (mask != (Image *) NULL)
{
if (status != MagickFalse)
{
PixelInfo
color;
layer_info->mask.image=CloneImage(image,image->columns,image->rows,
MagickTrue,exception);
layer_info->mask.image->alpha_trait=UndefinedPixelTrait;
GetPixelInfo(layer_info->mask.image,&color);
color.red=layer_info->mask.background == 0 ? 0 : QuantumRange;
SetImageColor(layer_info->mask.image,&color,exception);
(void) CompositeImage(layer_info->mask.image,mask,OverCompositeOp,
MagickTrue,layer_info->mask.page.x,layer_info->mask.page.y,
exception);
}
DestroyImage(mask);
}
return(status);
}
static MagickBooleanType ReadPSDLayer(Image *image,const PSDInfo *psd_info,
LayerInfo* layer_info,ExceptionInfo *exception)
{
char
message[MagickPathExtent];
MagickBooleanType
status;
PSDCompressionType
compression;
ssize_t
j;
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" setting up new layer image");
(void) SetImageBackgroundColor(layer_info->image,exception);
layer_info->image->compose=PSDBlendModeToCompositeOperator(
layer_info->blendkey);
if (layer_info->visible == MagickFalse)
layer_info->image->compose=NoCompositeOp;
if (psd_info->mode == CMYKMode)
SetImageColorspace(layer_info->image,CMYKColorspace,exception);
if ((psd_info->mode == BitmapMode) || (psd_info->mode == GrayscaleMode) ||
(psd_info->mode == DuotoneMode))
SetImageColorspace(layer_info->image,GRAYColorspace,exception);
/*
Set up some hidden attributes for folks that need them.
*/
(void) FormatLocaleString(message,MagickPathExtent,"%.20g",
(double) layer_info->page.x);
(void) SetImageArtifact(layer_info->image,"psd:layer.x",message);
(void) FormatLocaleString(message,MagickPathExtent,"%.20g",
(double) layer_info->page.y);
(void) SetImageArtifact(layer_info->image,"psd:layer.y",message);
(void) FormatLocaleString(message,MagickPathExtent,"%.20g",(double)
layer_info->opacity);
(void) SetImageArtifact(layer_info->image,"psd:layer.opacity",message);
(void) SetImageProperty(layer_info->image,"label",(char *) layer_info->name,
exception);
status=MagickTrue;
for (j=0; j < (ssize_t) layer_info->channels; j++)
{
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" reading data for channel %.20g",(double) j);
compression=(PSDCompressionType) ReadBlobShort(layer_info->image);
layer_info->image->compression=ConvertPSDCompression(compression);
if (layer_info->channel_info[j].type == -1)
layer_info->image->alpha_trait=BlendPixelTrait;
status=ReadPSDChannel(layer_info->image,psd_info,layer_info,j,
compression,exception);
if (status == MagickFalse)
break;
}
if (status != MagickFalse)
status=CorrectPSDOpacity(layer_info,exception);
if ((status != MagickFalse) &&
(layer_info->image->colorspace == CMYKColorspace))
status=NegateCMYK(layer_info->image,exception);
if ((status != MagickFalse) && (layer_info->mask.image != (Image *) NULL))
{
status=CompositeImage(layer_info->image,layer_info->mask.image,
CopyAlphaCompositeOp,MagickTrue,0,0,exception);
layer_info->mask.image=DestroyImage(layer_info->mask.image);
}
return(status);
}
ModuleExport MagickBooleanType ReadPSDLayers(Image *image,
const ImageInfo *image_info,const PSDInfo *psd_info,
const MagickBooleanType skip_layers,ExceptionInfo *exception)
{
char
type[4];
LayerInfo
*layer_info;
MagickSizeType
size;
MagickBooleanType
status;
register ssize_t
i;
ssize_t
count,
j,
number_layers;
size=GetPSDSize(psd_info,image);
if (size == 0)
{
/*
Skip layers & masks.
*/
(void) ReadBlobLong(image);
count=ReadBlob(image,4,(unsigned char *) type);
ReversePSDString(image,type,4);
status=MagickFalse;
if ((count == 0) || (LocaleNCompare(type,"8BIM",4) != 0))
return(MagickTrue);
else
{
count=ReadBlob(image,4,(unsigned char *) type);
ReversePSDString(image,type,4);
if ((count != 0) && (LocaleNCompare(type,"Lr16",4) == 0))
size=GetPSDSize(psd_info,image);
else
return(MagickTrue);
}
}
status=MagickTrue;
if (size != 0)
{
layer_info=(LayerInfo *) NULL;
number_layers=(short) ReadBlobShort(image);
if (number_layers < 0)
{
/*
The first alpha channel in the merged result contains the
transparency data for the merged result.
*/
number_layers=MagickAbsoluteValue(number_layers);
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" negative layer count corrected for");
image->alpha_trait=BlendPixelTrait;
}
/*
We only need to know if the image has an alpha channel
*/
if (skip_layers != MagickFalse)
return(MagickTrue);
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image contains %.20g layers",(double) number_layers);
if (number_layers == 0)
ThrowBinaryException(CorruptImageError,"InvalidNumberOfLayers",
image->filename);
layer_info=(LayerInfo *) AcquireQuantumMemory((size_t) number_layers,
sizeof(*layer_info));
if (layer_info == (LayerInfo *) NULL)
{
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" allocation of LayerInfo failed");
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
}
(void) ResetMagickMemory(layer_info,0,(size_t) number_layers*
sizeof(*layer_info));
for (i=0; i < number_layers; i++)
{
ssize_t
x,
y;
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" reading layer #%.20g",(double) i+1);
layer_info[i].page.y=(int) ReadBlobLong(image);
layer_info[i].page.x=(int) ReadBlobLong(image);
y=(int) ReadBlobLong(image);
x=(int) ReadBlobLong(image);
layer_info[i].page.width=(size_t) (x-layer_info[i].page.x);
layer_info[i].page.height=(size_t) (y-layer_info[i].page.y);
layer_info[i].channels=ReadBlobShort(image);
if (layer_info[i].channels > MaxPSDChannels)
{
layer_info=DestroyLayerInfo(layer_info,number_layers);
ThrowBinaryException(CorruptImageError,"MaximumChannelsExceeded",
image->filename);
}
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" offset(%.20g,%.20g), size(%.20g,%.20g), channels=%.20g",
(double) layer_info[i].page.x,(double) layer_info[i].page.y,
(double) layer_info[i].page.height,(double)
layer_info[i].page.width,(double) layer_info[i].channels);
for (j=0; j < (ssize_t) layer_info[i].channels; j++)
{
layer_info[i].channel_info[j].type=(short) ReadBlobShort(image);
layer_info[i].channel_info[j].size=(size_t) GetPSDSize(psd_info,
image);
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" channel[%.20g]: type=%.20g, size=%.20g",(double) j,
(double) layer_info[i].channel_info[j].type,
(double) layer_info[i].channel_info[j].size);
}
count=ReadBlob(image,4,(unsigned char *) type);
ReversePSDString(image,type,4);
if ((count == 0) || (LocaleNCompare(type,"8BIM",4) != 0))
{
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" layer type was %.4s instead of 8BIM", type);
layer_info=DestroyLayerInfo(layer_info,number_layers);
ThrowBinaryException(CorruptImageError,"ImproperImageHeader",
image->filename);
}
count=ReadBlob(image,4,(unsigned char *) layer_info[i].blendkey);
ReversePSDString(image,layer_info[i].blendkey,4);
layer_info[i].opacity=(Quantum) ScaleCharToQuantum((unsigned char)
ReadBlobByte(image));
layer_info[i].clipping=(unsigned char) ReadBlobByte(image);
layer_info[i].flags=(unsigned char) ReadBlobByte(image);
layer_info[i].visible=!(layer_info[i].flags & 0x02);
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" blend=%.4s, opacity=%.20g, clipping=%s, flags=%d, visible=%s",
layer_info[i].blendkey,(double) layer_info[i].opacity,
layer_info[i].clipping ? "true" : "false",layer_info[i].flags,
layer_info[i].visible ? "true" : "false");
(void) ReadBlobByte(image); /* filler */
size=ReadBlobLong(image);
if (size != 0)
{
MagickSizeType
combined_length,
length;
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" layer contains additional info");
length=ReadBlobLong(image);
combined_length=length+4;
if (length != 0)
{
/*
Layer mask info.
*/
layer_info[i].mask.page.y=(int) ReadBlobLong(image);
layer_info[i].mask.page.x=(int) ReadBlobLong(image);
layer_info[i].mask.page.height=(size_t) (ReadBlobLong(image)-
layer_info[i].mask.page.y);
layer_info[i].mask.page.width=(size_t) (ReadBlobLong(image)-
layer_info[i].mask.page.x);
layer_info[i].mask.background=(unsigned char) ReadBlobByte(
image);
layer_info[i].mask.flags=(unsigned char) ReadBlobByte(image);
if (!(layer_info[i].mask.flags & 0x01))
{
layer_info[i].mask.page.y=layer_info[i].mask.page.y-
layer_info[i].page.y;
layer_info[i].mask.page.x=layer_info[i].mask.page.x-
layer_info[i].page.x;
}
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" layer mask: offset(%.20g,%.20g), size(%.20g,%.20g), length=%.20g",
(double) layer_info[i].mask.page.x,(double)
layer_info[i].mask.page.y,(double) layer_info[i].mask.page.width,
(double) layer_info[i].mask.page.height,(double)
((MagickOffsetType) length)-18);
/*
Skip over the rest of the layer mask information.
*/
if (DiscardBlobBytes(image,(MagickSizeType) (length-18)) == MagickFalse)
{
layer_info=DestroyLayerInfo(layer_info,number_layers);
ThrowBinaryException(CorruptImageError,"UnexpectedEndOfFile",
image->filename);
}
}
length=ReadBlobLong(image);
combined_length+=length+4;
if (length != 0)
{
/*
Layer blending ranges info.
*/
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" layer blending ranges: length=%.20g",(double)
((MagickOffsetType) length));
/*
We read it, but don't use it...
*/
for (j=0; j < (ssize_t) (length); j+=8)
{
size_t blend_source=ReadBlobLong(image);
size_t blend_dest=ReadBlobLong(image);
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" source(%x), dest(%x)",(unsigned int)
blend_source,(unsigned int) blend_dest);
}
}
/*
Layer name.
*/
length=(size_t) ReadBlobByte(image);
combined_length+=length+1;
if (length > 0)
(void) ReadBlob(image,(size_t) length++,layer_info[i].name);
layer_info[i].name[length]='\0';
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" layer name: %s",layer_info[i].name);
/*
Skip the rest of the variable data until we support it.
*/
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" unsupported data: length=%.20g",(double)
((MagickOffsetType) (size-combined_length)));
if (DiscardBlobBytes(image,(MagickSizeType) (size-combined_length)) == MagickFalse)
{
layer_info=DestroyLayerInfo(layer_info,number_layers);
ThrowBinaryException(CorruptImageError,
"UnexpectedEndOfFile",image->filename);
}
}
}
for (i=0; i < number_layers; i++)
{
if ((layer_info[i].page.width == 0) ||
(layer_info[i].page.height == 0))
{
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" layer data is empty");
continue;
}
/*
Allocate layered image.
*/
layer_info[i].image=CloneImage(image,layer_info[i].page.width,
layer_info[i].page.height,MagickFalse,exception);
if (layer_info[i].image == (Image *) NULL)
{
layer_info=DestroyLayerInfo(layer_info,number_layers);
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" allocation of image for layer %.20g failed",(double) i);
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
}
}
if (image_info->ping == MagickFalse)
{
for (i=0; i < number_layers; i++)
{
if (layer_info[i].image == (Image *) NULL)
{
for (j=0; j < layer_info[i].channels; j++)
{
if (DiscardBlobBytes(image,(MagickSizeType)
layer_info[i].channel_info[j].size) == MagickFalse)
{
layer_info=DestroyLayerInfo(layer_info,number_layers);
ThrowBinaryException(CorruptImageError,
"UnexpectedEndOfFile",image->filename);
}
}
continue;
}
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" reading data for layer %.20g",(double) i);
status=ReadPSDLayer(image,psd_info,&layer_info[i],exception);
if (status == MagickFalse)
break;
status=SetImageProgress(image,LoadImagesTag,i,(MagickSizeType)
number_layers);
if (status == MagickFalse)
break;
}
}
if (status != MagickFalse)
{
for (i=0; i < number_layers; i++)
{
if (layer_info[i].image == (Image *) NULL)
{
for (j=i; j < number_layers - 1; j++)
layer_info[j] = layer_info[j+1];
number_layers--;
i--;
}
}
if (number_layers > 0)
{
for (i=0; i < number_layers; i++)
{
if (i > 0)
layer_info[i].image->previous=layer_info[i-1].image;
if (i < (number_layers-1))
layer_info[i].image->next=layer_info[i+1].image;
layer_info[i].image->page=layer_info[i].page;
}
image->next=layer_info[0].image;
layer_info[0].image->previous=image;
}
layer_info=(LayerInfo *) RelinquishMagickMemory(layer_info);
}
else
layer_info=DestroyLayerInfo(layer_info,number_layers);
}
return(status);
}
static MagickBooleanType ReadPSDMergedImage(const ImageInfo *image_info,
Image *image,const PSDInfo *psd_info,ExceptionInfo *exception)
{
MagickOffsetType
*offsets;
MagickBooleanType
status;
PSDCompressionType
compression;
register ssize_t
i;
compression=(PSDCompressionType) ReadBlobMSBShort(image);
image->compression=ConvertPSDCompression(compression);
if (compression != Raw && compression != RLE)
{
(void) ThrowMagickException(exception,GetMagickModule(),
TypeWarning,"CompressionNotSupported","'%.20g'",(double) compression);
return(MagickFalse);
}
offsets=(MagickOffsetType *) NULL;
if (compression == RLE)
{
offsets=ReadPSDRLEOffsets(image,psd_info,image->rows*psd_info->channels);
if (offsets == (MagickOffsetType *) NULL)
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
}
status=MagickTrue;
for (i=0; i < (ssize_t) psd_info->channels; i++)
{
if (compression == RLE)
status=ReadPSDChannelRLE(image,psd_info,i,offsets+(i*image->rows),
exception);
else
status=ReadPSDChannelRaw(image,psd_info->channels,i,exception);
if (status != MagickFalse)
status=SetImageProgress(image,LoadImagesTag,i,psd_info->channels);
if (status == MagickFalse)
break;
}
if ((status != MagickFalse) && (image->colorspace == CMYKColorspace))
status=NegateCMYK(image,exception);
if (status != MagickFalse)
status=CorrectPSDAlphaBlend(image_info,image,exception);
if (offsets != (MagickOffsetType *) NULL)
offsets=(MagickOffsetType *) RelinquishMagickMemory(offsets);
return(status);
}
static Image *ReadPSDImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
Image
*image;
MagickBooleanType
has_merged_image,
skip_layers;
MagickOffsetType
offset;
MagickSizeType
length;
MagickBooleanType
status;
PSDInfo
psd_info;
register ssize_t
i;
ssize_t
count;
unsigned char
*data;
/*
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 image header.
*/
image->endian=MSBEndian;
count=ReadBlob(image,4,(unsigned char *) psd_info.signature);
psd_info.version=ReadBlobMSBShort(image);
if ((count == 0) || (LocaleNCompare(psd_info.signature,"8BPS",4) != 0) ||
((psd_info.version != 1) && (psd_info.version != 2)))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
(void) ReadBlob(image,6,psd_info.reserved);
psd_info.channels=ReadBlobMSBShort(image);
if (psd_info.channels > MaxPSDChannels)
ThrowReaderException(CorruptImageError,"MaximumChannelsExceeded");
psd_info.rows=ReadBlobMSBLong(image);
psd_info.columns=ReadBlobMSBLong(image);
if ((psd_info.version == 1) && ((psd_info.rows > 30000) ||
(psd_info.columns > 30000)))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
psd_info.depth=ReadBlobMSBShort(image);
if ((psd_info.depth != 1) && (psd_info.depth != 8) && (psd_info.depth != 16))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
psd_info.mode=ReadBlobMSBShort(image);
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Image is %.20g x %.20g with channels=%.20g, depth=%.20g, mode=%s",
(double) psd_info.columns,(double) psd_info.rows,(double)
psd_info.channels,(double) psd_info.depth,ModeToString((PSDImageType)
psd_info.mode));
/*
Initialize image.
*/
image->depth=psd_info.depth;
image->columns=psd_info.columns;
image->rows=psd_info.rows;
status=SetImageExtent(image,image->columns,image->rows,exception);
if (status == MagickFalse)
return(DestroyImageList(image));
if (SetImageBackgroundColor(image,exception) == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
if (psd_info.mode == LabMode)
SetImageColorspace(image,LabColorspace,exception);
if (psd_info.mode == CMYKMode)
{
SetImageColorspace(image,CMYKColorspace,exception);
image->alpha_trait=psd_info.channels > 4 ? BlendPixelTrait :
UndefinedPixelTrait;
}
else if ((psd_info.mode == BitmapMode) || (psd_info.mode == GrayscaleMode) ||
(psd_info.mode == DuotoneMode))
{
status=AcquireImageColormap(image,psd_info.depth != 16 ? 256 : 65536,
exception);
if (status == MagickFalse)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Image colormap allocated");
SetImageColorspace(image,GRAYColorspace,exception);
image->alpha_trait=psd_info.channels > 1 ? BlendPixelTrait :
UndefinedPixelTrait;
}
else
image->alpha_trait=psd_info.channels > 3 ? BlendPixelTrait :
UndefinedPixelTrait;
/*
Read PSD raster colormap only present for indexed and duotone images.
*/
length=ReadBlobMSBLong(image);
if (length != 0)
{
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" reading colormap");
if (psd_info.mode == DuotoneMode)
{
/*
Duotone image data; the format of this data is undocumented.
*/
data=(unsigned char *) AcquireQuantumMemory((size_t) length,
sizeof(*data));
if (data == (unsigned char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
(void) ReadBlob(image,(size_t) length,data);
data=(unsigned char *) RelinquishMagickMemory(data);
}
else
{
size_t
number_colors;
/*
Read PSD raster colormap.
*/
number_colors=length/3;
if (number_colors > 65536)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if (AcquireImageColormap(image,number_colors,exception) == MagickFalse)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
for (i=0; i < (ssize_t) image->colors; i++)
image->colormap[i].red=ScaleCharToQuantum((unsigned char)
ReadBlobByte(image));
for (i=0; i < (ssize_t) image->colors; i++)
image->colormap[i].green=ScaleCharToQuantum((unsigned char)
ReadBlobByte(image));
for (i=0; i < (ssize_t) image->colors; i++)
image->colormap[i].blue=ScaleCharToQuantum((unsigned char)
ReadBlobByte(image));
image->alpha_trait=UndefinedPixelTrait;
}
}
if ((image->depth == 1) && (image->storage_class != PseudoClass))
ThrowReaderException(CorruptImageError, "ImproperImageHeader");
has_merged_image=MagickTrue;
length=ReadBlobMSBLong(image);
if (length != 0)
{
unsigned char
*blocks;
/*
Image resources block.
*/
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" reading image resource blocks - %.20g bytes",(double)
((MagickOffsetType) length));
blocks=(unsigned char *) AcquireQuantumMemory((size_t) length,
sizeof(*blocks));
if (blocks == (unsigned char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
count=ReadBlob(image,(size_t) length,blocks);
if ((count != (ssize_t) length) || (length < 4) ||
(LocaleNCompare((char *) blocks,"8BIM",4) != 0))
{
blocks=(unsigned char *) RelinquishMagickMemory(blocks);
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
ParseImageResourceBlocks(image,blocks,(size_t) length,&has_merged_image,
exception);
blocks=(unsigned char *) RelinquishMagickMemory(blocks);
}
/*
Layer and mask block.
*/
length=GetPSDSize(&psd_info,image);
if (length == 8)
{
length=ReadBlobMSBLong(image);
length=ReadBlobMSBLong(image);
}
offset=TellBlob(image);
skip_layers=MagickFalse;
if ((image_info->number_scenes == 1) && (image_info->scene == 0) &&
(has_merged_image != MagickFalse))
{
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" read composite only");
skip_layers=MagickTrue;
}
if (length == 0)
{
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image has no layers");
}
else
{
if (ReadPSDLayers(image,image_info,&psd_info,skip_layers,exception) !=
MagickTrue)
{
(void) CloseBlob(image);
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Skip the rest of the layer and mask information.
*/
SeekBlob(image,offset+length,SEEK_SET);
}
/*
If we are only "pinging" the image, then we're done - so return.
*/
if (image_info->ping != MagickFalse)
{
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
/*
Read the precombined layer, present for PSD < 4 compatibility.
*/
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" reading the precombined layer");
if ((has_merged_image != MagickFalse) || (GetImageListLength(image) == 1))
has_merged_image=(MagickBooleanType) ReadPSDMergedImage(image_info,image,
&psd_info,exception);
if ((has_merged_image == MagickFalse) && (GetImageListLength(image) == 1) &&
(length != 0))
{
SeekBlob(image,offset,SEEK_SET);
status=ReadPSDLayers(image,image_info,&psd_info,MagickFalse,exception);
if (status != MagickTrue)
{
(void) CloseBlob(image);
image=DestroyImageList(image);
return((Image *) NULL);
}
}
if ((has_merged_image == MagickFalse) && (GetImageListLength(image) > 1))
{
Image
*merged;
SetImageAlphaChannel(image,TransparentAlphaChannel,exception);
image->background_color.alpha=TransparentAlpha;
image->background_color.alpha_trait=BlendPixelTrait;
merged=MergeImageLayers(image,FlattenLayer,exception);
ReplaceImageInList(&image,merged);
}
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e g i s t e r P S D I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% RegisterPSDImage() adds properties for the PSD 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 RegisterPSDImage method is:
%
% size_t RegisterPSDImage(void)
%
*/
ModuleExport size_t RegisterPSDImage(void)
{
MagickInfo
*entry;
entry=AcquireMagickInfo("PSD","PSB","Adobe Large Document Format");
entry->decoder=(DecodeImageHandler *) ReadPSDImage;
entry->encoder=(EncodeImageHandler *) WritePSDImage;
entry->magick=(IsImageFormatHandler *) IsPSD;
entry->flags|=CoderSeekableStreamFlag;
(void) RegisterMagickInfo(entry);
entry=AcquireMagickInfo("PSD","PSD","Adobe Photoshop bitmap");
entry->decoder=(DecodeImageHandler *) ReadPSDImage;
entry->encoder=(EncodeImageHandler *) WritePSDImage;
entry->magick=(IsImageFormatHandler *) IsPSD;
entry->flags|=CoderSeekableStreamFlag;
(void) RegisterMagickInfo(entry);
return(MagickImageCoderSignature);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% U n r e g i s t e r P S D I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% UnregisterPSDImage() removes format registrations made by the
% PSD module from the list of supported formats.
%
% The format of the UnregisterPSDImage method is:
%
% UnregisterPSDImage(void)
%
*/
ModuleExport void UnregisterPSDImage(void)
{
(void) UnregisterMagickInfo("PSB");
(void) UnregisterMagickInfo("PSD");
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% W r i t e P S D I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% WritePSDImage() writes an image in the Adobe Photoshop encoded image format.
%
% The format of the WritePSDImage method is:
%
% MagickBooleanType WritePSDImage(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 inline ssize_t SetPSDOffset(const PSDInfo *psd_info,Image *image,
const size_t offset)
{
if (psd_info->version == 1)
return(WriteBlobMSBShort(image,(unsigned short) offset));
return(WriteBlobMSBLong(image,(unsigned short) offset));
}
static inline ssize_t SetPSDSize(const PSDInfo *psd_info,Image *image,
const MagickSizeType size)
{
if (psd_info->version == 1)
return(WriteBlobMSBLong(image,(unsigned int) size));
return(WriteBlobMSBLongLong(image,size));
}
static size_t PSDPackbitsEncodeImage(Image *image,const size_t length,
const unsigned char *pixels,unsigned char *compact_pixels,
ExceptionInfo *exception)
{
int
count;
register ssize_t
i,
j;
register unsigned char
*q;
unsigned char
*packbits;
/*
Compress pixels with Packbits encoding.
*/
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(pixels != (unsigned char *) NULL);
packbits=(unsigned char *) AcquireQuantumMemory(128UL,sizeof(*packbits));
if (packbits == (unsigned char *) NULL)
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
q=compact_pixels;
for (i=(ssize_t) length; i != 0; )
{
switch (i)
{
case 1:
{
i--;
*q++=(unsigned char) 0;
*q++=(*pixels);
break;
}
case 2:
{
i-=2;
*q++=(unsigned char) 1;
*q++=(*pixels);
*q++=pixels[1];
break;
}
case 3:
{
i-=3;
if ((*pixels == *(pixels+1)) && (*(pixels+1) == *(pixels+2)))
{
*q++=(unsigned char) ((256-3)+1);
*q++=(*pixels);
break;
}
*q++=(unsigned char) 2;
*q++=(*pixels);
*q++=pixels[1];
*q++=pixels[2];
break;
}
default:
{
if ((*pixels == *(pixels+1)) && (*(pixels+1) == *(pixels+2)))
{
/*
Packed run.
*/
count=3;
while (((ssize_t) count < i) && (*pixels == *(pixels+count)))
{
count++;
if (count >= 127)
break;
}
i-=count;
*q++=(unsigned char) ((256-count)+1);
*q++=(*pixels);
pixels+=count;
break;
}
/*
Literal run.
*/
count=0;
while ((*(pixels+count) != *(pixels+count+1)) ||
(*(pixels+count+1) != *(pixels+count+2)))
{
packbits[count+1]=pixels[count];
count++;
if (((ssize_t) count >= (i-3)) || (count >= 127))
break;
}
i-=count;
*packbits=(unsigned char) (count-1);
for (j=0; j <= (ssize_t) count; j++)
*q++=packbits[j];
pixels+=count;
break;
}
}
}
*q++=(unsigned char) 128; /* EOD marker */
packbits=(unsigned char *) RelinquishMagickMemory(packbits);
return((size_t) (q-compact_pixels));
}
static void WritePackbitsLength(const PSDInfo *psd_info,
const ImageInfo *image_info,Image *image,Image *next_image,
unsigned char *compact_pixels,const QuantumType quantum_type,
ExceptionInfo *exception)
{
QuantumInfo
*quantum_info;
register const Quantum
*p;
size_t
length,
packet_size;
ssize_t
y;
unsigned char
*pixels;
if (next_image->depth > 8)
next_image->depth=16;
packet_size=next_image->depth > 8UL ? 2UL : 1UL;
(void) packet_size;
quantum_info=AcquireQuantumInfo(image_info,image);
pixels=(unsigned char *) GetQuantumPixels(quantum_info);
for (y=0; y < (ssize_t) next_image->rows; y++)
{
p=GetVirtualPixels(next_image,0,y,next_image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
length=ExportQuantumPixels(next_image,(CacheView *) NULL,quantum_info,
quantum_type,pixels,exception);
length=PSDPackbitsEncodeImage(image,length,pixels,compact_pixels,
exception);
(void) SetPSDOffset(psd_info,image,length);
}
quantum_info=DestroyQuantumInfo(quantum_info);
}
static void WriteOneChannel(const PSDInfo *psd_info,const ImageInfo *image_info,
Image *image,Image *next_image,unsigned char *compact_pixels,
const QuantumType quantum_type,const MagickBooleanType compression_flag,
ExceptionInfo *exception)
{
int
y;
MagickBooleanType
monochrome;
QuantumInfo
*quantum_info;
register const Quantum
*p;
register ssize_t
i;
size_t
length,
packet_size;
unsigned char
*pixels;
(void) psd_info;
if ((compression_flag != MagickFalse) &&
(next_image->compression != RLECompression))
(void) WriteBlobMSBShort(image,0);
if (next_image->depth > 8)
next_image->depth=16;
monochrome=IsImageMonochrome(image) && (image->depth == 1) ?
MagickTrue : MagickFalse;
packet_size=next_image->depth > 8UL ? 2UL : 1UL;
(void) packet_size;
quantum_info=AcquireQuantumInfo(image_info,image);
pixels=(unsigned char *) GetQuantumPixels(quantum_info);
for (y=0; y < (ssize_t) next_image->rows; y++)
{
p=GetVirtualPixels(next_image,0,y,next_image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
length=ExportQuantumPixels(next_image,(CacheView *) NULL,quantum_info,
quantum_type,pixels,exception);
if (monochrome != MagickFalse)
for (i=0; i < (ssize_t) length; i++)
pixels[i]=(~pixels[i]);
if (next_image->compression != RLECompression)
(void) WriteBlob(image,length,pixels);
else
{
length=PSDPackbitsEncodeImage(image,length,pixels,compact_pixels,
exception);
(void) WriteBlob(image,length,compact_pixels);
}
}
quantum_info=DestroyQuantumInfo(quantum_info);
}
static MagickBooleanType WriteImageChannels(const PSDInfo *psd_info,
const ImageInfo *image_info,Image *image,Image *next_image,
const MagickBooleanType separate,ExceptionInfo *exception)
{
size_t
channels,
packet_size;
unsigned char
*compact_pixels;
/*
Write uncompressed pixels as separate planes.
*/
channels=1;
packet_size=next_image->depth > 8UL ? 2UL : 1UL;
compact_pixels=(unsigned char *) NULL;
if (next_image->compression == RLECompression)
{
compact_pixels=(unsigned char *) AcquireQuantumMemory((2*channels*
next_image->columns)+1,packet_size*sizeof(*compact_pixels));
if (compact_pixels == (unsigned char *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
}
if (IsImageGray(next_image) != MagickFalse)
{
if (next_image->compression == RLECompression)
{
/*
Packbits compression.
*/
(void) WriteBlobMSBShort(image,1);
WritePackbitsLength(psd_info,image_info,image,next_image,
compact_pixels,GrayQuantum,exception);
if (next_image->alpha_trait != UndefinedPixelTrait)
WritePackbitsLength(psd_info,image_info,image,next_image,
compact_pixels,AlphaQuantum,exception);
}
WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels,
GrayQuantum,MagickTrue,exception);
if (next_image->alpha_trait != UndefinedPixelTrait)
WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels,
AlphaQuantum,separate,exception);
(void) SetImageProgress(image,SaveImagesTag,0,1);
}
else
if (next_image->storage_class == PseudoClass)
{
if (next_image->compression == RLECompression)
{
/*
Packbits compression.
*/
(void) WriteBlobMSBShort(image,1);
WritePackbitsLength(psd_info,image_info,image,next_image,
compact_pixels,IndexQuantum,exception);
if (next_image->alpha_trait != UndefinedPixelTrait)
WritePackbitsLength(psd_info,image_info,image,next_image,
compact_pixels,AlphaQuantum,exception);
}
WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels,
IndexQuantum,MagickTrue,exception);
if (next_image->alpha_trait != UndefinedPixelTrait)
WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels,
AlphaQuantum,separate,exception);
(void) SetImageProgress(image,SaveImagesTag,0,1);
}
else
{
if (next_image->colorspace == CMYKColorspace)
(void) NegateCMYK(next_image,exception);
if (next_image->compression == RLECompression)
{
/*
Packbits compression.
*/
(void) WriteBlobMSBShort(image,1);
WritePackbitsLength(psd_info,image_info,image,next_image,
compact_pixels,RedQuantum,exception);
WritePackbitsLength(psd_info,image_info,image,next_image,
compact_pixels,GreenQuantum,exception);
WritePackbitsLength(psd_info,image_info,image,next_image,
compact_pixels,BlueQuantum,exception);
if (next_image->colorspace == CMYKColorspace)
WritePackbitsLength(psd_info,image_info,image,next_image,
compact_pixels,BlackQuantum,exception);
if (next_image->alpha_trait != UndefinedPixelTrait)
WritePackbitsLength(psd_info,image_info,image,next_image,
compact_pixels,AlphaQuantum,exception);
}
(void) SetImageProgress(image,SaveImagesTag,0,6);
WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels,
RedQuantum,MagickTrue,exception);
(void) SetImageProgress(image,SaveImagesTag,1,6);
WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels,
GreenQuantum,separate,exception);
(void) SetImageProgress(image,SaveImagesTag,2,6);
WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels,
BlueQuantum,separate,exception);
(void) SetImageProgress(image,SaveImagesTag,3,6);
if (next_image->colorspace == CMYKColorspace)
WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels,
BlackQuantum,separate,exception);
(void) SetImageProgress(image,SaveImagesTag,4,6);
if (next_image->alpha_trait != UndefinedPixelTrait)
WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels,
AlphaQuantum,separate,exception);
(void) SetImageProgress(image,SaveImagesTag,5,6);
if (next_image->colorspace == CMYKColorspace)
(void) NegateCMYK(next_image,exception);
}
if (next_image->compression == RLECompression)
compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels);
return(MagickTrue);
}
static void WritePascalString(Image* inImage,const char *inString,int inPad)
{
size_t
length;
register ssize_t
i;
/*
Max length is 255.
*/
length=(strlen(inString) > 255UL ) ? 255UL : strlen(inString);
if (length == 0)
(void) WriteBlobByte(inImage,0);
else
{
(void) WriteBlobByte(inImage,(unsigned char) length);
(void) WriteBlob(inImage, length, (const unsigned char *) inString);
}
length++;
if ((length % inPad) == 0)
return;
for (i=0; i < (ssize_t) (inPad-(length % inPad)); i++)
(void) WriteBlobByte(inImage,0);
}
static void WriteResolutionResourceBlock(Image *image)
{
double
x_resolution,
y_resolution;
unsigned short
units;
if (image->units == PixelsPerCentimeterResolution)
{
x_resolution=2.54*65536.0*image->resolution.x+0.5;
y_resolution=2.54*65536.0*image->resolution.y+0.5;
units=2;
}
else
{
x_resolution=65536.0*image->resolution.x+0.5;
y_resolution=65536.0*image->resolution.y+0.5;
units=1;
}
(void) WriteBlob(image,4,(const unsigned char *) "8BIM");
(void) WriteBlobMSBShort(image,0x03ED);
(void) WriteBlobMSBShort(image,0);
(void) WriteBlobMSBLong(image,16); /* resource size */
(void) WriteBlobMSBLong(image,(unsigned int) (x_resolution+0.5));
(void) WriteBlobMSBShort(image,units); /* horizontal resolution unit */
(void) WriteBlobMSBShort(image,units); /* width unit */
(void) WriteBlobMSBLong(image,(unsigned int) (y_resolution+0.5));
(void) WriteBlobMSBShort(image,units); /* vertical resolution unit */
(void) WriteBlobMSBShort(image,units); /* height unit */
}
static void RemoveICCProfileFromResourceBlock(StringInfo *bim_profile)
{
register const unsigned char
*p;
size_t
length;
unsigned char
*datum;
unsigned int
count,
long_sans;
unsigned short
id,
short_sans;
length=GetStringInfoLength(bim_profile);
if (length < 16)
return;
datum=GetStringInfoDatum(bim_profile);
for (p=datum; (p >= datum) && (p < (datum+length-16)); )
{
register unsigned char
*q;
q=(unsigned char *) p;
if (LocaleNCompare((const char *) p,"8BIM",4) != 0)
break;
p=PushLongPixel(MSBEndian,p,&long_sans);
p=PushShortPixel(MSBEndian,p,&id);
p=PushShortPixel(MSBEndian,p,&short_sans);
p=PushLongPixel(MSBEndian,p,&count);
if (id == 0x0000040f)
{
(void) CopyMagickMemory(q,q+PSDQuantum(count)+12,length-
(PSDQuantum(count)+12)-(q-datum));
SetStringInfoLength(bim_profile,length-(PSDQuantum(count)+12));
break;
}
p+=count;
if ((count & 0x01) != 0)
p++;
}
}
static void RemoveResolutionFromResourceBlock(StringInfo *bim_profile)
{
register const unsigned char
*p;
size_t
length;
unsigned char
*datum;
unsigned int
count,
long_sans;
unsigned short
id,
short_sans;
length=GetStringInfoLength(bim_profile);
if (length < 16)
return;
datum=GetStringInfoDatum(bim_profile);
for (p=datum; (p >= datum) && (p < (datum+length-16)); )
{
register unsigned char
*q;
q=(unsigned char *) p;
if (LocaleNCompare((const char *) p,"8BIM",4) != 0)
break;
p=PushLongPixel(MSBEndian,p,&long_sans);
p=PushShortPixel(MSBEndian,p,&id);
p=PushShortPixel(MSBEndian,p,&short_sans);
p=PushLongPixel(MSBEndian,p,&count);
if ((id == 0x000003ed) && (PSDQuantum(count) < (ssize_t) (length-12)))
{
(void) CopyMagickMemory(q,q+PSDQuantum(count)+12,length-
(PSDQuantum(count)+12)-(q-datum));
SetStringInfoLength(bim_profile,length-(PSDQuantum(count)+12));
break;
}
p+=count;
if ((count & 0x01) != 0)
p++;
}
}
static MagickBooleanType WritePSDImage(const ImageInfo *image_info,Image *image,
ExceptionInfo *exception)
{
const char
*property;
const StringInfo
*icc_profile;
Image
*base_image,
*next_image;
MagickBooleanType
status;
PSDInfo
psd_info;
register ssize_t
i;
size_t
channel_size,
channelLength,
layer_count,
layer_info_size,
length,
num_channels,
packet_size,
rounded_layer_info_size;
StringInfo
*bim_profile;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception);
if (status == MagickFalse)
return(status);
packet_size=(size_t) (image->depth > 8 ? 6 : 3);
if (image->alpha_trait != UndefinedPixelTrait)
packet_size+=image->depth > 8 ? 2 : 1;
psd_info.version=1;
if ((LocaleCompare(image_info->magick,"PSB") == 0) ||
(image->columns > 30000) || (image->rows > 30000))
psd_info.version=2;
(void) WriteBlob(image,4,(const unsigned char *) "8BPS");
(void) WriteBlobMSBShort(image,psd_info.version); /* version */
for (i=1; i <= 6; i++)
(void) WriteBlobByte(image, 0); /* 6 bytes of reserved */
if (SetImageGray(image,exception) != MagickFalse)
num_channels=(image->alpha_trait != UndefinedPixelTrait ? 2UL : 1UL);
else
if ((image_info->type != TrueColorType) && (image_info->type !=
TrueColorAlphaType) && (image->storage_class == PseudoClass))
num_channels=(image->alpha_trait != UndefinedPixelTrait ? 2UL : 1UL);
else
{
if (image->storage_class == PseudoClass)
(void) SetImageStorageClass(image,DirectClass,exception);
if (image->colorspace != CMYKColorspace)
num_channels=(image->alpha_trait != UndefinedPixelTrait ? 4UL : 3UL);
else
num_channels=(image->alpha_trait != UndefinedPixelTrait ? 5UL : 4UL);
}
(void) WriteBlobMSBShort(image,(unsigned short) num_channels);
(void) WriteBlobMSBLong(image,(unsigned int) image->rows);
(void) WriteBlobMSBLong(image,(unsigned int) image->columns);
if (IsImageGray(image) != MagickFalse)
{
MagickBooleanType
monochrome;
/*
Write depth & mode.
*/
monochrome=IsImageMonochrome(image) && (image->depth == 1) ?
MagickTrue : MagickFalse;
(void) WriteBlobMSBShort(image,(unsigned short)
(monochrome != MagickFalse ? 1 : image->depth > 8 ? 16 : 8));
(void) WriteBlobMSBShort(image,(unsigned short)
(monochrome != MagickFalse ? BitmapMode : GrayscaleMode));
}
else
{
(void) WriteBlobMSBShort(image,(unsigned short) (image->storage_class ==
PseudoClass ? 8 : image->depth > 8 ? 16 : 8));
if (((image_info->colorspace != UndefinedColorspace) ||
(image->colorspace != CMYKColorspace)) &&
(image_info->colorspace != CMYKColorspace))
{
(void) TransformImageColorspace(image,sRGBColorspace,exception);
(void) WriteBlobMSBShort(image,(unsigned short)
(image->storage_class == PseudoClass ? IndexedMode : RGBMode));
}
else
{
if (image->colorspace != CMYKColorspace)
(void) TransformImageColorspace(image,CMYKColorspace,exception);
(void) WriteBlobMSBShort(image,CMYKMode);
}
}
if ((IsImageGray(image) != MagickFalse) ||
(image->storage_class == DirectClass) || (image->colors > 256))
(void) WriteBlobMSBLong(image,0);
else
{
/*
Write PSD raster colormap.
*/
(void) WriteBlobMSBLong(image,768);
for (i=0; i < (ssize_t) image->colors; i++)
(void) WriteBlobByte(image,ScaleQuantumToChar(image->colormap[i].red));
for ( ; i < 256; i++)
(void) WriteBlobByte(image,0);
for (i=0; i < (ssize_t) image->colors; i++)
(void) WriteBlobByte(image,ScaleQuantumToChar(
image->colormap[i].green));
for ( ; i < 256; i++)
(void) WriteBlobByte(image,0);
for (i=0; i < (ssize_t) image->colors; i++)
(void) WriteBlobByte(image,ScaleQuantumToChar(image->colormap[i].blue));
for ( ; i < 256; i++)
(void) WriteBlobByte(image,0);
}
/*
Image resource block.
*/
length=28; /* 0x03EB */
bim_profile=(StringInfo *) GetImageProfile(image,"8bim");
icc_profile=GetImageProfile(image,"icc");
if (bim_profile != (StringInfo *) NULL)
{
bim_profile=CloneStringInfo(bim_profile);
if (icc_profile != (StringInfo *) NULL)
RemoveICCProfileFromResourceBlock(bim_profile);
RemoveResolutionFromResourceBlock(bim_profile);
length+=PSDQuantum(GetStringInfoLength(bim_profile));
}
if (icc_profile != (const StringInfo *) NULL)
length+=PSDQuantum(GetStringInfoLength(icc_profile))+12;
(void) WriteBlobMSBLong(image,(unsigned int) length);
WriteResolutionResourceBlock(image);
if (bim_profile != (StringInfo *) NULL)
{
(void) WriteBlob(image,GetStringInfoLength(bim_profile),
GetStringInfoDatum(bim_profile));
bim_profile=DestroyStringInfo(bim_profile);
}
if (icc_profile != (StringInfo *) NULL)
{
(void) WriteBlob(image,4,(const unsigned char *) "8BIM");
(void) WriteBlobMSBShort(image,0x0000040F);
(void) WriteBlobMSBShort(image,0);
(void) WriteBlobMSBLong(image,(unsigned int) GetStringInfoLength(
icc_profile));
(void) WriteBlob(image,GetStringInfoLength(icc_profile),
GetStringInfoDatum(icc_profile));
if ((MagickOffsetType) GetStringInfoLength(icc_profile) !=
PSDQuantum(GetStringInfoLength(icc_profile)))
(void) WriteBlobByte(image,0);
}
layer_count=0;
layer_info_size=2;
base_image=GetNextImageInList(image);
if ((image->alpha_trait != UndefinedPixelTrait) && (base_image == (Image *) NULL))
base_image=image;
next_image=base_image;
while ( next_image != NULL )
{
packet_size=next_image->depth > 8 ? 2UL : 1UL;
if (IsImageGray(next_image) != MagickFalse)
num_channels=next_image->alpha_trait != UndefinedPixelTrait ? 2UL : 1UL;
else
if (next_image->storage_class == PseudoClass)
num_channels=next_image->alpha_trait != UndefinedPixelTrait ? 2UL : 1UL;
else
if (next_image->colorspace != CMYKColorspace)
num_channels=next_image->alpha_trait != UndefinedPixelTrait ? 4UL : 3UL;
else
num_channels=next_image->alpha_trait != UndefinedPixelTrait ? 5UL : 4UL;
channelLength=(size_t) (next_image->columns*next_image->rows*packet_size+2);
layer_info_size+=(size_t) (4*4+2+num_channels*6+(psd_info.version == 1 ? 8 :
16)+4*1+4+num_channels*channelLength);
property=(const char *) GetImageProperty(next_image,"label",exception);
if (property == (const char *) NULL)
layer_info_size+=16;
else
{
size_t
layer_length;
layer_length=strlen(property);
layer_info_size+=8+layer_length+(4-(layer_length % 4));
}
layer_count++;
next_image=GetNextImageInList(next_image);
}
if (layer_count == 0)
(void) SetPSDSize(&psd_info,image,0);
else
{
CompressionType
compression;
(void) SetPSDSize(&psd_info,image,layer_info_size+
(psd_info.version == 1 ? 8 : 16));
if ((layer_info_size/2) != ((layer_info_size+1)/2))
rounded_layer_info_size=layer_info_size+1;
else
rounded_layer_info_size=layer_info_size;
(void) SetPSDSize(&psd_info,image,rounded_layer_info_size);
if (image->alpha_trait != UndefinedPixelTrait)
(void) WriteBlobMSBShort(image,-(unsigned short) layer_count);
else
(void) WriteBlobMSBShort(image,(unsigned short) layer_count);
layer_count=1;
compression=base_image->compression;
for (next_image=base_image; next_image != NULL; )
{
next_image->compression=NoCompression;
(void) WriteBlobMSBLong(image,(unsigned int) next_image->page.y);
(void) WriteBlobMSBLong(image,(unsigned int) next_image->page.x);
(void) WriteBlobMSBLong(image,(unsigned int) (next_image->page.y+
next_image->rows));
(void) WriteBlobMSBLong(image,(unsigned int) (next_image->page.x+
next_image->columns));
packet_size=next_image->depth > 8 ? 2UL : 1UL;
channel_size=(unsigned int) ((packet_size*next_image->rows*
next_image->columns)+2);
if ((IsImageGray(next_image) != MagickFalse) ||
(next_image->storage_class == PseudoClass))
{
(void) WriteBlobMSBShort(image,(unsigned short)
(next_image->alpha_trait != UndefinedPixelTrait ? 2 : 1));
(void) WriteBlobMSBShort(image,0);
(void) SetPSDSize(&psd_info,image,channel_size);
if (next_image->alpha_trait != UndefinedPixelTrait)
{
(void) WriteBlobMSBShort(image,(unsigned short) -1);
(void) SetPSDSize(&psd_info,image,channel_size);
}
}
else
if (next_image->colorspace != CMYKColorspace)
{
(void) WriteBlobMSBShort(image,(unsigned short)
(next_image->alpha_trait != UndefinedPixelTrait ? 4 : 3));
(void) WriteBlobMSBShort(image,0);
(void) SetPSDSize(&psd_info,image,channel_size);
(void) WriteBlobMSBShort(image,1);
(void) SetPSDSize(&psd_info,image,channel_size);
(void) WriteBlobMSBShort(image,2);
(void) SetPSDSize(&psd_info,image,channel_size);
if (next_image->alpha_trait != UndefinedPixelTrait)
{
(void) WriteBlobMSBShort(image,(unsigned short) -1);
(void) SetPSDSize(&psd_info,image,channel_size);
}
}
else
{
(void) WriteBlobMSBShort(image,(unsigned short)
(next_image->alpha_trait ? 5 : 4));
(void) WriteBlobMSBShort(image,0);
(void) SetPSDSize(&psd_info,image,channel_size);
(void) WriteBlobMSBShort(image,1);
(void) SetPSDSize(&psd_info,image,channel_size);
(void) WriteBlobMSBShort(image,2);
(void) SetPSDSize(&psd_info,image,channel_size);
(void) WriteBlobMSBShort(image,3);
(void) SetPSDSize(&psd_info,image,channel_size);
if (next_image->alpha_trait)
{
(void) WriteBlobMSBShort(image,(unsigned short) -1);
(void) SetPSDSize(&psd_info,image,channel_size);
}
}
(void) WriteBlob(image,4,(const unsigned char *) "8BIM");
(void) WriteBlob(image,4,(const unsigned char *)
CompositeOperatorToPSDBlendMode(next_image->compose));
(void) WriteBlobByte(image,255); /* layer opacity */
(void) WriteBlobByte(image,0);
(void) WriteBlobByte(image,next_image->compose==NoCompositeOp ?
1 << 0x02 : 1); /* layer properties - visible, etc. */
(void) WriteBlobByte(image,0);
property=(const char *) GetImageProperty(next_image,"label",exception);
if (property == (const char *) NULL)
{
char
layer_name[MagickPathExtent];
(void) WriteBlobMSBLong(image,16);
(void) WriteBlobMSBLong(image,0);
(void) WriteBlobMSBLong(image,0);
(void) FormatLocaleString(layer_name,MagickPathExtent,"L%04ld",(long)
layer_count++);
WritePascalString(image,layer_name,4);
}
else
{
size_t
label_length;
label_length=strlen(property);
(void) WriteBlobMSBLong(image,(unsigned int) (label_length+(4-
(label_length % 4))+8));
(void) WriteBlobMSBLong(image,0);
(void) WriteBlobMSBLong(image,0);
WritePascalString(image,property,4);
}
next_image=GetNextImageInList(next_image);
}
/*
Now the image data!
*/
next_image=base_image;
while (next_image != NULL)
{
status=WriteImageChannels(&psd_info,image_info,image,next_image,
MagickTrue,exception);
next_image=GetNextImageInList(next_image);
}
(void) WriteBlobMSBLong(image,0); /* user mask data */
base_image->compression=compression;
}
/*
Write composite image.
*/
if (status != MagickFalse)
status=WriteImageChannels(&psd_info,image_info,image,image,MagickFalse,
exception);
(void) CloseBlob(image);
return(status);
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_5312_0 |
crossvul-cpp_data_bad_4825_1 | /* Generated by re2c 0.13.7.5 */
#line 1 "ext/standard/var_unserializer.re"
/*
+----------------------------------------------------------------------+
| PHP Version 5 |
+----------------------------------------------------------------------+
| Copyright (c) 1997-2016 The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Author: Sascha Schumann <sascha@schumann.cx> |
+----------------------------------------------------------------------+
*/
/* $Id$ */
#include "php.h"
#include "ext/standard/php_var.h"
#include "php_incomplete_class.h"
/* {{{ reference-handling for unserializer: var_* */
#define VAR_ENTRIES_MAX 1024
#define VAR_ENTRIES_DBG 0
typedef struct {
zval *data[VAR_ENTRIES_MAX];
long used_slots;
void *next;
} var_entries;
static inline void var_push(php_unserialize_data_t *var_hashx, zval **rval)
{
var_entries *var_hash = (*var_hashx)->last;
#if VAR_ENTRIES_DBG
fprintf(stderr, "var_push(%ld): %d\n", var_hash?var_hash->used_slots:-1L, Z_TYPE_PP(rval));
#endif
if (!var_hash || var_hash->used_slots == VAR_ENTRIES_MAX) {
var_hash = emalloc(sizeof(var_entries));
var_hash->used_slots = 0;
var_hash->next = 0;
if (!(*var_hashx)->first) {
(*var_hashx)->first = var_hash;
} else {
((var_entries *) (*var_hashx)->last)->next = var_hash;
}
(*var_hashx)->last = var_hash;
}
var_hash->data[var_hash->used_slots++] = *rval;
}
PHPAPI void var_push_dtor(php_unserialize_data_t *var_hashx, zval **rval)
{
var_entries *var_hash;
if (!var_hashx || !*var_hashx) {
return;
}
var_hash = (*var_hashx)->last_dtor;
#if VAR_ENTRIES_DBG
fprintf(stderr, "var_push_dtor(%p, %ld): %d\n", *rval, var_hash?var_hash->used_slots:-1L, Z_TYPE_PP(rval));
#endif
if (!var_hash || var_hash->used_slots == VAR_ENTRIES_MAX) {
var_hash = emalloc(sizeof(var_entries));
var_hash->used_slots = 0;
var_hash->next = 0;
if (!(*var_hashx)->first_dtor) {
(*var_hashx)->first_dtor = var_hash;
} else {
((var_entries *) (*var_hashx)->last_dtor)->next = var_hash;
}
(*var_hashx)->last_dtor = var_hash;
}
Z_ADDREF_PP(rval);
var_hash->data[var_hash->used_slots++] = *rval;
}
PHPAPI void var_push_dtor_no_addref(php_unserialize_data_t *var_hashx, zval **rval)
{
var_entries *var_hash;
if (!var_hashx || !*var_hashx) {
return;
}
var_hash = (*var_hashx)->last_dtor;
#if VAR_ENTRIES_DBG
fprintf(stderr, "var_push_dtor_no_addref(%p, %ld): %d (%d)\n", *rval, var_hash?var_hash->used_slots:-1L, Z_TYPE_PP(rval), Z_REFCOUNT_PP(rval));
#endif
if (!var_hash || var_hash->used_slots == VAR_ENTRIES_MAX) {
var_hash = emalloc(sizeof(var_entries));
var_hash->used_slots = 0;
var_hash->next = 0;
if (!(*var_hashx)->first_dtor) {
(*var_hashx)->first_dtor = var_hash;
} else {
((var_entries *) (*var_hashx)->last_dtor)->next = var_hash;
}
(*var_hashx)->last_dtor = var_hash;
}
var_hash->data[var_hash->used_slots++] = *rval;
}
PHPAPI void var_replace(php_unserialize_data_t *var_hashx, zval *ozval, zval **nzval)
{
long i;
var_entries *var_hash = (*var_hashx)->first;
#if VAR_ENTRIES_DBG
fprintf(stderr, "var_replace(%ld): %d\n", var_hash?var_hash->used_slots:-1L, Z_TYPE_PP(nzval));
#endif
while (var_hash) {
for (i = 0; i < var_hash->used_slots; i++) {
if (var_hash->data[i] == ozval) {
var_hash->data[i] = *nzval;
/* do not break here */
}
}
var_hash = var_hash->next;
}
}
static int var_access(php_unserialize_data_t *var_hashx, long id, zval ***store)
{
var_entries *var_hash = (*var_hashx)->first;
#if VAR_ENTRIES_DBG
fprintf(stderr, "var_access(%ld): %ld\n", var_hash?var_hash->used_slots:-1L, id);
#endif
while (id >= VAR_ENTRIES_MAX && var_hash && var_hash->used_slots == VAR_ENTRIES_MAX) {
var_hash = var_hash->next;
id -= VAR_ENTRIES_MAX;
}
if (!var_hash) return !SUCCESS;
if (id < 0 || id >= var_hash->used_slots) return !SUCCESS;
*store = &var_hash->data[id];
return SUCCESS;
}
PHPAPI void var_destroy(php_unserialize_data_t *var_hashx)
{
void *next;
long i;
var_entries *var_hash = (*var_hashx)->first;
#if VAR_ENTRIES_DBG
fprintf(stderr, "var_destroy(%ld)\n", var_hash?var_hash->used_slots:-1L);
#endif
while (var_hash) {
next = var_hash->next;
efree(var_hash);
var_hash = next;
}
var_hash = (*var_hashx)->first_dtor;
while (var_hash) {
for (i = 0; i < var_hash->used_slots; i++) {
#if VAR_ENTRIES_DBG
fprintf(stderr, "var_destroy dtor(%p, %ld)\n", var_hash->data[i], Z_REFCOUNT_P(var_hash->data[i]));
#endif
zval_ptr_dtor(&var_hash->data[i]);
}
next = var_hash->next;
efree(var_hash);
var_hash = next;
}
}
/* }}} */
static char *unserialize_str(const unsigned char **p, size_t *len, size_t maxlen)
{
size_t i, j;
char *str = safe_emalloc(*len, 1, 1);
unsigned char *end = *(unsigned char **)p+maxlen;
if (end < *p) {
efree(str);
return NULL;
}
for (i = 0; i < *len; i++) {
if (*p >= end) {
efree(str);
return NULL;
}
if (**p != '\\') {
str[i] = (char)**p;
} else {
unsigned char ch = 0;
for (j = 0; j < 2; j++) {
(*p)++;
if (**p >= '0' && **p <= '9') {
ch = (ch << 4) + (**p -'0');
} else if (**p >= 'a' && **p <= 'f') {
ch = (ch << 4) + (**p -'a'+10);
} else if (**p >= 'A' && **p <= 'F') {
ch = (ch << 4) + (**p -'A'+10);
} else {
efree(str);
return NULL;
}
}
str[i] = (char)ch;
}
(*p)++;
}
str[i] = 0;
*len = i;
return str;
}
#define YYFILL(n) do { } while (0)
#define YYCTYPE unsigned char
#define YYCURSOR cursor
#define YYLIMIT limit
#define YYMARKER marker
#line 249 "ext/standard/var_unserializer.re"
static inline long parse_iv2(const unsigned char *p, const unsigned char **q)
{
char cursor;
long result = 0;
int neg = 0;
switch (*p) {
case '-':
neg++;
/* fall-through */
case '+':
p++;
}
while (1) {
cursor = (char)*p;
if (cursor >= '0' && cursor <= '9') {
result = result * 10 + (size_t)(cursor - (unsigned char)'0');
} else {
break;
}
p++;
}
if (q) *q = p;
if (neg) return -result;
return result;
}
static inline long parse_iv(const unsigned char *p)
{
return parse_iv2(p, NULL);
}
/* no need to check for length - re2c already did */
static inline size_t parse_uiv(const unsigned char *p)
{
unsigned char cursor;
size_t result = 0;
if (*p == '+') {
p++;
}
while (1) {
cursor = *p;
if (cursor >= '0' && cursor <= '9') {
result = result * 10 + (size_t)(cursor - (unsigned char)'0');
} else {
break;
}
p++;
}
return result;
}
#define UNSERIALIZE_PARAMETER zval **rval, const unsigned char **p, const unsigned char *max, php_unserialize_data_t *var_hash TSRMLS_DC
#define UNSERIALIZE_PASSTHRU rval, p, max, var_hash TSRMLS_CC
static inline int process_nested_data(UNSERIALIZE_PARAMETER, HashTable *ht, long elements, int objprops)
{
while (elements-- > 0) {
zval *key, *data, **old_data;
ALLOC_INIT_ZVAL(key);
if (!php_var_unserialize(&key, p, max, NULL TSRMLS_CC)) {
var_push_dtor_no_addref(var_hash, &key);
return 0;
}
if (Z_TYPE_P(key) != IS_LONG && Z_TYPE_P(key) != IS_STRING) {
var_push_dtor_no_addref(var_hash, &key);
return 0;
}
ALLOC_INIT_ZVAL(data);
if (!php_var_unserialize(&data, p, max, var_hash TSRMLS_CC)) {
var_push_dtor_no_addref(var_hash, &key);
var_push_dtor_no_addref(var_hash, &data);
return 0;
}
if (!objprops) {
switch (Z_TYPE_P(key)) {
case IS_LONG:
if (zend_hash_index_find(ht, Z_LVAL_P(key), (void **)&old_data)==SUCCESS) {
var_push_dtor(var_hash, old_data);
}
zend_hash_index_update(ht, Z_LVAL_P(key), &data, sizeof(data), NULL);
break;
case IS_STRING:
if (zend_symtable_find(ht, Z_STRVAL_P(key), Z_STRLEN_P(key) + 1, (void **)&old_data)==SUCCESS) {
var_push_dtor(var_hash, old_data);
}
zend_symtable_update(ht, Z_STRVAL_P(key), Z_STRLEN_P(key) + 1, &data, sizeof(data), NULL);
break;
}
} else {
/* object properties should include no integers */
convert_to_string(key);
if (zend_hash_find(ht, Z_STRVAL_P(key), Z_STRLEN_P(key) + 1, (void **)&old_data)==SUCCESS) {
var_push_dtor(var_hash, old_data);
}
zend_hash_update(ht, Z_STRVAL_P(key), Z_STRLEN_P(key) + 1, &data,
sizeof data, NULL);
}
var_push_dtor(var_hash, &data);
var_push_dtor_no_addref(var_hash, &key);
if (elements && *(*p-1) != ';' && *(*p-1) != '}') {
(*p)--;
return 0;
}
}
return 1;
}
static inline int finish_nested_data(UNSERIALIZE_PARAMETER)
{
if (*((*p)++) == '}')
return 1;
#if SOMETHING_NEW_MIGHT_LEAD_TO_CRASH_ENABLE_IF_YOU_ARE_BRAVE
zval_ptr_dtor(rval);
#endif
return 0;
}
static inline int object_custom(UNSERIALIZE_PARAMETER, zend_class_entry *ce)
{
long datalen;
datalen = parse_iv2((*p) + 2, p);
(*p) += 2;
if (datalen < 0 || (max - (*p)) <= datalen) {
zend_error(E_WARNING, "Insufficient data for unserializing - %ld required, %ld present", datalen, (long)(max - (*p)));
return 0;
}
if (ce->unserialize == NULL) {
zend_error(E_WARNING, "Class %s has no unserializer", ce->name);
object_init_ex(*rval, ce);
} else if (ce->unserialize(rval, ce, (const unsigned char*)*p, datalen, (zend_unserialize_data *)var_hash TSRMLS_CC) != SUCCESS) {
return 0;
}
(*p) += datalen;
return finish_nested_data(UNSERIALIZE_PASSTHRU);
}
static inline long object_common1(UNSERIALIZE_PARAMETER, zend_class_entry *ce)
{
long elements;
elements = parse_iv2((*p) + 2, p);
(*p) += 2;
if (ce->serialize == NULL) {
object_init_ex(*rval, ce);
} else {
/* If this class implements Serializable, it should not land here but in object_custom(). The passed string
obviously doesn't descend from the regular serializer. */
zend_error(E_WARNING, "Erroneous data format for unserializing '%s'", ce->name);
return 0;
}
return elements;
}
#ifdef PHP_WIN32
# pragma optimize("", off)
#endif
static inline int object_common2(UNSERIALIZE_PARAMETER, long elements)
{
zval *retval_ptr = NULL;
zval fname;
if (Z_TYPE_PP(rval) != IS_OBJECT) {
return 0;
}
if (!process_nested_data(UNSERIALIZE_PASSTHRU, Z_OBJPROP_PP(rval), elements, 1)) {
/* We've got partially constructed object on our hands here. Wipe it. */
if(Z_TYPE_PP(rval) == IS_OBJECT) {
zend_hash_clean(Z_OBJPROP_PP(rval));
zend_object_store_ctor_failed(*rval TSRMLS_CC);
}
ZVAL_NULL(*rval);
return 0;
}
if (Z_TYPE_PP(rval) != IS_OBJECT) {
return 0;
}
if (Z_OBJCE_PP(rval) != PHP_IC_ENTRY &&
zend_hash_exists(&Z_OBJCE_PP(rval)->function_table, "__wakeup", sizeof("__wakeup"))) {
INIT_PZVAL(&fname);
ZVAL_STRINGL(&fname, "__wakeup", sizeof("__wakeup") - 1, 0);
BG(serialize_lock)++;
call_user_function_ex(CG(function_table), rval, &fname, &retval_ptr, 0, 0, 1, NULL TSRMLS_CC);
BG(serialize_lock)--;
}
if (retval_ptr) {
zval_ptr_dtor(&retval_ptr);
}
if (EG(exception)) {
return 0;
}
return finish_nested_data(UNSERIALIZE_PASSTHRU);
}
#ifdef PHP_WIN32
# pragma optimize("", on)
#endif
PHPAPI int php_var_unserialize(UNSERIALIZE_PARAMETER)
{
const unsigned char *cursor, *limit, *marker, *start;
zval **rval_ref;
limit = max;
cursor = *p;
if (YYCURSOR >= YYLIMIT) {
return 0;
}
if (var_hash && cursor[0] != 'R') {
var_push(var_hash, rval);
}
start = cursor;
#line 496 "ext/standard/var_unserializer.c"
{
YYCTYPE yych;
static const unsigned char yybm[] = {
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
128, 128, 128, 128, 128, 128, 128, 128,
128, 128, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
};
if ((YYLIMIT - YYCURSOR) < 7) YYFILL(7);
yych = *YYCURSOR;
switch (yych) {
case 'C':
case 'O': goto yy13;
case 'N': goto yy5;
case 'R': goto yy2;
case 'S': goto yy10;
case 'a': goto yy11;
case 'b': goto yy6;
case 'd': goto yy8;
case 'i': goto yy7;
case 'o': goto yy12;
case 'r': goto yy4;
case 's': goto yy9;
case '}': goto yy14;
default: goto yy16;
}
yy2:
yych = *(YYMARKER = ++YYCURSOR);
if (yych == ':') goto yy95;
yy3:
#line 861 "ext/standard/var_unserializer.re"
{ return 0; }
#line 558 "ext/standard/var_unserializer.c"
yy4:
yych = *(YYMARKER = ++YYCURSOR);
if (yych == ':') goto yy89;
goto yy3;
yy5:
yych = *++YYCURSOR;
if (yych == ';') goto yy87;
goto yy3;
yy6:
yych = *(YYMARKER = ++YYCURSOR);
if (yych == ':') goto yy83;
goto yy3;
yy7:
yych = *(YYMARKER = ++YYCURSOR);
if (yych == ':') goto yy77;
goto yy3;
yy8:
yych = *(YYMARKER = ++YYCURSOR);
if (yych == ':') goto yy53;
goto yy3;
yy9:
yych = *(YYMARKER = ++YYCURSOR);
if (yych == ':') goto yy46;
goto yy3;
yy10:
yych = *(YYMARKER = ++YYCURSOR);
if (yych == ':') goto yy39;
goto yy3;
yy11:
yych = *(YYMARKER = ++YYCURSOR);
if (yych == ':') goto yy32;
goto yy3;
yy12:
yych = *(YYMARKER = ++YYCURSOR);
if (yych == ':') goto yy25;
goto yy3;
yy13:
yych = *(YYMARKER = ++YYCURSOR);
if (yych == ':') goto yy17;
goto yy3;
yy14:
++YYCURSOR;
#line 855 "ext/standard/var_unserializer.re"
{
/* this is the case where we have less data than planned */
php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Unexpected end of serialized data");
return 0; /* not sure if it should be 0 or 1 here? */
}
#line 607 "ext/standard/var_unserializer.c"
yy16:
yych = *++YYCURSOR;
goto yy3;
yy17:
yych = *++YYCURSOR;
if (yybm[0+yych] & 128) {
goto yy20;
}
if (yych == '+') goto yy19;
yy18:
YYCURSOR = YYMARKER;
goto yy3;
yy19:
yych = *++YYCURSOR;
if (yybm[0+yych] & 128) {
goto yy20;
}
goto yy18;
yy20:
++YYCURSOR;
if ((YYLIMIT - YYCURSOR) < 2) YYFILL(2);
yych = *YYCURSOR;
if (yybm[0+yych] & 128) {
goto yy20;
}
if (yych <= '/') goto yy18;
if (yych >= ';') goto yy18;
yych = *++YYCURSOR;
if (yych != '"') goto yy18;
++YYCURSOR;
#line 708 "ext/standard/var_unserializer.re"
{
size_t len, len2, len3, maxlen;
long elements;
char *class_name;
zend_class_entry *ce;
zend_class_entry **pce;
int incomplete_class = 0;
int custom_object = 0;
zval *user_func;
zval *retval_ptr;
zval **args[1];
zval *arg_func_name;
if (!var_hash) return 0;
if (*start == 'C') {
custom_object = 1;
}
INIT_PZVAL(*rval);
len2 = len = parse_uiv(start + 2);
maxlen = max - YYCURSOR;
if (maxlen < len || len == 0) {
*p = start + 2;
return 0;
}
class_name = (char*)YYCURSOR;
YYCURSOR += len;
if (*(YYCURSOR) != '"') {
*p = YYCURSOR;
return 0;
}
if (*(YYCURSOR+1) != ':') {
*p = YYCURSOR+1;
return 0;
}
len3 = strspn(class_name, "0123456789_abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\177\200\201\202\203\204\205\206\207\210\211\212\213\214\215\216\217\220\221\222\223\224\225\226\227\230\231\232\233\234\235\236\237\240\241\242\243\244\245\246\247\250\251\252\253\254\255\256\257\260\261\262\263\264\265\266\267\270\271\272\273\274\275\276\277\300\301\302\303\304\305\306\307\310\311\312\313\314\315\316\317\320\321\322\323\324\325\326\327\330\331\332\333\334\335\336\337\340\341\342\343\344\345\346\347\350\351\352\353\354\355\356\357\360\361\362\363\364\365\366\367\370\371\372\373\374\375\376\377\\");
if (len3 != len)
{
*p = YYCURSOR + len3 - len;
return 0;
}
class_name = estrndup(class_name, len);
do {
/* Try to find class directly */
BG(serialize_lock)++;
if (zend_lookup_class(class_name, len2, &pce TSRMLS_CC) == SUCCESS) {
BG(serialize_lock)--;
if (EG(exception)) {
efree(class_name);
return 0;
}
ce = *pce;
break;
}
BG(serialize_lock)--;
if (EG(exception)) {
efree(class_name);
return 0;
}
/* Check for unserialize callback */
if ((PG(unserialize_callback_func) == NULL) || (PG(unserialize_callback_func)[0] == '\0')) {
incomplete_class = 1;
ce = PHP_IC_ENTRY;
break;
}
/* Call unserialize callback */
MAKE_STD_ZVAL(user_func);
ZVAL_STRING(user_func, PG(unserialize_callback_func), 1);
args[0] = &arg_func_name;
MAKE_STD_ZVAL(arg_func_name);
ZVAL_STRING(arg_func_name, class_name, 1);
BG(serialize_lock)++;
if (call_user_function_ex(CG(function_table), NULL, user_func, &retval_ptr, 1, args, 0, NULL TSRMLS_CC) != SUCCESS) {
BG(serialize_lock)--;
if (EG(exception)) {
efree(class_name);
zval_ptr_dtor(&user_func);
zval_ptr_dtor(&arg_func_name);
return 0;
}
php_error_docref(NULL TSRMLS_CC, E_WARNING, "defined (%s) but not found", user_func->value.str.val);
incomplete_class = 1;
ce = PHP_IC_ENTRY;
zval_ptr_dtor(&user_func);
zval_ptr_dtor(&arg_func_name);
break;
}
BG(serialize_lock)--;
if (retval_ptr) {
zval_ptr_dtor(&retval_ptr);
}
if (EG(exception)) {
efree(class_name);
zval_ptr_dtor(&user_func);
zval_ptr_dtor(&arg_func_name);
return 0;
}
/* The callback function may have defined the class */
if (zend_lookup_class(class_name, len2, &pce TSRMLS_CC) == SUCCESS) {
ce = *pce;
} else {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Function %s() hasn't defined the class it was called for", user_func->value.str.val);
incomplete_class = 1;
ce = PHP_IC_ENTRY;
}
zval_ptr_dtor(&user_func);
zval_ptr_dtor(&arg_func_name);
break;
} while (1);
*p = YYCURSOR;
if (custom_object) {
int ret;
ret = object_custom(UNSERIALIZE_PASSTHRU, ce);
if (ret && incomplete_class) {
php_store_class_name(*rval, class_name, len2);
}
efree(class_name);
return ret;
}
elements = object_common1(UNSERIALIZE_PASSTHRU, ce);
if (incomplete_class) {
php_store_class_name(*rval, class_name, len2);
}
efree(class_name);
return object_common2(UNSERIALIZE_PASSTHRU, elements);
}
#line 785 "ext/standard/var_unserializer.c"
yy25:
yych = *++YYCURSOR;
if (yych <= ',') {
if (yych != '+') goto yy18;
} else {
if (yych <= '-') goto yy26;
if (yych <= '/') goto yy18;
if (yych <= '9') goto yy27;
goto yy18;
}
yy26:
yych = *++YYCURSOR;
if (yych <= '/') goto yy18;
if (yych >= ':') goto yy18;
yy27:
++YYCURSOR;
if ((YYLIMIT - YYCURSOR) < 2) YYFILL(2);
yych = *YYCURSOR;
if (yych <= '/') goto yy18;
if (yych <= '9') goto yy27;
if (yych >= ';') goto yy18;
yych = *++YYCURSOR;
if (yych != '"') goto yy18;
++YYCURSOR;
#line 699 "ext/standard/var_unserializer.re"
{
if (!var_hash) return 0;
INIT_PZVAL(*rval);
return object_common2(UNSERIALIZE_PASSTHRU,
object_common1(UNSERIALIZE_PASSTHRU, ZEND_STANDARD_CLASS_DEF_PTR));
}
#line 819 "ext/standard/var_unserializer.c"
yy32:
yych = *++YYCURSOR;
if (yych == '+') goto yy33;
if (yych <= '/') goto yy18;
if (yych <= '9') goto yy34;
goto yy18;
yy33:
yych = *++YYCURSOR;
if (yych <= '/') goto yy18;
if (yych >= ':') goto yy18;
yy34:
++YYCURSOR;
if ((YYLIMIT - YYCURSOR) < 2) YYFILL(2);
yych = *YYCURSOR;
if (yych <= '/') goto yy18;
if (yych <= '9') goto yy34;
if (yych >= ';') goto yy18;
yych = *++YYCURSOR;
if (yych != '{') goto yy18;
++YYCURSOR;
#line 678 "ext/standard/var_unserializer.re"
{
long elements = parse_iv(start + 2);
/* use iv() not uiv() in order to check data range */
*p = YYCURSOR;
if (!var_hash) return 0;
if (elements < 0) {
return 0;
}
INIT_PZVAL(*rval);
array_init_size(*rval, elements);
if (!process_nested_data(UNSERIALIZE_PASSTHRU, Z_ARRVAL_PP(rval), elements, 0)) {
return 0;
}
return finish_nested_data(UNSERIALIZE_PASSTHRU);
}
#line 861 "ext/standard/var_unserializer.c"
yy39:
yych = *++YYCURSOR;
if (yych == '+') goto yy40;
if (yych <= '/') goto yy18;
if (yych <= '9') goto yy41;
goto yy18;
yy40:
yych = *++YYCURSOR;
if (yych <= '/') goto yy18;
if (yych >= ':') goto yy18;
yy41:
++YYCURSOR;
if ((YYLIMIT - YYCURSOR) < 2) YYFILL(2);
yych = *YYCURSOR;
if (yych <= '/') goto yy18;
if (yych <= '9') goto yy41;
if (yych >= ';') goto yy18;
yych = *++YYCURSOR;
if (yych != '"') goto yy18;
++YYCURSOR;
#line 643 "ext/standard/var_unserializer.re"
{
size_t len, maxlen;
char *str;
len = parse_uiv(start + 2);
maxlen = max - YYCURSOR;
if (maxlen < len) {
*p = start + 2;
return 0;
}
if ((str = unserialize_str(&YYCURSOR, &len, maxlen)) == NULL) {
return 0;
}
if (*(YYCURSOR) != '"') {
efree(str);
*p = YYCURSOR;
return 0;
}
if (*(YYCURSOR + 1) != ';') {
efree(str);
*p = YYCURSOR + 1;
return 0;
}
YYCURSOR += 2;
*p = YYCURSOR;
INIT_PZVAL(*rval);
ZVAL_STRINGL(*rval, str, len, 0);
return 1;
}
#line 917 "ext/standard/var_unserializer.c"
yy46:
yych = *++YYCURSOR;
if (yych == '+') goto yy47;
if (yych <= '/') goto yy18;
if (yych <= '9') goto yy48;
goto yy18;
yy47:
yych = *++YYCURSOR;
if (yych <= '/') goto yy18;
if (yych >= ':') goto yy18;
yy48:
++YYCURSOR;
if ((YYLIMIT - YYCURSOR) < 2) YYFILL(2);
yych = *YYCURSOR;
if (yych <= '/') goto yy18;
if (yych <= '9') goto yy48;
if (yych >= ';') goto yy18;
yych = *++YYCURSOR;
if (yych != '"') goto yy18;
++YYCURSOR;
#line 610 "ext/standard/var_unserializer.re"
{
size_t len, maxlen;
char *str;
len = parse_uiv(start + 2);
maxlen = max - YYCURSOR;
if (maxlen < len) {
*p = start + 2;
return 0;
}
str = (char*)YYCURSOR;
YYCURSOR += len;
if (*(YYCURSOR) != '"') {
*p = YYCURSOR;
return 0;
}
if (*(YYCURSOR + 1) != ';') {
*p = YYCURSOR + 1;
return 0;
}
YYCURSOR += 2;
*p = YYCURSOR;
INIT_PZVAL(*rval);
ZVAL_STRINGL(*rval, str, len, 1);
return 1;
}
#line 971 "ext/standard/var_unserializer.c"
yy53:
yych = *++YYCURSOR;
if (yych <= '/') {
if (yych <= ',') {
if (yych == '+') goto yy57;
goto yy18;
} else {
if (yych <= '-') goto yy55;
if (yych <= '.') goto yy60;
goto yy18;
}
} else {
if (yych <= 'I') {
if (yych <= '9') goto yy58;
if (yych <= 'H') goto yy18;
goto yy56;
} else {
if (yych != 'N') goto yy18;
}
}
yych = *++YYCURSOR;
if (yych == 'A') goto yy76;
goto yy18;
yy55:
yych = *++YYCURSOR;
if (yych <= '/') {
if (yych == '.') goto yy60;
goto yy18;
} else {
if (yych <= '9') goto yy58;
if (yych != 'I') goto yy18;
}
yy56:
yych = *++YYCURSOR;
if (yych == 'N') goto yy72;
goto yy18;
yy57:
yych = *++YYCURSOR;
if (yych == '.') goto yy60;
if (yych <= '/') goto yy18;
if (yych >= ':') goto yy18;
yy58:
++YYCURSOR;
if ((YYLIMIT - YYCURSOR) < 4) YYFILL(4);
yych = *YYCURSOR;
if (yych <= ':') {
if (yych <= '.') {
if (yych <= '-') goto yy18;
goto yy70;
} else {
if (yych <= '/') goto yy18;
if (yych <= '9') goto yy58;
goto yy18;
}
} else {
if (yych <= 'E') {
if (yych <= ';') goto yy63;
if (yych <= 'D') goto yy18;
goto yy65;
} else {
if (yych == 'e') goto yy65;
goto yy18;
}
}
yy60:
yych = *++YYCURSOR;
if (yych <= '/') goto yy18;
if (yych >= ':') goto yy18;
yy61:
++YYCURSOR;
if ((YYLIMIT - YYCURSOR) < 4) YYFILL(4);
yych = *YYCURSOR;
if (yych <= ';') {
if (yych <= '/') goto yy18;
if (yych <= '9') goto yy61;
if (yych <= ':') goto yy18;
} else {
if (yych <= 'E') {
if (yych <= 'D') goto yy18;
goto yy65;
} else {
if (yych == 'e') goto yy65;
goto yy18;
}
}
yy63:
++YYCURSOR;
#line 600 "ext/standard/var_unserializer.re"
{
#if SIZEOF_LONG == 4
use_double:
#endif
*p = YYCURSOR;
INIT_PZVAL(*rval);
ZVAL_DOUBLE(*rval, zend_strtod((const char *)start + 2, NULL));
return 1;
}
#line 1069 "ext/standard/var_unserializer.c"
yy65:
yych = *++YYCURSOR;
if (yych <= ',') {
if (yych != '+') goto yy18;
} else {
if (yych <= '-') goto yy66;
if (yych <= '/') goto yy18;
if (yych <= '9') goto yy67;
goto yy18;
}
yy66:
yych = *++YYCURSOR;
if (yych <= ',') {
if (yych == '+') goto yy69;
goto yy18;
} else {
if (yych <= '-') goto yy69;
if (yych <= '/') goto yy18;
if (yych >= ':') goto yy18;
}
yy67:
++YYCURSOR;
if (YYLIMIT <= YYCURSOR) YYFILL(1);
yych = *YYCURSOR;
if (yych <= '/') goto yy18;
if (yych <= '9') goto yy67;
if (yych == ';') goto yy63;
goto yy18;
yy69:
yych = *++YYCURSOR;
if (yych <= '/') goto yy18;
if (yych <= '9') goto yy67;
goto yy18;
yy70:
++YYCURSOR;
if ((YYLIMIT - YYCURSOR) < 4) YYFILL(4);
yych = *YYCURSOR;
if (yych <= ';') {
if (yych <= '/') goto yy18;
if (yych <= '9') goto yy70;
if (yych <= ':') goto yy18;
goto yy63;
} else {
if (yych <= 'E') {
if (yych <= 'D') goto yy18;
goto yy65;
} else {
if (yych == 'e') goto yy65;
goto yy18;
}
}
yy72:
yych = *++YYCURSOR;
if (yych != 'F') goto yy18;
yy73:
yych = *++YYCURSOR;
if (yych != ';') goto yy18;
++YYCURSOR;
#line 585 "ext/standard/var_unserializer.re"
{
*p = YYCURSOR;
INIT_PZVAL(*rval);
if (!strncmp(start + 2, "NAN", 3)) {
ZVAL_DOUBLE(*rval, php_get_nan());
} else if (!strncmp(start + 2, "INF", 3)) {
ZVAL_DOUBLE(*rval, php_get_inf());
} else if (!strncmp(start + 2, "-INF", 4)) {
ZVAL_DOUBLE(*rval, -php_get_inf());
}
return 1;
}
#line 1143 "ext/standard/var_unserializer.c"
yy76:
yych = *++YYCURSOR;
if (yych == 'N') goto yy73;
goto yy18;
yy77:
yych = *++YYCURSOR;
if (yych <= ',') {
if (yych != '+') goto yy18;
} else {
if (yych <= '-') goto yy78;
if (yych <= '/') goto yy18;
if (yych <= '9') goto yy79;
goto yy18;
}
yy78:
yych = *++YYCURSOR;
if (yych <= '/') goto yy18;
if (yych >= ':') goto yy18;
yy79:
++YYCURSOR;
if (YYLIMIT <= YYCURSOR) YYFILL(1);
yych = *YYCURSOR;
if (yych <= '/') goto yy18;
if (yych <= '9') goto yy79;
if (yych != ';') goto yy18;
++YYCURSOR;
#line 558 "ext/standard/var_unserializer.re"
{
#if SIZEOF_LONG == 4
int digits = YYCURSOR - start - 3;
if (start[2] == '-' || start[2] == '+') {
digits--;
}
/* Use double for large long values that were serialized on a 64-bit system */
if (digits >= MAX_LENGTH_OF_LONG - 1) {
if (digits == MAX_LENGTH_OF_LONG - 1) {
int cmp = strncmp(YYCURSOR - MAX_LENGTH_OF_LONG, long_min_digits, MAX_LENGTH_OF_LONG - 1);
if (!(cmp < 0 || (cmp == 0 && start[2] == '-'))) {
goto use_double;
}
} else {
goto use_double;
}
}
#endif
*p = YYCURSOR;
INIT_PZVAL(*rval);
ZVAL_LONG(*rval, parse_iv(start + 2));
return 1;
}
#line 1197 "ext/standard/var_unserializer.c"
yy83:
yych = *++YYCURSOR;
if (yych <= '/') goto yy18;
if (yych >= '2') goto yy18;
yych = *++YYCURSOR;
if (yych != ';') goto yy18;
++YYCURSOR;
#line 551 "ext/standard/var_unserializer.re"
{
*p = YYCURSOR;
INIT_PZVAL(*rval);
ZVAL_BOOL(*rval, parse_iv(start + 2));
return 1;
}
#line 1212 "ext/standard/var_unserializer.c"
yy87:
++YYCURSOR;
#line 544 "ext/standard/var_unserializer.re"
{
*p = YYCURSOR;
INIT_PZVAL(*rval);
ZVAL_NULL(*rval);
return 1;
}
#line 1222 "ext/standard/var_unserializer.c"
yy89:
yych = *++YYCURSOR;
if (yych <= ',') {
if (yych != '+') goto yy18;
} else {
if (yych <= '-') goto yy90;
if (yych <= '/') goto yy18;
if (yych <= '9') goto yy91;
goto yy18;
}
yy90:
yych = *++YYCURSOR;
if (yych <= '/') goto yy18;
if (yych >= ':') goto yy18;
yy91:
++YYCURSOR;
if (YYLIMIT <= YYCURSOR) YYFILL(1);
yych = *YYCURSOR;
if (yych <= '/') goto yy18;
if (yych <= '9') goto yy91;
if (yych != ';') goto yy18;
++YYCURSOR;
#line 521 "ext/standard/var_unserializer.re"
{
long id;
*p = YYCURSOR;
if (!var_hash) return 0;
id = parse_iv(start + 2) - 1;
if (id == -1 || var_access(var_hash, id, &rval_ref) != SUCCESS) {
return 0;
}
if (*rval == *rval_ref) return 0;
if (*rval != NULL) {
var_push_dtor_no_addref(var_hash, rval);
}
*rval = *rval_ref;
Z_ADDREF_PP(rval);
Z_UNSET_ISREF_PP(rval);
return 1;
}
#line 1268 "ext/standard/var_unserializer.c"
yy95:
yych = *++YYCURSOR;
if (yych <= ',') {
if (yych != '+') goto yy18;
} else {
if (yych <= '-') goto yy96;
if (yych <= '/') goto yy18;
if (yych <= '9') goto yy97;
goto yy18;
}
yy96:
yych = *++YYCURSOR;
if (yych <= '/') goto yy18;
if (yych >= ':') goto yy18;
yy97:
++YYCURSOR;
if (YYLIMIT <= YYCURSOR) YYFILL(1);
yych = *YYCURSOR;
if (yych <= '/') goto yy18;
if (yych <= '9') goto yy97;
if (yych != ';') goto yy18;
++YYCURSOR;
#line 500 "ext/standard/var_unserializer.re"
{
long id;
*p = YYCURSOR;
if (!var_hash) return 0;
id = parse_iv(start + 2) - 1;
if (id == -1 || var_access(var_hash, id, &rval_ref) != SUCCESS) {
return 0;
}
if (*rval != NULL) {
var_push_dtor_no_addref(var_hash, rval);
}
*rval = *rval_ref;
Z_ADDREF_PP(rval);
Z_SET_ISREF_PP(rval);
return 1;
}
#line 1312 "ext/standard/var_unserializer.c"
}
#line 863 "ext/standard/var_unserializer.re"
return 0;
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_4825_1 |
crossvul-cpp_data_bad_3944_0 | /**
* WinPR: Windows Portable Runtime
* NTLM Security Package (Message)
*
* Copyright 2011-2014 Marc-Andre Moreau <marcandre.moreau@gmail.com>
*
* 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 HAVE_CONFIG_H
#include "config.h"
#endif
#include "ntlm.h"
#include "../sspi.h"
#include <winpr/crt.h>
#include <winpr/print.h>
#include <winpr/stream.h>
#include <winpr/sysinfo.h>
#include "ntlm_compute.h"
#include "ntlm_message.h"
#include "../log.h"
#define TAG WINPR_TAG("sspi.NTLM")
static const char NTLM_SIGNATURE[8] = { 'N', 'T', 'L', 'M', 'S', 'S', 'P', '\0' };
#ifdef WITH_DEBUG_NTLM
static const char* const NTLM_NEGOTIATE_STRINGS[] = { "NTLMSSP_NEGOTIATE_56",
"NTLMSSP_NEGOTIATE_KEY_EXCH",
"NTLMSSP_NEGOTIATE_128",
"NTLMSSP_RESERVED1",
"NTLMSSP_RESERVED2",
"NTLMSSP_RESERVED3",
"NTLMSSP_NEGOTIATE_VERSION",
"NTLMSSP_RESERVED4",
"NTLMSSP_NEGOTIATE_TARGET_INFO",
"NTLMSSP_REQUEST_NON_NT_SESSION_KEY",
"NTLMSSP_RESERVED5",
"NTLMSSP_NEGOTIATE_IDENTIFY",
"NTLMSSP_NEGOTIATE_EXTENDED_SESSION_SECURITY",
"NTLMSSP_RESERVED6",
"NTLMSSP_TARGET_TYPE_SERVER",
"NTLMSSP_TARGET_TYPE_DOMAIN",
"NTLMSSP_NEGOTIATE_ALWAYS_SIGN",
"NTLMSSP_RESERVED7",
"NTLMSSP_NEGOTIATE_WORKSTATION_SUPPLIED",
"NTLMSSP_NEGOTIATE_DOMAIN_SUPPLIED",
"NTLMSSP_NEGOTIATE_ANONYMOUS",
"NTLMSSP_RESERVED8",
"NTLMSSP_NEGOTIATE_NTLM",
"NTLMSSP_RESERVED9",
"NTLMSSP_NEGOTIATE_LM_KEY",
"NTLMSSP_NEGOTIATE_DATAGRAM",
"NTLMSSP_NEGOTIATE_SEAL",
"NTLMSSP_NEGOTIATE_SIGN",
"NTLMSSP_RESERVED10",
"NTLMSSP_REQUEST_TARGET",
"NTLMSSP_NEGOTIATE_OEM",
"NTLMSSP_NEGOTIATE_UNICODE" };
static void ntlm_print_negotiate_flags(UINT32 flags)
{
int i;
const char* str;
WLog_INFO(TAG, "negotiateFlags \"0x%08" PRIX32 "\"", flags);
for (i = 31; i >= 0; i--)
{
if ((flags >> i) & 1)
{
str = NTLM_NEGOTIATE_STRINGS[(31 - i)];
WLog_INFO(TAG, "\t%s (%d),", str, (31 - i));
}
}
}
#endif
static int ntlm_read_message_header(wStream* s, NTLM_MESSAGE_HEADER* header)
{
if (Stream_GetRemainingLength(s) < 12)
return -1;
Stream_Read(s, header->Signature, 8);
Stream_Read_UINT32(s, header->MessageType);
if (strncmp((char*)header->Signature, NTLM_SIGNATURE, 8) != 0)
return -1;
return 1;
}
static void ntlm_write_message_header(wStream* s, NTLM_MESSAGE_HEADER* header)
{
Stream_Write(s, header->Signature, sizeof(NTLM_SIGNATURE));
Stream_Write_UINT32(s, header->MessageType);
}
static void ntlm_populate_message_header(NTLM_MESSAGE_HEADER* header, UINT32 MessageType)
{
CopyMemory(header->Signature, NTLM_SIGNATURE, sizeof(NTLM_SIGNATURE));
header->MessageType = MessageType;
}
static int ntlm_read_message_fields(wStream* s, NTLM_MESSAGE_FIELDS* fields)
{
if (Stream_GetRemainingLength(s) < 8)
return -1;
Stream_Read_UINT16(s, fields->Len); /* Len (2 bytes) */
Stream_Read_UINT16(s, fields->MaxLen); /* MaxLen (2 bytes) */
Stream_Read_UINT32(s, fields->BufferOffset); /* BufferOffset (4 bytes) */
return 1;
}
static void ntlm_write_message_fields(wStream* s, NTLM_MESSAGE_FIELDS* fields)
{
if (fields->MaxLen < 1)
fields->MaxLen = fields->Len;
Stream_Write_UINT16(s, fields->Len); /* Len (2 bytes) */
Stream_Write_UINT16(s, fields->MaxLen); /* MaxLen (2 bytes) */
Stream_Write_UINT32(s, fields->BufferOffset); /* BufferOffset (4 bytes) */
}
static int ntlm_read_message_fields_buffer(wStream* s, NTLM_MESSAGE_FIELDS* fields)
{
if (fields->Len > 0)
{
const UINT32 offset = fields->BufferOffset + fields->Len;
if (fields->BufferOffset > UINT32_MAX - fields->Len)
return -1;
if (offset > Stream_Length(s))
return -1;
fields->Buffer = (PBYTE)malloc(fields->Len);
if (!fields->Buffer)
return -1;
Stream_SetPosition(s, fields->BufferOffset);
Stream_Read(s, fields->Buffer, fields->Len);
}
return 1;
}
static void ntlm_write_message_fields_buffer(wStream* s, NTLM_MESSAGE_FIELDS* fields)
{
if (fields->Len > 0)
{
Stream_SetPosition(s, fields->BufferOffset);
Stream_Write(s, fields->Buffer, fields->Len);
}
}
static void ntlm_free_message_fields_buffer(NTLM_MESSAGE_FIELDS* fields)
{
if (fields)
{
if (fields->Buffer)
{
free(fields->Buffer);
fields->Len = 0;
fields->MaxLen = 0;
fields->Buffer = NULL;
fields->BufferOffset = 0;
}
}
}
#ifdef WITH_DEBUG_NTLM
static void ntlm_print_message_fields(NTLM_MESSAGE_FIELDS* fields, const char* name)
{
WLog_DBG(TAG, "%s (Len: %" PRIu16 " MaxLen: %" PRIu16 " BufferOffset: %" PRIu32 ")", name,
fields->Len, fields->MaxLen, fields->BufferOffset);
if (fields->Len > 0)
winpr_HexDump(TAG, WLOG_DEBUG, fields->Buffer, fields->Len);
}
#endif
SECURITY_STATUS ntlm_read_NegotiateMessage(NTLM_CONTEXT* context, PSecBuffer buffer)
{
wStream* s;
size_t length;
NTLM_NEGOTIATE_MESSAGE* message;
message = &context->NEGOTIATE_MESSAGE;
ZeroMemory(message, sizeof(NTLM_NEGOTIATE_MESSAGE));
s = Stream_New((BYTE*)buffer->pvBuffer, buffer->cbBuffer);
if (!s)
return SEC_E_INTERNAL_ERROR;
if (ntlm_read_message_header(s, (NTLM_MESSAGE_HEADER*)message) < 0)
{
Stream_Free(s, FALSE);
return SEC_E_INVALID_TOKEN;
}
if (message->MessageType != MESSAGE_TYPE_NEGOTIATE)
{
Stream_Free(s, FALSE);
return SEC_E_INVALID_TOKEN;
}
if (Stream_GetRemainingLength(s) < 4)
{
Stream_Free(s, FALSE);
return SEC_E_INVALID_TOKEN;
}
Stream_Read_UINT32(s, message->NegotiateFlags); /* NegotiateFlags (4 bytes) */
if (!((message->NegotiateFlags & NTLMSSP_REQUEST_TARGET) &&
(message->NegotiateFlags & NTLMSSP_NEGOTIATE_NTLM) &&
(message->NegotiateFlags & NTLMSSP_NEGOTIATE_UNICODE)))
{
Stream_Free(s, FALSE);
return SEC_E_INVALID_TOKEN;
}
context->NegotiateFlags = message->NegotiateFlags;
/* only set if NTLMSSP_NEGOTIATE_DOMAIN_SUPPLIED is set */
if (ntlm_read_message_fields(s, &(message->DomainName)) < 0) /* DomainNameFields (8 bytes) */
{
Stream_Free(s, FALSE);
return SEC_E_INVALID_TOKEN;
}
/* only set if NTLMSSP_NEGOTIATE_WORKSTATION_SUPPLIED is set */
if (ntlm_read_message_fields(s, &(message->Workstation)) < 0) /* WorkstationFields (8 bytes) */
{
Stream_Free(s, FALSE);
return SEC_E_INVALID_TOKEN;
}
if (message->NegotiateFlags & NTLMSSP_NEGOTIATE_VERSION)
{
if (ntlm_read_version_info(s, &(message->Version)) < 0) /* Version (8 bytes) */
{
Stream_Free(s, FALSE);
return SEC_E_INVALID_TOKEN;
}
}
length = Stream_GetPosition(s);
buffer->cbBuffer = length;
if (!sspi_SecBufferAlloc(&context->NegotiateMessage, length))
{
Stream_Free(s, FALSE);
return SEC_E_INTERNAL_ERROR;
}
CopyMemory(context->NegotiateMessage.pvBuffer, buffer->pvBuffer, buffer->cbBuffer);
context->NegotiateMessage.BufferType = buffer->BufferType;
#ifdef WITH_DEBUG_NTLM
WLog_DBG(TAG, "NEGOTIATE_MESSAGE (length = %" PRIu32 ")", context->NegotiateMessage.cbBuffer);
winpr_HexDump(TAG, WLOG_DEBUG, context->NegotiateMessage.pvBuffer,
context->NegotiateMessage.cbBuffer);
ntlm_print_negotiate_flags(message->NegotiateFlags);
if (message->NegotiateFlags & NTLMSSP_NEGOTIATE_VERSION)
ntlm_print_version_info(&(message->Version));
#endif
context->state = NTLM_STATE_CHALLENGE;
Stream_Free(s, FALSE);
return SEC_I_CONTINUE_NEEDED;
}
SECURITY_STATUS ntlm_write_NegotiateMessage(NTLM_CONTEXT* context, PSecBuffer buffer)
{
wStream* s;
size_t length;
NTLM_NEGOTIATE_MESSAGE* message;
message = &context->NEGOTIATE_MESSAGE;
ZeroMemory(message, sizeof(NTLM_NEGOTIATE_MESSAGE));
s = Stream_New((BYTE*)buffer->pvBuffer, buffer->cbBuffer);
if (!s)
return SEC_E_INTERNAL_ERROR;
ntlm_populate_message_header((NTLM_MESSAGE_HEADER*)message, MESSAGE_TYPE_NEGOTIATE);
if (context->NTLMv2)
{
message->NegotiateFlags |= NTLMSSP_NEGOTIATE_56;
message->NegotiateFlags |= NTLMSSP_NEGOTIATE_VERSION;
message->NegotiateFlags |= NTLMSSP_NEGOTIATE_LM_KEY;
message->NegotiateFlags |= NTLMSSP_NEGOTIATE_OEM;
}
message->NegotiateFlags |= NTLMSSP_NEGOTIATE_KEY_EXCH;
message->NegotiateFlags |= NTLMSSP_NEGOTIATE_128;
message->NegotiateFlags |= NTLMSSP_NEGOTIATE_EXTENDED_SESSION_SECURITY;
message->NegotiateFlags |= NTLMSSP_NEGOTIATE_ALWAYS_SIGN;
message->NegotiateFlags |= NTLMSSP_NEGOTIATE_NTLM;
message->NegotiateFlags |= NTLMSSP_NEGOTIATE_SIGN;
message->NegotiateFlags |= NTLMSSP_REQUEST_TARGET;
message->NegotiateFlags |= NTLMSSP_NEGOTIATE_UNICODE;
if (context->confidentiality)
message->NegotiateFlags |= NTLMSSP_NEGOTIATE_SEAL;
if (context->SendVersionInfo)
message->NegotiateFlags |= NTLMSSP_NEGOTIATE_VERSION;
if (message->NegotiateFlags & NTLMSSP_NEGOTIATE_VERSION)
ntlm_get_version_info(&(message->Version));
context->NegotiateFlags = message->NegotiateFlags;
/* Message Header (12 bytes) */
ntlm_write_message_header(s, (NTLM_MESSAGE_HEADER*)message);
Stream_Write_UINT32(s, message->NegotiateFlags); /* NegotiateFlags (4 bytes) */
/* only set if NTLMSSP_NEGOTIATE_DOMAIN_SUPPLIED is set */
/* DomainNameFields (8 bytes) */
ntlm_write_message_fields(s, &(message->DomainName));
/* only set if NTLMSSP_NEGOTIATE_WORKSTATION_SUPPLIED is set */
/* WorkstationFields (8 bytes) */
ntlm_write_message_fields(s, &(message->Workstation));
if (message->NegotiateFlags & NTLMSSP_NEGOTIATE_VERSION)
ntlm_write_version_info(s, &(message->Version));
length = Stream_GetPosition(s);
buffer->cbBuffer = length;
if (!sspi_SecBufferAlloc(&context->NegotiateMessage, length))
{
Stream_Free(s, FALSE);
return SEC_E_INTERNAL_ERROR;
}
CopyMemory(context->NegotiateMessage.pvBuffer, buffer->pvBuffer, buffer->cbBuffer);
context->NegotiateMessage.BufferType = buffer->BufferType;
#ifdef WITH_DEBUG_NTLM
WLog_DBG(TAG, "NEGOTIATE_MESSAGE (length = %d)", length);
winpr_HexDump(TAG, WLOG_DEBUG, Stream_Buffer(s), length);
if (message->NegotiateFlags & NTLMSSP_NEGOTIATE_VERSION)
ntlm_print_version_info(&(message->Version));
#endif
context->state = NTLM_STATE_CHALLENGE;
Stream_Free(s, FALSE);
return SEC_I_CONTINUE_NEEDED;
}
SECURITY_STATUS ntlm_read_ChallengeMessage(NTLM_CONTEXT* context, PSecBuffer buffer)
{
wStream* s;
int length;
PBYTE StartOffset;
PBYTE PayloadOffset;
NTLM_AV_PAIR* AvTimestamp;
NTLM_CHALLENGE_MESSAGE* message;
ntlm_generate_client_challenge(context);
message = &context->CHALLENGE_MESSAGE;
ZeroMemory(message, sizeof(NTLM_CHALLENGE_MESSAGE));
s = Stream_New((BYTE*)buffer->pvBuffer, buffer->cbBuffer);
if (!s)
return SEC_E_INTERNAL_ERROR;
StartOffset = Stream_Pointer(s);
if (ntlm_read_message_header(s, (NTLM_MESSAGE_HEADER*)message) < 0)
{
Stream_Free(s, FALSE);
return SEC_E_INVALID_TOKEN;
}
if (message->MessageType != MESSAGE_TYPE_CHALLENGE)
{
Stream_Free(s, FALSE);
return SEC_E_INVALID_TOKEN;
}
if (ntlm_read_message_fields(s, &(message->TargetName)) < 0) /* TargetNameFields (8 bytes) */
{
Stream_Free(s, FALSE);
return SEC_E_INVALID_TOKEN;
}
if (Stream_GetRemainingLength(s) < 4)
{
Stream_Free(s, FALSE);
return SEC_E_INVALID_TOKEN;
}
Stream_Read_UINT32(s, message->NegotiateFlags); /* NegotiateFlags (4 bytes) */
context->NegotiateFlags = message->NegotiateFlags;
if (Stream_GetRemainingLength(s) < 8)
{
Stream_Free(s, FALSE);
return SEC_E_INVALID_TOKEN;
}
Stream_Read(s, message->ServerChallenge, 8); /* ServerChallenge (8 bytes) */
CopyMemory(context->ServerChallenge, message->ServerChallenge, 8);
if (Stream_GetRemainingLength(s) < 8)
{
Stream_Free(s, FALSE);
return SEC_E_INVALID_TOKEN;
}
Stream_Read(s, message->Reserved, 8); /* Reserved (8 bytes), should be ignored */
if (ntlm_read_message_fields(s, &(message->TargetInfo)) < 0) /* TargetInfoFields (8 bytes) */
{
Stream_Free(s, FALSE);
return SEC_E_INVALID_TOKEN;
}
if (context->NegotiateFlags & NTLMSSP_NEGOTIATE_VERSION)
{
if (ntlm_read_version_info(s, &(message->Version)) < 0) /* Version (8 bytes) */
{
Stream_Free(s, FALSE);
return SEC_E_INVALID_TOKEN;
}
}
/* Payload (variable) */
PayloadOffset = Stream_Pointer(s);
if (message->TargetName.Len > 0)
{
if (ntlm_read_message_fields_buffer(s, &(message->TargetName)) < 0)
{
Stream_Free(s, FALSE);
return SEC_E_INTERNAL_ERROR;
}
}
if (message->TargetInfo.Len > 0)
{
size_t cbAvTimestamp;
if (ntlm_read_message_fields_buffer(s, &(message->TargetInfo)) < 0)
{
Stream_Free(s, FALSE);
return SEC_E_INTERNAL_ERROR;
}
context->ChallengeTargetInfo.pvBuffer = message->TargetInfo.Buffer;
context->ChallengeTargetInfo.cbBuffer = message->TargetInfo.Len;
AvTimestamp = ntlm_av_pair_get((NTLM_AV_PAIR*)message->TargetInfo.Buffer,
message->TargetInfo.Len, MsvAvTimestamp, &cbAvTimestamp);
if (AvTimestamp)
{
PBYTE ptr = ntlm_av_pair_get_value_pointer(AvTimestamp);
if (!ptr)
return SEC_E_INTERNAL_ERROR;
if (context->NTLMv2)
context->UseMIC = TRUE;
CopyMemory(context->ChallengeTimestamp, ptr, 8);
}
}
length = (PayloadOffset - StartOffset) + message->TargetName.Len + message->TargetInfo.Len;
if (!sspi_SecBufferAlloc(&context->ChallengeMessage, length))
{
Stream_Free(s, FALSE);
return SEC_E_INTERNAL_ERROR;
}
CopyMemory(context->ChallengeMessage.pvBuffer, StartOffset, length);
#ifdef WITH_DEBUG_NTLM
WLog_DBG(TAG, "CHALLENGE_MESSAGE (length = %d)", length);
winpr_HexDump(TAG, WLOG_DEBUG, context->ChallengeMessage.pvBuffer,
context->ChallengeMessage.cbBuffer);
ntlm_print_negotiate_flags(context->NegotiateFlags);
if (context->NegotiateFlags & NTLMSSP_NEGOTIATE_VERSION)
ntlm_print_version_info(&(message->Version));
ntlm_print_message_fields(&(message->TargetName), "TargetName");
ntlm_print_message_fields(&(message->TargetInfo), "TargetInfo");
if (context->ChallengeTargetInfo.cbBuffer > 0)
{
WLog_DBG(TAG, "ChallengeTargetInfo (%" PRIu32 "):", context->ChallengeTargetInfo.cbBuffer);
ntlm_print_av_pair_list(context->ChallengeTargetInfo.pvBuffer,
context->ChallengeTargetInfo.cbBuffer);
}
#endif
/* AV_PAIRs */
if (context->NTLMv2)
{
if (ntlm_construct_authenticate_target_info(context) < 0)
{
Stream_Free(s, FALSE);
return SEC_E_INTERNAL_ERROR;
}
sspi_SecBufferFree(&context->ChallengeTargetInfo);
context->ChallengeTargetInfo.pvBuffer = context->AuthenticateTargetInfo.pvBuffer;
context->ChallengeTargetInfo.cbBuffer = context->AuthenticateTargetInfo.cbBuffer;
}
ntlm_generate_timestamp(context); /* Timestamp */
if (ntlm_compute_lm_v2_response(context) < 0) /* LmChallengeResponse */
{
Stream_Free(s, FALSE);
return SEC_E_INTERNAL_ERROR;
}
if (ntlm_compute_ntlm_v2_response(context) < 0) /* NtChallengeResponse */
{
Stream_Free(s, FALSE);
return SEC_E_INTERNAL_ERROR;
}
ntlm_generate_key_exchange_key(context); /* KeyExchangeKey */
ntlm_generate_random_session_key(context); /* RandomSessionKey */
ntlm_generate_exported_session_key(context); /* ExportedSessionKey */
ntlm_encrypt_random_session_key(context); /* EncryptedRandomSessionKey */
/* Generate signing keys */
ntlm_generate_client_signing_key(context);
ntlm_generate_server_signing_key(context);
/* Generate sealing keys */
ntlm_generate_client_sealing_key(context);
ntlm_generate_server_sealing_key(context);
/* Initialize RC4 seal state using client sealing key */
ntlm_init_rc4_seal_states(context);
#ifdef WITH_DEBUG_NTLM
WLog_DBG(TAG, "ClientChallenge");
winpr_HexDump(TAG, WLOG_DEBUG, context->ClientChallenge, 8);
WLog_DBG(TAG, "ServerChallenge");
winpr_HexDump(TAG, WLOG_DEBUG, context->ServerChallenge, 8);
WLog_DBG(TAG, "SessionBaseKey");
winpr_HexDump(TAG, WLOG_DEBUG, context->SessionBaseKey, 16);
WLog_DBG(TAG, "KeyExchangeKey");
winpr_HexDump(TAG, WLOG_DEBUG, context->KeyExchangeKey, 16);
WLog_DBG(TAG, "ExportedSessionKey");
winpr_HexDump(TAG, WLOG_DEBUG, context->ExportedSessionKey, 16);
WLog_DBG(TAG, "RandomSessionKey");
winpr_HexDump(TAG, WLOG_DEBUG, context->RandomSessionKey, 16);
WLog_DBG(TAG, "ClientSigningKey");
winpr_HexDump(TAG, WLOG_DEBUG, context->ClientSigningKey, 16);
WLog_DBG(TAG, "ClientSealingKey");
winpr_HexDump(TAG, WLOG_DEBUG, context->ClientSealingKey, 16);
WLog_DBG(TAG, "ServerSigningKey");
winpr_HexDump(TAG, WLOG_DEBUG, context->ServerSigningKey, 16);
WLog_DBG(TAG, "ServerSealingKey");
winpr_HexDump(TAG, WLOG_DEBUG, context->ServerSealingKey, 16);
WLog_DBG(TAG, "Timestamp");
winpr_HexDump(TAG, WLOG_DEBUG, context->Timestamp, 8);
#endif
context->state = NTLM_STATE_AUTHENTICATE;
ntlm_free_message_fields_buffer(&(message->TargetName));
Stream_Free(s, FALSE);
return SEC_I_CONTINUE_NEEDED;
}
SECURITY_STATUS ntlm_write_ChallengeMessage(NTLM_CONTEXT* context, PSecBuffer buffer)
{
wStream* s;
size_t length;
UINT32 PayloadOffset;
NTLM_CHALLENGE_MESSAGE* message;
message = &context->CHALLENGE_MESSAGE;
ZeroMemory(message, sizeof(NTLM_CHALLENGE_MESSAGE));
s = Stream_New((BYTE*)buffer->pvBuffer, buffer->cbBuffer);
if (!s)
return SEC_E_INTERNAL_ERROR;
ntlm_get_version_info(&(message->Version)); /* Version */
ntlm_generate_server_challenge(context); /* Server Challenge */
ntlm_generate_timestamp(context); /* Timestamp */
if (ntlm_construct_challenge_target_info(context) < 0) /* TargetInfo */
{
Stream_Free(s, FALSE);
return SEC_E_INTERNAL_ERROR;
}
CopyMemory(message->ServerChallenge, context->ServerChallenge, 8); /* ServerChallenge */
message->NegotiateFlags = context->NegotiateFlags;
ntlm_populate_message_header((NTLM_MESSAGE_HEADER*)message, MESSAGE_TYPE_CHALLENGE);
/* Message Header (12 bytes) */
ntlm_write_message_header(s, (NTLM_MESSAGE_HEADER*)message);
if (message->NegotiateFlags & NTLMSSP_REQUEST_TARGET)
{
message->TargetName.Len = (UINT16)context->TargetName.cbBuffer;
message->TargetName.Buffer = (PBYTE)context->TargetName.pvBuffer;
}
message->NegotiateFlags |= NTLMSSP_NEGOTIATE_TARGET_INFO;
if (message->NegotiateFlags & NTLMSSP_NEGOTIATE_TARGET_INFO)
{
message->TargetInfo.Len = (UINT16)context->ChallengeTargetInfo.cbBuffer;
message->TargetInfo.Buffer = (PBYTE)context->ChallengeTargetInfo.pvBuffer;
}
PayloadOffset = 48;
if (message->NegotiateFlags & NTLMSSP_NEGOTIATE_VERSION)
PayloadOffset += 8;
message->TargetName.BufferOffset = PayloadOffset;
message->TargetInfo.BufferOffset = message->TargetName.BufferOffset + message->TargetName.Len;
/* TargetNameFields (8 bytes) */
ntlm_write_message_fields(s, &(message->TargetName));
Stream_Write_UINT32(s, message->NegotiateFlags); /* NegotiateFlags (4 bytes) */
Stream_Write(s, message->ServerChallenge, 8); /* ServerChallenge (8 bytes) */
Stream_Write(s, message->Reserved, 8); /* Reserved (8 bytes), should be ignored */
/* TargetInfoFields (8 bytes) */
ntlm_write_message_fields(s, &(message->TargetInfo));
if (message->NegotiateFlags & NTLMSSP_NEGOTIATE_VERSION)
ntlm_write_version_info(s, &(message->Version)); /* Version (8 bytes) */
/* Payload (variable) */
if (message->NegotiateFlags & NTLMSSP_REQUEST_TARGET)
ntlm_write_message_fields_buffer(s, &(message->TargetName));
if (message->NegotiateFlags & NTLMSSP_NEGOTIATE_TARGET_INFO)
ntlm_write_message_fields_buffer(s, &(message->TargetInfo));
length = Stream_GetPosition(s);
buffer->cbBuffer = length;
if (!sspi_SecBufferAlloc(&context->ChallengeMessage, length))
{
Stream_Free(s, FALSE);
return SEC_E_INTERNAL_ERROR;
}
CopyMemory(context->ChallengeMessage.pvBuffer, Stream_Buffer(s), length);
#ifdef WITH_DEBUG_NTLM
WLog_DBG(TAG, "CHALLENGE_MESSAGE (length = %d)", length);
winpr_HexDump(TAG, WLOG_DEBUG, context->ChallengeMessage.pvBuffer,
context->ChallengeMessage.cbBuffer);
ntlm_print_negotiate_flags(message->NegotiateFlags);
if (message->NegotiateFlags & NTLMSSP_NEGOTIATE_VERSION)
ntlm_print_version_info(&(message->Version));
ntlm_print_message_fields(&(message->TargetName), "TargetName");
ntlm_print_message_fields(&(message->TargetInfo), "TargetInfo");
#endif
context->state = NTLM_STATE_AUTHENTICATE;
Stream_Free(s, FALSE);
return SEC_I_CONTINUE_NEEDED;
}
SECURITY_STATUS ntlm_read_AuthenticateMessage(NTLM_CONTEXT* context, PSecBuffer buffer)
{
wStream* s;
size_t length;
UINT32 flags;
NTLM_AV_PAIR* AvFlags;
UINT32 PayloadBufferOffset;
NTLM_AUTHENTICATE_MESSAGE* message;
SSPI_CREDENTIALS* credentials = context->credentials;
flags = 0;
AvFlags = NULL;
message = &context->AUTHENTICATE_MESSAGE;
ZeroMemory(message, sizeof(NTLM_AUTHENTICATE_MESSAGE));
s = Stream_New((BYTE*)buffer->pvBuffer, buffer->cbBuffer);
if (!s)
return SEC_E_INTERNAL_ERROR;
if (ntlm_read_message_header(s, (NTLM_MESSAGE_HEADER*)message) < 0)
{
Stream_Free(s, FALSE);
return SEC_E_INVALID_TOKEN;
}
if (message->MessageType != MESSAGE_TYPE_AUTHENTICATE)
{
Stream_Free(s, FALSE);
return SEC_E_INVALID_TOKEN;
}
if (ntlm_read_message_fields(s, &(message->LmChallengeResponse)) <
0) /* LmChallengeResponseFields (8 bytes) */
{
Stream_Free(s, FALSE);
return SEC_E_INVALID_TOKEN;
}
if (ntlm_read_message_fields(s, &(message->NtChallengeResponse)) <
0) /* NtChallengeResponseFields (8 bytes) */
{
Stream_Free(s, FALSE);
return SEC_E_INVALID_TOKEN;
}
if (ntlm_read_message_fields(s, &(message->DomainName)) < 0) /* DomainNameFields (8 bytes) */
{
Stream_Free(s, FALSE);
return SEC_E_INVALID_TOKEN;
}
if (ntlm_read_message_fields(s, &(message->UserName)) < 0) /* UserNameFields (8 bytes) */
{
Stream_Free(s, FALSE);
return SEC_E_INVALID_TOKEN;
}
if (ntlm_read_message_fields(s, &(message->Workstation)) < 0) /* WorkstationFields (8 bytes) */
{
Stream_Free(s, FALSE);
return SEC_E_INVALID_TOKEN;
}
if (ntlm_read_message_fields(s, &(message->EncryptedRandomSessionKey)) <
0) /* EncryptedRandomSessionKeyFields (8 bytes) */
{
Stream_Free(s, FALSE);
return SEC_E_INVALID_TOKEN;
}
Stream_Read_UINT32(s, message->NegotiateFlags); /* NegotiateFlags (4 bytes) */
context->NegotiateKeyExchange =
(message->NegotiateFlags & NTLMSSP_NEGOTIATE_KEY_EXCH) ? TRUE : FALSE;
if ((context->NegotiateKeyExchange && !message->EncryptedRandomSessionKey.Len) ||
(!context->NegotiateKeyExchange && message->EncryptedRandomSessionKey.Len))
{
Stream_Free(s, FALSE);
return SEC_E_INVALID_TOKEN;
}
if (message->NegotiateFlags & NTLMSSP_NEGOTIATE_VERSION)
{
if (ntlm_read_version_info(s, &(message->Version)) < 0) /* Version (8 bytes) */
{
Stream_Free(s, FALSE);
return SEC_E_INVALID_TOKEN;
}
}
PayloadBufferOffset = Stream_GetPosition(s);
if (ntlm_read_message_fields_buffer(s, &(message->DomainName)) < 0) /* DomainName */
{
Stream_Free(s, FALSE);
return SEC_E_INTERNAL_ERROR;
}
if (ntlm_read_message_fields_buffer(s, &(message->UserName)) < 0) /* UserName */
{
Stream_Free(s, FALSE);
return SEC_E_INTERNAL_ERROR;
}
if (ntlm_read_message_fields_buffer(s, &(message->Workstation)) < 0) /* Workstation */
{
Stream_Free(s, FALSE);
return SEC_E_INTERNAL_ERROR;
}
if (ntlm_read_message_fields_buffer(s, &(message->LmChallengeResponse)) <
0) /* LmChallengeResponse */
{
Stream_Free(s, FALSE);
return SEC_E_INTERNAL_ERROR;
}
if (ntlm_read_message_fields_buffer(s, &(message->NtChallengeResponse)) <
0) /* NtChallengeResponse */
{
Stream_Free(s, FALSE);
return SEC_E_INTERNAL_ERROR;
}
if (message->NtChallengeResponse.Len > 0)
{
size_t cbAvFlags;
wStream* snt =
Stream_New(message->NtChallengeResponse.Buffer, message->NtChallengeResponse.Len);
if (!snt)
{
Stream_Free(s, FALSE);
return SEC_E_INTERNAL_ERROR;
}
if (ntlm_read_ntlm_v2_response(snt, &(context->NTLMv2Response)) < 0)
{
Stream_Free(s, FALSE);
Stream_Free(snt, FALSE);
return SEC_E_INVALID_TOKEN;
}
Stream_Free(snt, FALSE);
context->NtChallengeResponse.pvBuffer = message->NtChallengeResponse.Buffer;
context->NtChallengeResponse.cbBuffer = message->NtChallengeResponse.Len;
sspi_SecBufferFree(&(context->ChallengeTargetInfo));
context->ChallengeTargetInfo.pvBuffer = (void*)context->NTLMv2Response.Challenge.AvPairs;
context->ChallengeTargetInfo.cbBuffer = message->NtChallengeResponse.Len - (28 + 16);
CopyMemory(context->ClientChallenge, context->NTLMv2Response.Challenge.ClientChallenge, 8);
AvFlags =
ntlm_av_pair_get(context->NTLMv2Response.Challenge.AvPairs,
context->NTLMv2Response.Challenge.cbAvPairs, MsvAvFlags, &cbAvFlags);
if (AvFlags)
Data_Read_UINT32(ntlm_av_pair_get_value_pointer(AvFlags), flags);
}
if (ntlm_read_message_fields_buffer(s, &(message->EncryptedRandomSessionKey)) <
0) /* EncryptedRandomSessionKey */
{
Stream_Free(s, FALSE);
return SEC_E_INTERNAL_ERROR;
}
if (message->EncryptedRandomSessionKey.Len > 0)
{
if (message->EncryptedRandomSessionKey.Len != 16)
{
Stream_Free(s, FALSE);
return SEC_E_INVALID_TOKEN;
}
CopyMemory(context->EncryptedRandomSessionKey, message->EncryptedRandomSessionKey.Buffer,
16);
}
length = Stream_GetPosition(s);
if (!sspi_SecBufferAlloc(&context->AuthenticateMessage, length))
{
Stream_Free(s, FALSE);
return SEC_E_INTERNAL_ERROR;
}
CopyMemory(context->AuthenticateMessage.pvBuffer, Stream_Buffer(s), length);
buffer->cbBuffer = length;
Stream_SetPosition(s, PayloadBufferOffset);
if (flags & MSV_AV_FLAGS_MESSAGE_INTEGRITY_CHECK)
{
context->MessageIntegrityCheckOffset = (UINT32)Stream_GetPosition(s);
if (Stream_GetRemainingLength(s) < 16)
{
Stream_Free(s, FALSE);
return SEC_E_INVALID_TOKEN;
}
Stream_Read(s, message->MessageIntegrityCheck, 16);
}
#ifdef WITH_DEBUG_NTLM
WLog_DBG(TAG, "AUTHENTICATE_MESSAGE (length = %" PRIu32 ")",
context->AuthenticateMessage.cbBuffer);
winpr_HexDump(TAG, WLOG_DEBUG, context->AuthenticateMessage.pvBuffer,
context->AuthenticateMessage.cbBuffer);
if (message->NegotiateFlags & NTLMSSP_NEGOTIATE_VERSION)
ntlm_print_version_info(&(message->Version));
ntlm_print_message_fields(&(message->DomainName), "DomainName");
ntlm_print_message_fields(&(message->UserName), "UserName");
ntlm_print_message_fields(&(message->Workstation), "Workstation");
ntlm_print_message_fields(&(message->LmChallengeResponse), "LmChallengeResponse");
ntlm_print_message_fields(&(message->NtChallengeResponse), "NtChallengeResponse");
ntlm_print_message_fields(&(message->EncryptedRandomSessionKey), "EncryptedRandomSessionKey");
ntlm_print_av_pair_list(context->NTLMv2Response.Challenge.AvPairs,
context->NTLMv2Response.Challenge.cbAvPairs);
if (flags & MSV_AV_FLAGS_MESSAGE_INTEGRITY_CHECK)
{
WLog_DBG(TAG, "MessageIntegrityCheck:");
winpr_HexDump(TAG, WLOG_DEBUG, message->MessageIntegrityCheck, 16);
}
#endif
if (message->UserName.Len > 0)
{
credentials->identity.User = (UINT16*)malloc(message->UserName.Len);
if (!credentials->identity.User)
{
Stream_Free(s, FALSE);
return SEC_E_INTERNAL_ERROR;
}
CopyMemory(credentials->identity.User, message->UserName.Buffer, message->UserName.Len);
credentials->identity.UserLength = message->UserName.Len / 2;
}
if (message->DomainName.Len > 0)
{
credentials->identity.Domain = (UINT16*)malloc(message->DomainName.Len);
if (!credentials->identity.Domain)
{
Stream_Free(s, FALSE);
return SEC_E_INTERNAL_ERROR;
}
CopyMemory(credentials->identity.Domain, message->DomainName.Buffer,
message->DomainName.Len);
credentials->identity.DomainLength = message->DomainName.Len / 2;
}
Stream_Free(s, FALSE);
/* Computations beyond this point require the NTLM hash of the password */
context->state = NTLM_STATE_COMPLETION;
return SEC_I_COMPLETE_NEEDED;
}
/**
* Send NTLMSSP AUTHENTICATE_MESSAGE.\n
* AUTHENTICATE_MESSAGE @msdn{cc236643}
* @param NTLM context
* @param buffer
*/
SECURITY_STATUS ntlm_write_AuthenticateMessage(NTLM_CONTEXT* context, PSecBuffer buffer)
{
wStream* s;
size_t length;
UINT32 PayloadBufferOffset;
NTLM_AUTHENTICATE_MESSAGE* message;
SSPI_CREDENTIALS* credentials = context->credentials;
message = &context->AUTHENTICATE_MESSAGE;
ZeroMemory(message, sizeof(NTLM_AUTHENTICATE_MESSAGE));
s = Stream_New((BYTE*)buffer->pvBuffer, buffer->cbBuffer);
if (!s)
return SEC_E_INTERNAL_ERROR;
if (context->NTLMv2)
{
message->NegotiateFlags |= NTLMSSP_NEGOTIATE_56;
if (context->SendVersionInfo)
message->NegotiateFlags |= NTLMSSP_NEGOTIATE_VERSION;
}
if (context->UseMIC)
message->NegotiateFlags |= NTLMSSP_NEGOTIATE_TARGET_INFO;
if (context->SendWorkstationName)
message->NegotiateFlags |= NTLMSSP_NEGOTIATE_WORKSTATION_SUPPLIED;
if (context->confidentiality)
message->NegotiateFlags |= NTLMSSP_NEGOTIATE_SEAL;
if (context->CHALLENGE_MESSAGE.NegotiateFlags & NTLMSSP_NEGOTIATE_KEY_EXCH)
message->NegotiateFlags |= NTLMSSP_NEGOTIATE_KEY_EXCH;
message->NegotiateFlags |= NTLMSSP_NEGOTIATE_128;
message->NegotiateFlags |= NTLMSSP_NEGOTIATE_EXTENDED_SESSION_SECURITY;
message->NegotiateFlags |= NTLMSSP_NEGOTIATE_ALWAYS_SIGN;
message->NegotiateFlags |= NTLMSSP_NEGOTIATE_NTLM;
message->NegotiateFlags |= NTLMSSP_NEGOTIATE_SIGN;
message->NegotiateFlags |= NTLMSSP_REQUEST_TARGET;
message->NegotiateFlags |= NTLMSSP_NEGOTIATE_UNICODE;
if (message->NegotiateFlags & NTLMSSP_NEGOTIATE_VERSION)
ntlm_get_version_info(&(message->Version));
if (message->NegotiateFlags & NTLMSSP_NEGOTIATE_WORKSTATION_SUPPLIED)
{
message->Workstation.Len = context->Workstation.Length;
message->Workstation.Buffer = (BYTE*)context->Workstation.Buffer;
}
if (credentials->identity.DomainLength > 0)
{
message->NegotiateFlags |= NTLMSSP_NEGOTIATE_DOMAIN_SUPPLIED;
message->DomainName.Len = (UINT16)credentials->identity.DomainLength * 2;
message->DomainName.Buffer = (BYTE*)credentials->identity.Domain;
}
message->UserName.Len = (UINT16)credentials->identity.UserLength * 2;
message->UserName.Buffer = (BYTE*)credentials->identity.User;
message->LmChallengeResponse.Len = (UINT16)context->LmChallengeResponse.cbBuffer;
message->LmChallengeResponse.Buffer = (BYTE*)context->LmChallengeResponse.pvBuffer;
message->NtChallengeResponse.Len = (UINT16)context->NtChallengeResponse.cbBuffer;
message->NtChallengeResponse.Buffer = (BYTE*)context->NtChallengeResponse.pvBuffer;
if (message->NegotiateFlags & NTLMSSP_NEGOTIATE_KEY_EXCH)
{
message->EncryptedRandomSessionKey.Len = 16;
message->EncryptedRandomSessionKey.Buffer = context->EncryptedRandomSessionKey;
}
PayloadBufferOffset = 64;
if (message->NegotiateFlags & NTLMSSP_NEGOTIATE_VERSION)
PayloadBufferOffset += 8; /* Version (8 bytes) */
if (context->UseMIC)
PayloadBufferOffset += 16; /* Message Integrity Check (16 bytes) */
message->DomainName.BufferOffset = PayloadBufferOffset;
message->UserName.BufferOffset = message->DomainName.BufferOffset + message->DomainName.Len;
message->Workstation.BufferOffset = message->UserName.BufferOffset + message->UserName.Len;
message->LmChallengeResponse.BufferOffset =
message->Workstation.BufferOffset + message->Workstation.Len;
message->NtChallengeResponse.BufferOffset =
message->LmChallengeResponse.BufferOffset + message->LmChallengeResponse.Len;
message->EncryptedRandomSessionKey.BufferOffset =
message->NtChallengeResponse.BufferOffset + message->NtChallengeResponse.Len;
ntlm_populate_message_header((NTLM_MESSAGE_HEADER*)message, MESSAGE_TYPE_AUTHENTICATE);
ntlm_write_message_header(s, (NTLM_MESSAGE_HEADER*)message); /* Message Header (12 bytes) */
ntlm_write_message_fields(
s, &(message->LmChallengeResponse)); /* LmChallengeResponseFields (8 bytes) */
ntlm_write_message_fields(
s, &(message->NtChallengeResponse)); /* NtChallengeResponseFields (8 bytes) */
ntlm_write_message_fields(s, &(message->DomainName)); /* DomainNameFields (8 bytes) */
ntlm_write_message_fields(s, &(message->UserName)); /* UserNameFields (8 bytes) */
ntlm_write_message_fields(s, &(message->Workstation)); /* WorkstationFields (8 bytes) */
ntlm_write_message_fields(
s, &(message->EncryptedRandomSessionKey)); /* EncryptedRandomSessionKeyFields (8 bytes) */
Stream_Write_UINT32(s, message->NegotiateFlags); /* NegotiateFlags (4 bytes) */
if (message->NegotiateFlags & NTLMSSP_NEGOTIATE_VERSION)
ntlm_write_version_info(s, &(message->Version)); /* Version (8 bytes) */
if (context->UseMIC)
{
context->MessageIntegrityCheckOffset = (UINT32)Stream_GetPosition(s);
Stream_Zero(s, 16); /* Message Integrity Check (16 bytes) */
}
if (message->NegotiateFlags & NTLMSSP_NEGOTIATE_DOMAIN_SUPPLIED)
ntlm_write_message_fields_buffer(s, &(message->DomainName)); /* DomainName */
ntlm_write_message_fields_buffer(s, &(message->UserName)); /* UserName */
if (message->NegotiateFlags & NTLMSSP_NEGOTIATE_WORKSTATION_SUPPLIED)
ntlm_write_message_fields_buffer(s, &(message->Workstation)); /* Workstation */
ntlm_write_message_fields_buffer(s, &(message->LmChallengeResponse)); /* LmChallengeResponse */
ntlm_write_message_fields_buffer(s, &(message->NtChallengeResponse)); /* NtChallengeResponse */
if (message->NegotiateFlags & NTLMSSP_NEGOTIATE_KEY_EXCH)
ntlm_write_message_fields_buffer(
s, &(message->EncryptedRandomSessionKey)); /* EncryptedRandomSessionKey */
length = Stream_GetPosition(s);
if (!sspi_SecBufferAlloc(&context->AuthenticateMessage, length))
{
Stream_Free(s, FALSE);
return SEC_E_INTERNAL_ERROR;
}
CopyMemory(context->AuthenticateMessage.pvBuffer, Stream_Buffer(s), length);
buffer->cbBuffer = length;
if (context->UseMIC)
{
/* Message Integrity Check */
ntlm_compute_message_integrity_check(context, message->MessageIntegrityCheck, 16);
Stream_SetPosition(s, context->MessageIntegrityCheckOffset);
Stream_Write(s, message->MessageIntegrityCheck, 16);
Stream_SetPosition(s, length);
}
#ifdef WITH_DEBUG_NTLM
WLog_DBG(TAG, "AUTHENTICATE_MESSAGE (length = %d)", length);
winpr_HexDump(TAG, WLOG_DEBUG, Stream_Buffer(s), length);
ntlm_print_negotiate_flags(message->NegotiateFlags);
if (message->NegotiateFlags & NTLMSSP_NEGOTIATE_VERSION)
ntlm_print_version_info(&(message->Version));
if (context->AuthenticateTargetInfo.cbBuffer > 0)
{
WLog_DBG(TAG,
"AuthenticateTargetInfo (%" PRIu32 "):", context->AuthenticateTargetInfo.cbBuffer);
ntlm_print_av_pair_list(context->AuthenticateTargetInfo.pvBuffer,
context->AuthenticateTargetInfo.cbBuffer);
}
ntlm_print_message_fields(&(message->DomainName), "DomainName");
ntlm_print_message_fields(&(message->UserName), "UserName");
ntlm_print_message_fields(&(message->Workstation), "Workstation");
ntlm_print_message_fields(&(message->LmChallengeResponse), "LmChallengeResponse");
ntlm_print_message_fields(&(message->NtChallengeResponse), "NtChallengeResponse");
ntlm_print_message_fields(&(message->EncryptedRandomSessionKey), "EncryptedRandomSessionKey");
if (context->UseMIC)
{
WLog_DBG(TAG, "MessageIntegrityCheck (length = 16)");
winpr_HexDump(TAG, WLOG_DEBUG, message->MessageIntegrityCheck, 16);
}
#endif
context->state = NTLM_STATE_FINAL;
Stream_Free(s, FALSE);
return SEC_I_COMPLETE_NEEDED;
}
SECURITY_STATUS ntlm_server_AuthenticateComplete(NTLM_CONTEXT* context)
{
UINT32 flags = 0;
size_t cbAvFlags;
NTLM_AV_PAIR* AvFlags = NULL;
NTLM_AUTHENTICATE_MESSAGE* message;
BYTE messageIntegrityCheck[16];
if (!context)
return SEC_E_INVALID_PARAMETER;
if (context->state != NTLM_STATE_COMPLETION)
return SEC_E_OUT_OF_SEQUENCE;
message = &context->AUTHENTICATE_MESSAGE;
AvFlags = ntlm_av_pair_get(context->NTLMv2Response.Challenge.AvPairs,
context->NTLMv2Response.Challenge.cbAvPairs, MsvAvFlags, &cbAvFlags);
if (AvFlags)
Data_Read_UINT32(ntlm_av_pair_get_value_pointer(AvFlags), flags);
if (ntlm_compute_lm_v2_response(context) < 0) /* LmChallengeResponse */
return SEC_E_INTERNAL_ERROR;
if (ntlm_compute_ntlm_v2_response(context) < 0) /* NtChallengeResponse */
return SEC_E_INTERNAL_ERROR;
/* KeyExchangeKey */
ntlm_generate_key_exchange_key(context);
/* EncryptedRandomSessionKey */
ntlm_decrypt_random_session_key(context);
/* ExportedSessionKey */
ntlm_generate_exported_session_key(context);
if (flags & MSV_AV_FLAGS_MESSAGE_INTEGRITY_CHECK)
{
ZeroMemory(
&((PBYTE)context->AuthenticateMessage.pvBuffer)[context->MessageIntegrityCheckOffset],
16);
ntlm_compute_message_integrity_check(context, messageIntegrityCheck,
sizeof(messageIntegrityCheck));
CopyMemory(
&((PBYTE)context->AuthenticateMessage.pvBuffer)[context->MessageIntegrityCheckOffset],
message->MessageIntegrityCheck, 16);
if (memcmp(messageIntegrityCheck, message->MessageIntegrityCheck, 16) != 0)
{
WLog_ERR(TAG, "Message Integrity Check (MIC) verification failed!");
#ifdef WITH_DEBUG_NTLM
WLog_ERR(TAG, "Expected MIC:");
winpr_HexDump(TAG, WLOG_ERROR, messageIntegrityCheck, sizeof(messageIntegrityCheck));
WLog_ERR(TAG, "Actual MIC:");
winpr_HexDump(TAG, WLOG_ERROR, message->MessageIntegrityCheck,
sizeof(message->MessageIntegrityCheck));
#endif
return SEC_E_MESSAGE_ALTERED;
}
}
else
{
/* no mic message was present
https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-nlmp/f9e6fbc4-a953-4f24-b229-ccdcc213b9ec
the mic is optional, as not supported in Windows NT, Windows 2000, Windows XP, and
Windows Server 2003 and, as it seems, in the NTLMv2 implementation of Qt5.
now check the NtProofString, to detect if the entered client password matches the
expected password.
*/
#ifdef WITH_DEBUG_NTLM
WLog_DBG(TAG, "No MIC present, using NtProofString for verification.");
#endif
if (memcmp(context->NTLMv2Response.Response, context->NtProofString, 16) != 0)
{
WLog_ERR(TAG, "NtProofString verification failed!");
#ifdef WITH_DEBUG_NTLM
WLog_ERR(TAG, "Expected NtProofString:");
winpr_HexDump(TAG, WLOG_ERROR, context->NtProofString, sizeof(context->NtProofString));
WLog_ERR(TAG, "Actual NtProofString:");
winpr_HexDump(TAG, WLOG_ERROR, context->NTLMv2Response.Response,
sizeof(context->NTLMv2Response));
#endif
return SEC_E_LOGON_DENIED;
}
}
/* Generate signing keys */
ntlm_generate_client_signing_key(context);
ntlm_generate_server_signing_key(context);
/* Generate sealing keys */
ntlm_generate_client_sealing_key(context);
ntlm_generate_server_sealing_key(context);
/* Initialize RC4 seal state */
ntlm_init_rc4_seal_states(context);
#ifdef WITH_DEBUG_NTLM
WLog_DBG(TAG, "ClientChallenge");
winpr_HexDump(TAG, WLOG_DEBUG, context->ClientChallenge, 8);
WLog_DBG(TAG, "ServerChallenge");
winpr_HexDump(TAG, WLOG_DEBUG, context->ServerChallenge, 8);
WLog_DBG(TAG, "SessionBaseKey");
winpr_HexDump(TAG, WLOG_DEBUG, context->SessionBaseKey, 16);
WLog_DBG(TAG, "KeyExchangeKey");
winpr_HexDump(TAG, WLOG_DEBUG, context->KeyExchangeKey, 16);
WLog_DBG(TAG, "ExportedSessionKey");
winpr_HexDump(TAG, WLOG_DEBUG, context->ExportedSessionKey, 16);
WLog_DBG(TAG, "RandomSessionKey");
winpr_HexDump(TAG, WLOG_DEBUG, context->RandomSessionKey, 16);
WLog_DBG(TAG, "ClientSigningKey");
winpr_HexDump(TAG, WLOG_DEBUG, context->ClientSigningKey, 16);
WLog_DBG(TAG, "ClientSealingKey");
winpr_HexDump(TAG, WLOG_DEBUG, context->ClientSealingKey, 16);
WLog_DBG(TAG, "ServerSigningKey");
winpr_HexDump(TAG, WLOG_DEBUG, context->ServerSigningKey, 16);
WLog_DBG(TAG, "ServerSealingKey");
winpr_HexDump(TAG, WLOG_DEBUG, context->ServerSealingKey, 16);
WLog_DBG(TAG, "Timestamp");
winpr_HexDump(TAG, WLOG_DEBUG, context->Timestamp, 8);
#endif
context->state = NTLM_STATE_FINAL;
ntlm_free_message_fields_buffer(&(message->DomainName));
ntlm_free_message_fields_buffer(&(message->UserName));
ntlm_free_message_fields_buffer(&(message->Workstation));
ntlm_free_message_fields_buffer(&(message->LmChallengeResponse));
ntlm_free_message_fields_buffer(&(message->NtChallengeResponse));
ntlm_free_message_fields_buffer(&(message->EncryptedRandomSessionKey));
return SEC_E_OK;
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_3944_0 |
crossvul-cpp_data_good_5492_1 | /*
* Copyright (c) 1999-2000 Image Power, Inc. and the University of
* British Columbia.
* Copyright (c) 2001-2003 Michael David Adams.
* All rights reserved.
*/
/* __START_OF_JASPER_LICENSE__
*
* JasPer License Version 2.0
*
* Copyright (c) 2001-2006 Michael David Adams
* Copyright (c) 1999-2000 Image Power, Inc.
* Copyright (c) 1999-2000 The University of British Columbia
*
* All rights reserved.
*
* Permission is hereby granted, free of charge, to any person (the
* "User") obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without restriction,
* including without limitation the rights to use, copy, modify, merge,
* publish, distribute, and/or sell copies of the Software, and to permit
* persons to whom the Software is furnished to do so, subject to the
* following conditions:
*
* 1. The above copyright notices and this permission notice (which
* includes the disclaimer below) shall be included in all copies or
* substantial portions of the Software.
*
* 2. The name of a copyright holder shall not be used to endorse or
* promote products derived from the Software without specific prior
* written permission.
*
* THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
* LICENSE. NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
* THIS DISCLAIMER. THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
* "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
* BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
* PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO
* EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
* INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
* FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
* NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
* WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. NO ASSURANCES ARE
* PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
* THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
* EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
* BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
* PROPERTY RIGHTS OR OTHERWISE. AS A CONDITION TO EXERCISING THE RIGHTS
* GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
* ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY. THE SOFTWARE
* IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
* SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
* AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
* SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
* THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
* PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
* RISK ACTIVITIES"). THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
* EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
*
* __END_OF_JASPER_LICENSE__
*/
/*
* Tier-2 Coding Library
*
* $Id$
*/
#include "jasper/jas_math.h"
#include "jasper/jas_malloc.h"
#include "jpc_cs.h"
#include "jpc_t2cod.h"
#include "jpc_math.h"
static int jpc_pi_nextlrcp(jpc_pi_t *pi);
static int jpc_pi_nextrlcp(jpc_pi_t *pi);
static int jpc_pi_nextrpcl(jpc_pi_t *pi);
static int jpc_pi_nextpcrl(jpc_pi_t *pi);
static int jpc_pi_nextcprl(jpc_pi_t *pi);
int jpc_pi_next(jpc_pi_t *pi)
{
jpc_pchg_t *pchg;
int ret;
for (;;) {
pi->valid = false;
if (!pi->pchg) {
++pi->pchgno;
pi->compno = 0;
pi->rlvlno = 0;
pi->prcno = 0;
pi->lyrno = 0;
pi->prgvolfirst = true;
if (pi->pchgno < jpc_pchglist_numpchgs(pi->pchglist)) {
pi->pchg = jpc_pchglist_get(pi->pchglist, pi->pchgno);
} else if (pi->pchgno == jpc_pchglist_numpchgs(pi->pchglist)) {
pi->pchg = &pi->defaultpchg;
} else {
return 1;
}
}
pchg = pi->pchg;
switch (pchg->prgord) {
case JPC_COD_LRCPPRG:
ret = jpc_pi_nextlrcp(pi);
break;
case JPC_COD_RLCPPRG:
ret = jpc_pi_nextrlcp(pi);
break;
case JPC_COD_RPCLPRG:
ret = jpc_pi_nextrpcl(pi);
break;
case JPC_COD_PCRLPRG:
ret = jpc_pi_nextpcrl(pi);
break;
case JPC_COD_CPRLPRG:
ret = jpc_pi_nextcprl(pi);
break;
default:
ret = -1;
break;
}
if (!ret) {
pi->valid = true;
++pi->pktno;
return 0;
}
pi->pchg = 0;
}
}
static int jpc_pi_nextlrcp(register jpc_pi_t *pi)
{
jpc_pchg_t *pchg;
int *prclyrno;
pchg = pi->pchg;
if (!pi->prgvolfirst) {
prclyrno = &pi->pirlvl->prclyrnos[pi->prcno];
goto skip;
} else {
pi->prgvolfirst = false;
}
for (pi->lyrno = 0; pi->lyrno < pi->numlyrs && pi->lyrno <
JAS_CAST(int, pchg->lyrnoend); ++pi->lyrno) {
for (pi->rlvlno = pchg->rlvlnostart; pi->rlvlno < pi->maxrlvls &&
pi->rlvlno < pchg->rlvlnoend; ++pi->rlvlno) {
for (pi->compno = pchg->compnostart, pi->picomp =
&pi->picomps[pi->compno]; pi->compno < pi->numcomps
&& pi->compno < JAS_CAST(int, pchg->compnoend); ++pi->compno,
++pi->picomp) {
if (pi->rlvlno >= pi->picomp->numrlvls) {
continue;
}
pi->pirlvl = &pi->picomp->pirlvls[pi->rlvlno];
for (pi->prcno = 0, prclyrno =
pi->pirlvl->prclyrnos; pi->prcno <
pi->pirlvl->numprcs; ++pi->prcno,
++prclyrno) {
if (pi->lyrno >= *prclyrno) {
*prclyrno = pi->lyrno;
++(*prclyrno);
return 0;
}
skip:
;
}
}
}
}
return 1;
}
static int jpc_pi_nextrlcp(register jpc_pi_t *pi)
{
jpc_pchg_t *pchg;
int *prclyrno;
pchg = pi->pchg;
if (!pi->prgvolfirst) {
assert(pi->prcno < pi->pirlvl->numprcs);
prclyrno = &pi->pirlvl->prclyrnos[pi->prcno];
goto skip;
} else {
pi->prgvolfirst = 0;
}
for (pi->rlvlno = pchg->rlvlnostart; pi->rlvlno < pi->maxrlvls &&
pi->rlvlno < pchg->rlvlnoend; ++pi->rlvlno) {
for (pi->lyrno = 0; pi->lyrno < pi->numlyrs && pi->lyrno <
JAS_CAST(int, pchg->lyrnoend); ++pi->lyrno) {
for (pi->compno = pchg->compnostart, pi->picomp =
&pi->picomps[pi->compno]; pi->compno < pi->numcomps &&
pi->compno < JAS_CAST(int, pchg->compnoend); ++pi->compno,
++pi->picomp) {
if (pi->rlvlno >= pi->picomp->numrlvls) {
continue;
}
pi->pirlvl = &pi->picomp->pirlvls[pi->rlvlno];
for (pi->prcno = 0, prclyrno = pi->pirlvl->prclyrnos;
pi->prcno < pi->pirlvl->numprcs; ++pi->prcno, ++prclyrno) {
if (pi->lyrno >= *prclyrno) {
*prclyrno = pi->lyrno;
++(*prclyrno);
return 0;
}
skip:
;
}
}
}
}
return 1;
}
static int jpc_pi_nextrpcl(register jpc_pi_t *pi)
{
int rlvlno;
jpc_pirlvl_t *pirlvl;
jpc_pchg_t *pchg;
int prchind;
int prcvind;
int *prclyrno;
int compno;
jpc_picomp_t *picomp;
int xstep;
int ystep;
uint_fast32_t r;
uint_fast32_t rpx;
uint_fast32_t rpy;
uint_fast32_t trx0;
uint_fast32_t try0;
pchg = pi->pchg;
if (!pi->prgvolfirst) {
goto skip;
} else {
pi->xstep = 0;
pi->ystep = 0;
for (compno = 0, picomp = pi->picomps; compno < pi->numcomps;
++compno, ++picomp) {
for (rlvlno = 0, pirlvl = picomp->pirlvls; rlvlno <
picomp->numrlvls; ++rlvlno, ++pirlvl) {
// Check for the potential for overflow problems.
if (pirlvl->prcwidthexpn + picomp->numrlvls >
JAS_UINTFAST32_NUMBITS - 2 ||
pirlvl->prcheightexpn + picomp->numrlvls >
JAS_UINTFAST32_NUMBITS - 2) {
return -1;
}
xstep = picomp->hsamp * (JAS_CAST(uint_fast32_t, 1) <<
(pirlvl->prcwidthexpn + picomp->numrlvls - rlvlno - 1));
ystep = picomp->vsamp * (JAS_CAST(uint_fast32_t, 1) <<
(pirlvl->prcheightexpn + picomp->numrlvls - rlvlno - 1));
pi->xstep = (!pi->xstep) ? xstep : JAS_MIN(pi->xstep, xstep);
pi->ystep = (!pi->ystep) ? ystep : JAS_MIN(pi->ystep, ystep);
}
}
pi->prgvolfirst = 0;
}
for (pi->rlvlno = pchg->rlvlnostart; pi->rlvlno < pchg->rlvlnoend &&
pi->rlvlno < pi->maxrlvls; ++pi->rlvlno) {
for (pi->y = pi->ystart; pi->y < pi->yend; pi->y +=
pi->ystep - (pi->y % pi->ystep)) {
for (pi->x = pi->xstart; pi->x < pi->xend; pi->x +=
pi->xstep - (pi->x % pi->xstep)) {
for (pi->compno = pchg->compnostart,
pi->picomp = &pi->picomps[pi->compno];
pi->compno < JAS_CAST(int, pchg->compnoend) && pi->compno <
pi->numcomps; ++pi->compno, ++pi->picomp) {
if (pi->rlvlno >= pi->picomp->numrlvls) {
continue;
}
pi->pirlvl = &pi->picomp->pirlvls[pi->rlvlno];
if (pi->pirlvl->numprcs == 0) {
continue;
}
r = pi->picomp->numrlvls - 1 - pi->rlvlno;
rpx = r + pi->pirlvl->prcwidthexpn;
rpy = r + pi->pirlvl->prcheightexpn;
trx0 = JPC_CEILDIV(pi->xstart, pi->picomp->hsamp << r);
try0 = JPC_CEILDIV(pi->ystart, pi->picomp->vsamp << r);
if (((pi->x == pi->xstart &&
((trx0 << r) % (JAS_CAST(uint_fast32_t, 1) << rpx)))
|| !(pi->x % (JAS_CAST(uint_fast32_t, 1) << rpx))) &&
((pi->y == pi->ystart &&
((try0 << r) % (JAS_CAST(uint_fast32_t, 1) << rpy)))
|| !(pi->y % (JAS_CAST(uint_fast32_t, 1) << rpy)))) {
prchind = JPC_FLOORDIVPOW2(JPC_CEILDIV(pi->x,
pi->picomp->hsamp << r), pi->pirlvl->prcwidthexpn) -
JPC_FLOORDIVPOW2(trx0, pi->pirlvl->prcwidthexpn);
prcvind = JPC_FLOORDIVPOW2(JPC_CEILDIV(pi->y,
pi->picomp->vsamp << r), pi->pirlvl->prcheightexpn) -
JPC_FLOORDIVPOW2(try0, pi->pirlvl->prcheightexpn);
pi->prcno = prcvind * pi->pirlvl->numhprcs + prchind;
assert(pi->prcno < pi->pirlvl->numprcs);
for (pi->lyrno = 0; pi->lyrno <
pi->numlyrs && pi->lyrno < JAS_CAST(int,
pchg->lyrnoend); ++pi->lyrno) {
prclyrno = &pi->pirlvl->prclyrnos[pi->prcno];
if (pi->lyrno >= *prclyrno) {
++(*prclyrno);
return 0;
}
skip:
;
}
}
}
}
}
}
return 1;
}
static int jpc_pi_nextpcrl(register jpc_pi_t *pi)
{
int rlvlno;
jpc_pirlvl_t *pirlvl;
jpc_pchg_t *pchg;
int prchind;
int prcvind;
int *prclyrno;
int compno;
jpc_picomp_t *picomp;
int xstep;
int ystep;
uint_fast32_t trx0;
uint_fast32_t try0;
uint_fast32_t r;
uint_fast32_t rpx;
uint_fast32_t rpy;
pchg = pi->pchg;
if (!pi->prgvolfirst) {
goto skip;
} else {
pi->xstep = 0;
pi->ystep = 0;
for (compno = 0, picomp = pi->picomps; compno < pi->numcomps;
++compno, ++picomp) {
for (rlvlno = 0, pirlvl = picomp->pirlvls; rlvlno <
picomp->numrlvls; ++rlvlno, ++pirlvl) {
// Check for the potential for overflow problems.
if (pirlvl->prcwidthexpn + pi->picomp->numrlvls >
JAS_UINTFAST32_NUMBITS - 2 ||
pirlvl->prcheightexpn + pi->picomp->numrlvls >
JAS_UINTFAST32_NUMBITS - 2) {
return -1;
}
xstep = picomp->hsamp * (JAS_CAST(uint_fast32_t, 1) <<
(pirlvl->prcwidthexpn + picomp->numrlvls - rlvlno - 1));
ystep = picomp->vsamp * (JAS_CAST(uint_fast32_t, 1) <<
(pirlvl->prcheightexpn + picomp->numrlvls - rlvlno - 1));
pi->xstep = (!pi->xstep) ? xstep : JAS_MIN(pi->xstep, xstep);
pi->ystep = (!pi->ystep) ? ystep : JAS_MIN(pi->ystep, ystep);
}
}
pi->prgvolfirst = 0;
}
for (pi->y = pi->ystart; pi->y < pi->yend; pi->y += pi->ystep -
(pi->y % pi->ystep)) {
for (pi->x = pi->xstart; pi->x < pi->xend; pi->x += pi->xstep -
(pi->x % pi->xstep)) {
for (pi->compno = pchg->compnostart, pi->picomp =
&pi->picomps[pi->compno]; pi->compno < pi->numcomps
&& pi->compno < JAS_CAST(int, pchg->compnoend); ++pi->compno,
++pi->picomp) {
for (pi->rlvlno = pchg->rlvlnostart,
pi->pirlvl = &pi->picomp->pirlvls[pi->rlvlno];
pi->rlvlno < pi->picomp->numrlvls &&
pi->rlvlno < pchg->rlvlnoend; ++pi->rlvlno,
++pi->pirlvl) {
if (pi->pirlvl->numprcs == 0) {
continue;
}
r = pi->picomp->numrlvls - 1 - pi->rlvlno;
trx0 = JPC_CEILDIV(pi->xstart, pi->picomp->hsamp << r);
try0 = JPC_CEILDIV(pi->ystart, pi->picomp->vsamp << r);
rpx = r + pi->pirlvl->prcwidthexpn;
rpy = r + pi->pirlvl->prcheightexpn;
if (((pi->x == pi->xstart &&
((trx0 << r) % (JAS_CAST(uint_fast32_t, 1) << rpx))) ||
!(pi->x % (pi->picomp->hsamp << rpx))) &&
((pi->y == pi->ystart &&
((try0 << r) % (JAS_CAST(uint_fast32_t, 1) << rpy))) ||
!(pi->y % (pi->picomp->vsamp << rpy)))) {
prchind = JPC_FLOORDIVPOW2(JPC_CEILDIV(pi->x,
pi->picomp->hsamp << r), pi->pirlvl->prcwidthexpn) -
JPC_FLOORDIVPOW2(trx0, pi->pirlvl->prcwidthexpn);
prcvind = JPC_FLOORDIVPOW2(JPC_CEILDIV(pi->y,
pi->picomp->vsamp << r), pi->pirlvl->prcheightexpn) -
JPC_FLOORDIVPOW2(try0, pi->pirlvl->prcheightexpn);
pi->prcno = prcvind * pi->pirlvl->numhprcs + prchind;
assert(pi->prcno < pi->pirlvl->numprcs);
for (pi->lyrno = 0; pi->lyrno < pi->numlyrs &&
pi->lyrno < JAS_CAST(int, pchg->lyrnoend);
++pi->lyrno) {
prclyrno = &pi->pirlvl->prclyrnos[pi->prcno];
if (pi->lyrno >= *prclyrno) {
++(*prclyrno);
return 0;
}
skip:
;
}
}
}
}
}
}
return 1;
}
static int jpc_pi_nextcprl(register jpc_pi_t *pi)
{
int rlvlno;
jpc_pirlvl_t *pirlvl;
jpc_pchg_t *pchg;
int prchind;
int prcvind;
int *prclyrno;
uint_fast32_t trx0;
uint_fast32_t try0;
uint_fast32_t r;
uint_fast32_t rpx;
uint_fast32_t rpy;
pchg = pi->pchg;
if (!pi->prgvolfirst) {
goto skip;
} else {
pi->prgvolfirst = 0;
}
for (pi->compno = pchg->compnostart, pi->picomp = &pi->picomps[pi->compno];
pi->compno < JAS_CAST(int, pchg->compnoend) && pi->compno < pi->numcomps;
++pi->compno, ++pi->picomp) {
pirlvl = pi->picomp->pirlvls;
// Check for the potential for overflow problems.
if (pirlvl->prcwidthexpn + pi->picomp->numrlvls >
JAS_UINTFAST32_NUMBITS - 2 ||
pirlvl->prcheightexpn + pi->picomp->numrlvls >
JAS_UINTFAST32_NUMBITS - 2) {
return -1;
}
pi->xstep = pi->picomp->hsamp * (JAS_CAST(uint_fast32_t, 1) <<
(pirlvl->prcwidthexpn + pi->picomp->numrlvls - 1));
pi->ystep = pi->picomp->vsamp * (JAS_CAST(uint_fast32_t, 1) <<
(pirlvl->prcheightexpn + pi->picomp->numrlvls - 1));
for (rlvlno = 1, pirlvl = &pi->picomp->pirlvls[1];
rlvlno < pi->picomp->numrlvls; ++rlvlno, ++pirlvl) {
pi->xstep = JAS_MIN(pi->xstep, pi->picomp->hsamp *
(JAS_CAST(uint_fast32_t, 1) << (pirlvl->prcwidthexpn +
pi->picomp->numrlvls - rlvlno - 1)));
pi->ystep = JAS_MIN(pi->ystep, pi->picomp->vsamp *
(JAS_CAST(uint_fast32_t, 1) << (pirlvl->prcheightexpn +
pi->picomp->numrlvls - rlvlno - 1)));
}
for (pi->y = pi->ystart; pi->y < pi->yend;
pi->y += pi->ystep - (pi->y % pi->ystep)) {
for (pi->x = pi->xstart; pi->x < pi->xend;
pi->x += pi->xstep - (pi->x % pi->xstep)) {
for (pi->rlvlno = pchg->rlvlnostart,
pi->pirlvl = &pi->picomp->pirlvls[pi->rlvlno];
pi->rlvlno < pi->picomp->numrlvls && pi->rlvlno <
pchg->rlvlnoend; ++pi->rlvlno, ++pi->pirlvl) {
if (pi->pirlvl->numprcs == 0) {
continue;
}
r = pi->picomp->numrlvls - 1 - pi->rlvlno;
trx0 = JPC_CEILDIV(pi->xstart, pi->picomp->hsamp << r);
try0 = JPC_CEILDIV(pi->ystart, pi->picomp->vsamp << r);
rpx = r + pi->pirlvl->prcwidthexpn;
rpy = r + pi->pirlvl->prcheightexpn;
if (((pi->x == pi->xstart &&
((trx0 << r) % (JAS_CAST(uint_fast32_t, 1) << rpx))) ||
!(pi->x % (pi->picomp->hsamp << rpx))) &&
((pi->y == pi->ystart &&
((try0 << r) % (JAS_CAST(uint_fast32_t, 1) << rpy))) ||
!(pi->y % (pi->picomp->vsamp << rpy)))) {
prchind = JPC_FLOORDIVPOW2(JPC_CEILDIV(pi->x,
pi->picomp->hsamp << r), pi->pirlvl->prcwidthexpn) -
JPC_FLOORDIVPOW2(trx0, pi->pirlvl->prcwidthexpn);
prcvind = JPC_FLOORDIVPOW2(JPC_CEILDIV(pi->y,
pi->picomp->vsamp << r), pi->pirlvl->prcheightexpn) -
JPC_FLOORDIVPOW2(try0, pi->pirlvl->prcheightexpn);
pi->prcno = prcvind * pi->pirlvl->numhprcs + prchind;
assert(pi->prcno < pi->pirlvl->numprcs);
for (pi->lyrno = 0; pi->lyrno < pi->numlyrs &&
pi->lyrno < JAS_CAST(int, pchg->lyrnoend);
++pi->lyrno) {
prclyrno = &pi->pirlvl->prclyrnos[pi->prcno];
if (pi->lyrno >= *prclyrno) {
++(*prclyrno);
return 0;
}
skip:
;
}
}
}
}
}
}
return 1;
}
static void pirlvl_destroy(jpc_pirlvl_t *rlvl)
{
if (rlvl->prclyrnos) {
jas_free(rlvl->prclyrnos);
}
}
static void jpc_picomp_destroy(jpc_picomp_t *picomp)
{
int rlvlno;
jpc_pirlvl_t *pirlvl;
if (picomp->pirlvls) {
for (rlvlno = 0, pirlvl = picomp->pirlvls; rlvlno <
picomp->numrlvls; ++rlvlno, ++pirlvl) {
pirlvl_destroy(pirlvl);
}
jas_free(picomp->pirlvls);
}
}
void jpc_pi_destroy(jpc_pi_t *pi)
{
jpc_picomp_t *picomp;
int compno;
if (pi->picomps) {
for (compno = 0, picomp = pi->picomps; compno < pi->numcomps;
++compno, ++picomp) {
jpc_picomp_destroy(picomp);
}
jas_free(pi->picomps);
}
if (pi->pchglist) {
jpc_pchglist_destroy(pi->pchglist);
}
jas_free(pi);
}
jpc_pi_t *jpc_pi_create0()
{
jpc_pi_t *pi;
if (!(pi = jas_malloc(sizeof(jpc_pi_t)))) {
return 0;
}
pi->picomps = 0;
pi->pchgno = 0;
if (!(pi->pchglist = jpc_pchglist_create())) {
jas_free(pi);
return 0;
}
return pi;
}
int jpc_pi_addpchg(jpc_pi_t *pi, jpc_pocpchg_t *pchg)
{
return jpc_pchglist_insert(pi->pchglist, -1, pchg);
}
jpc_pchglist_t *jpc_pchglist_create()
{
jpc_pchglist_t *pchglist;
if (!(pchglist = jas_malloc(sizeof(jpc_pchglist_t)))) {
return 0;
}
pchglist->numpchgs = 0;
pchglist->maxpchgs = 0;
pchglist->pchgs = 0;
return pchglist;
}
int jpc_pchglist_insert(jpc_pchglist_t *pchglist, int pchgno, jpc_pchg_t *pchg)
{
int i;
int newmaxpchgs;
jpc_pchg_t **newpchgs;
if (pchgno < 0) {
pchgno = pchglist->numpchgs;
}
if (pchglist->numpchgs >= pchglist->maxpchgs) {
newmaxpchgs = pchglist->maxpchgs + 128;
if (!(newpchgs = jas_realloc2(pchglist->pchgs, newmaxpchgs,
sizeof(jpc_pchg_t *)))) {
return -1;
}
pchglist->maxpchgs = newmaxpchgs;
pchglist->pchgs = newpchgs;
}
for (i = pchglist->numpchgs; i > pchgno; --i) {
pchglist->pchgs[i] = pchglist->pchgs[i - 1];
}
pchglist->pchgs[pchgno] = pchg;
++pchglist->numpchgs;
return 0;
}
jpc_pchg_t *jpc_pchglist_remove(jpc_pchglist_t *pchglist, int pchgno)
{
int i;
jpc_pchg_t *pchg;
assert(pchgno < pchglist->numpchgs);
pchg = pchglist->pchgs[pchgno];
for (i = pchgno + 1; i < pchglist->numpchgs; ++i) {
pchglist->pchgs[i - 1] = pchglist->pchgs[i];
}
--pchglist->numpchgs;
return pchg;
}
jpc_pchg_t *jpc_pchg_copy(jpc_pchg_t *pchg)
{
jpc_pchg_t *newpchg;
if (!(newpchg = jas_malloc(sizeof(jpc_pchg_t)))) {
return 0;
}
*newpchg = *pchg;
return newpchg;
}
jpc_pchglist_t *jpc_pchglist_copy(jpc_pchglist_t *pchglist)
{
jpc_pchglist_t *newpchglist;
jpc_pchg_t *newpchg;
int pchgno;
if (!(newpchglist = jpc_pchglist_create())) {
return 0;
}
for (pchgno = 0; pchgno < pchglist->numpchgs; ++pchgno) {
if (!(newpchg = jpc_pchg_copy(pchglist->pchgs[pchgno])) ||
jpc_pchglist_insert(newpchglist, -1, newpchg)) {
jpc_pchglist_destroy(newpchglist);
return 0;
}
}
return newpchglist;
}
void jpc_pchglist_destroy(jpc_pchglist_t *pchglist)
{
int pchgno;
if (pchglist->pchgs) {
for (pchgno = 0; pchgno < pchglist->numpchgs; ++pchgno) {
jpc_pchg_destroy(pchglist->pchgs[pchgno]);
}
jas_free(pchglist->pchgs);
}
jas_free(pchglist);
}
void jpc_pchg_destroy(jpc_pchg_t *pchg)
{
jas_free(pchg);
}
jpc_pchg_t *jpc_pchglist_get(jpc_pchglist_t *pchglist, int pchgno)
{
return pchglist->pchgs[pchgno];
}
int jpc_pchglist_numpchgs(jpc_pchglist_t *pchglist)
{
return pchglist->numpchgs;
}
int jpc_pi_init(jpc_pi_t *pi)
{
int compno;
int rlvlno;
int prcno;
jpc_picomp_t *picomp;
jpc_pirlvl_t *pirlvl;
int *prclyrno;
pi->prgvolfirst = 0;
pi->valid = 0;
pi->pktno = -1;
pi->pchgno = -1;
pi->pchg = 0;
for (compno = 0, picomp = pi->picomps; compno < pi->numcomps;
++compno, ++picomp) {
for (rlvlno = 0, pirlvl = picomp->pirlvls; rlvlno <
picomp->numrlvls; ++rlvlno, ++pirlvl) {
for (prcno = 0, prclyrno = pirlvl->prclyrnos;
prcno < pirlvl->numprcs; ++prcno, ++prclyrno) {
*prclyrno = 0;
}
}
}
return 0;
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/good_5492_1 |
crossvul-cpp_data_good_1178_0 | /** @file mat4.c
* Matlab MAT version 4 file functions
* @ingroup MAT
*/
/*
* Copyright (c) 2005-2019, Christopher C. Hulbert
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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.
*/
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <math.h>
#include <limits.h>
#if defined(__GLIBC__)
#include <endian.h>
#endif
#include "matio_private.h"
#include "mat4.h"
/** @if mat_devman
* @brief Creates a new Matlab MAT version 4 file
*
* Tries to create a new Matlab MAT file with the given name.
* @ingroup MAT
* @param matname Name of MAT file to create
* @return A pointer to the MAT file or NULL if it failed. This is not a
* simple FILE * and should not be used as one.
* @endif
*/
mat_t *
Mat_Create4(const char* matname)
{
FILE *fp = NULL;
mat_t *mat = NULL;
#if defined(_WIN32) && defined(_MSC_VER)
wchar_t* wname = utf82u(matname);
if ( NULL != wname ) {
fp = _wfopen(wname, L"w+b");
free(wname);
}
#else
fp = fopen(matname, "w+b");
#endif
if ( !fp )
return NULL;
mat = (mat_t*)malloc(sizeof(*mat));
if ( NULL == mat ) {
fclose(fp);
Mat_Critical("Couldn't allocate memory for the MAT file");
return NULL;
}
mat->fp = fp;
mat->header = NULL;
mat->subsys_offset = NULL;
mat->filename = strdup_printf("%s",matname);
mat->version = MAT_FT_MAT4;
mat->byteswap = 0;
mat->mode = 0;
mat->bof = 0;
mat->next_index = 0;
mat->num_datasets = 0;
#if defined(MAT73) && MAT73
mat->refs_id = -1;
#endif
mat->dir = NULL;
Mat_Rewind(mat);
return mat;
}
/** @if mat_devman
* @brief Writes a matlab variable to a version 4 matlab file
*
* @ingroup mat_internal
* @param mat MAT file pointer
* @param matvar pointer to the mat variable
* @retval 0 on success
* @endif
*/
int
Mat_VarWrite4(mat_t *mat,matvar_t *matvar)
{
typedef struct {
mat_int32_t type;
mat_int32_t mrows;
mat_int32_t ncols;
mat_int32_t imagf;
mat_int32_t namelen;
} Fmatrix;
mat_int32_t nelems = 1, i;
Fmatrix x;
if ( NULL == mat || NULL == matvar || NULL == matvar->name || matvar->rank != 2 )
return -1;
switch ( matvar->data_type ) {
case MAT_T_DOUBLE:
x.type = 0;
break;
case MAT_T_SINGLE:
x.type = 10;
break;
case MAT_T_INT32:
x.type = 20;
break;
case MAT_T_INT16:
x.type = 30;
break;
case MAT_T_UINT16:
x.type = 40;
break;
case MAT_T_UINT8:
x.type = 50;
break;
default:
return 2;
}
#if defined(__GLIBC__)
#if (__BYTE_ORDER == __LITTLE_ENDIAN)
#elif (__BYTE_ORDER == __BIG_ENDIAN)
x.type += 1000;
#else
return -1;
#endif
#elif defined(_BIG_ENDIAN) && !defined(_LITTLE_ENDIAN)
x.type += 1000;
#elif defined(_LITTLE_ENDIAN) && !defined(_BIG_ENDIAN)
#elif defined(__sparc) || defined(__sparc__) || defined(_POWER) || defined(__powerpc__) || \
defined(__ppc__) || defined(__hpux) || defined(_MIPSEB) || defined(_POWER) || defined(__s390__)
x.type += 1000;
#elif defined(__i386__) || defined(__alpha__) || defined(__ia64) || defined(__ia64__) || \
defined(_M_IX86) || defined(_M_IA64) || defined(_M_ALPHA) || defined(__amd64) || \
defined(__amd64__) || defined(_M_AMD64) || defined(__x86_64) || defined(__x86_64__) || \
defined(_M_X64) || defined(__bfin__)
#else
return -1;
#endif
x.namelen = (mat_int32_t)strlen(matvar->name) + 1;
/* FIXME: SEEK_END is not Guaranteed by the C standard */
(void)fseek((FILE*)mat->fp,0,SEEK_END); /* Always write at end of file */
switch ( matvar->class_type ) {
case MAT_C_CHAR:
x.type++;
/* Fall through */
case MAT_C_DOUBLE:
case MAT_C_SINGLE:
case MAT_C_INT32:
case MAT_C_INT16:
case MAT_C_UINT16:
case MAT_C_UINT8:
for ( i = 0; i < matvar->rank; i++ ) {
mat_int32_t dim;
dim = (mat_int32_t)matvar->dims[i];
nelems *= dim;
}
x.mrows = (mat_int32_t)matvar->dims[0];
x.ncols = (mat_int32_t)matvar->dims[1];
x.imagf = matvar->isComplex ? 1 : 0;
fwrite(&x, sizeof(Fmatrix), 1, (FILE*)mat->fp);
fwrite(matvar->name, sizeof(char), x.namelen, (FILE*)mat->fp);
if ( matvar->isComplex ) {
mat_complex_split_t *complex_data;
complex_data = (mat_complex_split_t*)matvar->data;
fwrite(complex_data->Re, matvar->data_size, nelems, (FILE*)mat->fp);
fwrite(complex_data->Im, matvar->data_size, nelems, (FILE*)mat->fp);
}
else {
fwrite(matvar->data, matvar->data_size, nelems, (FILE*)mat->fp);
}
break;
case MAT_C_SPARSE:
{
mat_sparse_t* sparse;
double tmp;
int j;
size_t stride = Mat_SizeOf(matvar->data_type);
#if !defined(EXTENDED_SPARSE)
if ( MAT_T_DOUBLE != matvar->data_type )
break;
#endif
sparse = (mat_sparse_t*)matvar->data;
x.type += 2;
x.mrows = sparse->njc > 0 ? sparse->jc[sparse->njc - 1] + 1 : 1;
x.ncols = matvar->isComplex ? 4 : 3;
x.imagf = 0;
fwrite(&x, sizeof(Fmatrix), 1, (FILE*)mat->fp);
fwrite(matvar->name, sizeof(char), x.namelen, (FILE*)mat->fp);
for ( i = 0; i < sparse->njc - 1; i++ ) {
for ( j = sparse->jc[i];
j < sparse->jc[i + 1] && j < sparse->ndata; j++ ) {
tmp = sparse->ir[j] + 1;
fwrite(&tmp, sizeof(double), 1, (FILE*)mat->fp);
}
}
tmp = (double)matvar->dims[0];
fwrite(&tmp, sizeof(double), 1, (FILE*)mat->fp);
for ( i = 0; i < sparse->njc - 1; i++ ) {
for ( j = sparse->jc[i];
j < sparse->jc[i + 1] && j < sparse->ndata; j++ ) {
tmp = i + 1;
fwrite(&tmp, sizeof(double), 1, (FILE*)mat->fp);
}
}
tmp = (double)matvar->dims[1];
fwrite(&tmp, sizeof(double), 1, (FILE*)mat->fp);
tmp = 0.;
if ( matvar->isComplex ) {
mat_complex_split_t *complex_data;
char* re, *im;
complex_data = (mat_complex_split_t*)sparse->data;
re = (char*)complex_data->Re;
im = (char*)complex_data->Im;
for ( i = 0; i < sparse->njc - 1; i++ ) {
for ( j = sparse->jc[i];
j < sparse->jc[i + 1] && j < sparse->ndata; j++ ) {
fwrite(re + j*stride, stride, 1, (FILE*)mat->fp);
}
}
fwrite(&tmp, stride, 1, (FILE*)mat->fp);
for ( i = 0; i < sparse->njc - 1; i++ ) {
for ( j = sparse->jc[i];
j < sparse->jc[i + 1] && j < sparse->ndata; j++ ) {
fwrite(im + j*stride, stride, 1, (FILE*)mat->fp);
}
}
} else {
char *data = (char*)sparse->data;
for ( i = 0; i < sparse->njc - 1; i++ ) {
for ( j = sparse->jc[i];
j < sparse->jc[i + 1] && j < sparse->ndata; j++ ) {
fwrite(data + j*stride, stride, 1, (FILE*)mat->fp);
}
}
}
fwrite(&tmp, stride, 1, (FILE*)mat->fp);
break;
}
default:
break;
}
return 0;
}
/** @if mat_devman
* @brief Reads the data of a version 4 MAT file variable
*
* @ingroup mat_internal
* @param mat MAT file pointer
* @param matvar MAT variable pointer to read the data
* @endif
*/
void
Mat_VarRead4(mat_t *mat,matvar_t *matvar)
{
int err;
size_t nelems = 1;
err = SafeMulDims(matvar, &nelems);
if ( err ) {
Mat_Critical("Integer multiplication overflow");
return;
}
(void)fseek((FILE*)mat->fp,matvar->internal->datapos,SEEK_SET);
switch ( matvar->class_type ) {
case MAT_C_DOUBLE:
matvar->data_size = sizeof(double);
err = SafeMul(&matvar->nbytes, nelems, matvar->data_size);
if ( err ) {
Mat_Critical("Integer multiplication overflow");
return;
}
if ( matvar->isComplex ) {
mat_complex_split_t *complex_data = ComplexMalloc(matvar->nbytes);
if ( NULL != complex_data ) {
matvar->data = complex_data;
ReadDoubleData(mat, (double*)complex_data->Re, matvar->data_type, nelems);
ReadDoubleData(mat, (double*)complex_data->Im, matvar->data_type, nelems);
}
else {
Mat_Critical("Couldn't allocate memory for the complex data");
}
} else {
matvar->data = malloc(matvar->nbytes);
if ( NULL != matvar->data ) {
ReadDoubleData(mat, (double*)matvar->data, matvar->data_type, nelems);
}
else {
Mat_Critical("Couldn't allocate memory for the data");
}
}
/* Update data type to match format of matvar->data */
matvar->data_type = MAT_T_DOUBLE;
break;
case MAT_C_CHAR:
matvar->data_size = 1;
matvar->nbytes = nelems;
matvar->data = malloc(matvar->nbytes);
if ( NULL != matvar->data ) {
ReadUInt8Data(mat, (mat_uint8_t*)matvar->data, matvar->data_type, nelems);
}
else {
Mat_Critical("Couldn't allocate memory for the data");
}
matvar->data_type = MAT_T_UINT8;
break;
case MAT_C_SPARSE:
matvar->data_size = sizeof(mat_sparse_t);
matvar->data = malloc(matvar->data_size);
if ( NULL != matvar->data ) {
double tmp;
int i;
mat_sparse_t* sparse;
long fpos;
enum matio_types data_type = MAT_T_DOUBLE;
/* matvar->dims[1] either is 3 for real or 4 for complex sparse */
matvar->isComplex = matvar->dims[1] == 4 ? 1 : 0;
sparse = (mat_sparse_t*)matvar->data;
sparse->nir = matvar->dims[0] - 1;
sparse->nzmax = sparse->nir;
sparse->ir = (mat_int32_t*)malloc(sparse->nir*sizeof(mat_int32_t));
if ( sparse->ir != NULL ) {
ReadInt32Data(mat, sparse->ir, data_type, sparse->nir);
for ( i = 0; i < sparse->nir; i++ )
sparse->ir[i] = sparse->ir[i] - 1;
} else {
free(matvar->data);
matvar->data = NULL;
Mat_Critical("Couldn't allocate memory for the sparse row array");
return;
}
ReadDoubleData(mat, &tmp, data_type, 1);
matvar->dims[0] = (size_t)tmp;
fpos = ftell((FILE*)mat->fp);
if ( fpos == -1L ) {
free(sparse->ir);
free(matvar->data);
matvar->data = NULL;
Mat_Critical("Couldn't determine file position");
return;
}
(void)fseek((FILE*)mat->fp,sparse->nir*Mat_SizeOf(data_type),
SEEK_CUR);
ReadDoubleData(mat, &tmp, data_type, 1);
if ( tmp > INT_MAX-1 || tmp < 0 ) {
free(sparse->ir);
free(matvar->data);
matvar->data = NULL;
Mat_Critical("Invalid column dimension for sparse matrix");
return;
}
matvar->dims[1] = (size_t)tmp;
(void)fseek((FILE*)mat->fp,fpos,SEEK_SET);
if ( matvar->dims[1] > INT_MAX-1 ) {
free(sparse->ir);
free(matvar->data);
matvar->data = NULL;
Mat_Critical("Invalid column dimension for sparse matrix");
return;
}
sparse->njc = (int)matvar->dims[1] + 1;
sparse->jc = (mat_int32_t*)malloc(sparse->njc*sizeof(mat_int32_t));
if ( sparse->jc != NULL ) {
mat_int32_t *jc;
jc = (mat_int32_t*)malloc(sparse->nir*sizeof(mat_int32_t));
if ( jc != NULL ) {
int j = 0;
sparse->jc[0] = 0;
ReadInt32Data(mat, jc, data_type, sparse->nir);
for ( i = 1; i < sparse->njc-1; i++ ) {
while ( j < sparse->nir && jc[j] <= i )
j++;
sparse->jc[i] = j;
}
free(jc);
/* terminating nnz */
sparse->jc[sparse->njc-1] = sparse->nir;
} else {
free(sparse->jc);
free(sparse->ir);
free(matvar->data);
matvar->data = NULL;
Mat_Critical("Couldn't allocate memory for the sparse index array");
return;
}
} else {
free(sparse->ir);
free(matvar->data);
matvar->data = NULL;
Mat_Critical("Couldn't allocate memory for the sparse index array");
return;
}
ReadDoubleData(mat, &tmp, data_type, 1);
sparse->ndata = sparse->nir;
data_type = matvar->data_type;
if ( matvar->isComplex ) {
mat_complex_split_t *complex_data =
ComplexMalloc(sparse->ndata*Mat_SizeOf(data_type));
if ( NULL != complex_data ) {
sparse->data = complex_data;
#if defined(EXTENDED_SPARSE)
switch ( data_type ) {
case MAT_T_DOUBLE:
ReadDoubleData(mat, (double*)complex_data->Re,
data_type, sparse->ndata);
ReadDoubleData(mat, &tmp, data_type, 1);
ReadDoubleData(mat, (double*)complex_data->Im,
data_type, sparse->ndata);
ReadDoubleData(mat, &tmp, data_type, 1);
break;
case MAT_T_SINGLE:
{
float tmp2;
ReadSingleData(mat, (float*)complex_data->Re,
data_type, sparse->ndata);
ReadSingleData(mat, &tmp2, data_type, 1);
ReadSingleData(mat, (float*)complex_data->Im,
data_type, sparse->ndata);
ReadSingleData(mat, &tmp2, data_type, 1);
break;
}
case MAT_T_INT32:
{
mat_int32_t tmp2;
ReadInt32Data(mat, (mat_int32_t*)complex_data->Re,
data_type, sparse->ndata);
ReadInt32Data(mat, &tmp2, data_type, 1);
ReadInt32Data(mat, (mat_int32_t*)complex_data->Im,
data_type, sparse->ndata);
ReadInt32Data(mat, &tmp2, data_type, 1);
break;
}
case MAT_T_INT16:
{
mat_int16_t tmp2;
ReadInt16Data(mat, (mat_int16_t*)complex_data->Re,
data_type, sparse->ndata);
ReadInt16Data(mat, &tmp2, data_type, 1);
ReadInt16Data(mat, (mat_int16_t*)complex_data->Im,
data_type, sparse->ndata);
ReadInt16Data(mat, &tmp2, data_type, 1);
break;
}
case MAT_T_UINT16:
{
mat_uint16_t tmp2;
ReadUInt16Data(mat, (mat_uint16_t*)complex_data->Re,
data_type, sparse->ndata);
ReadUInt16Data(mat, &tmp2, data_type, 1);
ReadUInt16Data(mat, (mat_uint16_t*)complex_data->Im,
data_type, sparse->ndata);
ReadUInt16Data(mat, &tmp2, data_type, 1);
break;
}
case MAT_T_UINT8:
{
mat_uint8_t tmp2;
ReadUInt8Data(mat, (mat_uint8_t*)complex_data->Re,
data_type, sparse->ndata);
ReadUInt8Data(mat, &tmp2, data_type, 1);
ReadUInt8Data(mat, (mat_uint8_t*)complex_data->Im,
data_type, sparse->ndata);
ReadUInt8Data(mat, &tmp2, data_type, 1);
break;
}
default:
free(complex_data->Re);
free(complex_data->Im);
free(complex_data);
free(sparse->jc);
free(sparse->ir);
free(matvar->data);
matvar->data = NULL;
Mat_Critical("Mat_VarRead4: %d is not a supported data type for "
"extended sparse", data_type);
return;
}
#else
ReadDoubleData(mat, (double*)complex_data->Re,
data_type, sparse->ndata);
ReadDoubleData(mat, &tmp, data_type, 1);
ReadDoubleData(mat, (double*)complex_data->Im,
data_type, sparse->ndata);
ReadDoubleData(mat, &tmp, data_type, 1);
#endif
}
else {
free(sparse->jc);
free(sparse->ir);
free(matvar->data);
matvar->data = NULL;
Mat_Critical("Couldn't allocate memory for the complex sparse data");
return;
}
} else {
sparse->data = malloc(sparse->ndata*Mat_SizeOf(data_type));
if ( sparse->data != NULL ) {
#if defined(EXTENDED_SPARSE)
switch ( data_type ) {
case MAT_T_DOUBLE:
ReadDoubleData(mat, (double*)sparse->data,
data_type, sparse->ndata);
ReadDoubleData(mat, &tmp, data_type, 1);
break;
case MAT_T_SINGLE:
{
float tmp2;
ReadSingleData(mat, (float*)sparse->data,
data_type, sparse->ndata);
ReadSingleData(mat, &tmp2, data_type, 1);
break;
}
case MAT_T_INT32:
{
mat_int32_t tmp2;
ReadInt32Data(mat, (mat_int32_t*)sparse->data,
data_type, sparse->ndata);
ReadInt32Data(mat, &tmp2, data_type, 1);
break;
}
case MAT_T_INT16:
{
mat_int16_t tmp2;
ReadInt16Data(mat, (mat_int16_t*)sparse->data,
data_type, sparse->ndata);
ReadInt16Data(mat, &tmp2, data_type, 1);
break;
}
case MAT_T_UINT16:
{
mat_uint16_t tmp2;
ReadUInt16Data(mat, (mat_uint16_t*)sparse->data,
data_type, sparse->ndata);
ReadUInt16Data(mat, &tmp2, data_type, 1);
break;
}
case MAT_T_UINT8:
{
mat_uint8_t tmp2;
ReadUInt8Data(mat, (mat_uint8_t*)sparse->data,
data_type, sparse->ndata);
ReadUInt8Data(mat, &tmp2, data_type, 1);
break;
}
default:
free(sparse->data);
free(sparse->jc);
free(sparse->ir);
free(matvar->data);
matvar->data = NULL;
Mat_Critical("Mat_VarRead4: %d is not a supported data type for "
"extended sparse", data_type);
return;
}
#else
ReadDoubleData(mat, (double*)sparse->data, data_type, sparse->ndata);
ReadDoubleData(mat, &tmp, data_type, 1);
#endif
} else {
free(sparse->jc);
free(sparse->ir);
free(matvar->data);
matvar->data = NULL;
Mat_Critical("Couldn't allocate memory for the sparse data");
return;
}
}
break;
}
else {
Mat_Critical("Couldn't allocate memory for the data");
return;
}
default:
Mat_Critical("MAT V4 data type error");
return;
}
return;
}
/** @if mat_devman
* @brief Reads a slab of data from a version 4 MAT file for the @c matvar variable
*
* @ingroup mat_internal
* @param mat Version 4 MAT file pointer
* @param matvar pointer to the mat variable
* @param data pointer to store the read data in (must be of size
* edge[0]*...edge[rank-1]*Mat_SizeOfClass(matvar->class_type))
* @param start index to start reading data in each dimension
* @param stride write data every @c stride elements in each dimension
* @param edge number of elements to read in each dimension
* @retval 0 on success
* @endif
*/
int
Mat_VarReadData4(mat_t *mat,matvar_t *matvar,void *data,
int *start,int *stride,int *edge)
{
int err = 0;
(void)fseek((FILE*)mat->fp,matvar->internal->datapos,SEEK_SET);
switch( matvar->data_type ) {
case MAT_T_DOUBLE:
case MAT_T_SINGLE:
case MAT_T_INT32:
case MAT_T_INT16:
case MAT_T_UINT16:
case MAT_T_UINT8:
break;
default:
return 1;
}
if ( matvar->rank == 2 ) {
if ( (size_t)stride[0]*(edge[0]-1)+start[0]+1 > matvar->dims[0] )
err = 1;
else if ( (size_t)stride[1]*(edge[1]-1)+start[1]+1 > matvar->dims[1] )
err = 1;
if ( matvar->isComplex ) {
mat_complex_split_t *cdata = (mat_complex_split_t*)data;
size_t nbytes = Mat_SizeOf(matvar->data_type);
err = SafeMulDims(matvar, &nbytes);
if ( err ) {
Mat_Critical("Integer multiplication overflow");
return err;
}
ReadDataSlab2(mat,cdata->Re,matvar->class_type,matvar->data_type,
matvar->dims,start,stride,edge);
(void)fseek((FILE*)mat->fp,matvar->internal->datapos+nbytes,SEEK_SET);
ReadDataSlab2(mat,cdata->Im,matvar->class_type,
matvar->data_type,matvar->dims,start,stride,edge);
} else {
ReadDataSlab2(mat,data,matvar->class_type,matvar->data_type,
matvar->dims,start,stride,edge);
}
} else if ( matvar->isComplex ) {
mat_complex_split_t *cdata = (mat_complex_split_t*)data;
size_t nbytes = Mat_SizeOf(matvar->data_type);
err = SafeMulDims(matvar, &nbytes);
if ( err ) {
Mat_Critical("Integer multiplication overflow");
return err;
}
ReadDataSlabN(mat,cdata->Re,matvar->class_type,matvar->data_type,
matvar->rank,matvar->dims,start,stride,edge);
(void)fseek((FILE*)mat->fp,matvar->internal->datapos+nbytes,SEEK_SET);
ReadDataSlabN(mat,cdata->Im,matvar->class_type,matvar->data_type,
matvar->rank,matvar->dims,start,stride,edge);
} else {
ReadDataSlabN(mat,data,matvar->class_type,matvar->data_type,
matvar->rank,matvar->dims,start,stride,edge);
}
return err;
}
/** @brief Reads a subset of a MAT variable using a 1-D indexing
*
* Reads data from a MAT variable using a linear (1-D) indexing mode. The
* variable must have been read by Mat_VarReadInfo.
* @ingroup MAT
* @param mat MAT file to read data from
* @param matvar MAT variable information
* @param data pointer to store data in (must be pre-allocated)
* @param start starting index
* @param stride stride of data
* @param edge number of elements to read
* @retval 0 on success
*/
int
Mat_VarReadDataLinear4(mat_t *mat,matvar_t *matvar,void *data,int start,
int stride,int edge)
{
int err;
size_t nelems = 1;
err = SafeMulDims(matvar, &nelems);
if ( err ) {
Mat_Critical("Integer multiplication overflow");
return err;
}
(void)fseek((FILE*)mat->fp,matvar->internal->datapos,SEEK_SET);
matvar->data_size = Mat_SizeOf(matvar->data_type);
if ( (size_t)stride*(edge-1)+start+1 > nelems ) {
return 1;
}
if ( matvar->isComplex ) {
mat_complex_split_t *complex_data = (mat_complex_split_t*)data;
err = SafeMul(&nelems, nelems, matvar->data_size);
if ( err ) {
Mat_Critical("Integer multiplication overflow");
return err;
}
ReadDataSlab1(mat,complex_data->Re,matvar->class_type,
matvar->data_type,start,stride,edge);
(void)fseek((FILE*)mat->fp,matvar->internal->datapos+nelems,SEEK_SET);
ReadDataSlab1(mat,complex_data->Im,matvar->class_type,
matvar->data_type,start,stride,edge);
} else {
ReadDataSlab1(mat,data,matvar->class_type,matvar->data_type,start,
stride,edge);
}
return err;
}
/** @if mat_devman
* @brief Reads the header information for the next MAT variable in a version 4 MAT file
*
* @ingroup mat_internal
* @param mat MAT file pointer
* @return pointer to the MAT variable or NULL
* @endif
*/
matvar_t *
Mat_VarReadNextInfo4(mat_t *mat)
{
int M,O,data_type,class_type;
mat_int32_t tmp;
long nBytes;
size_t readresult;
matvar_t *matvar = NULL;
union {
mat_uint32_t u;
mat_uint8_t c[4];
} endian;
if ( mat == NULL || mat->fp == NULL )
return NULL;
else if ( NULL == (matvar = Mat_VarCalloc()) )
return NULL;
readresult = fread(&tmp,sizeof(int),1,(FILE*)mat->fp);
if ( 1 != readresult ) {
Mat_VarFree(matvar);
return NULL;
}
endian.u = 0x01020304;
/* See if MOPT may need byteswapping */
if ( tmp < 0 || tmp > 4052 ) {
if ( Mat_int32Swap(&tmp) > 4052 ) {
Mat_VarFree(matvar);
return NULL;
}
}
M = (int)floor(tmp / 1000.0);
switch ( M ) {
case 0:
/* IEEE little endian */
mat->byteswap = endian.c[0] != 4;
break;
case 1:
/* IEEE big endian */
mat->byteswap = endian.c[0] != 1;
break;
default:
/* VAX, Cray, or bogus */
Mat_VarFree(matvar);
return NULL;
}
tmp -= M*1000;
O = (int)floor(tmp / 100.0);
/* O must be zero */
if ( 0 != O ) {
Mat_VarFree(matvar);
return NULL;
}
tmp -= O*100;
data_type = (int)floor(tmp / 10.0);
/* Convert the V4 data type */
switch ( data_type ) {
case 0:
matvar->data_type = MAT_T_DOUBLE;
break;
case 1:
matvar->data_type = MAT_T_SINGLE;
break;
case 2:
matvar->data_type = MAT_T_INT32;
break;
case 3:
matvar->data_type = MAT_T_INT16;
break;
case 4:
matvar->data_type = MAT_T_UINT16;
break;
case 5:
matvar->data_type = MAT_T_UINT8;
break;
default:
Mat_VarFree(matvar);
return NULL;
}
tmp -= data_type*10;
class_type = (int)floor(tmp / 1.0);
switch ( class_type ) {
case 0:
matvar->class_type = MAT_C_DOUBLE;
break;
case 1:
matvar->class_type = MAT_C_CHAR;
break;
case 2:
matvar->class_type = MAT_C_SPARSE;
break;
default:
Mat_VarFree(matvar);
return NULL;
}
matvar->rank = 2;
matvar->dims = (size_t*)calloc(2, sizeof(*matvar->dims));
if ( NULL == matvar->dims ) {
Mat_VarFree(matvar);
return NULL;
}
readresult = fread(&tmp,sizeof(int),1,(FILE*)mat->fp);
if ( mat->byteswap )
Mat_int32Swap(&tmp);
matvar->dims[0] = tmp;
if ( 1 != readresult ) {
Mat_VarFree(matvar);
return NULL;
}
readresult = fread(&tmp,sizeof(int),1,(FILE*)mat->fp);
if ( mat->byteswap )
Mat_int32Swap(&tmp);
matvar->dims[1] = tmp;
if ( 1 != readresult ) {
Mat_VarFree(matvar);
return NULL;
}
readresult = fread(&(matvar->isComplex),sizeof(int),1,(FILE*)mat->fp);
if ( 1 != readresult ) {
Mat_VarFree(matvar);
return NULL;
}
if ( matvar->isComplex && MAT_C_CHAR == matvar->class_type ) {
Mat_VarFree(matvar);
return NULL;
}
readresult = fread(&tmp,sizeof(int),1,(FILE*)mat->fp);
if ( 1 != readresult ) {
Mat_VarFree(matvar);
return NULL;
}
if ( mat->byteswap )
Mat_int32Swap(&tmp);
/* Check that the length of the variable name is at least 1 */
if ( tmp < 1 ) {
Mat_VarFree(matvar);
return NULL;
}
matvar->name = (char*)malloc(tmp);
if ( NULL == matvar->name ) {
Mat_VarFree(matvar);
return NULL;
}
readresult = fread(matvar->name,1,tmp,(FILE*)mat->fp);
if ( tmp != readresult ) {
Mat_VarFree(matvar);
return NULL;
} else {
matvar->name[tmp - 1] = '\0';
}
matvar->internal->datapos = ftell((FILE*)mat->fp);
if ( matvar->internal->datapos == -1L ) {
Mat_VarFree(matvar);
Mat_Critical("Couldn't determine file position");
return NULL;
}
{
int err;
size_t tmp2 = Mat_SizeOf(matvar->data_type);
if ( matvar->isComplex )
tmp2 *= 2;
err = SafeMulDims(matvar, &tmp2);
if ( err ) {
Mat_VarFree(matvar);
Mat_Critical("Integer multiplication overflow");
return NULL;
}
nBytes = (long)tmp2;
}
(void)fseek((FILE*)mat->fp,nBytes,SEEK_CUR);
return matvar;
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/good_1178_0 |
crossvul-cpp_data_good_2697_0 | /*
* Copyright (c) 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997
* The Regents of the University of California. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that: (1) source code distributions
* retain the above copyright notice and this paragraph in its entirety, (2)
* distributions including binary code include the above copyright notice and
* this paragraph in its entirety in the documentation or other materials
* provided with the distribution, and (3) all advertising materials mentioning
* features or use of this software display the following acknowledgement:
* ``This product includes software developed by the University of California,
* Lawrence Berkeley Laboratory and its contributors.'' Neither the name of
* the University nor the names of its contributors may be used to endorse
* or promote products derived from this software without specific prior
* written permission.
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
/* \summary: IP printer */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <netdissect-stdinc.h>
#include <string.h>
#include "netdissect.h"
#include "addrtoname.h"
#include "extract.h"
#include "ip.h"
#include "ipproto.h"
static const char tstr[] = "[|ip]";
static const struct tok ip_option_values[] = {
{ IPOPT_EOL, "EOL" },
{ IPOPT_NOP, "NOP" },
{ IPOPT_TS, "timestamp" },
{ IPOPT_SECURITY, "security" },
{ IPOPT_RR, "RR" },
{ IPOPT_SSRR, "SSRR" },
{ IPOPT_LSRR, "LSRR" },
{ IPOPT_RA, "RA" },
{ IPOPT_RFC1393, "traceroute" },
{ 0, NULL }
};
/*
* print the recorded route in an IP RR, LSRR or SSRR option.
*/
static int
ip_printroute(netdissect_options *ndo,
register const u_char *cp, u_int length)
{
register u_int ptr;
register u_int len;
if (length < 3) {
ND_PRINT((ndo, " [bad length %u]", length));
return (0);
}
if ((length + 1) & 3)
ND_PRINT((ndo, " [bad length %u]", length));
ND_TCHECK(cp[2]);
ptr = cp[2] - 1;
if (ptr < 3 || ((ptr + 1) & 3) || ptr > length + 1)
ND_PRINT((ndo, " [bad ptr %u]", cp[2]));
for (len = 3; len < length; len += 4) {
ND_TCHECK2(cp[len], 4);
ND_PRINT((ndo, " %s", ipaddr_string(ndo, &cp[len])));
if (ptr > len)
ND_PRINT((ndo, ","));
}
return (0);
trunc:
return (-1);
}
/*
* If source-routing is present and valid, return the final destination.
* Otherwise, return IP destination.
*
* This is used for UDP and TCP pseudo-header in the checksum
* calculation.
*/
static uint32_t
ip_finddst(netdissect_options *ndo,
const struct ip *ip)
{
int length;
int len;
const u_char *cp;
uint32_t retval;
cp = (const u_char *)(ip + 1);
length = (IP_HL(ip) << 2) - sizeof(struct ip);
for (; length > 0; cp += len, length -= len) {
int tt;
ND_TCHECK(*cp);
tt = *cp;
if (tt == IPOPT_EOL)
break;
else if (tt == IPOPT_NOP)
len = 1;
else {
ND_TCHECK(cp[1]);
len = cp[1];
if (len < 2)
break;
}
ND_TCHECK2(*cp, len);
switch (tt) {
case IPOPT_SSRR:
case IPOPT_LSRR:
if (len < 7)
break;
UNALIGNED_MEMCPY(&retval, cp + len - 4, 4);
return retval;
}
}
trunc:
UNALIGNED_MEMCPY(&retval, &ip->ip_dst, sizeof(uint32_t));
return retval;
}
/*
* Compute a V4-style checksum by building a pseudoheader.
*/
int
nextproto4_cksum(netdissect_options *ndo,
const struct ip *ip, const uint8_t *data,
u_int len, u_int covlen, u_int next_proto)
{
struct phdr {
uint32_t src;
uint32_t dst;
u_char mbz;
u_char proto;
uint16_t len;
} ph;
struct cksum_vec vec[2];
/* pseudo-header.. */
ph.len = htons((uint16_t)len);
ph.mbz = 0;
ph.proto = next_proto;
UNALIGNED_MEMCPY(&ph.src, &ip->ip_src, sizeof(uint32_t));
if (IP_HL(ip) == 5)
UNALIGNED_MEMCPY(&ph.dst, &ip->ip_dst, sizeof(uint32_t));
else
ph.dst = ip_finddst(ndo, ip);
vec[0].ptr = (const uint8_t *)(void *)&ph;
vec[0].len = sizeof(ph);
vec[1].ptr = data;
vec[1].len = covlen;
return (in_cksum(vec, 2));
}
static void
ip_printts(netdissect_options *ndo,
register const u_char *cp, u_int length)
{
register u_int ptr;
register u_int len;
int hoplen;
const char *type;
if (length < 4) {
ND_PRINT((ndo, "[bad length %u]", length));
return;
}
ND_PRINT((ndo, " TS{"));
hoplen = ((cp[3]&0xF) != IPOPT_TS_TSONLY) ? 8 : 4;
if ((length - 4) & (hoplen-1))
ND_PRINT((ndo, "[bad length %u]", length));
ptr = cp[2] - 1;
len = 0;
if (ptr < 4 || ((ptr - 4) & (hoplen-1)) || ptr > length + 1)
ND_PRINT((ndo, "[bad ptr %u]", cp[2]));
switch (cp[3]&0xF) {
case IPOPT_TS_TSONLY:
ND_PRINT((ndo, "TSONLY"));
break;
case IPOPT_TS_TSANDADDR:
ND_PRINT((ndo, "TS+ADDR"));
break;
/*
* prespecified should really be 3, but some ones might send 2
* instead, and the IPOPT_TS_PRESPEC constant can apparently
* have both values, so we have to hard-code it here.
*/
case 2:
ND_PRINT((ndo, "PRESPEC2.0"));
break;
case 3: /* IPOPT_TS_PRESPEC */
ND_PRINT((ndo, "PRESPEC"));
break;
default:
ND_PRINT((ndo, "[bad ts type %d]", cp[3]&0xF));
goto done;
}
type = " ";
for (len = 4; len < length; len += hoplen) {
if (ptr == len)
type = " ^ ";
ND_PRINT((ndo, "%s%d@%s", type, EXTRACT_32BITS(&cp[len+hoplen-4]),
hoplen!=8 ? "" : ipaddr_string(ndo, &cp[len])));
type = " ";
}
done:
ND_PRINT((ndo, "%s", ptr == len ? " ^ " : ""));
if (cp[3]>>4)
ND_PRINT((ndo, " [%d hops not recorded]} ", cp[3]>>4));
else
ND_PRINT((ndo, "}"));
}
/*
* print IP options.
*/
static void
ip_optprint(netdissect_options *ndo,
register const u_char *cp, u_int length)
{
register u_int option_len;
const char *sep = "";
for (; length > 0; cp += option_len, length -= option_len) {
u_int option_code;
ND_PRINT((ndo, "%s", sep));
sep = ",";
ND_TCHECK(*cp);
option_code = *cp;
ND_PRINT((ndo, "%s",
tok2str(ip_option_values,"unknown %u",option_code)));
if (option_code == IPOPT_NOP ||
option_code == IPOPT_EOL)
option_len = 1;
else {
ND_TCHECK(cp[1]);
option_len = cp[1];
if (option_len < 2) {
ND_PRINT((ndo, " [bad length %u]", option_len));
return;
}
}
if (option_len > length) {
ND_PRINT((ndo, " [bad length %u]", option_len));
return;
}
ND_TCHECK2(*cp, option_len);
switch (option_code) {
case IPOPT_EOL:
return;
case IPOPT_TS:
ip_printts(ndo, cp, option_len);
break;
case IPOPT_RR: /* fall through */
case IPOPT_SSRR:
case IPOPT_LSRR:
if (ip_printroute(ndo, cp, option_len) == -1)
goto trunc;
break;
case IPOPT_RA:
if (option_len < 4) {
ND_PRINT((ndo, " [bad length %u]", option_len));
break;
}
ND_TCHECK(cp[3]);
if (EXTRACT_16BITS(&cp[2]) != 0)
ND_PRINT((ndo, " value %u", EXTRACT_16BITS(&cp[2])));
break;
case IPOPT_NOP: /* nothing to print - fall through */
case IPOPT_SECURITY:
default:
break;
}
}
return;
trunc:
ND_PRINT((ndo, "%s", tstr));
}
#define IP_RES 0x8000
static const struct tok ip_frag_values[] = {
{ IP_MF, "+" },
{ IP_DF, "DF" },
{ IP_RES, "rsvd" }, /* The RFC3514 evil ;-) bit */
{ 0, NULL }
};
struct ip_print_demux_state {
const struct ip *ip;
const u_char *cp;
u_int len, off;
u_char nh;
int advance;
};
static void
ip_print_demux(netdissect_options *ndo,
struct ip_print_demux_state *ipds)
{
const char *p_name;
again:
switch (ipds->nh) {
case IPPROTO_AH:
if (!ND_TTEST(*ipds->cp)) {
ND_PRINT((ndo, "[|AH]"));
break;
}
ipds->nh = *ipds->cp;
ipds->advance = ah_print(ndo, ipds->cp);
if (ipds->advance <= 0)
break;
ipds->cp += ipds->advance;
ipds->len -= ipds->advance;
goto again;
case IPPROTO_ESP:
{
int enh, padlen;
ipds->advance = esp_print(ndo, ipds->cp, ipds->len,
(const u_char *)ipds->ip,
&enh, &padlen);
if (ipds->advance <= 0)
break;
ipds->cp += ipds->advance;
ipds->len -= ipds->advance + padlen;
ipds->nh = enh & 0xff;
goto again;
}
case IPPROTO_IPCOMP:
{
ipcomp_print(ndo, ipds->cp);
/*
* Either this has decompressed the payload and
* printed it, in which case there's nothing more
* to do, or it hasn't, in which case there's
* nothing more to do.
*/
break;
}
case IPPROTO_SCTP:
sctp_print(ndo, ipds->cp, (const u_char *)ipds->ip, ipds->len);
break;
case IPPROTO_DCCP:
dccp_print(ndo, ipds->cp, (const u_char *)ipds->ip, ipds->len);
break;
case IPPROTO_TCP:
/* pass on the MF bit plus the offset to detect fragments */
tcp_print(ndo, ipds->cp, ipds->len, (const u_char *)ipds->ip,
ipds->off & (IP_MF|IP_OFFMASK));
break;
case IPPROTO_UDP:
/* pass on the MF bit plus the offset to detect fragments */
udp_print(ndo, ipds->cp, ipds->len, (const u_char *)ipds->ip,
ipds->off & (IP_MF|IP_OFFMASK));
break;
case IPPROTO_ICMP:
/* pass on the MF bit plus the offset to detect fragments */
icmp_print(ndo, ipds->cp, ipds->len, (const u_char *)ipds->ip,
ipds->off & (IP_MF|IP_OFFMASK));
break;
case IPPROTO_PIGP:
/*
* XXX - the current IANA protocol number assignments
* page lists 9 as "any private interior gateway
* (used by Cisco for their IGRP)" and 88 as
* "EIGRP" from Cisco.
*
* Recent BSD <netinet/in.h> headers define
* IP_PROTO_PIGP as 9 and IP_PROTO_IGRP as 88.
* We define IP_PROTO_PIGP as 9 and
* IP_PROTO_EIGRP as 88; those names better
* match was the current protocol number
* assignments say.
*/
igrp_print(ndo, ipds->cp, ipds->len);
break;
case IPPROTO_EIGRP:
eigrp_print(ndo, ipds->cp, ipds->len);
break;
case IPPROTO_ND:
ND_PRINT((ndo, " nd %d", ipds->len));
break;
case IPPROTO_EGP:
egp_print(ndo, ipds->cp, ipds->len);
break;
case IPPROTO_OSPF:
ospf_print(ndo, ipds->cp, ipds->len, (const u_char *)ipds->ip);
break;
case IPPROTO_IGMP:
igmp_print(ndo, ipds->cp, ipds->len);
break;
case IPPROTO_IPV4:
/* DVMRP multicast tunnel (ip-in-ip encapsulation) */
ip_print(ndo, ipds->cp, ipds->len);
if (! ndo->ndo_vflag) {
ND_PRINT((ndo, " (ipip-proto-4)"));
return;
}
break;
case IPPROTO_IPV6:
/* ip6-in-ip encapsulation */
ip6_print(ndo, ipds->cp, ipds->len);
break;
case IPPROTO_RSVP:
rsvp_print(ndo, ipds->cp, ipds->len);
break;
case IPPROTO_GRE:
/* do it */
gre_print(ndo, ipds->cp, ipds->len);
break;
case IPPROTO_MOBILE:
mobile_print(ndo, ipds->cp, ipds->len);
break;
case IPPROTO_PIM:
pim_print(ndo, ipds->cp, ipds->len, (const u_char *)ipds->ip);
break;
case IPPROTO_VRRP:
if (ndo->ndo_packettype == PT_CARP) {
if (ndo->ndo_vflag)
ND_PRINT((ndo, "carp %s > %s: ",
ipaddr_string(ndo, &ipds->ip->ip_src),
ipaddr_string(ndo, &ipds->ip->ip_dst)));
carp_print(ndo, ipds->cp, ipds->len, ipds->ip->ip_ttl);
} else {
if (ndo->ndo_vflag)
ND_PRINT((ndo, "vrrp %s > %s: ",
ipaddr_string(ndo, &ipds->ip->ip_src),
ipaddr_string(ndo, &ipds->ip->ip_dst)));
vrrp_print(ndo, ipds->cp, ipds->len,
(const u_char *)ipds->ip, ipds->ip->ip_ttl);
}
break;
case IPPROTO_PGM:
pgm_print(ndo, ipds->cp, ipds->len, (const u_char *)ipds->ip);
break;
default:
if (ndo->ndo_nflag==0 && (p_name = netdb_protoname(ipds->nh)) != NULL)
ND_PRINT((ndo, " %s", p_name));
else
ND_PRINT((ndo, " ip-proto-%d", ipds->nh));
ND_PRINT((ndo, " %d", ipds->len));
break;
}
}
void
ip_print_inner(netdissect_options *ndo,
const u_char *bp,
u_int length, u_int nh,
const u_char *bp2)
{
struct ip_print_demux_state ipd;
ipd.ip = (const struct ip *)bp2;
ipd.cp = bp;
ipd.len = length;
ipd.off = 0;
ipd.nh = nh;
ipd.advance = 0;
ip_print_demux(ndo, &ipd);
}
/*
* print an IP datagram.
*/
void
ip_print(netdissect_options *ndo,
const u_char *bp,
u_int length)
{
struct ip_print_demux_state ipd;
struct ip_print_demux_state *ipds=&ipd;
const u_char *ipend;
u_int hlen;
struct cksum_vec vec[1];
uint16_t sum, ip_sum;
const char *p_name;
ipds->ip = (const struct ip *)bp;
ND_TCHECK(ipds->ip->ip_vhl);
if (IP_V(ipds->ip) != 4) { /* print version and fail if != 4 */
if (IP_V(ipds->ip) == 6)
ND_PRINT((ndo, "IP6, wrong link-layer encapsulation "));
else
ND_PRINT((ndo, "IP%u ", IP_V(ipds->ip)));
return;
}
if (!ndo->ndo_eflag)
ND_PRINT((ndo, "IP "));
ND_TCHECK(*ipds->ip);
if (length < sizeof (struct ip)) {
ND_PRINT((ndo, "truncated-ip %u", length));
return;
}
hlen = IP_HL(ipds->ip) * 4;
if (hlen < sizeof (struct ip)) {
ND_PRINT((ndo, "bad-hlen %u", hlen));
return;
}
ipds->len = EXTRACT_16BITS(&ipds->ip->ip_len);
if (length < ipds->len)
ND_PRINT((ndo, "truncated-ip - %u bytes missing! ",
ipds->len - length));
if (ipds->len < hlen) {
#ifdef GUESS_TSO
if (ipds->len) {
ND_PRINT((ndo, "bad-len %u", ipds->len));
return;
}
else {
/* we guess that it is a TSO send */
ipds->len = length;
}
#else
ND_PRINT((ndo, "bad-len %u", ipds->len));
return;
#endif /* GUESS_TSO */
}
/*
* Cut off the snapshot length to the end of the IP payload.
*/
ipend = bp + ipds->len;
if (ipend < ndo->ndo_snapend)
ndo->ndo_snapend = ipend;
ipds->len -= hlen;
ipds->off = EXTRACT_16BITS(&ipds->ip->ip_off);
if (ndo->ndo_vflag) {
ND_PRINT((ndo, "(tos 0x%x", (int)ipds->ip->ip_tos));
/* ECN bits */
switch (ipds->ip->ip_tos & 0x03) {
case 0:
break;
case 1:
ND_PRINT((ndo, ",ECT(1)"));
break;
case 2:
ND_PRINT((ndo, ",ECT(0)"));
break;
case 3:
ND_PRINT((ndo, ",CE"));
break;
}
if (ipds->ip->ip_ttl >= 1)
ND_PRINT((ndo, ", ttl %u", ipds->ip->ip_ttl));
/*
* for the firewall guys, print id, offset.
* On all but the last stick a "+" in the flags portion.
* For unfragmented datagrams, note the don't fragment flag.
*/
ND_PRINT((ndo, ", id %u, offset %u, flags [%s], proto %s (%u)",
EXTRACT_16BITS(&ipds->ip->ip_id),
(ipds->off & 0x1fff) * 8,
bittok2str(ip_frag_values, "none", ipds->off&0xe000),
tok2str(ipproto_values,"unknown",ipds->ip->ip_p),
ipds->ip->ip_p));
ND_PRINT((ndo, ", length %u", EXTRACT_16BITS(&ipds->ip->ip_len)));
if ((hlen - sizeof(struct ip)) > 0) {
ND_PRINT((ndo, ", options ("));
ip_optprint(ndo, (const u_char *)(ipds->ip + 1), hlen - sizeof(struct ip));
ND_PRINT((ndo, ")"));
}
if (!ndo->ndo_Kflag && (const u_char *)ipds->ip + hlen <= ndo->ndo_snapend) {
vec[0].ptr = (const uint8_t *)(const void *)ipds->ip;
vec[0].len = hlen;
sum = in_cksum(vec, 1);
if (sum != 0) {
ip_sum = EXTRACT_16BITS(&ipds->ip->ip_sum);
ND_PRINT((ndo, ", bad cksum %x (->%x)!", ip_sum,
in_cksum_shouldbe(ip_sum, sum)));
}
}
ND_PRINT((ndo, ")\n "));
}
/*
* If this is fragment zero, hand it to the next higher
* level protocol.
*/
if ((ipds->off & 0x1fff) == 0) {
ipds->cp = (const u_char *)ipds->ip + hlen;
ipds->nh = ipds->ip->ip_p;
if (ipds->nh != IPPROTO_TCP && ipds->nh != IPPROTO_UDP &&
ipds->nh != IPPROTO_SCTP && ipds->nh != IPPROTO_DCCP) {
ND_PRINT((ndo, "%s > %s: ",
ipaddr_string(ndo, &ipds->ip->ip_src),
ipaddr_string(ndo, &ipds->ip->ip_dst)));
}
ip_print_demux(ndo, ipds);
} else {
/*
* Ultra quiet now means that all this stuff should be
* suppressed.
*/
if (ndo->ndo_qflag > 1)
return;
/*
* This isn't the first frag, so we're missing the
* next level protocol header. print the ip addr
* and the protocol.
*/
ND_PRINT((ndo, "%s > %s:", ipaddr_string(ndo, &ipds->ip->ip_src),
ipaddr_string(ndo, &ipds->ip->ip_dst)));
if (!ndo->ndo_nflag && (p_name = netdb_protoname(ipds->ip->ip_p)) != NULL)
ND_PRINT((ndo, " %s", p_name));
else
ND_PRINT((ndo, " ip-proto-%d", ipds->ip->ip_p));
}
return;
trunc:
ND_PRINT((ndo, "%s", tstr));
return;
}
void
ipN_print(netdissect_options *ndo, register const u_char *bp, register u_int length)
{
if (length < 1) {
ND_PRINT((ndo, "truncated-ip %d", length));
return;
}
ND_TCHECK(*bp);
switch (*bp & 0xF0) {
case 0x40:
ip_print (ndo, bp, length);
break;
case 0x60:
ip6_print (ndo, bp, length);
break;
default:
ND_PRINT((ndo, "unknown ip %d", (*bp & 0xF0) >> 4));
break;
}
return;
trunc:
ND_PRINT((ndo, "%s", tstr));
return;
}
/*
* Local Variables:
* c-style: whitesmith
* c-basic-offset: 8
* End:
*/
| ./CrossVul/dataset_final_sorted/CWE-125/c/good_2697_0 |
crossvul-cpp_data_bad_145_0 | /* radare - LGPL - Copyright 2010-2018 - nibble, pancake */
#include <stdio.h>
#include <r_types.h>
#include <r_util.h>
#include "mach0.h"
#define bprintf if (bin->verbose) eprintf
typedef struct _ulebr {
ut8 *p;
} ulebr;
// OMG; THIS SHOULD BE KILLED; this var exposes the local native endian, which is completely unnecessary
static bool little_;
static ut64 read_uleb128(ulebr *r, ut8 *end) {
ut64 result = 0;
int bit = 0;
ut64 slice = 0;
ut8 *p = r->p;
do {
if (p == end) {
eprintf ("malformed uleb128");
break;
}
slice = *p & 0x7f;
if (bit > 63) {
eprintf ("uleb128 too big for uint64, bit=%d, result=0x%"PFMT64x, bit, result);
} else {
result |= (slice << bit);
bit += 7;
}
} while (*p++ & 0x80);
r->p = p;
return result;
}
static st64 read_sleb128(ulebr *r, ut8 *end) {
st64 result = 0;
int bit = 0;
ut8 byte = 0;
ut8 *p = r->p;
do {
if (p == end) {
eprintf ("malformed sleb128");
break;
}
byte = *p++;
result |= (((st64)(byte & 0x7f)) << bit);
bit += 7;
} while (byte & 0x80);
// sign extend negative numbers
if ((byte & 0x40)) {
result |= (-1LL) << bit;
}
r->p = p;
return result;
}
static ut64 entry_to_vaddr(struct MACH0_(obj_t)* bin) {
switch (bin->main_cmd.cmd) {
case LC_MAIN:
return bin->entry + bin->baddr;
case LC_UNIXTHREAD:
case LC_THREAD:
return bin->entry;
default:
return 0;
}
}
static ut64 addr_to_offset(struct MACH0_(obj_t)* bin, ut64 addr) {
ut64 segment_base, segment_size;
int i;
if (!bin->segs) {
return 0;
}
for (i = 0; i < bin->nsegs; i++) {
segment_base = (ut64)bin->segs[i].vmaddr;
segment_size = (ut64)bin->segs[i].vmsize;
if (addr >= segment_base && addr < segment_base + segment_size) {
return bin->segs[i].fileoff + (addr - segment_base);
}
}
return 0;
}
static int init_hdr(struct MACH0_(obj_t)* bin) {
ut8 magicbytes[4] = {0};
ut8 machohdrbytes[sizeof (struct MACH0_(mach_header))] = {0};
int len;
if (r_buf_read_at (bin->b, 0, magicbytes, 4) < 1) {
return false;
}
if (r_read_le32 (magicbytes) == 0xfeedface) {
bin->big_endian = false;
} else if (r_read_be32 (magicbytes) == 0xfeedface) {
bin->big_endian = true;
} else if (r_read_le32(magicbytes) == FAT_MAGIC) {
bin->big_endian = false;
} else if (r_read_be32(magicbytes) == FAT_MAGIC) {
bin->big_endian = true;
} else if (r_read_le32(magicbytes) == 0xfeedfacf) {
bin->big_endian = false;
} else if (r_read_be32(magicbytes) == 0xfeedfacf) {
bin->big_endian = true;
} else {
return false; // object files are magic == 0, but body is different :?
}
len = r_buf_read_at (bin->b, 0, machohdrbytes, sizeof (machohdrbytes));
if (len != sizeof (machohdrbytes)) {
bprintf ("Error: read (hdr)\n");
return false;
}
bin->hdr.magic = r_read_ble (&machohdrbytes[0], bin->big_endian, 32);
bin->hdr.cputype = r_read_ble (&machohdrbytes[4], bin->big_endian, 32);
bin->hdr.cpusubtype = r_read_ble (&machohdrbytes[8], bin->big_endian, 32);
bin->hdr.filetype = r_read_ble (&machohdrbytes[12], bin->big_endian, 32);
bin->hdr.ncmds = r_read_ble (&machohdrbytes[16], bin->big_endian, 32);
bin->hdr.sizeofcmds = r_read_ble (&machohdrbytes[20], bin->big_endian, 32);
bin->hdr.flags = r_read_ble (&machohdrbytes[24], bin->big_endian, 32);
#if R_BIN_MACH064
bin->hdr.reserved = r_read_ble (&machohdrbytes[28], bin->big_endian, 32);
#endif
sdb_set (bin->kv, "mach0_header.format",
"xxxxddx "
"magic cputype cpusubtype filetype ncmds sizeofcmds flags", 0);
sdb_num_set (bin->kv, "mach0_header.offset", 0, 0); // wat about fatmach0?
sdb_set (bin->kv, "mach_filetype.cparse", "enum mach_filetype{MH_OBJECT=1,"
"MH_EXECUTE=2, MH_FVMLIB=3, MH_CORE=4, MH_PRELOAD=5, MH_DYLIB=6,"
"MH_DYLINKER=7, MH_BUNDLE=8, MH_DYLIB_STUB=9, MH_DSYM=10,"
"MH_KEXT_BUNDLE=11}"
,0);
sdb_set (bin->kv, "mach_flags.cparse", "enum mach_flags{MH_NOUNDEFS=1,"
"MH_INCRLINK=2,MH_DYLDLINK=4,MH_BINDATLOAD=8,MH_PREBOUND=0x10,"
"MH_SPLIT_SEGS=0x20,MH_LAZY_INIT=0x40,MH_TWOLEVEL=0x80,"
"MH_FORCE_FLAT=0x100,MH_NOMULTIDEFS=0x200,MH_NOFIXPREBINDING=0x400,"
"MH_PREBINDABLE=0x800, MH_ALLMODSBOUND=0x1000,"
"MH_SUBSECTIONS_VIA_SYMBOLS=0x2000,"
"MH_CANONICAL=0x4000,MH_WEAK_DEFINES=0x8000,"
"MH_BINDS_TO_WEAK=0x10000,MH_ALLOW_STACK_EXECUTION=0x20000,"
"MH_ROOT_SAFE=0x40000,MH_SETUID_SAFE=0x80000,"
"MH_NO_REEXPORTED_DYLIBS=0x100000,MH_PIE=0x200000,"
"MH_DEAD_STRIPPABLE_DYLIB=0x400000,"
"MH_HAS_TLV_DESCRIPTORS=0x800000,"
"MH_NO_HEAP_EXECUTION=0x1000000 }",0);
return true;
}
static int parse_segments(struct MACH0_(obj_t)* bin, ut64 off) {
int i, j, k, sect, len;
ut32 size_sects;
ut8 segcom[sizeof (struct MACH0_(segment_command))] = {0};
ut8 sec[sizeof (struct MACH0_(section))] = {0};
if (!UT32_MUL (&size_sects, bin->nsegs, sizeof (struct MACH0_(segment_command)))) {
return false;
}
if (!size_sects || size_sects > bin->size) {
return false;
}
if (off > bin->size || off + sizeof (struct MACH0_(segment_command)) > bin->size) {
return false;
}
if (!(bin->segs = realloc (bin->segs, bin->nsegs * sizeof(struct MACH0_(segment_command))))) {
perror ("realloc (seg)");
return false;
}
j = bin->nsegs - 1;
len = r_buf_read_at (bin->b, off, segcom, sizeof (struct MACH0_(segment_command)));
if (len != sizeof (struct MACH0_(segment_command))) {
bprintf ("Error: read (seg)\n");
return false;
}
i = 0;
bin->segs[j].cmd = r_read_ble32 (&segcom[i], bin->big_endian);
i += sizeof (ut32);
bin->segs[j].cmdsize = r_read_ble32 (&segcom[i], bin->big_endian);
i += sizeof (ut32);
memcpy (&bin->segs[j].segname, &segcom[i], 16);
i += 16;
#if R_BIN_MACH064
bin->segs[j].vmaddr = r_read_ble64 (&segcom[i], bin->big_endian);
i += sizeof (ut64);
bin->segs[j].vmsize = r_read_ble64 (&segcom[i], bin->big_endian);
i += sizeof (ut64);
bin->segs[j].fileoff = r_read_ble64 (&segcom[i], bin->big_endian);
i += sizeof (ut64);
bin->segs[j].filesize = r_read_ble64 (&segcom[i], bin->big_endian);
i += sizeof (ut64);
#else
bin->segs[j].vmaddr = r_read_ble32 (&segcom[i], bin->big_endian);
i += sizeof (ut32);
bin->segs[j].vmsize = r_read_ble32 (&segcom[i], bin->big_endian);
i += sizeof (ut32);
bin->segs[j].fileoff = r_read_ble32 (&segcom[i], bin->big_endian);
i += sizeof (ut32);
bin->segs[j].filesize = r_read_ble32 (&segcom[i], bin->big_endian);
i += sizeof (ut32);
#endif
bin->segs[j].maxprot = r_read_ble32 (&segcom[i], bin->big_endian);
i += sizeof (ut32);
bin->segs[j].initprot = r_read_ble32 (&segcom[i], bin->big_endian);
i += sizeof (ut32);
bin->segs[j].nsects = r_read_ble32 (&segcom[i], bin->big_endian);
i += sizeof (ut32);
bin->segs[j].flags = r_read_ble32 (&segcom[i], bin->big_endian);
sdb_num_set (bin->kv, sdb_fmt ("mach0_segment_%d.offset", j), off, 0);
sdb_num_set (bin->kv, "mach0_segments.count", 0, 0);
sdb_set (bin->kv, "mach0_segment.format",
"xd[16]zxxxxoodx "
"cmd cmdsize segname vmaddr vmsize "
"fileoff filesize maxprot initprot nsects flags", 0);
if (bin->segs[j].nsects > 0) {
sect = bin->nsects;
bin->nsects += bin->segs[j].nsects;
if (bin->nsects > 128) {
int new_nsects = bin->nsects & 0xf;
bprintf ("WARNING: mach0 header contains too many sections (%d). Wrapping to %d\n",
bin->nsects, new_nsects);
bin->nsects = new_nsects;
}
if ((int)bin->nsects < 1) {
bprintf ("Warning: Invalid number of sections\n");
bin->nsects = sect;
return false;
}
if (!UT32_MUL (&size_sects, bin->nsects-sect, sizeof (struct MACH0_(section)))){
bin->nsects = sect;
return false;
}
if (!size_sects || size_sects > bin->size){
bin->nsects = sect;
return false;
}
if (bin->segs[j].cmdsize != sizeof (struct MACH0_(segment_command)) \
+ (sizeof (struct MACH0_(section))*bin->segs[j].nsects)){
bin->nsects = sect;
return false;
}
if (off + sizeof (struct MACH0_(segment_command)) > bin->size ||\
off + sizeof (struct MACH0_(segment_command)) + size_sects > bin->size){
bin->nsects = sect;
return false;
}
if (!(bin->sects = realloc (bin->sects, bin->nsects * sizeof (struct MACH0_(section))))) {
perror ("realloc (sects)");
bin->nsects = sect;
return false;
}
for (k = sect, j = 0; k < bin->nsects; k++, j++) {
ut64 offset = off + sizeof (struct MACH0_(segment_command)) + j * sizeof (struct MACH0_(section));
len = r_buf_read_at (bin->b, offset, sec, sizeof (struct MACH0_(section)));
if (len != sizeof (struct MACH0_(section))) {
bprintf ("Error: read (sects)\n");
bin->nsects = sect;
return false;
}
i = 0;
memcpy (&bin->sects[k].sectname, &sec[i], 16);
i += 16;
memcpy (&bin->sects[k].segname, &sec[i], 16);
bin->sects[k].segname[15] = 0;
i += 16;
#if R_BIN_MACH064
bin->sects[k].addr = r_read_ble64 (&sec[i], bin->big_endian);
i += sizeof (ut64);
bin->sects[k].size = r_read_ble64 (&sec[i], bin->big_endian);
i += sizeof (ut64);
#else
bin->sects[k].addr = r_read_ble32 (&sec[i], bin->big_endian);
i += sizeof (ut32);
bin->sects[k].size = r_read_ble32 (&sec[i], bin->big_endian);
i += sizeof (ut32);
#endif
bin->sects[k].offset = r_read_ble32 (&sec[i], bin->big_endian);
i += sizeof (ut32);
bin->sects[k].align = r_read_ble32 (&sec[i], bin->big_endian);
i += sizeof (ut32);
bin->sects[k].reloff = r_read_ble32 (&sec[i], bin->big_endian);
i += sizeof (ut32);
bin->sects[k].nreloc = r_read_ble32 (&sec[i], bin->big_endian);
i += sizeof (ut32);
bin->sects[k].flags = r_read_ble32 (&sec[i], bin->big_endian);
i += sizeof (ut32);
bin->sects[k].reserved1 = r_read_ble32 (&sec[i], bin->big_endian);
i += sizeof (ut32);
bin->sects[k].reserved2 = r_read_ble32 (&sec[i], bin->big_endian);
#if R_BIN_MACH064
i += sizeof (ut32);
bin->sects[k].reserved3 = r_read_ble32 (&sec[i], bin->big_endian);
#endif
}
}
return true;
}
static int parse_symtab(struct MACH0_(obj_t)* bin, ut64 off) {
struct symtab_command st;
ut32 size_sym;
int i;
ut8 symt[sizeof (struct symtab_command)] = {0};
ut8 nlst[sizeof (struct MACH0_(nlist))] = {0};
if (off > (ut64)bin->size || off + sizeof (struct symtab_command) > (ut64)bin->size) {
return false;
}
int len = r_buf_read_at (bin->b, off, symt, sizeof (struct symtab_command));
if (len != sizeof (struct symtab_command)) {
bprintf ("Error: read (symtab)\n");
return false;
}
st.cmd = r_read_ble32 (&symt[0], bin->big_endian);
st.cmdsize = r_read_ble32 (&symt[4], bin->big_endian);
st.symoff = r_read_ble32 (&symt[8], bin->big_endian);
st.nsyms = r_read_ble32 (&symt[12], bin->big_endian);
st.stroff = r_read_ble32 (&symt[16], bin->big_endian);
st.strsize = r_read_ble32 (&symt[20], bin->big_endian);
bin->symtab = NULL;
bin->nsymtab = 0;
if (st.strsize > 0 && st.strsize < bin->size && st.nsyms > 0) {
bin->nsymtab = st.nsyms;
if (st.stroff > bin->size || st.stroff + st.strsize > bin->size) {
return false;
}
if (!UT32_MUL (&size_sym, bin->nsymtab, sizeof (struct MACH0_(nlist)))) {
bprintf("fail2\n");
return false;
}
if (!size_sym) {
bprintf("fail3\n");
return false;
}
if (st.symoff > bin->size || st.symoff + size_sym > bin->size) {
bprintf("fail4\n");
return false;
}
if (!(bin->symstr = calloc (1, st.strsize + 2))) {
perror ("calloc (symstr)");
return false;
}
bin->symstrlen = st.strsize;
len = r_buf_read_at (bin->b, st.stroff, (ut8*)bin->symstr, st.strsize);
if (len != st.strsize) {
bprintf ("Error: read (symstr)\n");
R_FREE (bin->symstr);
return false;
}
if (!(bin->symtab = calloc (bin->nsymtab, sizeof (struct MACH0_(nlist))))) {
perror ("calloc (symtab)");
return false;
}
for (i = 0; i < bin->nsymtab; i++) {
len = r_buf_read_at (bin->b, st.symoff + (i * sizeof (struct MACH0_(nlist))),
nlst, sizeof (struct MACH0_(nlist)));
if (len != sizeof (struct MACH0_(nlist))) {
bprintf ("Error: read (nlist)\n");
R_FREE (bin->symtab);
return false;
}
//XXX not very safe what if is n_un.n_name instead?
bin->symtab[i].n_strx = r_read_ble32 (&nlst[0], bin->big_endian);
bin->symtab[i].n_type = r_read_ble8 (&nlst[4]);
bin->symtab[i].n_sect = r_read_ble8 (&nlst[5]);
bin->symtab[i].n_desc = r_read_ble16 (&nlst[6], bin->big_endian);
#if R_BIN_MACH064
bin->symtab[i].n_value = r_read_ble64 (&nlst[8], bin->big_endian);
#else
bin->symtab[i].n_value = r_read_ble32 (&nlst[8], bin->big_endian);
#endif
}
}
return true;
}
static int parse_dysymtab(struct MACH0_(obj_t)* bin, ut64 off) {
int len, i;
ut32 size_tab;
ut8 dysym[sizeof (struct dysymtab_command)] = {0};
ut8 dytoc[sizeof (struct dylib_table_of_contents)] = {0};
ut8 dymod[sizeof (struct MACH0_(dylib_module))] = {0};
ut8 idsyms[sizeof (ut32)] = {0};
if (off > bin->size || off + sizeof (struct dysymtab_command) > bin->size) {
return false;
}
len = r_buf_read_at (bin->b, off, dysym, sizeof (struct dysymtab_command));
if (len != sizeof (struct dysymtab_command)) {
bprintf ("Error: read (dysymtab)\n");
return false;
}
bin->dysymtab.cmd = r_read_ble32 (&dysym[0], bin->big_endian);
bin->dysymtab.cmdsize = r_read_ble32 (&dysym[4], bin->big_endian);
bin->dysymtab.ilocalsym = r_read_ble32 (&dysym[8], bin->big_endian);
bin->dysymtab.nlocalsym = r_read_ble32 (&dysym[12], bin->big_endian);
bin->dysymtab.iextdefsym = r_read_ble32 (&dysym[16], bin->big_endian);
bin->dysymtab.nextdefsym = r_read_ble32 (&dysym[20], bin->big_endian);
bin->dysymtab.iundefsym = r_read_ble32 (&dysym[24], bin->big_endian);
bin->dysymtab.nundefsym = r_read_ble32 (&dysym[28], bin->big_endian);
bin->dysymtab.tocoff = r_read_ble32 (&dysym[32], bin->big_endian);
bin->dysymtab.ntoc = r_read_ble32 (&dysym[36], bin->big_endian);
bin->dysymtab.modtaboff = r_read_ble32 (&dysym[40], bin->big_endian);
bin->dysymtab.nmodtab = r_read_ble32 (&dysym[44], bin->big_endian);
bin->dysymtab.extrefsymoff = r_read_ble32 (&dysym[48], bin->big_endian);
bin->dysymtab.nextrefsyms = r_read_ble32 (&dysym[52], bin->big_endian);
bin->dysymtab.indirectsymoff = r_read_ble32 (&dysym[56], bin->big_endian);
bin->dysymtab.nindirectsyms = r_read_ble32 (&dysym[60], bin->big_endian);
bin->dysymtab.extreloff = r_read_ble32 (&dysym[64], bin->big_endian);
bin->dysymtab.nextrel = r_read_ble32 (&dysym[68], bin->big_endian);
bin->dysymtab.locreloff = r_read_ble32 (&dysym[72], bin->big_endian);
bin->dysymtab.nlocrel = r_read_ble32 (&dysym[76], bin->big_endian);
bin->ntoc = bin->dysymtab.ntoc;
if (bin->ntoc > 0) {
if (!(bin->toc = calloc (bin->ntoc, sizeof (struct dylib_table_of_contents)))) {
perror ("calloc (toc)");
return false;
}
if (!UT32_MUL (&size_tab, bin->ntoc, sizeof (struct dylib_table_of_contents))){
R_FREE (bin->toc);
return false;
}
if (!size_tab){
R_FREE (bin->toc);
return false;
}
if (bin->dysymtab.tocoff > bin->size || bin->dysymtab.tocoff + size_tab > bin->size){
R_FREE (bin->toc);
return false;
}
for (i = 0; i < bin->ntoc; i++) {
len = r_buf_read_at (bin->b, bin->dysymtab.tocoff +
i * sizeof (struct dylib_table_of_contents),
dytoc, sizeof (struct dylib_table_of_contents));
if (len != sizeof (struct dylib_table_of_contents)) {
bprintf ("Error: read (toc)\n");
R_FREE (bin->toc);
return false;
}
bin->toc[i].symbol_index = r_read_ble32 (&dytoc[0], bin->big_endian);
bin->toc[i].module_index = r_read_ble32 (&dytoc[4], bin->big_endian);
}
}
bin->nmodtab = bin->dysymtab.nmodtab;
if (bin->nmodtab > 0) {
if (!(bin->modtab = calloc (bin->nmodtab, sizeof (struct MACH0_(dylib_module))))) {
perror ("calloc (modtab)");
return false;
}
if (!UT32_MUL (&size_tab, bin->nmodtab, sizeof (struct MACH0_(dylib_module)))){
R_FREE (bin->modtab);
return false;
}
if (!size_tab){
R_FREE (bin->modtab);
return false;
}
if (bin->dysymtab.modtaboff > bin->size || \
bin->dysymtab.modtaboff + size_tab > bin->size){
R_FREE (bin->modtab);
return false;
}
for (i = 0; i < bin->nmodtab; i++) {
len = r_buf_read_at (bin->b, bin->dysymtab.modtaboff +
i * sizeof (struct MACH0_(dylib_module)),
dymod, sizeof (struct MACH0_(dylib_module)));
if (len == -1) {
bprintf ("Error: read (modtab)\n");
R_FREE (bin->modtab);
return false;
}
bin->modtab[i].module_name = r_read_ble32 (&dymod[0], bin->big_endian);
bin->modtab[i].iextdefsym = r_read_ble32 (&dymod[4], bin->big_endian);
bin->modtab[i].nextdefsym = r_read_ble32 (&dymod[8], bin->big_endian);
bin->modtab[i].irefsym = r_read_ble32 (&dymod[12], bin->big_endian);
bin->modtab[i].nrefsym = r_read_ble32 (&dymod[16], bin->big_endian);
bin->modtab[i].ilocalsym = r_read_ble32 (&dymod[20], bin->big_endian);
bin->modtab[i].nlocalsym = r_read_ble32 (&dymod[24], bin->big_endian);
bin->modtab[i].iextrel = r_read_ble32 (&dymod[28], bin->big_endian);
bin->modtab[i].nextrel = r_read_ble32 (&dymod[32], bin->big_endian);
bin->modtab[i].iinit_iterm = r_read_ble32 (&dymod[36], bin->big_endian);
bin->modtab[i].ninit_nterm = r_read_ble32 (&dymod[40], bin->big_endian);
#if R_BIN_MACH064
bin->modtab[i].objc_module_info_size = r_read_ble32 (&dymod[44], bin->big_endian);
bin->modtab[i].objc_module_info_addr = r_read_ble64 (&dymod[48], bin->big_endian);
#else
bin->modtab[i].objc_module_info_addr = r_read_ble32 (&dymod[44], bin->big_endian);
bin->modtab[i].objc_module_info_size = r_read_ble32 (&dymod[48], bin->big_endian);
#endif
}
}
bin->nindirectsyms = bin->dysymtab.nindirectsyms;
if (bin->nindirectsyms > 0) {
if (!(bin->indirectsyms = calloc (bin->nindirectsyms, sizeof (ut32)))) {
perror ("calloc (indirectsyms)");
return false;
}
if (!UT32_MUL (&size_tab, bin->nindirectsyms, sizeof (ut32))){
R_FREE (bin->indirectsyms);
return false;
}
if (!size_tab){
R_FREE (bin->indirectsyms);
return false;
}
if (bin->dysymtab.indirectsymoff > bin->size || \
bin->dysymtab.indirectsymoff + size_tab > bin->size){
R_FREE (bin->indirectsyms);
return false;
}
for (i = 0; i < bin->nindirectsyms; i++) {
len = r_buf_read_at (bin->b, bin->dysymtab.indirectsymoff + i * sizeof (ut32), idsyms, 4);
if (len == -1) {
bprintf ("Error: read (indirect syms)\n");
R_FREE (bin->indirectsyms);
return false;
}
bin->indirectsyms[i] = r_read_ble32 (&idsyms[0], bin->big_endian);
}
}
/* TODO extrefsyms, extrel, locrel */
return true;
}
static bool parse_signature(struct MACH0_(obj_t) *bin, ut64 off) {
int i,len;
ut32 data;
bin->signature = NULL;
struct linkedit_data_command link = {0};
ut8 lit[sizeof (struct linkedit_data_command)] = {0};
struct blob_index_t idx = {0};
struct super_blob_t super = {{0}};
if (off > bin->size || off + sizeof (struct linkedit_data_command) > bin->size) {
return false;
}
len = r_buf_read_at (bin->b, off, lit, sizeof (struct linkedit_data_command));
if (len != sizeof (struct linkedit_data_command)) {
bprintf ("Failed to get data while parsing LC_CODE_SIGNATURE command\n");
return false;
}
link.cmd = r_read_ble32 (&lit[0], bin->big_endian);
link.cmdsize = r_read_ble32 (&lit[4], bin->big_endian);
link.dataoff = r_read_ble32 (&lit[8], bin->big_endian);
link.datasize = r_read_ble32 (&lit[12], bin->big_endian);
data = link.dataoff;
if (data > bin->size || data + sizeof (struct super_blob_t) > bin->size) {
bin->signature = (ut8 *)strdup ("Malformed entitlement");
return true;
}
super.blob.magic = r_read_ble32 (bin->b->buf + data, little_);
super.blob.length = r_read_ble32 (bin->b->buf + data + 4, little_);
super.count = r_read_ble32 (bin->b->buf + data + 8, little_);
for (i = 0; i < super.count; ++i) {
if ((ut8 *)(bin->b->buf + data + i) > (ut8 *)(bin->b->buf + bin->size)) {
bin->signature = (ut8 *)strdup ("Malformed entitlement");
break;
}
struct blob_index_t bi;
if (r_buf_read_at (bin->b, data + 12 + (i * sizeof (struct blob_index_t)),
(ut8*)&bi, sizeof (struct blob_index_t)) < sizeof (struct blob_index_t)) {
break;
}
idx.type = r_read_ble32 (&bi.type, little_);
idx.offset = r_read_ble32 (&bi.offset, little_);
if (idx.type == CSSLOT_ENTITLEMENTS) {
ut64 off = data + idx.offset;
if (off > bin->size || off + sizeof (struct blob_t) > bin->size) {
bin->signature = (ut8 *)strdup ("Malformed entitlement");
break;
}
struct blob_t entitlements = {0};
entitlements.magic = r_read_ble32 (bin->b->buf + off, little_);
entitlements.length = r_read_ble32 (bin->b->buf + off + 4, little_);
len = entitlements.length - sizeof (struct blob_t);
if (len <= bin->size && len > 1) {
bin->signature = calloc (1, len + 1);
if (bin->signature) {
ut8 *src = bin->b->buf + off + sizeof (struct blob_t);
if (off + sizeof (struct blob_t) + len < bin->b->length) {
memcpy (bin->signature, src, len);
bin->signature[len] = '\0';
return true;
}
bin->signature = (ut8 *)strdup ("Malformed entitlement");
return true;
}
} else {
bin->signature = (ut8 *)strdup ("Malformed entitlement");
}
}
}
if (!bin->signature) {
bin->signature = (ut8 *)strdup ("No entitlement found");
}
return true;
}
static int parse_thread(struct MACH0_(obj_t)* bin, struct load_command *lc, ut64 off, bool is_first_thread) {
ut64 ptr_thread, pc = UT64_MAX, pc_offset = UT64_MAX;
ut32 flavor, count;
ut8 *arw_ptr = NULL;
int arw_sz, len = 0;
ut8 thc[sizeof (struct thread_command)] = {0};
ut8 tmp[4];
if (off > bin->size || off + sizeof (struct thread_command) > bin->size)
return false;
len = r_buf_read_at (bin->b, off, thc, 8);
if (len < 1) {
goto wrong_read;
}
bin->thread.cmd = r_read_ble32 (&thc[0], bin->big_endian);
bin->thread.cmdsize = r_read_ble32 (&thc[4], bin->big_endian);
if (r_buf_read_at (bin->b, off + sizeof (struct thread_command), tmp, 4) < 4) {
goto wrong_read;
}
flavor = r_read_ble32 (tmp, bin->big_endian);
if (len == -1)
goto wrong_read;
if (off + sizeof (struct thread_command) + sizeof (flavor) > bin->size || \
off + sizeof (struct thread_command) + sizeof (flavor) + sizeof (ut32) > bin->size)
return false;
// TODO: use count for checks
if (r_buf_read_at (bin->b, off + sizeof (struct thread_command) + sizeof (flavor), tmp, 4) < 4) {
goto wrong_read;
}
count = r_read_ble32 (tmp, bin->big_endian);
ptr_thread = off + sizeof (struct thread_command) + sizeof (flavor) + sizeof (count);
if (ptr_thread > bin->size)
return false;
switch (bin->hdr.cputype) {
case CPU_TYPE_I386:
case CPU_TYPE_X86_64:
switch (flavor) {
case X86_THREAD_STATE32:
if (ptr_thread + sizeof (struct x86_thread_state32) > bin->size)
return false;
if ((len = r_buf_fread_at (bin->b, ptr_thread,
(ut8*)&bin->thread_state.x86_32, "16i", 1)) == -1) {
bprintf ("Error: read (thread state x86_32)\n");
return false;
}
pc = bin->thread_state.x86_32.eip;
pc_offset = ptr_thread + r_offsetof(struct x86_thread_state32, eip);
arw_ptr = (ut8 *)&bin->thread_state.x86_32;
arw_sz = sizeof (struct x86_thread_state32);
break;
case X86_THREAD_STATE64:
if (ptr_thread + sizeof (struct x86_thread_state64) > bin->size)
return false;
if ((len = r_buf_fread_at (bin->b, ptr_thread,
(ut8*)&bin->thread_state.x86_64, "32l", 1)) == -1) {
bprintf ("Error: read (thread state x86_64)\n");
return false;
}
pc = bin->thread_state.x86_64.rip;
pc_offset = ptr_thread + r_offsetof(struct x86_thread_state64, rip);
arw_ptr = (ut8 *)&bin->thread_state.x86_64;
arw_sz = sizeof (struct x86_thread_state64);
break;
//default: bprintf ("Unknown type\n");
}
break;
case CPU_TYPE_POWERPC:
case CPU_TYPE_POWERPC64:
if (flavor == X86_THREAD_STATE32) {
if (ptr_thread + sizeof (struct ppc_thread_state32) > bin->size)
return false;
if ((len = r_buf_fread_at (bin->b, ptr_thread,
(ut8*)&bin->thread_state.ppc_32, bin->big_endian?"40I":"40i", 1)) == -1) {
bprintf ("Error: read (thread state ppc_32)\n");
return false;
}
pc = bin->thread_state.ppc_32.srr0;
pc_offset = ptr_thread + r_offsetof(struct ppc_thread_state32, srr0);
arw_ptr = (ut8 *)&bin->thread_state.ppc_32;
arw_sz = sizeof (struct ppc_thread_state32);
} else if (flavor == X86_THREAD_STATE64) {
if (ptr_thread + sizeof (struct ppc_thread_state64) > bin->size)
return false;
if ((len = r_buf_fread_at (bin->b, ptr_thread,
(ut8*)&bin->thread_state.ppc_64, bin->big_endian?"34LI3LI":"34li3li", 1)) == -1) {
bprintf ("Error: read (thread state ppc_64)\n");
return false;
}
pc = bin->thread_state.ppc_64.srr0;
pc_offset = ptr_thread + r_offsetof(struct ppc_thread_state64, srr0);
arw_ptr = (ut8 *)&bin->thread_state.ppc_64;
arw_sz = sizeof (struct ppc_thread_state64);
}
break;
case CPU_TYPE_ARM:
if (ptr_thread + sizeof (struct arm_thread_state32) > bin->size)
return false;
if ((len = r_buf_fread_at (bin->b, ptr_thread,
(ut8*)&bin->thread_state.arm_32, bin->big_endian?"17I":"17i", 1)) == -1) {
bprintf ("Error: read (thread state arm)\n");
return false;
}
pc = bin->thread_state.arm_32.r15;
pc_offset = ptr_thread + r_offsetof (struct arm_thread_state32, r15);
arw_ptr = (ut8 *)&bin->thread_state.arm_32;
arw_sz = sizeof (struct arm_thread_state32);
break;
case CPU_TYPE_ARM64:
if (ptr_thread + sizeof (struct arm_thread_state64) > bin->size) {
return false;
}
if ((len = r_buf_fread_at(bin->b, ptr_thread,
(ut8*)&bin->thread_state.arm_64, bin->big_endian?"34LI1I":"34Li1i", 1)) == -1) {
bprintf ("Error: read (thread state arm)\n");
return false;
}
pc = r_read_be64 (&bin->thread_state.arm_64.pc);
pc_offset = ptr_thread + r_offsetof (struct arm_thread_state64, pc);
arw_ptr = (ut8*)&bin->thread_state.arm_64;
arw_sz = sizeof (struct arm_thread_state64);
break;
default:
bprintf ("Error: read (unknown thread state structure)\n");
return false;
}
// TODO: this shouldnt be an bprintf...
if (arw_ptr && arw_sz > 0) {
int i;
ut8 *p = arw_ptr;
bprintf ("arw ");
for (i = 0; i < arw_sz; i++) {
bprintf ("%02x", 0xff & p[i]);
}
bprintf ("\n");
}
if (is_first_thread) {
bin->main_cmd = *lc;
if (pc != UT64_MAX) {
bin->entry = pc;
}
if (pc_offset != UT64_MAX) {
sdb_num_set (bin->kv, "mach0.entry.offset", pc_offset, 0);
}
}
return true;
wrong_read:
bprintf ("Error: read (thread)\n");
return false;
}
static int parse_function_starts (struct MACH0_(obj_t)* bin, ut64 off) {
struct linkedit_data_command fc;
ut8 sfc[sizeof (struct linkedit_data_command)] = {0};
ut8 *buf;
int len;
if (off > bin->size || off + sizeof (struct linkedit_data_command) > bin->size) {
bprintf ("Likely overflow while parsing"
" LC_FUNCTION_STARTS command\n");
}
bin->func_start = NULL;
len = r_buf_read_at (bin->b, off, sfc, sizeof (struct linkedit_data_command));
if (len < 1) {
bprintf ("Failed to get data while parsing"
" LC_FUNCTION_STARTS command\n");
}
fc.cmd = r_read_ble32 (&sfc[0], bin->big_endian);
fc.cmdsize = r_read_ble32 (&sfc[4], bin->big_endian);
fc.dataoff = r_read_ble32 (&sfc[8], bin->big_endian);
fc.datasize = r_read_ble32 (&sfc[12], bin->big_endian);
buf = calloc (1, fc.datasize + 1);
if (!buf) {
bprintf ("Failed to allocate buffer\n");
return false;
}
bin->func_size = fc.datasize;
if (fc.dataoff > bin->size || fc.dataoff + fc.datasize > bin->size) {
free (buf);
bprintf ("Likely overflow while parsing "
"LC_FUNCTION_STARTS command\n");
return false;
}
len = r_buf_read_at (bin->b, fc.dataoff, buf, fc.datasize);
if (len != fc.datasize) {
free (buf);
bprintf ("Failed to get data while parsing"
" LC_FUNCTION_STARTS\n");
return false;
}
buf[fc.datasize] = 0; // null-terminated buffer
bin->func_start = buf;
return true;
}
static int parse_dylib(struct MACH0_(obj_t)* bin, ut64 off) {
struct dylib_command dl;
int lib, len;
ut8 sdl[sizeof (struct dylib_command)] = {0};
if (off > bin->size || off + sizeof (struct dylib_command) > bin->size)
return false;
lib = bin->nlibs - 1;
if (!(bin->libs = realloc (bin->libs, bin->nlibs * R_BIN_MACH0_STRING_LENGTH))) {
perror ("realloc (libs)");
return false;
}
len = r_buf_read_at (bin->b, off, sdl, sizeof (struct dylib_command));
if (len < 1) {
bprintf ("Error: read (dylib)\n");
return false;
}
dl.cmd = r_read_ble32 (&sdl[0], bin->big_endian);
dl.cmdsize = r_read_ble32 (&sdl[4], bin->big_endian);
dl.dylib.name = r_read_ble32 (&sdl[8], bin->big_endian);
dl.dylib.timestamp = r_read_ble32 (&sdl[12], bin->big_endian);
dl.dylib.current_version = r_read_ble32 (&sdl[16], bin->big_endian);
dl.dylib.compatibility_version = r_read_ble32 (&sdl[20], bin->big_endian);
if (off + dl.dylib.name > bin->size ||\
off + dl.dylib.name + R_BIN_MACH0_STRING_LENGTH > bin->size)
return false;
len = r_buf_read_at (bin->b, off+dl.dylib.name, (ut8*)bin->libs[lib], R_BIN_MACH0_STRING_LENGTH);
if (len < 1) {
bprintf ("Error: read (dylib str)");
return false;
}
return true;
}
static const char *cmd_to_string(ut32 cmd) {
switch (cmd) {
case LC_DATA_IN_CODE:
return "LC_DATA_IN_CODE";
case LC_CODE_SIGNATURE:
return "LC_CODE_SIGNATURE";
case LC_RPATH:
return "LC_RPATH";
case LC_SEGMENT:
return "LC_SEGMENT";
case LC_SEGMENT_64:
return "LC_SEGMENT_64";
case LC_SYMTAB:
return "LC_SYMTAB";
case LC_SYMSEG:
return "LC_SYMSEG";
case LC_ID_DYLIB:
return "LC_ID_DYLIB";
case LC_DYSYMTAB:
return "LC_DYSYMTAB";
case LC_FUNCTION_STARTS:
return "LC_FUNCTION_STARTS";
case LC_DYLIB_CODE_SIGN_DRS:
return "LC_DYLIB_CODE_SIGN_DRS";
case LC_VERSION_MIN_MACOSX:
return "LC_VERSION_MIN_MACOSX";
case LC_VERSION_MIN_IPHONEOS:
return "LC_VERSION_MIN_IPHONEOS";
case LC_VERSION_MIN_TVOS:
return "LC_VERSION_MIN_TVOS";
case LC_VERSION_MIN_WATCHOS:
return "LC_VERSION_MIN_WATCHOS";
case LC_DYLD_INFO:
return "LC_DYLD_INFO";
case LC_SOURCE_VERSION:
return "LC_SOURCE_VERSION";
case LC_MAIN:
return "LC_MAIN";
case LC_UUID:
return "LC_UUID";
case LC_ENCRYPTION_INFO_64:
return "LC_ENCRYPTION_INFO_64";
case LC_ENCRYPTION_INFO:
return "LC_ENCRYPTION_INFO";
case LC_LOAD_DYLINKER:
return "LC_LOAD_DYLINKER";
case LC_LOAD_DYLIB:
return "LC_LOAD_DYLIB";
case LC_THREAD:
return "LC_THREAD";
case LC_UNIXTHREAD:
return "LC_UNIXTHREAD";
case LC_IDENT:
return "LC_IDENT";
case LC_DYLD_INFO_ONLY:
return "LC_DYLD_INFO_ONLY";
}
return "";
}
static int init_items(struct MACH0_(obj_t)* bin) {
struct load_command lc = {0, 0};
ut8 loadc[sizeof (struct load_command)] = {0};
bool is_first_thread = true;
ut64 off = 0LL;
int i, len;
bin->uuidn = 0;
bin->os = 0;
bin->has_crypto = 0;
if (bin->hdr.sizeofcmds > bin->size) {
bprintf ("Warning: chopping hdr.sizeofcmds\n");
bin->hdr.sizeofcmds = bin->size - 128;
//return false;
}
//bprintf ("Commands: %d\n", bin->hdr.ncmds);
for (i = 0, off = sizeof (struct MACH0_(mach_header)); \
i < bin->hdr.ncmds; i++, off += lc.cmdsize) {
if (off > bin->size || off + sizeof (struct load_command) > bin->size){
bprintf ("mach0: out of bounds command\n");
return false;
}
len = r_buf_read_at (bin->b, off, loadc, sizeof (struct load_command));
if (len < 1) {
bprintf ("Error: read (lc) at 0x%08"PFMT64x"\n", off);
return false;
}
lc.cmd = r_read_ble32 (&loadc[0], bin->big_endian);
lc.cmdsize = r_read_ble32 (&loadc[4], bin->big_endian);
if (lc.cmdsize < 1 || off + lc.cmdsize > bin->size) {
bprintf ("Warning: mach0_header %d = cmdsize<1. (0x%llx vs 0x%llx)\n", i,
(ut64)(off + lc.cmdsize), (ut64)(bin->size));
break;
}
// TODO: a different format for each cmd
sdb_num_set (bin->kv, sdb_fmt ("mach0_cmd_%d.offset", i), off, 0);
sdb_set (bin->kv, sdb_fmt ("mach0_cmd_%d.format", i), "xd cmd size", 0);
//bprintf ("%d\n", lc.cmd);
switch (lc.cmd) {
case LC_DATA_IN_CODE:
sdb_set (bin->kv, sdb_fmt ("mach0_cmd_%d.cmd", i), "data_in_code", 0);
// TODO table of non-instructions in __text
break;
case LC_RPATH:
sdb_set (bin->kv, sdb_fmt ("mach0_cmd_%d.cmd", i), "rpath", 0);
//bprintf ("--->\n");
break;
case LC_SEGMENT_64:
case LC_SEGMENT:
sdb_set (bin->kv, sdb_fmt ("mach0_cmd_%d.cmd", i), "segment", 0);
bin->nsegs++;
if (!parse_segments (bin, off)) {
bprintf ("error parsing segment\n");
bin->nsegs--;
return false;
}
break;
case LC_SYMTAB:
sdb_set (bin->kv, sdb_fmt ("mach0_cmd_%d.cmd", i), "symtab", 0);
if (!parse_symtab (bin, off)) {
bprintf ("error parsing symtab\n");
return false;
}
break;
case LC_DYSYMTAB:
sdb_set (bin->kv, sdb_fmt ("mach0_cmd_%d.cmd", i), "dysymtab", 0);
if (!parse_dysymtab(bin, off)) {
bprintf ("error parsing dysymtab\n");
return false;
}
break;
case LC_DYLIB_CODE_SIGN_DRS:
sdb_set (bin->kv, sdb_fmt ("mach0_cmd_%d.cmd", i), "dylib_code_sign_drs", 0);
//bprintf ("[mach0] code is signed\n");
break;
case LC_VERSION_MIN_MACOSX:
sdb_set (bin->kv, sdb_fmt ("mach0_cmd_%d.cmd", i), "version_min_macosx", 0);
bin->os = 1;
// set OS = osx
//bprintf ("[mach0] Requires OSX >= x\n");
break;
case LC_VERSION_MIN_IPHONEOS:
sdb_set (bin->kv, sdb_fmt ("mach0_cmd_%d.cmd", i), "version_min_iphoneos", 0);
bin->os = 2;
// set OS = ios
//bprintf ("[mach0] Requires iOS >= x\n");
break;
case LC_VERSION_MIN_TVOS:
sdb_set (bin->kv, sdb_fmt ("mach0_cmd_%d.cmd", i), "version_min_tvos", 0);
bin->os = 4;
break;
case LC_VERSION_MIN_WATCHOS:
sdb_set (bin->kv, sdb_fmt ("mach0_cmd_%d.cmd", i), "version_min_watchos", 0);
bin->os = 3;
break;
case LC_UUID:
sdb_set (bin->kv, sdb_fmt ("mach0_cmd_%d.cmd", i), "uuid", 0);
{
struct uuid_command uc = {0};
if (off + sizeof (struct uuid_command) > bin->size) {
bprintf ("UUID out of obunds\n");
return false;
}
if (r_buf_fread_at (bin->b, off, (ut8*)&uc, "24c", 1) != -1) {
char key[128];
char val[128];
snprintf (key, sizeof (key)-1, "uuid.%d", bin->uuidn++);
r_hex_bin2str ((ut8*)&uc.uuid, 16, val);
sdb_set (bin->kv, key, val, 0);
//for (i=0;i<16; i++) bprintf ("%02x%c", uc.uuid[i], (i==15)?'\n':'-');
}
}
break;
case LC_ENCRYPTION_INFO_64:
/* TODO: the struct is probably different here */
case LC_ENCRYPTION_INFO:
sdb_set (bin->kv, sdb_fmt ("mach0_cmd_%d.cmd", i), "encryption_info", 0);
{
struct MACH0_(encryption_info_command) eic = {0};
ut8 seic[sizeof (struct MACH0_(encryption_info_command))] = {0};
if (off + sizeof (struct MACH0_(encryption_info_command)) > bin->size) {
bprintf ("encryption info out of bounds\n");
return false;
}
if (r_buf_read_at (bin->b, off, seic, sizeof (struct MACH0_(encryption_info_command))) != -1) {
eic.cmd = r_read_ble32 (&seic[0], bin->big_endian);
eic.cmdsize = r_read_ble32 (&seic[4], bin->big_endian);
eic.cryptoff = r_read_ble32 (&seic[8], bin->big_endian);
eic.cryptsize = r_read_ble32 (&seic[12], bin->big_endian);
eic.cryptid = r_read_ble32 (&seic[16], bin->big_endian);
bin->has_crypto = eic.cryptid;
sdb_set (bin->kv, "crypto", "true", 0);
sdb_num_set (bin->kv, "cryptid", eic.cryptid, 0);
sdb_num_set (bin->kv, "cryptoff", eic.cryptoff, 0);
sdb_num_set (bin->kv, "cryptsize", eic.cryptsize, 0);
sdb_num_set (bin->kv, "cryptheader", off, 0);
} }
break;
case LC_LOAD_DYLINKER:
{
sdb_set (bin->kv, sdb_fmt ("mach0_cmd_%d.cmd", i), "dylinker", 0);
free (bin->intrp);
bin->intrp = NULL;
//bprintf ("[mach0] load dynamic linker\n");
struct dylinker_command dy = {0};
ut8 sdy[sizeof (struct dylinker_command)] = {0};
if (off + sizeof (struct dylinker_command) > bin->size){
bprintf ("Warning: Cannot parse dylinker command\n");
return false;
}
if (r_buf_read_at (bin->b, off, sdy, sizeof (struct dylinker_command)) == -1) {
bprintf ("Warning: read (LC_DYLD_INFO) at 0x%08"PFMT64x"\n", off);
} else {
dy.cmd = r_read_ble32 (&sdy[0], bin->big_endian);
dy.cmdsize = r_read_ble32 (&sdy[4], bin->big_endian);
dy.name = r_read_ble32 (&sdy[8], bin->big_endian);
int len = dy.cmdsize;
char *buf = malloc (len+1);
if (buf) {
// wtf @ off + 0xc ?
r_buf_read_at (bin->b, off + 0xc, (ut8*)buf, len);
buf[len] = 0;
free (bin->intrp);
bin->intrp = buf;
}
}
}
break;
case LC_MAIN:
{
struct {
ut64 eo;
ut64 ss;
} ep = {0};
ut8 sep[2 * sizeof (ut64)] = {0};
sdb_set (bin->kv, sdb_fmt ("mach0_cmd_%d.cmd", i), "main", 0);
if (!is_first_thread) {
bprintf("Error: LC_MAIN with other threads\n");
return false;
}
if (off + 8 > bin->size || off + sizeof (ep) > bin->size) {
bprintf ("invalid command size for main\n");
return false;
}
r_buf_read_at (bin->b, off + 8, sep, 2 * sizeof (ut64));
ep.eo = r_read_ble64 (&sep[0], bin->big_endian);
ep.ss = r_read_ble64 (&sep[8], bin->big_endian);
bin->entry = ep.eo;
bin->main_cmd = lc;
sdb_num_set (bin->kv, "mach0.entry.offset", off + 8, 0);
sdb_num_set (bin->kv, "stacksize", ep.ss, 0);
is_first_thread = false;
}
break;
case LC_UNIXTHREAD:
sdb_set (bin->kv, sdb_fmt ("mach0_cmd_%d.cmd", i), "unixthread", 0);
if (!is_first_thread) {
bprintf("Error: LC_UNIXTHREAD with other threads\n");
return false;
}
case LC_THREAD:
sdb_set (bin->kv, sdb_fmt ("mach0_cmd_%d.cmd", i), "thread", 0);
if (!parse_thread (bin, &lc, off, is_first_thread)) {
bprintf ("Cannot parse thread\n");
return false;
}
is_first_thread = false;
break;
case LC_LOAD_DYLIB:
case LC_LOAD_WEAK_DYLIB:
sdb_set (bin->kv, sdb_fmt ("mach0_cmd_%d.cmd", i), "load_dylib", 0);
bin->nlibs++;
if (!parse_dylib (bin, off)){
bprintf ("Cannot parse dylib\n");
bin->nlibs--;
return false;
}
break;
case LC_DYLD_INFO:
case LC_DYLD_INFO_ONLY:
{
ut8 dyldi[sizeof (struct dyld_info_command)] = {0};
sdb_set (bin->kv, sdb_fmt ("mach0_cmd_%d.cmd", i), "dyld_info", 0);
bin->dyld_info = calloc (1, sizeof (struct dyld_info_command));
if (bin->dyld_info) {
if (off + sizeof (struct dyld_info_command) > bin->size){
bprintf ("Cannot parse dyldinfo\n");
R_FREE (bin->dyld_info);
return false;
}
if (r_buf_read_at (bin->b, off, dyldi, sizeof (struct dyld_info_command)) == -1) {
free (bin->dyld_info);
bin->dyld_info = NULL;
bprintf ("Error: read (LC_DYLD_INFO) at 0x%08"PFMT64x"\n", off);
} else {
bin->dyld_info->cmd = r_read_ble32 (&dyldi[0], bin->big_endian);
bin->dyld_info->cmdsize = r_read_ble32 (&dyldi[4], bin->big_endian);
bin->dyld_info->rebase_off = r_read_ble32 (&dyldi[8], bin->big_endian);
bin->dyld_info->rebase_size = r_read_ble32 (&dyldi[12], bin->big_endian);
bin->dyld_info->bind_off = r_read_ble32 (&dyldi[16], bin->big_endian);
bin->dyld_info->bind_size = r_read_ble32 (&dyldi[20], bin->big_endian);
bin->dyld_info->weak_bind_off = r_read_ble32 (&dyldi[24], bin->big_endian);
bin->dyld_info->weak_bind_size = r_read_ble32 (&dyldi[28], bin->big_endian);
bin->dyld_info->lazy_bind_off = r_read_ble32 (&dyldi[32], bin->big_endian);
bin->dyld_info->lazy_bind_size = r_read_ble32 (&dyldi[36], bin->big_endian);
bin->dyld_info->export_off = r_read_ble32 (&dyldi[40], bin->big_endian);
bin->dyld_info->export_size = r_read_ble32 (&dyldi[44], bin->big_endian);
}
}
}
break;
case LC_CODE_SIGNATURE:
parse_signature (bin, off);
sdb_set (bin->kv, sdb_fmt ("mach0_cmd_%d.cmd", i), "signature", 0);
/* ut32 dataoff
// ut32 datasize */
break;
case LC_SOURCE_VERSION:
sdb_set (bin->kv, sdb_fmt ("mach0_cmd_%d.cmd", i), "version", 0);
/* uint64_t version; */
/* A.B.C.D.E packed as a24.b10.c10.d10.e10 */
//bprintf ("mach0: TODO: Show source version\n");
break;
case LC_SEGMENT_SPLIT_INFO:
sdb_set (bin->kv, sdb_fmt ("mach0_cmd_%d.cmd", i), "split_info", 0);
/* TODO */
break;
case LC_FUNCTION_STARTS:
sdb_set (bin->kv, sdb_fmt ("mach0_cmd_%d.cmd", i), "function_starts", 0);
if (!parse_function_starts (bin, off)) {
bprintf ("Cannot parse LC_FUNCTION_STARTS\n");
}
break;
case LC_REEXPORT_DYLIB:
sdb_set (bin->kv, sdb_fmt ("mach0_cmd_%d.cmd", i), "dylib", 0);
/* TODO */
break;
default:
//bprintf ("mach0: Unknown header command %x\n", lc.cmd);
break;
}
}
return true;
}
static int init(struct MACH0_(obj_t)* bin) {
union {
ut16 word;
ut8 byte[2];
} endian = { 1 };
little_ = endian.byte[0];
if (!init_hdr (bin)) {
bprintf ("Warning: File is not MACH0\n");
return false;
}
if (!init_items (bin)) {
bprintf ("Warning: Cannot initialize items\n");
}
bin->baddr = MACH0_(get_baddr)(bin);
return true;
}
void* MACH0_(mach0_free)(struct MACH0_(obj_t)* bin) {
if (!bin) {
return NULL;
}
free (bin->segs);
free (bin->sects);
free (bin->symtab);
free (bin->symstr);
free (bin->indirectsyms);
free (bin->imports_by_ord);
free (bin->dyld_info);
free (bin->toc);
free (bin->modtab);
free (bin->libs);
free (bin->func_start);
free (bin->signature);
r_buf_free (bin->b);
free (bin);
return NULL;
}
struct MACH0_(obj_t)* MACH0_(mach0_new)(const char* file, bool verbose) {
ut8 *buf;
struct MACH0_(obj_t) *bin;
if (!(bin = malloc (sizeof (struct MACH0_(obj_t))))) {
return NULL;
}
memset (bin, 0, sizeof (struct MACH0_(obj_t)));
bin->verbose = verbose;
bin->file = file;
if (!(buf = (ut8*)r_file_slurp (file, &bin->size))) {
return MACH0_(mach0_free)(bin);
}
bin->b = r_buf_new ();
if (!r_buf_set_bytes (bin->b, buf, bin->size)) {
free (buf);
return MACH0_(mach0_free)(bin);
}
free (buf);
bin->dyld_info = NULL;
if (!init (bin)) {
return MACH0_(mach0_free)(bin);
}
bin->imports_by_ord_size = 0;
bin->imports_by_ord = NULL;
return bin;
}
struct MACH0_(obj_t)* MACH0_(new_buf)(RBuffer *buf, bool verbose) {
if (!buf) {
return NULL;
}
RBuffer * buf_copy = r_buf_new_with_buf (buf);
if (!buf_copy) {
return NULL;
}
return MACH0_(new_buf_steal) (buf_copy, verbose);
}
struct MACH0_(obj_t)* MACH0_(new_buf_steal)(RBuffer *buf, bool verbose) {
struct MACH0_(obj_t) *bin = R_NEW0 (struct MACH0_(obj_t));
if (!bin) {
return NULL;
}
bin->kv = sdb_new (NULL, "bin.mach0", 0);
bin->size = r_buf_size (buf);
bin->verbose = verbose;
bin->b = buf;
if (!init (bin)) {
return MACH0_(mach0_free)(bin);
}
return bin;
}
// prot: r = 1, w = 2, x = 4
// perm: r = 4, w = 2, x = 1
static int prot2perm (int x) {
int r = 0;
if (x&1) r |= 4;
if (x&2) r |= 2;
if (x&4) r |= 1;
return r;
}
struct section_t* MACH0_(get_sections)(struct MACH0_(obj_t)* bin) {
struct section_t *sections;
char segname[32], sectname[32];
int i, j, to;
if (!bin) {
return NULL;
}
/* for core files */
if (bin->nsects < 1 && bin->nsegs > 0) {
struct MACH0_(segment_command) *seg;
if (!(sections = calloc ((bin->nsegs + 1), sizeof (struct section_t)))) {
return NULL;
}
for (i = 0; i < bin->nsegs; i++) {
seg = &bin->segs[i];
sections[i].addr = seg->vmaddr;
sections[i].offset = seg->fileoff;
sections[i].size = seg->vmsize;
sections[i].vsize = seg->vmsize;
sections[i].align = 4096;
sections[i].flags = seg->flags;
r_str_ncpy (sectname, seg->segname, sizeof (sectname));
r_str_filter (sectname, -1);
// hack to support multiple sections with same name
sections[i].srwx = prot2perm (seg->initprot);
sections[i].last = 0;
}
sections[i].last = 1;
return sections;
}
if (!bin->sects) {
return NULL;
}
to = R_MIN (bin->nsects, 128); // limit number of sections here to avoid fuzzed bins
if (to < 1) {
return NULL;
}
if (!(sections = calloc (bin->nsects + 1, sizeof (struct section_t)))) {
return NULL;
}
for (i = 0; i < to; i++) {
sections[i].offset = (ut64)bin->sects[i].offset;
sections[i].addr = (ut64)bin->sects[i].addr;
sections[i].size = (bin->sects[i].flags == S_ZEROFILL) ? 0 : (ut64)bin->sects[i].size;
sections[i].vsize = (ut64)bin->sects[i].size;
sections[i].align = bin->sects[i].align;
sections[i].flags = bin->sects[i].flags;
r_str_ncpy (sectname, bin->sects[i].sectname, sizeof (sectname));
r_str_filter (sectname, -1);
// hack to support multiple sections with same name
// snprintf (segname, sizeof (segname), "%d", i); // wtf
snprintf (segname, sizeof (segname), "%d.%s", i, bin->sects[i].segname);
for (j = 0; j < bin->nsegs; j++) {
if (sections[i].addr >= bin->segs[j].vmaddr &&
sections[i].addr < (bin->segs[j].vmaddr + bin->segs[j].vmsize)) {
sections[i].srwx = prot2perm (bin->segs[j].initprot);
break;
}
}
// XXX: if two sections have the same name are merged :O
// XXX: append section index in flag name maybe?
// XXX: do not load out of bound sections?
// XXX: load segments instead of sections? what about PAGEZERO and ...
snprintf (sections[i].name, sizeof (sections[i].name), "%s.%s", segname, sectname);
sections[i].last = 0;
}
sections[i].last = 1;
return sections;
}
static int parse_import_stub(struct MACH0_(obj_t)* bin, struct symbol_t *symbol, int idx) {
int i, j, nsyms, stridx;
const char *symstr;
if (idx < 0) {
return 0;
}
symbol->offset = 0LL;
symbol->addr = 0LL;
symbol->name[0] = '\0';
if (!bin || !bin->sects) {
return false;
}
for (i = 0; i < bin->nsects; i++) {
if ((bin->sects[i].flags & SECTION_TYPE) == S_SYMBOL_STUBS && bin->sects[i].reserved2 > 0) {
nsyms = (int)(bin->sects[i].size / bin->sects[i].reserved2);
if (nsyms > bin->size) {
bprintf ("mach0: Invalid symbol table size\n");
}
for (j = 0; j < nsyms; j++) {
if (bin->sects) {
if (bin->sects[i].reserved1 + j >= bin->nindirectsyms) {
continue;
}
}
if (bin->indirectsyms) {
if (idx != bin->indirectsyms[bin->sects[i].reserved1 + j]) {
continue;
}
}
if (idx > bin->nsymtab) {
continue;
}
symbol->type = R_BIN_MACH0_SYMBOL_TYPE_LOCAL;
symbol->offset = bin->sects[i].offset + j * bin->sects[i].reserved2;
symbol->addr = bin->sects[i].addr + j * bin->sects[i].reserved2;
symbol->size = 0;
stridx = bin->symtab[idx].n_strx;
if (stridx >= 0 && stridx < bin->symstrlen) {
symstr = (char *)bin->symstr + stridx;
} else {
symstr = "???";
}
// Remove the extra underscore that every import seems to have in Mach-O.
if (*symstr == '_') {
symstr++;
}
snprintf (symbol->name, R_BIN_MACH0_STRING_LENGTH, "imp.%s", symstr);
return true;
}
}
}
return false;
}
#if 0
static ut64 get_text_base(struct MACH0_(obj_t)* bin) {
ut64 ret = 0LL;
struct section_t *sections;
if ((sections = MACH0_(get_sections) (bin))) {
int i;
for (i = 0; !sections[i].last; i++) {
if (strstr(sections[i].name, "text")) {
ret = sections[i].offset;
break;
}
}
free (sections);
}
return ret;
}
#endif
static int inSymtab(SdbHash *hash, struct symbol_t *symbols, const char *name, ut64 addr) {
bool found;
const char *key = sdb_fmt ("%s.%"PFMT64x, name, addr);
(void)sdb_ht_find (hash, key, &found);
if (found) {
return true;
}
sdb_ht_insert (hash, key, "1");
return false;
}
struct symbol_t* MACH0_(get_symbols)(struct MACH0_(obj_t)* bin) {
const char *symstr;
struct symbol_t *symbols;
int from, to, i, j, s, stridx, symbols_size, symbols_count;
SdbHash *hash;
//ut64 text_base = get_text_base (bin);
if (!bin || !bin->symtab || !bin->symstr) {
return NULL;
}
/* parse symbol table */
/* parse dynamic symbol table */
symbols_count = (bin->dysymtab.nextdefsym + \
bin->dysymtab.nlocalsym + \
bin->dysymtab.nundefsym );
symbols_count += bin->nsymtab;
//symbols_count = bin->nsymtab;
symbols_size = (symbols_count + 1) * 2 * sizeof (struct symbol_t);
if (symbols_size < 1) {
return NULL;
}
if (!(symbols = calloc (1, symbols_size))) {
return NULL;
}
hash = sdb_ht_new ();
j = 0; // symbol_idx
for (s = 0; s < 2; s++) {
switch (s) {
case 0:
from = bin->dysymtab.iextdefsym;
to = from + bin->dysymtab.nextdefsym;
break;
case 1:
from = bin->dysymtab.ilocalsym;
to = from + bin->dysymtab.nlocalsym;
break;
#if NOT_USED
case 2:
from = bin->dysymtab.iundefsym;
to = from + bin->dysymtab.nundefsym;
break;
#endif
}
if (from == to) {
continue;
}
#define OLD 1
#if OLD
from = R_MIN (R_MAX (0, from), symbols_size / sizeof (struct symbol_t));
to = R_MIN (to , symbols_size / sizeof (struct symbol_t));
to = R_MIN (to, bin->nsymtab);
#else
from = R_MIN (R_MAX (0, from), symbols_size/sizeof (struct symbol_t));
to = symbols_count; //symbols_size/sizeof(struct symbol_t);
#endif
int maxsymbols = symbols_size / sizeof (struct symbol_t);
if (to > 0x500000) {
bprintf ("WARNING: corrupted mach0 header: symbol table is too big %d\n", to);
free (symbols);
sdb_ht_free (hash);
return NULL;
}
if (symbols_count >= maxsymbols) {
symbols_count = maxsymbols - 1;
}
for (i = from; i < to && j < symbols_count; i++, j++) {
symbols[j].offset = addr_to_offset (bin, bin->symtab[i].n_value);
symbols[j].addr = bin->symtab[i].n_value;
symbols[j].size = 0; /* TODO: Is it anywhere? */
if (bin->symtab[i].n_type & N_EXT) {
symbols[j].type = R_BIN_MACH0_SYMBOL_TYPE_EXT;
} else {
symbols[j].type = R_BIN_MACH0_SYMBOL_TYPE_LOCAL;
}
stridx = bin->symtab[i].n_strx;
if (stridx >= 0 && stridx < bin->symstrlen) {
symstr = (char*)bin->symstr + stridx;
} else {
symstr = "???";
}
{
int i = 0;
int len = 0;
len = bin->symstrlen - stridx;
if (len > 0) {
for (i = 0; i < len; i++) {
if ((ut8)(symstr[i] & 0xff) == 0xff || !symstr[i]) {
len = i;
break;
}
}
char *symstr_dup = NULL;
if (len > 0) {
symstr_dup = r_str_ndup (symstr, len);
}
if (!symstr_dup) {
symbols[j].name[0] = 0;
} else {
r_str_ncpy (symbols[j].name, symstr_dup, R_BIN_MACH0_STRING_LENGTH);
r_str_filter (symbols[j].name, -1);
symbols[j].name[R_BIN_MACH0_STRING_LENGTH - 2] = 0;
}
free (symstr_dup);
} else {
symbols[j].name[0] = 0;
}
symbols[j].last = 0;
}
if (inSymtab (hash, symbols, symbols[j].name, symbols[j].addr)) {
symbols[j].name[0] = 0;
j--;
}
}
}
to = R_MIN (bin->nsymtab, bin->dysymtab.iundefsym + bin->dysymtab.nundefsym);
for (i = bin->dysymtab.iundefsym; i < to; i++) {
if (j > symbols_count) {
bprintf ("mach0-get-symbols: error\n");
break;
}
if (parse_import_stub(bin, &symbols[j], i))
symbols[j++].last = 0;
}
#if 1
// symtab is wrongly parsed and produces dupped syms with incorrect vaddr */
for (i = 0; i < bin->nsymtab; i++) {
struct MACH0_(nlist) *st = &bin->symtab[i];
#if 0
bprintf ("stridx %d -> section %d type %d value = %d\n",
st->n_strx, st->n_sect, st->n_type, st->n_value);
#endif
stridx = st->n_strx;
if (stridx >= 0 && stridx < bin->symstrlen) {
symstr = (char*)bin->symstr + stridx;
} else {
symstr = "???";
}
// 0 is for imports
// 1 is for symbols
// 2 is for func.eh (exception handlers?)
int section = st->n_sect;
if (section == 1 && j < symbols_count) { // text ??st->n_type == 1)
/* is symbol */
symbols[j].addr = st->n_value; // + text_base;
symbols[j].offset = addr_to_offset (bin, symbols[j].addr);
symbols[j].size = 0; /* find next symbol and crop */
if (st->n_type & N_EXT) {
symbols[j].type = R_BIN_MACH0_SYMBOL_TYPE_EXT;
} else {
symbols[j].type = R_BIN_MACH0_SYMBOL_TYPE_LOCAL;
}
strncpy (symbols[j].name, symstr, R_BIN_MACH0_STRING_LENGTH);
symbols[j].name[R_BIN_MACH0_STRING_LENGTH - 1] = 0;
symbols[j].last = 0;
if (inSymtab (hash, symbols, symbols[j].name, symbols[j].addr)) {
symbols[j].name[0] = 0;
} else {
j++;
}
}
}
#endif
sdb_ht_free (hash);
symbols[j].last = 1;
return symbols;
}
static int parse_import_ptr(struct MACH0_(obj_t)* bin, struct reloc_t *reloc, int idx) {
int i, j, sym, wordsize;
ut32 stype;
wordsize = MACH0_(get_bits)(bin) / 8;
if (idx < 0 || idx >= bin->nsymtab) {
return 0;
}
if ((bin->symtab[idx].n_desc & REFERENCE_TYPE) == REFERENCE_FLAG_UNDEFINED_LAZY) {
stype = S_LAZY_SYMBOL_POINTERS;
} else {
stype = S_NON_LAZY_SYMBOL_POINTERS;
}
reloc->offset = 0;
reloc->addr = 0;
reloc->addend = 0;
#define CASE(T) case (T / 8): reloc->type = R_BIN_RELOC_ ## T; break
switch (wordsize) {
CASE(8);
CASE(16);
CASE(32);
CASE(64);
default: return false;
}
#undef CASE
for (i = 0; i < bin->nsects; i++) {
if ((bin->sects[i].flags & SECTION_TYPE) == stype) {
for (j=0, sym=-1; bin->sects[i].reserved1+j < bin->nindirectsyms; j++)
if (idx == bin->indirectsyms[bin->sects[i].reserved1 + j]) {
sym = j;
break;
}
reloc->offset = sym == -1 ? 0 : bin->sects[i].offset + sym * wordsize;
reloc->addr = sym == -1 ? 0 : bin->sects[i].addr + sym * wordsize;
return true;
}
}
return false;
}
struct import_t* MACH0_(get_imports)(struct MACH0_(obj_t)* bin) {
struct import_t *imports;
int i, j, idx, stridx;
const char *symstr;
if (!bin->symtab || !bin->symstr || !bin->sects || !bin->indirectsyms)
return NULL;
if (bin->dysymtab.nundefsym < 1 || bin->dysymtab.nundefsym > 0xfffff) {
return NULL;
}
if (!(imports = malloc ((bin->dysymtab.nundefsym + 1) * sizeof (struct import_t)))) {
return NULL;
}
for (i = j = 0; i < bin->dysymtab.nundefsym; i++) {
idx = bin->dysymtab.iundefsym + i;
if (idx < 0 || idx >= bin->nsymtab) {
bprintf ("WARNING: Imports index out of bounds. Ignoring relocs\n");
free (imports);
return NULL;
}
stridx = bin->symtab[idx].n_strx;
if (stridx >= 0 && stridx < bin->symstrlen) {
symstr = (char *)bin->symstr + stridx;
} else {
symstr = "";
}
if (!*symstr) {
continue;
}
{
int i = 0;
int len = 0;
char *symstr_dup = NULL;
len = bin->symstrlen - stridx;
imports[j].name[0] = 0;
if (len > 0) {
for (i = 0; i < len; i++) {
if ((unsigned char)symstr[i] == 0xff || !symstr[i]) {
len = i;
break;
}
}
symstr_dup = r_str_ndup (symstr, len);
if (symstr_dup) {
r_str_ncpy (imports[j].name, symstr_dup, R_BIN_MACH0_STRING_LENGTH);
r_str_filter (imports[j].name, - 1);
imports[j].name[R_BIN_MACH0_STRING_LENGTH - 2] = 0;
free (symstr_dup);
}
}
}
imports[j].ord = i;
imports[j++].last = 0;
}
imports[j].last = 1;
if (!bin->imports_by_ord_size) {
if (j > 0) {
bin->imports_by_ord_size = j;
bin->imports_by_ord = (RBinImport**)calloc (j, sizeof (RBinImport*));
} else {
bin->imports_by_ord_size = 0;
bin->imports_by_ord = NULL;
}
}
return imports;
}
struct reloc_t* MACH0_(get_relocs)(struct MACH0_(obj_t)* bin) {
struct reloc_t *relocs;
int i = 0, len;
ulebr ur = {NULL};
int wordsize = MACH0_(get_bits)(bin) / 8;
if (bin->dyld_info) {
ut8 *opcodes,*end, type = 0, rel_type = 0;
int lib_ord, seg_idx = -1, sym_ord = -1;
size_t j, count, skip, bind_size, lazy_size;
st64 addend = 0;
ut64 segmentAddress = 0LL;
ut64 addr = 0LL;
ut8 done = 0;
#define CASE(T) case (T / 8): rel_type = R_BIN_RELOC_ ## T; break
switch (wordsize) {
CASE(8);
CASE(16);
CASE(32);
CASE(64);
default: return NULL;
}
#undef CASE
bind_size = bin->dyld_info->bind_size;
lazy_size = bin->dyld_info->lazy_bind_size;
if (!bind_size || !lazy_size) {
return NULL;
}
if ((bind_size + lazy_size)<1) {
return NULL;
}
if (bin->dyld_info->bind_off > bin->size || bin->dyld_info->bind_off + bind_size > bin->size) {
return NULL;
}
if (bin->dyld_info->lazy_bind_off > bin->size || \
bin->dyld_info->lazy_bind_off + lazy_size > bin->size) {
return NULL;
}
if (bin->dyld_info->bind_off+bind_size+lazy_size > bin->size) {
return NULL;
}
// NOTE(eddyb) it's a waste of memory, but we don't know the actual number of relocs.
if (!(relocs = calloc (1, (1 + bind_size + lazy_size) * sizeof (struct reloc_t)))) {
return NULL;
}
opcodes = calloc (1, bind_size + lazy_size + 1);
if (!opcodes) {
free (relocs);
return NULL;
}
len = r_buf_read_at (bin->b, bin->dyld_info->bind_off, opcodes, bind_size);
i = r_buf_read_at (bin->b, bin->dyld_info->lazy_bind_off, opcodes + bind_size, lazy_size);
if (len < 1 || i < 1) {
bprintf ("Error: read (dyld_info bind) at 0x%08"PFMT64x"\n",
(ut64)(size_t)bin->dyld_info->bind_off);
free (opcodes);
relocs[i].last = 1;
return relocs;
}
i = 0;
// that +2 is a minimum required for uleb128, this may be wrong,
// the correct fix would be to make ULEB() must use rutil's
// implementation that already checks for buffer boundaries
for (ur.p = opcodes, end = opcodes + bind_size + lazy_size ; (ur.p+2 < end) && !done; ) {
ut8 imm = *ur.p & BIND_IMMEDIATE_MASK, op = *ur.p & BIND_OPCODE_MASK;
++ur.p;
switch (op) {
#define ULEB() read_uleb128 (&ur,end)
#define SLEB() read_sleb128 (&ur,end)
case BIND_OPCODE_DONE:
done = 1;
break;
case BIND_OPCODE_SET_DYLIB_ORDINAL_IMM:
lib_ord = imm;
break;
case BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB:
lib_ord = ULEB();
break;
case BIND_OPCODE_SET_DYLIB_SPECIAL_IMM:
lib_ord = imm? (st8)(BIND_OPCODE_MASK | imm) : 0;
break;
case BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM: {
char *sym_name = (char*)ur.p;
//ut8 sym_flags = imm;
while (*ur.p++ && ur.p<end) {
/* empty loop */
}
sym_ord = -1;
if (bin->symtab && bin->dysymtab.nundefsym < 0xffff)
for (j = 0; j < bin->dysymtab.nundefsym; j++) {
int stridx = 0;
int iundefsym = bin->dysymtab.iundefsym;
if (iundefsym>=0 && iundefsym < bin->nsymtab) {
int sidx = iundefsym +j;
if (sidx<0 || sidx>= bin->nsymtab)
continue;
stridx = bin->symtab[sidx].n_strx;
if (stridx < 0 || stridx >= bin->symstrlen)
continue;
}
if (!strcmp ((char *)bin->symstr + stridx, sym_name)) {
sym_ord = j;
break;
}
}
break;
}
case BIND_OPCODE_SET_TYPE_IMM:
type = imm;
break;
case BIND_OPCODE_SET_ADDEND_SLEB:
addend = SLEB();
break;
case BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB:
seg_idx = imm;
if (seg_idx < 0 || seg_idx >= bin->nsegs) {
bprintf ("Error: BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB"
" has unexistent segment %d\n", seg_idx);
addr = 0LL;
return 0; // early exit to avoid future mayhem
} else {
addr = bin->segs[seg_idx].vmaddr + ULEB();
segmentAddress = bin->segs[seg_idx].vmaddr \
+ bin->segs[seg_idx].vmsize;
}
break;
case BIND_OPCODE_ADD_ADDR_ULEB:
addr += ULEB();
break;
#define DO_BIND() do {\
if (sym_ord < 0 || seg_idx < 0 ) break;\
if (i >= (bind_size + lazy_size)) break;\
relocs[i].addr = addr;\
relocs[i].offset = addr - bin->segs[seg_idx].vmaddr + bin->segs[seg_idx].fileoff;\
if (type == BIND_TYPE_TEXT_PCREL32)\
relocs[i].addend = addend - (bin->baddr + addr);\
else relocs[i].addend = addend;\
/* library ordinal ??? */ \
relocs[i].ord = lib_ord;\
relocs[i].ord = sym_ord;\
relocs[i].type = rel_type;\
relocs[i++].last = 0;\
} while (0)
case BIND_OPCODE_DO_BIND:
if (addr >= segmentAddress) {
bprintf ("Error: Malformed DO bind opcode\n");
goto beach;
}
DO_BIND();
addr += wordsize;
break;
case BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB:
if (addr >= segmentAddress) {
bprintf ("Error: Malformed ADDR ULEB bind opcode\n");
goto beach;
}
DO_BIND();
addr += ULEB() + wordsize;
break;
case BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED:
if (addr >= segmentAddress) {
bprintf ("Error: Malformed IMM SCALED bind opcode\n");
goto beach;
}
DO_BIND();
addr += (ut64)imm * (ut64)wordsize + wordsize;
break;
case BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB:
count = ULEB();
skip = ULEB();
for (j = 0; j < count; j++) {
if (addr >= segmentAddress) {
bprintf ("Error: Malformed ULEB TIMES bind opcode\n");
goto beach;
}
DO_BIND();
addr += skip + wordsize;
}
break;
#undef DO_BIND
#undef ULEB
#undef SLEB
default:
bprintf ("Error: unknown bind opcode 0x%02x in dyld_info\n", *ur.p);
free (opcodes);
relocs[i].last = 1;
return relocs;
}
}
free (opcodes);
} else {
int j;
if (!bin->symtab || !bin->symstr || !bin->sects || !bin->indirectsyms) {
return NULL;
}
if (!(relocs = malloc ((bin->dysymtab.nundefsym + 1) * sizeof (struct reloc_t)))) {
return NULL;
}
for (j = 0; j < bin->dysymtab.nundefsym; j++) {
if (parse_import_ptr (bin, &relocs[i], bin->dysymtab.iundefsym + j)) {
relocs[i].ord = j;
relocs[i++].last = 0;
}
}
}
beach:
relocs[i].last = 1;
return relocs;
}
struct addr_t* MACH0_(get_entrypoint)(struct MACH0_(obj_t)* bin) {
struct addr_t *entry;
int i;
if (!bin->entry && !bin->sects) {
return NULL;
}
if (!(entry = calloc (1, sizeof (struct addr_t)))) {
return NULL;
}
if (bin->entry) {
entry->addr = entry_to_vaddr (bin);
entry->offset = addr_to_offset (bin, entry->addr);
entry->haddr = sdb_num_get (bin->kv, "mach0.entry.offset", 0);
sdb_num_set (bin->kv, "mach0.entry.vaddr", entry->addr, 0);
sdb_num_set (bin->kv, "mach0.entry.paddr", bin->entry, 0);
}
if (!bin->entry || entry->offset == 0) {
// XXX: section name doesnt matters at all.. just check for exec flags
for (i = 0; i < bin->nsects; i++) {
if (!strncmp (bin->sects[i].sectname, "__text", 6)) {
entry->offset = (ut64)bin->sects[i].offset;
sdb_num_set (bin->kv, "mach0.entry", entry->offset, 0);
entry->addr = (ut64)bin->sects[i].addr;
if (!entry->addr) { // workaround for object files
entry->addr = entry->offset;
}
break;
}
}
bin->entry = entry->addr;
}
return entry;
}
void MACH0_(kv_loadlibs)(struct MACH0_(obj_t)* bin) {
int i;
for (i = 0; i < bin->nlibs; i++) {
sdb_set (bin->kv, sdb_fmt ("libs.%d.name", i), bin->libs[i], 0);
}
}
struct lib_t* MACH0_(get_libs)(struct MACH0_(obj_t)* bin) {
struct lib_t *libs;
int i;
if (!bin->nlibs) {
return NULL;
}
if (!(libs = calloc ((bin->nlibs + 1), sizeof (struct lib_t)))) {
return NULL;
}
for (i = 0; i < bin->nlibs; i++) {
sdb_set (bin->kv, sdb_fmt ("libs.%d.name", i), bin->libs[i], 0);
strncpy (libs[i].name, bin->libs[i], R_BIN_MACH0_STRING_LENGTH);
libs[i].name[R_BIN_MACH0_STRING_LENGTH-1] = '\0';
libs[i].last = 0;
}
libs[i].last = 1;
return libs;
}
ut64 MACH0_(get_baddr)(struct MACH0_(obj_t)* bin) {
int i;
if (bin->hdr.filetype != MH_EXECUTE && bin->hdr.filetype != MH_DYLINKER) {
return 0;
}
for (i = 0; i < bin->nsegs; ++i) {
if (bin->segs[i].fileoff == 0 && bin->segs[i].filesize != 0) {
return bin->segs[i].vmaddr;
}
}
return 0;
}
char* MACH0_(get_class)(struct MACH0_(obj_t)* bin) {
#if R_BIN_MACH064
return r_str_new ("MACH064");
#else
return r_str_new ("MACH0");
#endif
}
//XXX we are mixing up bits from cpu and opcodes
//since thumb use 16 bits opcode but run in 32 bits
//cpus so here we should only return 32 or 64
int MACH0_(get_bits)(struct MACH0_(obj_t)* bin) {
if (bin) {
int bits = MACH0_(get_bits_from_hdr) (&bin->hdr);
if (bin->hdr.cputype == CPU_TYPE_ARM && bin->entry & 1) {
return 16;
}
return bits;
}
return 32;
}
int MACH0_(get_bits_from_hdr)(struct MACH0_(mach_header)* hdr) {
if (hdr->magic == MH_MAGIC_64 || hdr->magic == MH_CIGAM_64) {
return 64;
}
if ((hdr->cpusubtype & CPU_SUBTYPE_MASK) == (CPU_SUBTYPE_ARM_V7K << 24)) {
return 16;
}
return 32;
}
bool MACH0_(is_big_endian)(struct MACH0_(obj_t)* bin) {
if (bin) {
const int cpu = bin->hdr.cputype;
return cpu == CPU_TYPE_POWERPC || cpu == CPU_TYPE_POWERPC64;
}
return false;
}
const char* MACH0_(get_intrp)(struct MACH0_(obj_t)* bin) {
return bin? bin->intrp: NULL;
}
const char* MACH0_(get_os)(struct MACH0_(obj_t)* bin) {
if (bin)
switch (bin->os) {
case 1: return "macos";
case 2: return "ios";
case 3: return "watchos";
case 4: return "tvos";
}
return "darwin";
}
const char* MACH0_(get_cputype_from_hdr)(struct MACH0_(mach_header) *hdr) {
const char *archstr = "unknown";
switch (hdr->cputype) {
case CPU_TYPE_VAX:
archstr = "vax";
break;
case CPU_TYPE_MC680x0:
archstr = "mc680x0";
break;
case CPU_TYPE_I386:
case CPU_TYPE_X86_64:
archstr = "x86";
break;
case CPU_TYPE_MC88000:
archstr = "mc88000";
break;
case CPU_TYPE_MC98000:
archstr = "mc98000";
break;
case CPU_TYPE_HPPA:
archstr = "hppa";
break;
case CPU_TYPE_ARM:
case CPU_TYPE_ARM64:
archstr = "arm";
break;
case CPU_TYPE_SPARC:
archstr = "sparc";
break;
case CPU_TYPE_MIPS:
archstr = "mips";
break;
case CPU_TYPE_I860:
archstr = "i860";
break;
case CPU_TYPE_POWERPC:
case CPU_TYPE_POWERPC64:
archstr = "ppc";
}
return archstr;
}
const char* MACH0_(get_cputype)(struct MACH0_(obj_t)* bin) {
return bin? MACH0_(get_cputype_from_hdr) (&bin->hdr): "unknown";
}
// TODO: use const char*
char* MACH0_(get_cpusubtype_from_hdr)(struct MACH0_(mach_header) *hdr) {
if (hdr) {
switch (hdr->cputype) {
case CPU_TYPE_VAX:
switch (hdr->cpusubtype) {
case CPU_SUBTYPE_VAX_ALL: return strdup ("all");
case CPU_SUBTYPE_VAX780: return strdup ("vax780");
case CPU_SUBTYPE_VAX785: return strdup ("vax785");
case CPU_SUBTYPE_VAX750: return strdup ("vax750");
case CPU_SUBTYPE_VAX730: return strdup ("vax730");
case CPU_SUBTYPE_UVAXI: return strdup ("uvaxI");
case CPU_SUBTYPE_UVAXII: return strdup ("uvaxII");
case CPU_SUBTYPE_VAX8200: return strdup ("vax8200");
case CPU_SUBTYPE_VAX8500: return strdup ("vax8500");
case CPU_SUBTYPE_VAX8600: return strdup ("vax8600");
case CPU_SUBTYPE_VAX8650: return strdup ("vax8650");
case CPU_SUBTYPE_VAX8800: return strdup ("vax8800");
case CPU_SUBTYPE_UVAXIII: return strdup ("uvaxIII");
default: return strdup ("Unknown vax subtype");
}
case CPU_TYPE_MC680x0:
switch (hdr->cpusubtype) {
case CPU_SUBTYPE_MC68030: return strdup ("mc68030");
case CPU_SUBTYPE_MC68040: return strdup ("mc68040");
case CPU_SUBTYPE_MC68030_ONLY: return strdup ("mc68030 only");
default: return strdup ("Unknown mc680x0 subtype");
}
case CPU_TYPE_I386:
switch (hdr->cpusubtype) {
case CPU_SUBTYPE_386: return strdup ("386");
case CPU_SUBTYPE_486: return strdup ("486");
case CPU_SUBTYPE_486SX: return strdup ("486sx");
case CPU_SUBTYPE_PENT: return strdup ("Pentium");
case CPU_SUBTYPE_PENTPRO: return strdup ("Pentium Pro");
case CPU_SUBTYPE_PENTII_M3: return strdup ("Pentium 3 M3");
case CPU_SUBTYPE_PENTII_M5: return strdup ("Pentium 3 M5");
case CPU_SUBTYPE_CELERON: return strdup ("Celeron");
case CPU_SUBTYPE_CELERON_MOBILE: return strdup ("Celeron Mobile");
case CPU_SUBTYPE_PENTIUM_3: return strdup ("Pentium 3");
case CPU_SUBTYPE_PENTIUM_3_M: return strdup ("Pentium 3 M");
case CPU_SUBTYPE_PENTIUM_3_XEON: return strdup ("Pentium 3 Xeon");
case CPU_SUBTYPE_PENTIUM_M: return strdup ("Pentium Mobile");
case CPU_SUBTYPE_PENTIUM_4: return strdup ("Pentium 4");
case CPU_SUBTYPE_PENTIUM_4_M: return strdup ("Pentium 4 M");
case CPU_SUBTYPE_ITANIUM: return strdup ("Itanium");
case CPU_SUBTYPE_ITANIUM_2: return strdup ("Itanium 2");
case CPU_SUBTYPE_XEON: return strdup ("Xeon");
case CPU_SUBTYPE_XEON_MP: return strdup ("Xeon MP");
default: return strdup ("Unknown i386 subtype");
}
case CPU_TYPE_X86_64:
switch (hdr->cpusubtype & 0xff) {
case CPU_SUBTYPE_X86_64_ALL: return strdup ("x86 64 all");
case CPU_SUBTYPE_X86_ARCH1: return strdup ("x86 arch 1");
default: return strdup ("Unknown x86 subtype");
}
case CPU_TYPE_MC88000:
switch (hdr->cpusubtype & 0xff) {
case CPU_SUBTYPE_MC88000_ALL: return strdup ("all");
case CPU_SUBTYPE_MC88100: return strdup ("mc88100");
case CPU_SUBTYPE_MC88110: return strdup ("mc88110");
default: return strdup ("Unknown mc88000 subtype");
}
case CPU_TYPE_MC98000:
switch (hdr->cpusubtype & 0xff) {
case CPU_SUBTYPE_MC98000_ALL: return strdup ("all");
case CPU_SUBTYPE_MC98601: return strdup ("mc98601");
default: return strdup ("Unknown mc98000 subtype");
}
case CPU_TYPE_HPPA:
switch (hdr->cpusubtype & 0xff) {
case CPU_SUBTYPE_HPPA_7100: return strdup ("hppa7100");
case CPU_SUBTYPE_HPPA_7100LC: return strdup ("hppa7100LC");
default: return strdup ("Unknown hppa subtype");
}
case CPU_TYPE_ARM64:
return strdup ("v8");
case CPU_TYPE_ARM:
switch (hdr->cpusubtype & 0xff) {
case CPU_SUBTYPE_ARM_ALL:
return strdup ("all");
case CPU_SUBTYPE_ARM_V4T:
return strdup ("v4t");
case CPU_SUBTYPE_ARM_V5:
return strdup ("v5");
case CPU_SUBTYPE_ARM_V6:
return strdup ("v6");
case CPU_SUBTYPE_ARM_XSCALE:
return strdup ("xscale");
case CPU_SUBTYPE_ARM_V7:
return strdup ("v7");
case CPU_SUBTYPE_ARM_V7F:
return strdup ("v7f");
case CPU_SUBTYPE_ARM_V7S:
return strdup ("v7s");
case CPU_SUBTYPE_ARM_V7K:
return strdup ("v7k");
case CPU_SUBTYPE_ARM_V7M:
return strdup ("v7m");
case CPU_SUBTYPE_ARM_V7EM:
return strdup ("v7em");
default:
return r_str_newf ("unknown ARM subtype %d", hdr->cpusubtype & 0xff);
}
case CPU_TYPE_SPARC:
switch (hdr->cpusubtype & 0xff) {
case CPU_SUBTYPE_SPARC_ALL: return strdup ("all");
default: return strdup ("Unknown sparc subtype");
}
case CPU_TYPE_MIPS:
switch (hdr->cpusubtype & 0xff) {
case CPU_SUBTYPE_MIPS_ALL: return strdup ("all");
case CPU_SUBTYPE_MIPS_R2300: return strdup ("r2300");
case CPU_SUBTYPE_MIPS_R2600: return strdup ("r2600");
case CPU_SUBTYPE_MIPS_R2800: return strdup ("r2800");
case CPU_SUBTYPE_MIPS_R2000a: return strdup ("r2000a");
case CPU_SUBTYPE_MIPS_R2000: return strdup ("r2000");
case CPU_SUBTYPE_MIPS_R3000a: return strdup ("r3000a");
case CPU_SUBTYPE_MIPS_R3000: return strdup ("r3000");
default: return strdup ("Unknown mips subtype");
}
case CPU_TYPE_I860:
switch (hdr->cpusubtype & 0xff) {
case CPU_SUBTYPE_I860_ALL: return strdup ("all");
case CPU_SUBTYPE_I860_860: return strdup ("860");
default: return strdup ("Unknown i860 subtype");
}
case CPU_TYPE_POWERPC:
case CPU_TYPE_POWERPC64:
switch (hdr->cpusubtype & 0xff) {
case CPU_SUBTYPE_POWERPC_ALL: return strdup ("all");
case CPU_SUBTYPE_POWERPC_601: return strdup ("601");
case CPU_SUBTYPE_POWERPC_602: return strdup ("602");
case CPU_SUBTYPE_POWERPC_603: return strdup ("603");
case CPU_SUBTYPE_POWERPC_603e: return strdup ("603e");
case CPU_SUBTYPE_POWERPC_603ev: return strdup ("603ev");
case CPU_SUBTYPE_POWERPC_604: return strdup ("604");
case CPU_SUBTYPE_POWERPC_604e: return strdup ("604e");
case CPU_SUBTYPE_POWERPC_620: return strdup ("620");
case CPU_SUBTYPE_POWERPC_750: return strdup ("750");
case CPU_SUBTYPE_POWERPC_7400: return strdup ("7400");
case CPU_SUBTYPE_POWERPC_7450: return strdup ("7450");
case CPU_SUBTYPE_POWERPC_970: return strdup ("970");
default: return strdup ("Unknown ppc subtype");
}
}
}
return strdup ("Unknown cputype");
}
char* MACH0_(get_cpusubtype)(struct MACH0_(obj_t)* bin) {
if (bin) {
return MACH0_(get_cpusubtype_from_hdr) (&bin->hdr);
}
return strdup ("Unknown");
}
int MACH0_(is_pie)(struct MACH0_(obj_t)* bin) {
return (bin && bin->hdr.filetype == MH_EXECUTE && bin->hdr.flags & MH_PIE);
}
int MACH0_(has_nx)(struct MACH0_(obj_t)* bin) {
return (bin && bin->hdr.filetype == MH_EXECUTE &&
bin->hdr.flags & MH_NO_HEAP_EXECUTION);
}
char* MACH0_(get_filetype_from_hdr)(struct MACH0_(mach_header) *hdr) {
const char *mhtype = "Unknown";
switch (hdr->filetype) {
case MH_OBJECT: mhtype = "Relocatable object"; break;
case MH_EXECUTE: mhtype = "Executable file"; break;
case MH_FVMLIB: mhtype = "Fixed VM shared library"; break;
case MH_CORE: mhtype = "Core file"; break;
case MH_PRELOAD: mhtype = "Preloaded executable file"; break;
case MH_DYLIB: mhtype = "Dynamically bound shared library"; break;
case MH_DYLINKER: mhtype = "Dynamic link editor"; break;
case MH_BUNDLE: mhtype = "Dynamically bound bundle file"; break;
case MH_DYLIB_STUB: mhtype = "Shared library stub for static linking (no sections)"; break;
case MH_DSYM: mhtype = "Companion file with only debug sections"; break;
}
return strdup (mhtype);
}
char* MACH0_(get_filetype)(struct MACH0_(obj_t)* bin) {
if (bin) {
return MACH0_(get_filetype_from_hdr) (&bin->hdr);
}
return strdup ("Unknown");
}
ut64 MACH0_(get_main)(struct MACH0_(obj_t)* bin) {
ut64 addr = 0LL;
struct symbol_t *symbols;
int i;
if (!(symbols = MACH0_(get_symbols) (bin))) {
return 0;
}
for (i = 0; !symbols[i].last; i++) {
const char *name = symbols[i].name;
if (!strcmp (name, "__Dmain")) {
addr = symbols[i].addr;
break;
}
if (strstr (name, "4main") && !strstr (name, "STATIC")) {
addr = symbols[i].addr;
break;
}
if (!strcmp (symbols[i].name, "_main")) {
addr = symbols[i].addr;
// break;
}
}
free (symbols);
if (!addr && bin->main_cmd.cmd == LC_MAIN) {
addr = bin->entry + bin->baddr;
}
if (!addr) {
ut8 b[128];
ut64 entry = addr_to_offset(bin, bin->entry);
// XXX: X86 only and hacky!
if (entry > bin->size || entry + sizeof (b) > bin->size) {
return 0;
}
i = r_buf_read_at (bin->b, entry, b, sizeof (b));
if (i < 1) {
return 0;
}
for (i = 0; i < 64; i++) {
if (b[i] == 0xe8 && !b[i+3] && !b[i+4]) {
int delta = b[i+1] | (b[i+2] << 8) | (b[i+3] << 16) | (b[i+4] << 24);
return bin->entry + i + 5 + delta;
}
}
}
return addr;
}
void MACH0_(mach_headerfields)(RBinFile *file) {
RBuffer *buf = file->buf;
int n = 0;
struct MACH0_(mach_header) *mh = MACH0_(get_hdr_from_bytes)(buf);
if (!mh) {
return;
}
printf ("0x00000000 Magic 0x%x\n", mh->magic);
printf ("0x00000004 CpuType 0x%x\n", mh->cputype);
printf ("0x00000008 CpuSubType 0x%x\n", mh->cpusubtype);
printf ("0x0000000c FileType 0x%x\n", mh->filetype);
printf ("0x00000010 nCmds %d\n", mh->ncmds);
printf ("0x00000014 sizeOfCmds %d\n", mh->sizeofcmds);
printf ("0x00000018 Flags 0x%x\n", mh->flags);
ut64 addr = 0x20 - 4;
ut32 word = 0;
ut8 wordbuf[sizeof (word)];
#define READWORD() \
addr += 4; \
if (!r_buf_read_at (buf, addr, (ut8*)wordbuf, 4)) { \
eprintf ("Invalid address in buffer."); \
break; \
} \
word = r_read_le32 (wordbuf);
for (n = 0; n < mh->ncmds; n++) {
printf ("\n# Load Command %d\n", n);
READWORD();
int lcType = word;
eprintf ("0x%08"PFMT64x" cmd 0x%x %s\n",
addr, lcType, cmd_to_string (lcType));
READWORD();
int lcSize = word;
word &= 0xFFFFFF;
printf ("0x%08"PFMT64x" cmdsize %d\n", addr, word);
if (lcSize < 1) {
eprintf ("Invalid size for a load command\n");
break;
}
switch (lcType) {
case LC_ID_DYLIB: // install_name_tool
printf ("0x%08"PFMT64x" id %s\n",
addr + 20, r_buf_get_at (buf, addr + 20, NULL));
break;
case LC_UUID:
printf ("0x%08"PFMT64x" uuid %s\n",
addr + 20, r_buf_get_at (buf, addr + 32, NULL));
break;
case LC_LOAD_DYLIB:
printf ("0x%08"PFMT64x" uuid %s\n",
addr + 20, r_buf_get_at (buf, addr + 20, NULL));
break;
case LC_RPATH:
printf ("0x%08"PFMT64x" uuid %s\n",
addr + 8, r_buf_get_at (buf, addr + 8, NULL));
break;
case LC_CODE_SIGNATURE:
{
ut32 *words = (ut32*)r_buf_get_at (buf, addr + 4, NULL);
printf ("0x%08"PFMT64x" dataoff 0x%08x\n", addr + 4, words[0]);
printf ("0x%08"PFMT64x" datasize %d\n", addr + 8, words[1]);
printf ("# wtf mach0.sign %d @ 0x%x\n", words[1], words[0]);
}
break;
}
addr += word - 8;
}
free (mh);
}
RList* MACH0_(mach_fields)(RBinFile *bf) {
struct MACH0_(mach_header) *mh = MACH0_(get_hdr_from_bytes)(bf->buf);
if (!mh) {
return NULL;
}
RList *ret = r_list_new ();
if (!ret) {
return NULL;
}
ret->free = free;
ut64 addr = 0;
#define ROW(nam,siz,val,fmt) \
r_list_append (ret, r_bin_field_new (addr, addr, siz, nam, sdb_fmt ("0x%08x", val), fmt)); \
addr += 4;
ROW("hdr.magic", 4, mh->magic, "x");
ROW("hdr.cputype", 4, mh->cputype, NULL);
ROW("hdr.cpusubtype", 4, mh->cpusubtype, NULL);
ROW("hdr.filetype", 4, mh->filetype, NULL);
ROW("hdr.ncmds", 4, mh->ncmds, NULL);
ROW("hdr.sizeofcmds", 4, mh->sizeofcmds, NULL);
free (mh);
return ret;
}
struct MACH0_(mach_header) * MACH0_(get_hdr_from_bytes)(RBuffer *buf) {
ut8 magicbytes[sizeof (ut32)] = {0};
ut8 machohdrbytes[sizeof (struct MACH0_(mach_header))] = {0};
int len;
struct MACH0_(mach_header) *macho_hdr = R_NEW0 (struct MACH0_(mach_header));
bool big_endian = false;
if (!macho_hdr) {
return NULL;
}
if (r_buf_read_at (buf, 0, magicbytes, 4) < 1) {
free (macho_hdr);
return false;
}
if (r_read_le32 (magicbytes) == 0xfeedface) {
big_endian = false;
} else if (r_read_be32 (magicbytes) == 0xfeedface) {
big_endian = true;
} else if (r_read_le32 (magicbytes) == FAT_MAGIC) {
big_endian = false;
} else if (r_read_be32 (magicbytes) == FAT_MAGIC) {
big_endian = true;
} else if (r_read_le32 (magicbytes) == 0xfeedfacf) {
big_endian = false;
} else if (r_read_be32 (magicbytes) == 0xfeedfacf) {
big_endian = true;
} else {
/* also extract non-mach0s */
#if 0
free (macho_hdr);
return NULL;
#endif
}
len = r_buf_read_at (buf, 0, machohdrbytes, sizeof (machohdrbytes));
if (len != sizeof (struct MACH0_(mach_header))) {
free (macho_hdr);
return NULL;
}
macho_hdr->magic = r_read_ble (&machohdrbytes[0], big_endian, 32);
macho_hdr->cputype = r_read_ble (&machohdrbytes[4], big_endian, 32);
macho_hdr->cpusubtype = r_read_ble (&machohdrbytes[8], big_endian, 32);
macho_hdr->filetype = r_read_ble (&machohdrbytes[12], big_endian, 32);
macho_hdr->ncmds = r_read_ble (&machohdrbytes[16], big_endian, 32);
macho_hdr->sizeofcmds = r_read_ble (&machohdrbytes[20], big_endian, 32);
macho_hdr->flags = r_read_ble (&machohdrbytes[24], big_endian, 32);
#if R_BIN_MACH064
macho_hdr->reserved = r_read_ble (&machohdrbytes[28], big_endian, 32);
#endif
return macho_hdr;
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_145_0 |
crossvul-cpp_data_bad_2646_0 | /*
* Copyright (c) 1992, 1993, 1994, 1995, 1996, 1997
* The Regents of the University of California. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that: (1) source code distributions
* retain the above copyright notice and this paragraph in its entirety, (2)
* distributions including binary code include the above copyright notice and
* this paragraph in its entirety in the documentation or other materials
* provided with the distribution, and (3) all advertising materials mentioning
* features or use of this software display the following acknowledgement:
* ``This product includes software developed by the University of California,
* Lawrence Berkeley Laboratory and its contributors.'' Neither the name of
* the University nor the names of its contributors may be used to endorse
* or promote products derived from this software without specific prior
* written permission.
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
/* \summary: DECnet printer */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <netdissect-stdinc.h>
struct mbuf;
struct rtentry;
#ifdef HAVE_NETDNET_DNETDB_H
#include <netdnet/dnetdb.h>
#endif
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "extract.h"
#include "netdissect.h"
#include "addrtoname.h"
static const char tstr[] = "[|decnet]";
#ifndef _WIN32
typedef uint8_t byte[1]; /* single byte field */
#else
/*
* the keyword 'byte' generates conflicts in Windows
*/
typedef unsigned char Byte[1]; /* single byte field */
#define byte Byte
#endif /* _WIN32 */
typedef uint8_t word[2]; /* 2 byte field */
typedef uint8_t longword[4]; /* 4 bytes field */
/*
* Definitions for DECNET Phase IV protocol headers
*/
union etheraddress {
uint8_t dne_addr[6]; /* full ethernet address */
struct {
uint8_t dne_hiord[4]; /* DECnet HIORD prefix */
uint8_t dne_nodeaddr[2]; /* DECnet node address */
} dne_remote;
};
typedef union etheraddress etheraddr; /* Ethernet address */
#define HIORD 0x000400aa /* high 32-bits of address (swapped) */
#define AREAMASK 0176000 /* mask for area field */
#define AREASHIFT 10 /* bit-offset for area field */
#define NODEMASK 01777 /* mask for node address field */
#define DN_MAXADDL 20 /* max size of DECnet address */
struct dn_naddr {
uint16_t a_len; /* length of address */
uint8_t a_addr[DN_MAXADDL]; /* address as bytes */
};
/*
* Define long and short header formats.
*/
struct shorthdr
{
byte sh_flags; /* route flags */
word sh_dst; /* destination node address */
word sh_src; /* source node address */
byte sh_visits; /* visit count */
};
struct longhdr
{
byte lg_flags; /* route flags */
byte lg_darea; /* destination area (reserved) */
byte lg_dsarea; /* destination subarea (reserved) */
etheraddr lg_dst; /* destination id */
byte lg_sarea; /* source area (reserved) */
byte lg_ssarea; /* source subarea (reserved) */
etheraddr lg_src; /* source id */
byte lg_nextl2; /* next level 2 router (reserved) */
byte lg_visits; /* visit count */
byte lg_service; /* service class (reserved) */
byte lg_pt; /* protocol type (reserved) */
};
union routehdr
{
struct shorthdr rh_short; /* short route header */
struct longhdr rh_long; /* long route header */
};
/*
* Define the values of various fields in the protocol messages.
*
* 1. Data packet formats.
*/
#define RMF_MASK 7 /* mask for message type */
#define RMF_SHORT 2 /* short message format */
#define RMF_LONG 6 /* long message format */
#ifndef RMF_RQR
#define RMF_RQR 010 /* request return to sender */
#define RMF_RTS 020 /* returning to sender */
#define RMF_IE 040 /* intra-ethernet packet */
#endif /* RMR_RQR */
#define RMF_FVER 0100 /* future version flag */
#define RMF_PAD 0200 /* pad field */
#define RMF_PADMASK 0177 /* pad field mask */
#define VIS_MASK 077 /* visit field mask */
/*
* 2. Control packet formats.
*/
#define RMF_CTLMASK 017 /* mask for message type */
#define RMF_CTLMSG 01 /* control message indicator */
#define RMF_INIT 01 /* initialization message */
#define RMF_VER 03 /* verification message */
#define RMF_TEST 05 /* hello and test message */
#define RMF_L1ROUT 07 /* level 1 routing message */
#define RMF_L2ROUT 011 /* level 2 routing message */
#define RMF_RHELLO 013 /* router hello message */
#define RMF_EHELLO 015 /* endnode hello message */
#define TI_L2ROUT 01 /* level 2 router */
#define TI_L1ROUT 02 /* level 1 router */
#define TI_ENDNODE 03 /* endnode */
#define TI_VERIF 04 /* verification required */
#define TI_BLOCK 010 /* blocking requested */
#define VE_VERS 2 /* version number (2) */
#define VE_ECO 0 /* ECO number */
#define VE_UECO 0 /* user ECO number (0) */
#define P3_VERS 1 /* phase III version number (1) */
#define P3_ECO 3 /* ECO number (3) */
#define P3_UECO 0 /* user ECO number (0) */
#define II_L2ROUT 01 /* level 2 router */
#define II_L1ROUT 02 /* level 1 router */
#define II_ENDNODE 03 /* endnode */
#define II_VERIF 04 /* verification required */
#define II_NOMCAST 040 /* no multicast traffic accepted */
#define II_BLOCK 0100 /* blocking requested */
#define II_TYPEMASK 03 /* mask for node type */
#define TESTDATA 0252 /* test data bytes */
#define TESTLEN 1 /* length of transmitted test data */
/*
* Define control message formats.
*/
struct initmsgIII /* phase III initialization message */
{
byte inIII_flags; /* route flags */
word inIII_src; /* source node address */
byte inIII_info; /* routing layer information */
word inIII_blksize; /* maximum data link block size */
byte inIII_vers; /* version number */
byte inIII_eco; /* ECO number */
byte inIII_ueco; /* user ECO number */
byte inIII_rsvd; /* reserved image field */
};
struct initmsg /* initialization message */
{
byte in_flags; /* route flags */
word in_src; /* source node address */
byte in_info; /* routing layer information */
word in_blksize; /* maximum data link block size */
byte in_vers; /* version number */
byte in_eco; /* ECO number */
byte in_ueco; /* user ECO number */
word in_hello; /* hello timer */
byte in_rsvd; /* reserved image field */
};
struct verifmsg /* verification message */
{
byte ve_flags; /* route flags */
word ve_src; /* source node address */
byte ve_fcnval; /* function value image field */
};
struct testmsg /* hello and test message */
{
byte te_flags; /* route flags */
word te_src; /* source node address */
byte te_data; /* test data image field */
};
struct l1rout /* level 1 routing message */
{
byte r1_flags; /* route flags */
word r1_src; /* source node address */
byte r1_rsvd; /* reserved field */
};
struct l2rout /* level 2 routing message */
{
byte r2_flags; /* route flags */
word r2_src; /* source node address */
byte r2_rsvd; /* reserved field */
};
struct rhellomsg /* router hello message */
{
byte rh_flags; /* route flags */
byte rh_vers; /* version number */
byte rh_eco; /* ECO number */
byte rh_ueco; /* user ECO number */
etheraddr rh_src; /* source id */
byte rh_info; /* routing layer information */
word rh_blksize; /* maximum data link block size */
byte rh_priority; /* router's priority */
byte rh_area; /* reserved */
word rh_hello; /* hello timer */
byte rh_mpd; /* reserved */
};
struct ehellomsg /* endnode hello message */
{
byte eh_flags; /* route flags */
byte eh_vers; /* version number */
byte eh_eco; /* ECO number */
byte eh_ueco; /* user ECO number */
etheraddr eh_src; /* source id */
byte eh_info; /* routing layer information */
word eh_blksize; /* maximum data link block size */
byte eh_area; /* area (reserved) */
byte eh_seed[8]; /* verification seed */
etheraddr eh_router; /* designated router */
word eh_hello; /* hello timer */
byte eh_mpd; /* (reserved) */
byte eh_data; /* test data image field */
};
union controlmsg
{
struct initmsg cm_init; /* initialization message */
struct verifmsg cm_ver; /* verification message */
struct testmsg cm_test; /* hello and test message */
struct l1rout cm_l1rou; /* level 1 routing message */
struct l2rout cm_l2rout; /* level 2 routing message */
struct rhellomsg cm_rhello; /* router hello message */
struct ehellomsg cm_ehello; /* endnode hello message */
};
/* Macros for decoding routing-info fields */
#define RI_COST(x) ((x)&0777)
#define RI_HOPS(x) (((x)>>10)&037)
/*
* NSP protocol fields and values.
*/
#define NSP_TYPEMASK 014 /* mask to isolate type code */
#define NSP_SUBMASK 0160 /* mask to isolate subtype code */
#define NSP_SUBSHFT 4 /* shift to move subtype code */
#define MFT_DATA 0 /* data message */
#define MFT_ACK 04 /* acknowledgement message */
#define MFT_CTL 010 /* control message */
#define MFS_ILS 020 /* data or I/LS indicator */
#define MFS_BOM 040 /* beginning of message (data) */
#define MFS_MOM 0 /* middle of message (data) */
#define MFS_EOM 0100 /* end of message (data) */
#define MFS_INT 040 /* interrupt message */
#define MFS_DACK 0 /* data acknowledgement */
#define MFS_IACK 020 /* I/LS acknowledgement */
#define MFS_CACK 040 /* connect acknowledgement */
#define MFS_NOP 0 /* no operation */
#define MFS_CI 020 /* connect initiate */
#define MFS_CC 040 /* connect confirm */
#define MFS_DI 060 /* disconnect initiate */
#define MFS_DC 0100 /* disconnect confirm */
#define MFS_RCI 0140 /* retransmitted connect initiate */
#define SGQ_ACK 0100000 /* ack */
#define SGQ_NAK 0110000 /* negative ack */
#define SGQ_OACK 0120000 /* other channel ack */
#define SGQ_ONAK 0130000 /* other channel negative ack */
#define SGQ_MASK 07777 /* mask to isolate seq # */
#define SGQ_OTHER 020000 /* other channel qualifier */
#define SGQ_DELAY 010000 /* ack delay flag */
#define SGQ_EOM 0100000 /* pseudo flag for end-of-message */
#define LSM_MASK 03 /* mask for modifier field */
#define LSM_NOCHANGE 0 /* no change */
#define LSM_DONOTSEND 1 /* do not send data */
#define LSM_SEND 2 /* send data */
#define LSI_MASK 014 /* mask for interpretation field */
#define LSI_DATA 0 /* data segment or message count */
#define LSI_INTR 4 /* interrupt request count */
#define LSI_INTM 0377 /* funny marker for int. message */
#define COS_MASK 014 /* mask for flow control field */
#define COS_NONE 0 /* no flow control */
#define COS_SEGMENT 04 /* segment flow control */
#define COS_MESSAGE 010 /* message flow control */
#define COS_DEFAULT 1 /* default value for field */
#define COI_MASK 3 /* mask for version field */
#define COI_32 0 /* version 3.2 */
#define COI_31 1 /* version 3.1 */
#define COI_40 2 /* version 4.0 */
#define COI_41 3 /* version 4.1 */
#define MNU_MASK 140 /* mask for session control version */
#define MNU_10 000 /* session V1.0 */
#define MNU_20 040 /* session V2.0 */
#define MNU_ACCESS 1 /* access control present */
#define MNU_USRDATA 2 /* user data field present */
#define MNU_INVKPROXY 4 /* invoke proxy field present */
#define MNU_UICPROXY 8 /* use uic-based proxy */
#define DC_NORESOURCES 1 /* no resource reason code */
#define DC_NOLINK 41 /* no link terminate reason code */
#define DC_COMPLETE 42 /* disconnect complete reason code */
#define DI_NOERROR 0 /* user disconnect */
#define DI_SHUT 3 /* node is shutting down */
#define DI_NOUSER 4 /* destination end user does not exist */
#define DI_INVDEST 5 /* invalid end user destination */
#define DI_REMRESRC 6 /* insufficient remote resources */
#define DI_TPA 8 /* third party abort */
#define DI_PROTOCOL 7 /* protocol error discovered */
#define DI_ABORT 9 /* user abort */
#define DI_LOCALRESRC 32 /* insufficient local resources */
#define DI_REMUSERRESRC 33 /* insufficient remote user resources */
#define DI_BADACCESS 34 /* bad access control information */
#define DI_BADACCNT 36 /* bad ACCOUNT information */
#define DI_CONNECTABORT 38 /* connect request cancelled */
#define DI_TIMEDOUT 38 /* remote node or user crashed */
#define DI_UNREACHABLE 39 /* local timers expired due to ... */
#define DI_BADIMAGE 43 /* bad image data in connect */
#define DI_SERVMISMATCH 54 /* cryptographic service mismatch */
#define UC_OBJREJECT 0 /* object rejected connect */
#define UC_USERDISCONNECT 0 /* user disconnect */
#define UC_RESOURCES 1 /* insufficient resources (local or remote) */
#define UC_NOSUCHNODE 2 /* unrecognized node name */
#define UC_REMOTESHUT 3 /* remote node shutting down */
#define UC_NOSUCHOBJ 4 /* unrecognized object */
#define UC_INVOBJFORMAT 5 /* invalid object name format */
#define UC_OBJTOOBUSY 6 /* object too busy */
#define UC_NETWORKABORT 8 /* network abort */
#define UC_USERABORT 9 /* user abort */
#define UC_INVNODEFORMAT 10 /* invalid node name format */
#define UC_LOCALSHUT 11 /* local node shutting down */
#define UC_ACCESSREJECT 34 /* invalid access control information */
#define UC_NORESPONSE 38 /* no response from object */
#define UC_UNREACHABLE 39 /* node unreachable */
/*
* NSP message formats.
*/
struct nsphdr /* general nsp header */
{
byte nh_flags; /* message flags */
word nh_dst; /* destination link address */
word nh_src; /* source link address */
};
struct seghdr /* data segment header */
{
byte sh_flags; /* message flags */
word sh_dst; /* destination link address */
word sh_src; /* source link address */
word sh_seq[3]; /* sequence numbers */
};
struct minseghdr /* minimum data segment header */
{
byte ms_flags; /* message flags */
word ms_dst; /* destination link address */
word ms_src; /* source link address */
word ms_seq; /* sequence number */
};
struct lsmsg /* link service message (after hdr) */
{
byte ls_lsflags; /* link service flags */
byte ls_fcval; /* flow control value */
};
struct ackmsg /* acknowledgement message */
{
byte ak_flags; /* message flags */
word ak_dst; /* destination link address */
word ak_src; /* source link address */
word ak_acknum[2]; /* acknowledgement numbers */
};
struct minackmsg /* minimum acknowledgement message */
{
byte mk_flags; /* message flags */
word mk_dst; /* destination link address */
word mk_src; /* source link address */
word mk_acknum; /* acknowledgement number */
};
struct ciackmsg /* connect acknowledgement message */
{
byte ck_flags; /* message flags */
word ck_dst; /* destination link address */
};
struct cimsg /* connect initiate message */
{
byte ci_flags; /* message flags */
word ci_dst; /* destination link address (0) */
word ci_src; /* source link address */
byte ci_services; /* requested services */
byte ci_info; /* information */
word ci_segsize; /* maximum segment size */
};
struct ccmsg /* connect confirm message */
{
byte cc_flags; /* message flags */
word cc_dst; /* destination link address */
word cc_src; /* source link address */
byte cc_services; /* requested services */
byte cc_info; /* information */
word cc_segsize; /* maximum segment size */
byte cc_optlen; /* optional data length */
};
struct cnmsg /* generic connect message */
{
byte cn_flags; /* message flags */
word cn_dst; /* destination link address */
word cn_src; /* source link address */
byte cn_services; /* requested services */
byte cn_info; /* information */
word cn_segsize; /* maximum segment size */
};
struct dimsg /* disconnect initiate message */
{
byte di_flags; /* message flags */
word di_dst; /* destination link address */
word di_src; /* source link address */
word di_reason; /* reason code */
byte di_optlen; /* optional data length */
};
struct dcmsg /* disconnect confirm message */
{
byte dc_flags; /* message flags */
word dc_dst; /* destination link address */
word dc_src; /* source link address */
word dc_reason; /* reason code */
};
/* Forwards */
static int print_decnet_ctlmsg(netdissect_options *, const union routehdr *, u_int, u_int);
static void print_t_info(netdissect_options *, int);
static int print_l1_routes(netdissect_options *, const char *, u_int);
static int print_l2_routes(netdissect_options *, const char *, u_int);
static void print_i_info(netdissect_options *, int);
static int print_elist(const char *, u_int);
static int print_nsp(netdissect_options *, const u_char *, u_int);
static void print_reason(netdissect_options *, int);
#ifndef HAVE_NETDNET_DNETDB_H_DNET_HTOA
extern char *dnet_htoa(struct dn_naddr *);
#endif
void
decnet_print(netdissect_options *ndo,
register const u_char *ap, register u_int length,
register u_int caplen)
{
register const union routehdr *rhp;
register int mflags;
int dst, src, hops;
u_int nsplen, pktlen;
const u_char *nspp;
if (length < sizeof(struct shorthdr)) {
ND_PRINT((ndo, "%s", tstr));
return;
}
ND_TCHECK2(*ap, sizeof(short));
pktlen = EXTRACT_LE_16BITS(ap);
if (pktlen < sizeof(struct shorthdr)) {
ND_PRINT((ndo, "%s", tstr));
return;
}
if (pktlen > length) {
ND_PRINT((ndo, "%s", tstr));
return;
}
length = pktlen;
rhp = (const union routehdr *)&(ap[sizeof(short)]);
ND_TCHECK(rhp->rh_short.sh_flags);
mflags = EXTRACT_LE_8BITS(rhp->rh_short.sh_flags);
if (mflags & RMF_PAD) {
/* pad bytes of some sort in front of message */
u_int padlen = mflags & RMF_PADMASK;
if (ndo->ndo_vflag)
ND_PRINT((ndo, "[pad:%d] ", padlen));
if (length < padlen + 2) {
ND_PRINT((ndo, "%s", tstr));
return;
}
ND_TCHECK2(ap[sizeof(short)], padlen);
ap += padlen;
length -= padlen;
caplen -= padlen;
rhp = (const union routehdr *)&(ap[sizeof(short)]);
mflags = EXTRACT_LE_8BITS(rhp->rh_short.sh_flags);
}
if (mflags & RMF_FVER) {
ND_PRINT((ndo, "future-version-decnet"));
ND_DEFAULTPRINT(ap, min(length, caplen));
return;
}
/* is it a control message? */
if (mflags & RMF_CTLMSG) {
if (!print_decnet_ctlmsg(ndo, rhp, length, caplen))
goto trunc;
return;
}
switch (mflags & RMF_MASK) {
case RMF_LONG:
if (length < sizeof(struct longhdr)) {
ND_PRINT((ndo, "%s", tstr));
return;
}
ND_TCHECK(rhp->rh_long);
dst =
EXTRACT_LE_16BITS(rhp->rh_long.lg_dst.dne_remote.dne_nodeaddr);
src =
EXTRACT_LE_16BITS(rhp->rh_long.lg_src.dne_remote.dne_nodeaddr);
hops = EXTRACT_LE_8BITS(rhp->rh_long.lg_visits);
nspp = &(ap[sizeof(short) + sizeof(struct longhdr)]);
nsplen = length - sizeof(struct longhdr);
break;
case RMF_SHORT:
ND_TCHECK(rhp->rh_short);
dst = EXTRACT_LE_16BITS(rhp->rh_short.sh_dst);
src = EXTRACT_LE_16BITS(rhp->rh_short.sh_src);
hops = (EXTRACT_LE_8BITS(rhp->rh_short.sh_visits) & VIS_MASK)+1;
nspp = &(ap[sizeof(short) + sizeof(struct shorthdr)]);
nsplen = length - sizeof(struct shorthdr);
break;
default:
ND_PRINT((ndo, "unknown message flags under mask"));
ND_DEFAULTPRINT((const u_char *)ap, min(length, caplen));
return;
}
ND_PRINT((ndo, "%s > %s %d ",
dnaddr_string(ndo, src), dnaddr_string(ndo, dst), pktlen));
if (ndo->ndo_vflag) {
if (mflags & RMF_RQR)
ND_PRINT((ndo, "RQR "));
if (mflags & RMF_RTS)
ND_PRINT((ndo, "RTS "));
if (mflags & RMF_IE)
ND_PRINT((ndo, "IE "));
ND_PRINT((ndo, "%d hops ", hops));
}
if (!print_nsp(ndo, nspp, nsplen))
goto trunc;
return;
trunc:
ND_PRINT((ndo, "%s", tstr));
return;
}
static int
print_decnet_ctlmsg(netdissect_options *ndo,
register const union routehdr *rhp, u_int length,
u_int caplen)
{
int mflags = EXTRACT_LE_8BITS(rhp->rh_short.sh_flags);
register const union controlmsg *cmp = (const union controlmsg *)rhp;
int src, dst, info, blksize, eco, ueco, hello, other, vers;
etheraddr srcea, rtea;
int priority;
const char *rhpx = (const char *)rhp;
int ret;
switch (mflags & RMF_CTLMASK) {
case RMF_INIT:
ND_PRINT((ndo, "init "));
if (length < sizeof(struct initmsg))
goto trunc;
ND_TCHECK(cmp->cm_init);
src = EXTRACT_LE_16BITS(cmp->cm_init.in_src);
info = EXTRACT_LE_8BITS(cmp->cm_init.in_info);
blksize = EXTRACT_LE_16BITS(cmp->cm_init.in_blksize);
vers = EXTRACT_LE_8BITS(cmp->cm_init.in_vers);
eco = EXTRACT_LE_8BITS(cmp->cm_init.in_eco);
ueco = EXTRACT_LE_8BITS(cmp->cm_init.in_ueco);
hello = EXTRACT_LE_16BITS(cmp->cm_init.in_hello);
print_t_info(ndo, info);
ND_PRINT((ndo,
"src %sblksize %d vers %d eco %d ueco %d hello %d",
dnaddr_string(ndo, src), blksize, vers, eco, ueco,
hello));
ret = 1;
break;
case RMF_VER:
ND_PRINT((ndo, "verification "));
if (length < sizeof(struct verifmsg))
goto trunc;
ND_TCHECK(cmp->cm_ver);
src = EXTRACT_LE_16BITS(cmp->cm_ver.ve_src);
other = EXTRACT_LE_8BITS(cmp->cm_ver.ve_fcnval);
ND_PRINT((ndo, "src %s fcnval %o", dnaddr_string(ndo, src), other));
ret = 1;
break;
case RMF_TEST:
ND_PRINT((ndo, "test "));
if (length < sizeof(struct testmsg))
goto trunc;
ND_TCHECK(cmp->cm_test);
src = EXTRACT_LE_16BITS(cmp->cm_test.te_src);
other = EXTRACT_LE_8BITS(cmp->cm_test.te_data);
ND_PRINT((ndo, "src %s data %o", dnaddr_string(ndo, src), other));
ret = 1;
break;
case RMF_L1ROUT:
ND_PRINT((ndo, "lev-1-routing "));
if (length < sizeof(struct l1rout))
goto trunc;
ND_TCHECK(cmp->cm_l1rou);
src = EXTRACT_LE_16BITS(cmp->cm_l1rou.r1_src);
ND_PRINT((ndo, "src %s ", dnaddr_string(ndo, src)));
ret = print_l1_routes(ndo, &(rhpx[sizeof(struct l1rout)]),
length - sizeof(struct l1rout));
break;
case RMF_L2ROUT:
ND_PRINT((ndo, "lev-2-routing "));
if (length < sizeof(struct l2rout))
goto trunc;
ND_TCHECK(cmp->cm_l2rout);
src = EXTRACT_LE_16BITS(cmp->cm_l2rout.r2_src);
ND_PRINT((ndo, "src %s ", dnaddr_string(ndo, src)));
ret = print_l2_routes(ndo, &(rhpx[sizeof(struct l2rout)]),
length - sizeof(struct l2rout));
break;
case RMF_RHELLO:
ND_PRINT((ndo, "router-hello "));
if (length < sizeof(struct rhellomsg))
goto trunc;
ND_TCHECK(cmp->cm_rhello);
vers = EXTRACT_LE_8BITS(cmp->cm_rhello.rh_vers);
eco = EXTRACT_LE_8BITS(cmp->cm_rhello.rh_eco);
ueco = EXTRACT_LE_8BITS(cmp->cm_rhello.rh_ueco);
memcpy((char *)&srcea, (const char *)&(cmp->cm_rhello.rh_src),
sizeof(srcea));
src = EXTRACT_LE_16BITS(srcea.dne_remote.dne_nodeaddr);
info = EXTRACT_LE_8BITS(cmp->cm_rhello.rh_info);
blksize = EXTRACT_LE_16BITS(cmp->cm_rhello.rh_blksize);
priority = EXTRACT_LE_8BITS(cmp->cm_rhello.rh_priority);
hello = EXTRACT_LE_16BITS(cmp->cm_rhello.rh_hello);
print_i_info(ndo, info);
ND_PRINT((ndo,
"vers %d eco %d ueco %d src %s blksize %d pri %d hello %d",
vers, eco, ueco, dnaddr_string(ndo, src),
blksize, priority, hello));
ret = print_elist(&(rhpx[sizeof(struct rhellomsg)]),
length - sizeof(struct rhellomsg));
break;
case RMF_EHELLO:
ND_PRINT((ndo, "endnode-hello "));
if (length < sizeof(struct ehellomsg))
goto trunc;
ND_TCHECK(cmp->cm_ehello);
vers = EXTRACT_LE_8BITS(cmp->cm_ehello.eh_vers);
eco = EXTRACT_LE_8BITS(cmp->cm_ehello.eh_eco);
ueco = EXTRACT_LE_8BITS(cmp->cm_ehello.eh_ueco);
memcpy((char *)&srcea, (const char *)&(cmp->cm_ehello.eh_src),
sizeof(srcea));
src = EXTRACT_LE_16BITS(srcea.dne_remote.dne_nodeaddr);
info = EXTRACT_LE_8BITS(cmp->cm_ehello.eh_info);
blksize = EXTRACT_LE_16BITS(cmp->cm_ehello.eh_blksize);
/*seed*/
memcpy((char *)&rtea, (const char *)&(cmp->cm_ehello.eh_router),
sizeof(rtea));
dst = EXTRACT_LE_16BITS(rtea.dne_remote.dne_nodeaddr);
hello = EXTRACT_LE_16BITS(cmp->cm_ehello.eh_hello);
other = EXTRACT_LE_8BITS(cmp->cm_ehello.eh_data);
print_i_info(ndo, info);
ND_PRINT((ndo,
"vers %d eco %d ueco %d src %s blksize %d rtr %s hello %d data %o",
vers, eco, ueco, dnaddr_string(ndo, src),
blksize, dnaddr_string(ndo, dst), hello, other));
ret = 1;
break;
default:
ND_PRINT((ndo, "unknown control message"));
ND_DEFAULTPRINT((const u_char *)rhp, min(length, caplen));
ret = 1;
break;
}
return (ret);
trunc:
return (0);
}
static void
print_t_info(netdissect_options *ndo,
int info)
{
int ntype = info & 3;
switch (ntype) {
case 0: ND_PRINT((ndo, "reserved-ntype? ")); break;
case TI_L2ROUT: ND_PRINT((ndo, "l2rout ")); break;
case TI_L1ROUT: ND_PRINT((ndo, "l1rout ")); break;
case TI_ENDNODE: ND_PRINT((ndo, "endnode ")); break;
}
if (info & TI_VERIF)
ND_PRINT((ndo, "verif "));
if (info & TI_BLOCK)
ND_PRINT((ndo, "blo "));
}
static int
print_l1_routes(netdissect_options *ndo,
const char *rp, u_int len)
{
int count;
int id;
int info;
/* The last short is a checksum */
while (len > (3 * sizeof(short))) {
ND_TCHECK2(*rp, 3 * sizeof(short));
count = EXTRACT_LE_16BITS(rp);
if (count > 1024)
return (1); /* seems to be bogus from here on */
rp += sizeof(short);
len -= sizeof(short);
id = EXTRACT_LE_16BITS(rp);
rp += sizeof(short);
len -= sizeof(short);
info = EXTRACT_LE_16BITS(rp);
rp += sizeof(short);
len -= sizeof(short);
ND_PRINT((ndo, "{ids %d-%d cost %d hops %d} ", id, id + count,
RI_COST(info), RI_HOPS(info)));
}
return (1);
trunc:
return (0);
}
static int
print_l2_routes(netdissect_options *ndo,
const char *rp, u_int len)
{
int count;
int area;
int info;
/* The last short is a checksum */
while (len > (3 * sizeof(short))) {
ND_TCHECK2(*rp, 3 * sizeof(short));
count = EXTRACT_LE_16BITS(rp);
if (count > 1024)
return (1); /* seems to be bogus from here on */
rp += sizeof(short);
len -= sizeof(short);
area = EXTRACT_LE_16BITS(rp);
rp += sizeof(short);
len -= sizeof(short);
info = EXTRACT_LE_16BITS(rp);
rp += sizeof(short);
len -= sizeof(short);
ND_PRINT((ndo, "{areas %d-%d cost %d hops %d} ", area, area + count,
RI_COST(info), RI_HOPS(info)));
}
return (1);
trunc:
return (0);
}
static void
print_i_info(netdissect_options *ndo,
int info)
{
int ntype = info & II_TYPEMASK;
switch (ntype) {
case 0: ND_PRINT((ndo, "reserved-ntype? ")); break;
case II_L2ROUT: ND_PRINT((ndo, "l2rout ")); break;
case II_L1ROUT: ND_PRINT((ndo, "l1rout ")); break;
case II_ENDNODE: ND_PRINT((ndo, "endnode ")); break;
}
if (info & II_VERIF)
ND_PRINT((ndo, "verif "));
if (info & II_NOMCAST)
ND_PRINT((ndo, "nomcast "));
if (info & II_BLOCK)
ND_PRINT((ndo, "blo "));
}
static int
print_elist(const char *elp _U_, u_int len _U_)
{
/* Not enough examples available for me to debug this */
return (1);
}
static int
print_nsp(netdissect_options *ndo,
const u_char *nspp, u_int nsplen)
{
const struct nsphdr *nsphp = (const struct nsphdr *)nspp;
int dst, src, flags;
if (nsplen < sizeof(struct nsphdr))
goto trunc;
ND_TCHECK(*nsphp);
flags = EXTRACT_LE_8BITS(nsphp->nh_flags);
dst = EXTRACT_LE_16BITS(nsphp->nh_dst);
src = EXTRACT_LE_16BITS(nsphp->nh_src);
switch (flags & NSP_TYPEMASK) {
case MFT_DATA:
switch (flags & NSP_SUBMASK) {
case MFS_BOM:
case MFS_MOM:
case MFS_EOM:
case MFS_BOM+MFS_EOM:
ND_PRINT((ndo, "data %d>%d ", src, dst));
{
const struct seghdr *shp = (const struct seghdr *)nspp;
int ack;
u_int data_off = sizeof(struct minseghdr);
if (nsplen < data_off)
goto trunc;
ND_TCHECK(shp->sh_seq[0]);
ack = EXTRACT_LE_16BITS(shp->sh_seq[0]);
if (ack & SGQ_ACK) { /* acknum field */
if ((ack & SGQ_NAK) == SGQ_NAK)
ND_PRINT((ndo, "nak %d ", ack & SGQ_MASK));
else
ND_PRINT((ndo, "ack %d ", ack & SGQ_MASK));
data_off += sizeof(short);
if (nsplen < data_off)
goto trunc;
ND_TCHECK(shp->sh_seq[1]);
ack = EXTRACT_LE_16BITS(shp->sh_seq[1]);
if (ack & SGQ_OACK) { /* ackoth field */
if ((ack & SGQ_ONAK) == SGQ_ONAK)
ND_PRINT((ndo, "onak %d ", ack & SGQ_MASK));
else
ND_PRINT((ndo, "oack %d ", ack & SGQ_MASK));
data_off += sizeof(short);
if (nsplen < data_off)
goto trunc;
ND_TCHECK(shp->sh_seq[2]);
ack = EXTRACT_LE_16BITS(shp->sh_seq[2]);
}
}
ND_PRINT((ndo, "seg %d ", ack & SGQ_MASK));
}
break;
case MFS_ILS+MFS_INT:
ND_PRINT((ndo, "intr "));
{
const struct seghdr *shp = (const struct seghdr *)nspp;
int ack;
u_int data_off = sizeof(struct minseghdr);
if (nsplen < data_off)
goto trunc;
ND_TCHECK(shp->sh_seq[0]);
ack = EXTRACT_LE_16BITS(shp->sh_seq[0]);
if (ack & SGQ_ACK) { /* acknum field */
if ((ack & SGQ_NAK) == SGQ_NAK)
ND_PRINT((ndo, "nak %d ", ack & SGQ_MASK));
else
ND_PRINT((ndo, "ack %d ", ack & SGQ_MASK));
data_off += sizeof(short);
if (nsplen < data_off)
goto trunc;
ND_TCHECK(shp->sh_seq[1]);
ack = EXTRACT_LE_16BITS(shp->sh_seq[1]);
if (ack & SGQ_OACK) { /* ackdat field */
if ((ack & SGQ_ONAK) == SGQ_ONAK)
ND_PRINT((ndo, "nakdat %d ", ack & SGQ_MASK));
else
ND_PRINT((ndo, "ackdat %d ", ack & SGQ_MASK));
data_off += sizeof(short);
if (nsplen < data_off)
goto trunc;
ND_TCHECK(shp->sh_seq[2]);
ack = EXTRACT_LE_16BITS(shp->sh_seq[2]);
}
}
ND_PRINT((ndo, "seg %d ", ack & SGQ_MASK));
}
break;
case MFS_ILS:
ND_PRINT((ndo, "link-service %d>%d ", src, dst));
{
const struct seghdr *shp = (const struct seghdr *)nspp;
const struct lsmsg *lsmp =
(const struct lsmsg *)&(nspp[sizeof(struct seghdr)]);
int ack;
int lsflags, fcval;
if (nsplen < sizeof(struct seghdr) + sizeof(struct lsmsg))
goto trunc;
ND_TCHECK(shp->sh_seq[0]);
ack = EXTRACT_LE_16BITS(shp->sh_seq[0]);
if (ack & SGQ_ACK) { /* acknum field */
if ((ack & SGQ_NAK) == SGQ_NAK)
ND_PRINT((ndo, "nak %d ", ack & SGQ_MASK));
else
ND_PRINT((ndo, "ack %d ", ack & SGQ_MASK));
ND_TCHECK(shp->sh_seq[1]);
ack = EXTRACT_LE_16BITS(shp->sh_seq[1]);
if (ack & SGQ_OACK) { /* ackdat field */
if ((ack & SGQ_ONAK) == SGQ_ONAK)
ND_PRINT((ndo, "nakdat %d ", ack & SGQ_MASK));
else
ND_PRINT((ndo, "ackdat %d ", ack & SGQ_MASK));
ND_TCHECK(shp->sh_seq[2]);
ack = EXTRACT_LE_16BITS(shp->sh_seq[2]);
}
}
ND_PRINT((ndo, "seg %d ", ack & SGQ_MASK));
ND_TCHECK(*lsmp);
lsflags = EXTRACT_LE_8BITS(lsmp->ls_lsflags);
fcval = EXTRACT_LE_8BITS(lsmp->ls_fcval);
switch (lsflags & LSI_MASK) {
case LSI_DATA:
ND_PRINT((ndo, "dat seg count %d ", fcval));
switch (lsflags & LSM_MASK) {
case LSM_NOCHANGE:
break;
case LSM_DONOTSEND:
ND_PRINT((ndo, "donotsend-data "));
break;
case LSM_SEND:
ND_PRINT((ndo, "send-data "));
break;
default:
ND_PRINT((ndo, "reserved-fcmod? %x", lsflags));
break;
}
break;
case LSI_INTR:
ND_PRINT((ndo, "intr req count %d ", fcval));
break;
default:
ND_PRINT((ndo, "reserved-fcval-int? %x", lsflags));
break;
}
}
break;
default:
ND_PRINT((ndo, "reserved-subtype? %x %d > %d", flags, src, dst));
break;
}
break;
case MFT_ACK:
switch (flags & NSP_SUBMASK) {
case MFS_DACK:
ND_PRINT((ndo, "data-ack %d>%d ", src, dst));
{
const struct ackmsg *amp = (const struct ackmsg *)nspp;
int ack;
if (nsplen < sizeof(struct ackmsg))
goto trunc;
ND_TCHECK(*amp);
ack = EXTRACT_LE_16BITS(amp->ak_acknum[0]);
if (ack & SGQ_ACK) { /* acknum field */
if ((ack & SGQ_NAK) == SGQ_NAK)
ND_PRINT((ndo, "nak %d ", ack & SGQ_MASK));
else
ND_PRINT((ndo, "ack %d ", ack & SGQ_MASK));
ack = EXTRACT_LE_16BITS(amp->ak_acknum[1]);
if (ack & SGQ_OACK) { /* ackoth field */
if ((ack & SGQ_ONAK) == SGQ_ONAK)
ND_PRINT((ndo, "onak %d ", ack & SGQ_MASK));
else
ND_PRINT((ndo, "oack %d ", ack & SGQ_MASK));
}
}
}
break;
case MFS_IACK:
ND_PRINT((ndo, "ils-ack %d>%d ", src, dst));
{
const struct ackmsg *amp = (const struct ackmsg *)nspp;
int ack;
if (nsplen < sizeof(struct ackmsg))
goto trunc;
ND_TCHECK(*amp);
ack = EXTRACT_LE_16BITS(amp->ak_acknum[0]);
if (ack & SGQ_ACK) { /* acknum field */
if ((ack & SGQ_NAK) == SGQ_NAK)
ND_PRINT((ndo, "nak %d ", ack & SGQ_MASK));
else
ND_PRINT((ndo, "ack %d ", ack & SGQ_MASK));
ND_TCHECK(amp->ak_acknum[1]);
ack = EXTRACT_LE_16BITS(amp->ak_acknum[1]);
if (ack & SGQ_OACK) { /* ackdat field */
if ((ack & SGQ_ONAK) == SGQ_ONAK)
ND_PRINT((ndo, "nakdat %d ", ack & SGQ_MASK));
else
ND_PRINT((ndo, "ackdat %d ", ack & SGQ_MASK));
}
}
}
break;
case MFS_CACK:
ND_PRINT((ndo, "conn-ack %d", dst));
break;
default:
ND_PRINT((ndo, "reserved-acktype? %x %d > %d", flags, src, dst));
break;
}
break;
case MFT_CTL:
switch (flags & NSP_SUBMASK) {
case MFS_CI:
case MFS_RCI:
if ((flags & NSP_SUBMASK) == MFS_CI)
ND_PRINT((ndo, "conn-initiate "));
else
ND_PRINT((ndo, "retrans-conn-initiate "));
ND_PRINT((ndo, "%d>%d ", src, dst));
{
const struct cimsg *cimp = (const struct cimsg *)nspp;
int services, info, segsize;
if (nsplen < sizeof(struct cimsg))
goto trunc;
ND_TCHECK(*cimp);
services = EXTRACT_LE_8BITS(cimp->ci_services);
info = EXTRACT_LE_8BITS(cimp->ci_info);
segsize = EXTRACT_LE_16BITS(cimp->ci_segsize);
switch (services & COS_MASK) {
case COS_NONE:
break;
case COS_SEGMENT:
ND_PRINT((ndo, "seg "));
break;
case COS_MESSAGE:
ND_PRINT((ndo, "msg "));
break;
}
switch (info & COI_MASK) {
case COI_32:
ND_PRINT((ndo, "ver 3.2 "));
break;
case COI_31:
ND_PRINT((ndo, "ver 3.1 "));
break;
case COI_40:
ND_PRINT((ndo, "ver 4.0 "));
break;
case COI_41:
ND_PRINT((ndo, "ver 4.1 "));
break;
}
ND_PRINT((ndo, "segsize %d ", segsize));
}
break;
case MFS_CC:
ND_PRINT((ndo, "conn-confirm %d>%d ", src, dst));
{
const struct ccmsg *ccmp = (const struct ccmsg *)nspp;
int services, info;
u_int segsize, optlen;
if (nsplen < sizeof(struct ccmsg))
goto trunc;
ND_TCHECK(*ccmp);
services = EXTRACT_LE_8BITS(ccmp->cc_services);
info = EXTRACT_LE_8BITS(ccmp->cc_info);
segsize = EXTRACT_LE_16BITS(ccmp->cc_segsize);
optlen = EXTRACT_LE_8BITS(ccmp->cc_optlen);
switch (services & COS_MASK) {
case COS_NONE:
break;
case COS_SEGMENT:
ND_PRINT((ndo, "seg "));
break;
case COS_MESSAGE:
ND_PRINT((ndo, "msg "));
break;
}
switch (info & COI_MASK) {
case COI_32:
ND_PRINT((ndo, "ver 3.2 "));
break;
case COI_31:
ND_PRINT((ndo, "ver 3.1 "));
break;
case COI_40:
ND_PRINT((ndo, "ver 4.0 "));
break;
case COI_41:
ND_PRINT((ndo, "ver 4.1 "));
break;
}
ND_PRINT((ndo, "segsize %d ", segsize));
if (optlen) {
ND_PRINT((ndo, "optlen %d ", optlen));
}
}
break;
case MFS_DI:
ND_PRINT((ndo, "disconn-initiate %d>%d ", src, dst));
{
const struct dimsg *dimp = (const struct dimsg *)nspp;
int reason;
u_int optlen;
if (nsplen < sizeof(struct dimsg))
goto trunc;
ND_TCHECK(*dimp);
reason = EXTRACT_LE_16BITS(dimp->di_reason);
optlen = EXTRACT_LE_8BITS(dimp->di_optlen);
print_reason(ndo, reason);
if (optlen) {
ND_PRINT((ndo, "optlen %d ", optlen));
}
}
break;
case MFS_DC:
ND_PRINT((ndo, "disconn-confirm %d>%d ", src, dst));
{
const struct dcmsg *dcmp = (const struct dcmsg *)nspp;
int reason;
ND_TCHECK(*dcmp);
reason = EXTRACT_LE_16BITS(dcmp->dc_reason);
print_reason(ndo, reason);
}
break;
default:
ND_PRINT((ndo, "reserved-ctltype? %x %d > %d", flags, src, dst));
break;
}
break;
default:
ND_PRINT((ndo, "reserved-type? %x %d > %d", flags, src, dst));
break;
}
return (1);
trunc:
return (0);
}
static const struct tok reason2str[] = {
{ UC_OBJREJECT, "object rejected connect" },
{ UC_RESOURCES, "insufficient resources" },
{ UC_NOSUCHNODE, "unrecognized node name" },
{ DI_SHUT, "node is shutting down" },
{ UC_NOSUCHOBJ, "unrecognized object" },
{ UC_INVOBJFORMAT, "invalid object name format" },
{ UC_OBJTOOBUSY, "object too busy" },
{ DI_PROTOCOL, "protocol error discovered" },
{ DI_TPA, "third party abort" },
{ UC_USERABORT, "user abort" },
{ UC_INVNODEFORMAT, "invalid node name format" },
{ UC_LOCALSHUT, "local node shutting down" },
{ DI_LOCALRESRC, "insufficient local resources" },
{ DI_REMUSERRESRC, "insufficient remote user resources" },
{ UC_ACCESSREJECT, "invalid access control information" },
{ DI_BADACCNT, "bad ACCOUNT information" },
{ UC_NORESPONSE, "no response from object" },
{ UC_UNREACHABLE, "node unreachable" },
{ DC_NOLINK, "no link terminate" },
{ DC_COMPLETE, "disconnect complete" },
{ DI_BADIMAGE, "bad image data in connect" },
{ DI_SERVMISMATCH, "cryptographic service mismatch" },
{ 0, NULL }
};
static void
print_reason(netdissect_options *ndo,
register int reason)
{
ND_PRINT((ndo, "%s ", tok2str(reason2str, "reason-%d", reason)));
}
const char *
dnnum_string(netdissect_options *ndo, u_short dnaddr)
{
char *str;
size_t siz;
int area = (u_short)(dnaddr & AREAMASK) >> AREASHIFT;
int node = dnaddr & NODEMASK;
str = (char *)malloc(siz = sizeof("00.0000"));
if (str == NULL)
(*ndo->ndo_error)(ndo, "dnnum_string: malloc");
snprintf(str, siz, "%d.%d", area, node);
return(str);
}
const char *
dnname_string(netdissect_options *ndo, u_short dnaddr)
{
#ifdef HAVE_DNET_HTOA
struct dn_naddr dna;
char *dnname;
dna.a_len = sizeof(short);
memcpy((char *)dna.a_addr, (char *)&dnaddr, sizeof(short));
dnname = dnet_htoa(&dna);
if(dnname != NULL)
return (strdup(dnname));
else
return(dnnum_string(ndo, dnaddr));
#else
return(dnnum_string(ndo, dnaddr)); /* punt */
#endif
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_2646_0 |
crossvul-cpp_data_good_2889_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)
vstart += verdef->vd_aux;
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-125/c/good_2889_0 |
crossvul-cpp_data_good_5298_0 | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% H H DDDD RRRR %
% H H D D R R %
% HHHHH D D RRRR %
% H H D D R R %
% H H DDDD R R %
% %
% %
% Read/Write Radiance RGBE Image Format %
% %
% Software Design %
% Cristy %
% July 1992 %
% %
% %
% Copyright 1999-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/blob.h"
#include "MagickCore/blob-private.h"
#include "MagickCore/cache.h"
#include "MagickCore/colorspace.h"
#include "MagickCore/colorspace-private.h"
#include "MagickCore/exception.h"
#include "MagickCore/exception-private.h"
#include "MagickCore/image.h"
#include "MagickCore/image-private.h"
#include "MagickCore/list.h"
#include "MagickCore/magick.h"
#include "MagickCore/memory_.h"
#include "MagickCore/monitor.h"
#include "MagickCore/monitor-private.h"
#include "MagickCore/pixel-accessor.h"
#include "MagickCore/property.h"
#include "MagickCore/quantum-private.h"
#include "MagickCore/static.h"
#include "MagickCore/string_.h"
#include "MagickCore/string-private.h"
#include "MagickCore/module.h"
/*
Forward declarations.
*/
static MagickBooleanType
WriteHDRImage(const ImageInfo *,Image *,ExceptionInfo *);
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% I s H D R %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% IsHDR() returns MagickTrue if the image format type, identified by the
% magick string, is Radiance RGBE image format.
%
% The format of the IsHDR method is:
%
% MagickBooleanType IsHDR(const unsigned char *magick,
% const size_t length)
%
% A description of each parameter follows:
%
% o magick: compare image format pattern against these bytes.
%
% o length: Specifies the length of the magick string.
%
*/
static MagickBooleanType IsHDR(const unsigned char *magick,
const size_t length)
{
if (length < 10)
return(MagickFalse);
if (LocaleNCompare((const char *) magick,"#?RADIANCE",10) == 0)
return(MagickTrue);
if (LocaleNCompare((const char *) magick,"#?RGBE",6) == 0)
return(MagickTrue);
return(MagickFalse);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e a d H D R I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ReadHDRImage() reads the Radiance RGBE image format and returns it. It
% allocates the memory necessary for the new Image structure and returns a
% pointer to the new image.
%
% The format of the ReadHDRImage method is:
%
% Image *ReadHDRImage(const ImageInfo *image_info,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image_info: the image info.
%
% o exception: return any errors or warnings in this structure.
%
*/
static Image *ReadHDRImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
char
format[MagickPathExtent],
keyword[MagickPathExtent],
tag[MagickPathExtent],
value[MagickPathExtent];
double
gamma;
Image
*image;
int
c;
MagickBooleanType
status,
value_expected;
register Quantum
*q;
register ssize_t
i,
x;
register unsigned char
*p;
ssize_t
count,
y;
unsigned char
*end,
pixel[4],
*pixels;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == 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);
}
/*
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=MagickPathExtent;
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+
MagickPathExtent,sizeof(*comment));
if (comment == (char *) NULL)
break;
p=comment+strlen(comment);
}
*p=(char) c;
}
if (comment == (char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
*p='\0';
(void) SetImageProperty(image,"comment",comment,exception);
comment=DestroyString(comment);
c=ReadBlobByte(image);
}
else
if (isalnum(c) == MagickFalse)
c=ReadBlobByte(image);
else
{
register char
*p;
/*
Determine a keyword and its value.
*/
p=keyword;
do
{
if ((size_t) (p-keyword) < (MagickPathExtent-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') && (c != EOF))
{
if ((size_t) (p-value) < (MagickPathExtent-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,MagickPathExtent);
break;
}
(void) FormatLocaleString(tag,MagickPathExtent,"hdr:%s",keyword);
(void) SetImageProperty(image,tag,value,exception);
break;
}
case 'G':
case 'g':
{
if (LocaleCompare(keyword,"gamma") == 0)
{
image->gamma=StringToDouble(value,(char **) NULL);
break;
}
(void) FormatLocaleString(tag,MagickPathExtent,"hdr:%s",keyword);
(void) SetImageProperty(image,tag,value,exception);
break;
}
case 'P':
case 'p':
{
if (LocaleCompare(keyword,"primaries") == 0)
{
float
chromaticity[6],
white_point[2];
int
count;
count=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]);
if (count == 8)
{
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,MagickPathExtent,"hdr:%s",keyword);
(void) SetImageProperty(image,tag,value,exception);
break;
}
case 'Y':
case 'y':
{
char
target[] = "Y";
if (strcmp(keyword,target) == 0)
{
int
height,
width;
if (sscanf(value,"%d +X %d",&height,&width) == 2)
{
image->columns=(size_t) width;
image->rows=(size_t) height;
}
break;
}
(void) FormatLocaleString(tag,MagickPathExtent,"hdr:%s",keyword);
(void) SetImageProperty(image,tag,value,exception);
break;
}
default:
{
(void) FormatLocaleString(tag,MagickPathExtent,"hdr:%s",keyword);
(void) SetImageProperty(image,tag,value,exception);
break;
}
}
}
if ((image->columns == 0) && (image->rows == 0))
while (isspace((int) ((unsigned char) c)) != 0)
c=ReadBlobByte(image);
}
if ((LocaleCompare(format,"32-bit_rle_rgbe") != 0) &&
(LocaleCompare(format,"32-bit_rle_xyze") != 0))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if ((image->columns == 0) || (image->rows == 0))
ThrowReaderException(CorruptImageError,"NegativeOrZeroImageSize");
(void) SetImageColorspace(image,RGBColorspace,exception);
if (LocaleCompare(format,"32-bit_rle_xyze") == 0)
(void) SetImageColorspace(image,XYZColorspace,exception);
image->compression=(image->columns < 8) || (image->columns > 0x7ffff) ?
NoCompression : RLECompression;
if (image_info->ping != MagickFalse)
{
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
status=SetImageExtent(image,image->columns,image->rows,exception);
if (status == MagickFalse)
return(DestroyImageList(image));
/*
Read RGBE (red+green+blue+exponent) pixels.
*/
pixels=(unsigned char *) AcquireQuantumMemory(image->columns,4*
sizeof(*pixels));
if (pixels == (unsigned char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
for (y=0; y < (ssize_t) image->rows; y++)
{
if (image->compression != RLECompression)
{
count=ReadBlob(image,4*image->columns*sizeof(*pixels),pixels);
if (count != (ssize_t) (4*image->columns*sizeof(*pixels)))
break;
}
else
{
count=ReadBlob(image,4*sizeof(*pixel),pixel);
if (count != 4)
break;
if ((size_t) ((((size_t) pixel[2]) << 8) | pixel[3]) != image->columns)
{
(void) memcpy(pixels,pixel,4*sizeof(*pixel));
count=ReadBlob(image,4*(image->columns-1)*sizeof(*pixels),pixels+4);
image->compression=NoCompression;
}
else
{
p=pixels;
for (i=0; i < 4; i++)
{
end=&pixels[(i+1)*image->columns];
while (p < end)
{
count=ReadBlob(image,2*sizeof(*pixel),pixel);
if (count < 1)
break;
if (pixel[0] > 128)
{
count=(ssize_t) pixel[0]-128;
if ((count == 0) || (count > (ssize_t) (end-p)))
break;
while (count-- > 0)
*p++=pixel[1];
}
else
{
count=(ssize_t) pixel[0];
if ((count == 0) || (count > (ssize_t) (end-p)))
break;
*p++=pixel[1];
if (--count > 0)
{
count=ReadBlob(image,(size_t) count*sizeof(*p),p);
if (count < 1)
break;
p+=count;
}
}
}
}
}
}
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
i=0;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (image->compression == RLECompression)
{
pixel[0]=pixels[x];
pixel[1]=pixels[x+image->columns];
pixel[2]=pixels[x+2*image->columns];
pixel[3]=pixels[x+3*image->columns];
}
else
{
pixel[0]=pixels[i++];
pixel[1]=pixels[i++];
pixel[2]=pixels[i++];
pixel[3]=pixels[i++];
}
SetPixelRed(image,0,q);
SetPixelGreen(image,0,q);
SetPixelBlue(image,0,q);
if (pixel[3] != 0)
{
gamma=pow(2.0,pixel[3]-(128.0+8.0));
SetPixelRed(image,ClampToQuantum(QuantumRange*gamma*pixel[0]),q);
SetPixelGreen(image,ClampToQuantum(QuantumRange*gamma*pixel[1]),q);
SetPixelBlue(image,ClampToQuantum(QuantumRange*gamma*pixel[2]),q);
}
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
pixels=(unsigned char *) RelinquishMagickMemory(pixels);
if (EOFBlob(image) != MagickFalse)
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e g i s t e r H D R I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% RegisterHDRImage() adds attributes for the Radiance RGBE image format to the
% list of supported formats. The attributes include the image format tag, a
% method to read and/or write the format, whether the format supports the
% saving of more than one frame to the same file or blob, whether the format
% supports native in-memory I/O, and a brief description of the format.
%
% The format of the RegisterHDRImage method is:
%
% size_t RegisterHDRImage(void)
%
*/
ModuleExport size_t RegisterHDRImage(void)
{
MagickInfo
*entry;
entry=AcquireMagickInfo("HDR","HDR","Radiance RGBE image format");
entry->decoder=(DecodeImageHandler *) ReadHDRImage;
entry->encoder=(EncodeImageHandler *) WriteHDRImage;
entry->magick=(IsImageFormatHandler *) IsHDR;
(void) RegisterMagickInfo(entry);
return(MagickImageCoderSignature);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% U n r e g i s t e r H D R I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% UnregisterHDRImage() removes format registrations made by the
% HDR module from the list of supported formats.
%
% The format of the UnregisterHDRImage method is:
%
% UnregisterHDRImage(void)
%
*/
ModuleExport void UnregisterHDRImage(void)
{
(void) UnregisterMagickInfo("HDR");
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% W r i t e H D R I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% WriteHDRImage() writes an image in the Radience RGBE image format.
%
% The format of the WriteHDRImage method is:
%
% MagickBooleanType WriteHDRImage(const ImageInfo *image_info,
% Image *image,ExceptionInfo *exception)
%
% A description of each parameter follows.
%
% o image_info: the image info.
%
% o image: The image.
%
*/
static size_t HDRWriteRunlengthPixels(Image *image,unsigned char *pixels)
{
#define MinimumRunlength 4
register size_t
p,
q;
size_t
runlength;
ssize_t
count,
previous_count;
unsigned char
pixel[2];
for (p=0; p < image->columns; )
{
q=p;
runlength=0;
previous_count=0;
while ((runlength < MinimumRunlength) && (q < image->columns))
{
q+=runlength;
previous_count=(ssize_t) runlength;
runlength=1;
while ((pixels[q] == pixels[q+runlength]) &&
((q+runlength) < image->columns) && (runlength < 127))
runlength++;
}
if ((previous_count > 1) && (previous_count == (ssize_t) (q-p)))
{
pixel[0]=(unsigned char) (128+previous_count);
pixel[1]=pixels[p];
if (WriteBlob(image,2*sizeof(*pixel),pixel) < 1)
break;
p=q;
}
while (p < q)
{
count=(ssize_t) (q-p);
if (count > 128)
count=128;
pixel[0]=(unsigned char) count;
if (WriteBlob(image,sizeof(*pixel),pixel) < 1)
break;
if (WriteBlob(image,(size_t) count*sizeof(*pixel),&pixels[p]) < 1)
break;
p+=count;
}
if (runlength >= MinimumRunlength)
{
pixel[0]=(unsigned char) (128+runlength);
pixel[1]=pixels[q];
if (WriteBlob(image,2*sizeof(*pixel),pixel) < 1)
break;
p+=runlength;
}
}
return(p);
}
static MagickBooleanType WriteHDRImage(const ImageInfo *image_info,Image *image,
ExceptionInfo *exception)
{
char
header[MagickPathExtent];
const char
*property;
MagickBooleanType
status;
register const Quantum
*p;
register ssize_t
i,
x;
size_t
length;
ssize_t
count,
y;
unsigned char
pixel[4],
*pixels;
/*
Open output image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception);
if (status == MagickFalse)
return(status);
if (IsRGBColorspace(image->colorspace) == MagickFalse)
(void) TransformImageColorspace(image,RGBColorspace,exception);
/*
Write header.
*/
(void) ResetMagickMemory(header,' ',MagickPathExtent);
length=CopyMagickString(header,"#?RGBE\n",MagickPathExtent);
(void) WriteBlob(image,length,(unsigned char *) header);
property=GetImageProperty(image,"comment",exception);
if ((property != (const char *) NULL) &&
(strchr(property,'\n') == (char *) NULL))
{
count=FormatLocaleString(header,MagickPathExtent,"#%s\n",property);
(void) WriteBlob(image,(size_t) count,(unsigned char *) header);
}
property=GetImageProperty(image,"hdr:exposure",exception);
if (property != (const char *) NULL)
{
count=FormatLocaleString(header,MagickPathExtent,"EXPOSURE=%g\n",
strtod(property,(char **) NULL));
(void) WriteBlob(image,(size_t) count,(unsigned char *) header);
}
if (image->gamma != 0.0)
{
count=FormatLocaleString(header,MagickPathExtent,"GAMMA=%g\n",
image->gamma);
(void) WriteBlob(image,(size_t) count,(unsigned char *) header);
}
count=FormatLocaleString(header,MagickPathExtent,
"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",MagickPathExtent);
(void) WriteBlob(image,length,(unsigned char *) header);
count=FormatLocaleString(header,MagickPathExtent,"-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+128,4*
sizeof(*pixels));
if (pixels == (unsigned char *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
(void) ResetMagickMemory(pixels,0,4*(image->columns+128)*sizeof(*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->columns >= 8) && (image->columns <= 0x7ffff))
{
pixel[0]=2;
pixel[1]=2;
pixel[2]=(unsigned char) (image->columns >> 8);
pixel[3]=(unsigned char) (image->columns & 0xff);
count=WriteBlob(image,4*sizeof(*pixel),pixel);
if (count != (ssize_t) (4*sizeof(*pixel)))
break;
}
i=0;
for (x=0; x < (ssize_t) image->columns; x++)
{
double
gamma;
pixel[0]=0;
pixel[1]=0;
pixel[2]=0;
pixel[3]=0;
gamma=QuantumScale*GetPixelRed(image,p);
if ((QuantumScale*GetPixelGreen(image,p)) > gamma)
gamma=QuantumScale*GetPixelGreen(image,p);
if ((QuantumScale*GetPixelBlue(image,p)) > gamma)
gamma=QuantumScale*GetPixelBlue(image,p);
if (gamma > MagickEpsilon)
{
int
exponent;
gamma=frexp(gamma,&exponent)*256.0/gamma;
pixel[0]=(unsigned char) (gamma*QuantumScale*GetPixelRed(image,p));
pixel[1]=(unsigned char) (gamma*QuantumScale*GetPixelGreen(image,p));
pixel[2]=(unsigned char) (gamma*QuantumScale*GetPixelBlue(image,p));
pixel[3]=(unsigned char) (exponent+128);
}
if ((image->columns >= 8) && (image->columns <= 0x7ffff))
{
pixels[x]=pixel[0];
pixels[x+image->columns]=pixel[1];
pixels[x+2*image->columns]=pixel[2];
pixels[x+3*image->columns]=pixel[3];
}
else
{
pixels[i++]=pixel[0];
pixels[i++]=pixel[1];
pixels[i++]=pixel[2];
pixels[i++]=pixel[3];
}
p+=GetPixelChannels(image);
}
if ((image->columns >= 8) && (image->columns <= 0x7ffff))
{
for (i=0; i < 4; i++)
length=HDRWriteRunlengthPixels(image,&pixels[i*image->columns]);
}
else
{
count=WriteBlob(image,4*image->columns*sizeof(*pixels),pixels);
if (count != (ssize_t) (4*image->columns*sizeof(*pixels)))
break;
}
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
pixels=(unsigned char *) RelinquishMagickMemory(pixels);
(void) CloseBlob(image);
return(MagickTrue);
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/good_5298_0 |
crossvul-cpp_data_bad_2697_0 | /*
* Copyright (c) 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997
* The Regents of the University of California. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that: (1) source code distributions
* retain the above copyright notice and this paragraph in its entirety, (2)
* distributions including binary code include the above copyright notice and
* this paragraph in its entirety in the documentation or other materials
* provided with the distribution, and (3) all advertising materials mentioning
* features or use of this software display the following acknowledgement:
* ``This product includes software developed by the University of California,
* Lawrence Berkeley Laboratory and its contributors.'' Neither the name of
* the University nor the names of its contributors may be used to endorse
* or promote products derived from this software without specific prior
* written permission.
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
/* \summary: IP printer */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <netdissect-stdinc.h>
#include <string.h>
#include "netdissect.h"
#include "addrtoname.h"
#include "extract.h"
#include "ip.h"
#include "ipproto.h"
static const char tstr[] = "[|ip]";
static const struct tok ip_option_values[] = {
{ IPOPT_EOL, "EOL" },
{ IPOPT_NOP, "NOP" },
{ IPOPT_TS, "timestamp" },
{ IPOPT_SECURITY, "security" },
{ IPOPT_RR, "RR" },
{ IPOPT_SSRR, "SSRR" },
{ IPOPT_LSRR, "LSRR" },
{ IPOPT_RA, "RA" },
{ IPOPT_RFC1393, "traceroute" },
{ 0, NULL }
};
/*
* print the recorded route in an IP RR, LSRR or SSRR option.
*/
static void
ip_printroute(netdissect_options *ndo,
register const u_char *cp, u_int length)
{
register u_int ptr;
register u_int len;
if (length < 3) {
ND_PRINT((ndo, " [bad length %u]", length));
return;
}
if ((length + 1) & 3)
ND_PRINT((ndo, " [bad length %u]", length));
ptr = cp[2] - 1;
if (ptr < 3 || ((ptr + 1) & 3) || ptr > length + 1)
ND_PRINT((ndo, " [bad ptr %u]", cp[2]));
for (len = 3; len < length; len += 4) {
ND_PRINT((ndo, " %s", ipaddr_string(ndo, &cp[len])));
if (ptr > len)
ND_PRINT((ndo, ","));
}
}
/*
* If source-routing is present and valid, return the final destination.
* Otherwise, return IP destination.
*
* This is used for UDP and TCP pseudo-header in the checksum
* calculation.
*/
static uint32_t
ip_finddst(netdissect_options *ndo,
const struct ip *ip)
{
int length;
int len;
const u_char *cp;
uint32_t retval;
cp = (const u_char *)(ip + 1);
length = (IP_HL(ip) << 2) - sizeof(struct ip);
for (; length > 0; cp += len, length -= len) {
int tt;
ND_TCHECK(*cp);
tt = *cp;
if (tt == IPOPT_EOL)
break;
else if (tt == IPOPT_NOP)
len = 1;
else {
ND_TCHECK(cp[1]);
len = cp[1];
if (len < 2)
break;
}
ND_TCHECK2(*cp, len);
switch (tt) {
case IPOPT_SSRR:
case IPOPT_LSRR:
if (len < 7)
break;
UNALIGNED_MEMCPY(&retval, cp + len - 4, 4);
return retval;
}
}
trunc:
UNALIGNED_MEMCPY(&retval, &ip->ip_dst, sizeof(uint32_t));
return retval;
}
/*
* Compute a V4-style checksum by building a pseudoheader.
*/
int
nextproto4_cksum(netdissect_options *ndo,
const struct ip *ip, const uint8_t *data,
u_int len, u_int covlen, u_int next_proto)
{
struct phdr {
uint32_t src;
uint32_t dst;
u_char mbz;
u_char proto;
uint16_t len;
} ph;
struct cksum_vec vec[2];
/* pseudo-header.. */
ph.len = htons((uint16_t)len);
ph.mbz = 0;
ph.proto = next_proto;
UNALIGNED_MEMCPY(&ph.src, &ip->ip_src, sizeof(uint32_t));
if (IP_HL(ip) == 5)
UNALIGNED_MEMCPY(&ph.dst, &ip->ip_dst, sizeof(uint32_t));
else
ph.dst = ip_finddst(ndo, ip);
vec[0].ptr = (const uint8_t *)(void *)&ph;
vec[0].len = sizeof(ph);
vec[1].ptr = data;
vec[1].len = covlen;
return (in_cksum(vec, 2));
}
static void
ip_printts(netdissect_options *ndo,
register const u_char *cp, u_int length)
{
register u_int ptr;
register u_int len;
int hoplen;
const char *type;
if (length < 4) {
ND_PRINT((ndo, "[bad length %u]", length));
return;
}
ND_PRINT((ndo, " TS{"));
hoplen = ((cp[3]&0xF) != IPOPT_TS_TSONLY) ? 8 : 4;
if ((length - 4) & (hoplen-1))
ND_PRINT((ndo, "[bad length %u]", length));
ptr = cp[2] - 1;
len = 0;
if (ptr < 4 || ((ptr - 4) & (hoplen-1)) || ptr > length + 1)
ND_PRINT((ndo, "[bad ptr %u]", cp[2]));
switch (cp[3]&0xF) {
case IPOPT_TS_TSONLY:
ND_PRINT((ndo, "TSONLY"));
break;
case IPOPT_TS_TSANDADDR:
ND_PRINT((ndo, "TS+ADDR"));
break;
/*
* prespecified should really be 3, but some ones might send 2
* instead, and the IPOPT_TS_PRESPEC constant can apparently
* have both values, so we have to hard-code it here.
*/
case 2:
ND_PRINT((ndo, "PRESPEC2.0"));
break;
case 3: /* IPOPT_TS_PRESPEC */
ND_PRINT((ndo, "PRESPEC"));
break;
default:
ND_PRINT((ndo, "[bad ts type %d]", cp[3]&0xF));
goto done;
}
type = " ";
for (len = 4; len < length; len += hoplen) {
if (ptr == len)
type = " ^ ";
ND_PRINT((ndo, "%s%d@%s", type, EXTRACT_32BITS(&cp[len+hoplen-4]),
hoplen!=8 ? "" : ipaddr_string(ndo, &cp[len])));
type = " ";
}
done:
ND_PRINT((ndo, "%s", ptr == len ? " ^ " : ""));
if (cp[3]>>4)
ND_PRINT((ndo, " [%d hops not recorded]} ", cp[3]>>4));
else
ND_PRINT((ndo, "}"));
}
/*
* print IP options.
*/
static void
ip_optprint(netdissect_options *ndo,
register const u_char *cp, u_int length)
{
register u_int option_len;
const char *sep = "";
for (; length > 0; cp += option_len, length -= option_len) {
u_int option_code;
ND_PRINT((ndo, "%s", sep));
sep = ",";
ND_TCHECK(*cp);
option_code = *cp;
ND_PRINT((ndo, "%s",
tok2str(ip_option_values,"unknown %u",option_code)));
if (option_code == IPOPT_NOP ||
option_code == IPOPT_EOL)
option_len = 1;
else {
ND_TCHECK(cp[1]);
option_len = cp[1];
if (option_len < 2) {
ND_PRINT((ndo, " [bad length %u]", option_len));
return;
}
}
if (option_len > length) {
ND_PRINT((ndo, " [bad length %u]", option_len));
return;
}
ND_TCHECK2(*cp, option_len);
switch (option_code) {
case IPOPT_EOL:
return;
case IPOPT_TS:
ip_printts(ndo, cp, option_len);
break;
case IPOPT_RR: /* fall through */
case IPOPT_SSRR:
case IPOPT_LSRR:
ip_printroute(ndo, cp, option_len);
break;
case IPOPT_RA:
if (option_len < 4) {
ND_PRINT((ndo, " [bad length %u]", option_len));
break;
}
ND_TCHECK(cp[3]);
if (EXTRACT_16BITS(&cp[2]) != 0)
ND_PRINT((ndo, " value %u", EXTRACT_16BITS(&cp[2])));
break;
case IPOPT_NOP: /* nothing to print - fall through */
case IPOPT_SECURITY:
default:
break;
}
}
return;
trunc:
ND_PRINT((ndo, "%s", tstr));
}
#define IP_RES 0x8000
static const struct tok ip_frag_values[] = {
{ IP_MF, "+" },
{ IP_DF, "DF" },
{ IP_RES, "rsvd" }, /* The RFC3514 evil ;-) bit */
{ 0, NULL }
};
struct ip_print_demux_state {
const struct ip *ip;
const u_char *cp;
u_int len, off;
u_char nh;
int advance;
};
static void
ip_print_demux(netdissect_options *ndo,
struct ip_print_demux_state *ipds)
{
const char *p_name;
again:
switch (ipds->nh) {
case IPPROTO_AH:
if (!ND_TTEST(*ipds->cp)) {
ND_PRINT((ndo, "[|AH]"));
break;
}
ipds->nh = *ipds->cp;
ipds->advance = ah_print(ndo, ipds->cp);
if (ipds->advance <= 0)
break;
ipds->cp += ipds->advance;
ipds->len -= ipds->advance;
goto again;
case IPPROTO_ESP:
{
int enh, padlen;
ipds->advance = esp_print(ndo, ipds->cp, ipds->len,
(const u_char *)ipds->ip,
&enh, &padlen);
if (ipds->advance <= 0)
break;
ipds->cp += ipds->advance;
ipds->len -= ipds->advance + padlen;
ipds->nh = enh & 0xff;
goto again;
}
case IPPROTO_IPCOMP:
{
ipcomp_print(ndo, ipds->cp);
/*
* Either this has decompressed the payload and
* printed it, in which case there's nothing more
* to do, or it hasn't, in which case there's
* nothing more to do.
*/
break;
}
case IPPROTO_SCTP:
sctp_print(ndo, ipds->cp, (const u_char *)ipds->ip, ipds->len);
break;
case IPPROTO_DCCP:
dccp_print(ndo, ipds->cp, (const u_char *)ipds->ip, ipds->len);
break;
case IPPROTO_TCP:
/* pass on the MF bit plus the offset to detect fragments */
tcp_print(ndo, ipds->cp, ipds->len, (const u_char *)ipds->ip,
ipds->off & (IP_MF|IP_OFFMASK));
break;
case IPPROTO_UDP:
/* pass on the MF bit plus the offset to detect fragments */
udp_print(ndo, ipds->cp, ipds->len, (const u_char *)ipds->ip,
ipds->off & (IP_MF|IP_OFFMASK));
break;
case IPPROTO_ICMP:
/* pass on the MF bit plus the offset to detect fragments */
icmp_print(ndo, ipds->cp, ipds->len, (const u_char *)ipds->ip,
ipds->off & (IP_MF|IP_OFFMASK));
break;
case IPPROTO_PIGP:
/*
* XXX - the current IANA protocol number assignments
* page lists 9 as "any private interior gateway
* (used by Cisco for their IGRP)" and 88 as
* "EIGRP" from Cisco.
*
* Recent BSD <netinet/in.h> headers define
* IP_PROTO_PIGP as 9 and IP_PROTO_IGRP as 88.
* We define IP_PROTO_PIGP as 9 and
* IP_PROTO_EIGRP as 88; those names better
* match was the current protocol number
* assignments say.
*/
igrp_print(ndo, ipds->cp, ipds->len);
break;
case IPPROTO_EIGRP:
eigrp_print(ndo, ipds->cp, ipds->len);
break;
case IPPROTO_ND:
ND_PRINT((ndo, " nd %d", ipds->len));
break;
case IPPROTO_EGP:
egp_print(ndo, ipds->cp, ipds->len);
break;
case IPPROTO_OSPF:
ospf_print(ndo, ipds->cp, ipds->len, (const u_char *)ipds->ip);
break;
case IPPROTO_IGMP:
igmp_print(ndo, ipds->cp, ipds->len);
break;
case IPPROTO_IPV4:
/* DVMRP multicast tunnel (ip-in-ip encapsulation) */
ip_print(ndo, ipds->cp, ipds->len);
if (! ndo->ndo_vflag) {
ND_PRINT((ndo, " (ipip-proto-4)"));
return;
}
break;
case IPPROTO_IPV6:
/* ip6-in-ip encapsulation */
ip6_print(ndo, ipds->cp, ipds->len);
break;
case IPPROTO_RSVP:
rsvp_print(ndo, ipds->cp, ipds->len);
break;
case IPPROTO_GRE:
/* do it */
gre_print(ndo, ipds->cp, ipds->len);
break;
case IPPROTO_MOBILE:
mobile_print(ndo, ipds->cp, ipds->len);
break;
case IPPROTO_PIM:
pim_print(ndo, ipds->cp, ipds->len, (const u_char *)ipds->ip);
break;
case IPPROTO_VRRP:
if (ndo->ndo_packettype == PT_CARP) {
if (ndo->ndo_vflag)
ND_PRINT((ndo, "carp %s > %s: ",
ipaddr_string(ndo, &ipds->ip->ip_src),
ipaddr_string(ndo, &ipds->ip->ip_dst)));
carp_print(ndo, ipds->cp, ipds->len, ipds->ip->ip_ttl);
} else {
if (ndo->ndo_vflag)
ND_PRINT((ndo, "vrrp %s > %s: ",
ipaddr_string(ndo, &ipds->ip->ip_src),
ipaddr_string(ndo, &ipds->ip->ip_dst)));
vrrp_print(ndo, ipds->cp, ipds->len,
(const u_char *)ipds->ip, ipds->ip->ip_ttl);
}
break;
case IPPROTO_PGM:
pgm_print(ndo, ipds->cp, ipds->len, (const u_char *)ipds->ip);
break;
default:
if (ndo->ndo_nflag==0 && (p_name = netdb_protoname(ipds->nh)) != NULL)
ND_PRINT((ndo, " %s", p_name));
else
ND_PRINT((ndo, " ip-proto-%d", ipds->nh));
ND_PRINT((ndo, " %d", ipds->len));
break;
}
}
void
ip_print_inner(netdissect_options *ndo,
const u_char *bp,
u_int length, u_int nh,
const u_char *bp2)
{
struct ip_print_demux_state ipd;
ipd.ip = (const struct ip *)bp2;
ipd.cp = bp;
ipd.len = length;
ipd.off = 0;
ipd.nh = nh;
ipd.advance = 0;
ip_print_demux(ndo, &ipd);
}
/*
* print an IP datagram.
*/
void
ip_print(netdissect_options *ndo,
const u_char *bp,
u_int length)
{
struct ip_print_demux_state ipd;
struct ip_print_demux_state *ipds=&ipd;
const u_char *ipend;
u_int hlen;
struct cksum_vec vec[1];
uint16_t sum, ip_sum;
const char *p_name;
ipds->ip = (const struct ip *)bp;
ND_TCHECK(ipds->ip->ip_vhl);
if (IP_V(ipds->ip) != 4) { /* print version and fail if != 4 */
if (IP_V(ipds->ip) == 6)
ND_PRINT((ndo, "IP6, wrong link-layer encapsulation "));
else
ND_PRINT((ndo, "IP%u ", IP_V(ipds->ip)));
return;
}
if (!ndo->ndo_eflag)
ND_PRINT((ndo, "IP "));
ND_TCHECK(*ipds->ip);
if (length < sizeof (struct ip)) {
ND_PRINT((ndo, "truncated-ip %u", length));
return;
}
hlen = IP_HL(ipds->ip) * 4;
if (hlen < sizeof (struct ip)) {
ND_PRINT((ndo, "bad-hlen %u", hlen));
return;
}
ipds->len = EXTRACT_16BITS(&ipds->ip->ip_len);
if (length < ipds->len)
ND_PRINT((ndo, "truncated-ip - %u bytes missing! ",
ipds->len - length));
if (ipds->len < hlen) {
#ifdef GUESS_TSO
if (ipds->len) {
ND_PRINT((ndo, "bad-len %u", ipds->len));
return;
}
else {
/* we guess that it is a TSO send */
ipds->len = length;
}
#else
ND_PRINT((ndo, "bad-len %u", ipds->len));
return;
#endif /* GUESS_TSO */
}
/*
* Cut off the snapshot length to the end of the IP payload.
*/
ipend = bp + ipds->len;
if (ipend < ndo->ndo_snapend)
ndo->ndo_snapend = ipend;
ipds->len -= hlen;
ipds->off = EXTRACT_16BITS(&ipds->ip->ip_off);
if (ndo->ndo_vflag) {
ND_PRINT((ndo, "(tos 0x%x", (int)ipds->ip->ip_tos));
/* ECN bits */
switch (ipds->ip->ip_tos & 0x03) {
case 0:
break;
case 1:
ND_PRINT((ndo, ",ECT(1)"));
break;
case 2:
ND_PRINT((ndo, ",ECT(0)"));
break;
case 3:
ND_PRINT((ndo, ",CE"));
break;
}
if (ipds->ip->ip_ttl >= 1)
ND_PRINT((ndo, ", ttl %u", ipds->ip->ip_ttl));
/*
* for the firewall guys, print id, offset.
* On all but the last stick a "+" in the flags portion.
* For unfragmented datagrams, note the don't fragment flag.
*/
ND_PRINT((ndo, ", id %u, offset %u, flags [%s], proto %s (%u)",
EXTRACT_16BITS(&ipds->ip->ip_id),
(ipds->off & 0x1fff) * 8,
bittok2str(ip_frag_values, "none", ipds->off&0xe000),
tok2str(ipproto_values,"unknown",ipds->ip->ip_p),
ipds->ip->ip_p));
ND_PRINT((ndo, ", length %u", EXTRACT_16BITS(&ipds->ip->ip_len)));
if ((hlen - sizeof(struct ip)) > 0) {
ND_PRINT((ndo, ", options ("));
ip_optprint(ndo, (const u_char *)(ipds->ip + 1), hlen - sizeof(struct ip));
ND_PRINT((ndo, ")"));
}
if (!ndo->ndo_Kflag && (const u_char *)ipds->ip + hlen <= ndo->ndo_snapend) {
vec[0].ptr = (const uint8_t *)(const void *)ipds->ip;
vec[0].len = hlen;
sum = in_cksum(vec, 1);
if (sum != 0) {
ip_sum = EXTRACT_16BITS(&ipds->ip->ip_sum);
ND_PRINT((ndo, ", bad cksum %x (->%x)!", ip_sum,
in_cksum_shouldbe(ip_sum, sum)));
}
}
ND_PRINT((ndo, ")\n "));
}
/*
* If this is fragment zero, hand it to the next higher
* level protocol.
*/
if ((ipds->off & 0x1fff) == 0) {
ipds->cp = (const u_char *)ipds->ip + hlen;
ipds->nh = ipds->ip->ip_p;
if (ipds->nh != IPPROTO_TCP && ipds->nh != IPPROTO_UDP &&
ipds->nh != IPPROTO_SCTP && ipds->nh != IPPROTO_DCCP) {
ND_PRINT((ndo, "%s > %s: ",
ipaddr_string(ndo, &ipds->ip->ip_src),
ipaddr_string(ndo, &ipds->ip->ip_dst)));
}
ip_print_demux(ndo, ipds);
} else {
/*
* Ultra quiet now means that all this stuff should be
* suppressed.
*/
if (ndo->ndo_qflag > 1)
return;
/*
* This isn't the first frag, so we're missing the
* next level protocol header. print the ip addr
* and the protocol.
*/
ND_PRINT((ndo, "%s > %s:", ipaddr_string(ndo, &ipds->ip->ip_src),
ipaddr_string(ndo, &ipds->ip->ip_dst)));
if (!ndo->ndo_nflag && (p_name = netdb_protoname(ipds->ip->ip_p)) != NULL)
ND_PRINT((ndo, " %s", p_name));
else
ND_PRINT((ndo, " ip-proto-%d", ipds->ip->ip_p));
}
return;
trunc:
ND_PRINT((ndo, "%s", tstr));
return;
}
void
ipN_print(netdissect_options *ndo, register const u_char *bp, register u_int length)
{
if (length < 1) {
ND_PRINT((ndo, "truncated-ip %d", length));
return;
}
ND_TCHECK(*bp);
switch (*bp & 0xF0) {
case 0x40:
ip_print (ndo, bp, length);
break;
case 0x60:
ip6_print (ndo, bp, length);
break;
default:
ND_PRINT((ndo, "unknown ip %d", (*bp & 0xF0) >> 4));
break;
}
return;
trunc:
ND_PRINT((ndo, "%s", tstr));
return;
}
/*
* Local Variables:
* c-style: whitesmith
* c-basic-offset: 8
* End:
*/
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_2697_0 |
crossvul-cpp_data_good_3944_0 | /**
* WinPR: Windows Portable Runtime
* NTLM Security Package (Message)
*
* Copyright 2011-2014 Marc-Andre Moreau <marcandre.moreau@gmail.com>
*
* 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 HAVE_CONFIG_H
#include "config.h"
#endif
#include "ntlm.h"
#include "../sspi.h"
#include <winpr/crt.h>
#include <winpr/print.h>
#include <winpr/stream.h>
#include <winpr/sysinfo.h>
#include "ntlm_compute.h"
#include "ntlm_message.h"
#include "../log.h"
#define TAG WINPR_TAG("sspi.NTLM")
static const char NTLM_SIGNATURE[8] = { 'N', 'T', 'L', 'M', 'S', 'S', 'P', '\0' };
#ifdef WITH_DEBUG_NTLM
static const char* const NTLM_NEGOTIATE_STRINGS[] = { "NTLMSSP_NEGOTIATE_56",
"NTLMSSP_NEGOTIATE_KEY_EXCH",
"NTLMSSP_NEGOTIATE_128",
"NTLMSSP_RESERVED1",
"NTLMSSP_RESERVED2",
"NTLMSSP_RESERVED3",
"NTLMSSP_NEGOTIATE_VERSION",
"NTLMSSP_RESERVED4",
"NTLMSSP_NEGOTIATE_TARGET_INFO",
"NTLMSSP_REQUEST_NON_NT_SESSION_KEY",
"NTLMSSP_RESERVED5",
"NTLMSSP_NEGOTIATE_IDENTIFY",
"NTLMSSP_NEGOTIATE_EXTENDED_SESSION_SECURITY",
"NTLMSSP_RESERVED6",
"NTLMSSP_TARGET_TYPE_SERVER",
"NTLMSSP_TARGET_TYPE_DOMAIN",
"NTLMSSP_NEGOTIATE_ALWAYS_SIGN",
"NTLMSSP_RESERVED7",
"NTLMSSP_NEGOTIATE_WORKSTATION_SUPPLIED",
"NTLMSSP_NEGOTIATE_DOMAIN_SUPPLIED",
"NTLMSSP_NEGOTIATE_ANONYMOUS",
"NTLMSSP_RESERVED8",
"NTLMSSP_NEGOTIATE_NTLM",
"NTLMSSP_RESERVED9",
"NTLMSSP_NEGOTIATE_LM_KEY",
"NTLMSSP_NEGOTIATE_DATAGRAM",
"NTLMSSP_NEGOTIATE_SEAL",
"NTLMSSP_NEGOTIATE_SIGN",
"NTLMSSP_RESERVED10",
"NTLMSSP_REQUEST_TARGET",
"NTLMSSP_NEGOTIATE_OEM",
"NTLMSSP_NEGOTIATE_UNICODE" };
static void ntlm_print_negotiate_flags(UINT32 flags)
{
int i;
const char* str;
WLog_INFO(TAG, "negotiateFlags \"0x%08" PRIX32 "\"", flags);
for (i = 31; i >= 0; i--)
{
if ((flags >> i) & 1)
{
str = NTLM_NEGOTIATE_STRINGS[(31 - i)];
WLog_INFO(TAG, "\t%s (%d),", str, (31 - i));
}
}
}
#endif
static int ntlm_read_message_header(wStream* s, NTLM_MESSAGE_HEADER* header)
{
if (Stream_GetRemainingLength(s) < 12)
return -1;
Stream_Read(s, header->Signature, 8);
Stream_Read_UINT32(s, header->MessageType);
if (strncmp((char*)header->Signature, NTLM_SIGNATURE, 8) != 0)
return -1;
return 1;
}
static void ntlm_write_message_header(wStream* s, NTLM_MESSAGE_HEADER* header)
{
Stream_Write(s, header->Signature, sizeof(NTLM_SIGNATURE));
Stream_Write_UINT32(s, header->MessageType);
}
static void ntlm_populate_message_header(NTLM_MESSAGE_HEADER* header, UINT32 MessageType)
{
CopyMemory(header->Signature, NTLM_SIGNATURE, sizeof(NTLM_SIGNATURE));
header->MessageType = MessageType;
}
static int ntlm_read_message_fields(wStream* s, NTLM_MESSAGE_FIELDS* fields)
{
if (Stream_GetRemainingLength(s) < 8)
return -1;
Stream_Read_UINT16(s, fields->Len); /* Len (2 bytes) */
Stream_Read_UINT16(s, fields->MaxLen); /* MaxLen (2 bytes) */
Stream_Read_UINT32(s, fields->BufferOffset); /* BufferOffset (4 bytes) */
return 1;
}
static void ntlm_write_message_fields(wStream* s, NTLM_MESSAGE_FIELDS* fields)
{
if (fields->MaxLen < 1)
fields->MaxLen = fields->Len;
Stream_Write_UINT16(s, fields->Len); /* Len (2 bytes) */
Stream_Write_UINT16(s, fields->MaxLen); /* MaxLen (2 bytes) */
Stream_Write_UINT32(s, fields->BufferOffset); /* BufferOffset (4 bytes) */
}
static int ntlm_read_message_fields_buffer(wStream* s, NTLM_MESSAGE_FIELDS* fields)
{
if (fields->Len > 0)
{
const UINT32 offset = fields->BufferOffset + fields->Len;
if (fields->BufferOffset > UINT32_MAX - fields->Len)
return -1;
if (offset > Stream_Length(s))
return -1;
fields->Buffer = (PBYTE)malloc(fields->Len);
if (!fields->Buffer)
return -1;
Stream_SetPosition(s, fields->BufferOffset);
Stream_Read(s, fields->Buffer, fields->Len);
}
return 1;
}
static void ntlm_write_message_fields_buffer(wStream* s, NTLM_MESSAGE_FIELDS* fields)
{
if (fields->Len > 0)
{
Stream_SetPosition(s, fields->BufferOffset);
Stream_Write(s, fields->Buffer, fields->Len);
}
}
static void ntlm_free_message_fields_buffer(NTLM_MESSAGE_FIELDS* fields)
{
if (fields)
{
if (fields->Buffer)
{
free(fields->Buffer);
fields->Len = 0;
fields->MaxLen = 0;
fields->Buffer = NULL;
fields->BufferOffset = 0;
}
}
}
#ifdef WITH_DEBUG_NTLM
static void ntlm_print_message_fields(NTLM_MESSAGE_FIELDS* fields, const char* name)
{
WLog_DBG(TAG, "%s (Len: %" PRIu16 " MaxLen: %" PRIu16 " BufferOffset: %" PRIu32 ")", name,
fields->Len, fields->MaxLen, fields->BufferOffset);
if (fields->Len > 0)
winpr_HexDump(TAG, WLOG_DEBUG, fields->Buffer, fields->Len);
}
#endif
SECURITY_STATUS ntlm_read_NegotiateMessage(NTLM_CONTEXT* context, PSecBuffer buffer)
{
wStream* s;
size_t length;
NTLM_NEGOTIATE_MESSAGE* message;
message = &context->NEGOTIATE_MESSAGE;
ZeroMemory(message, sizeof(NTLM_NEGOTIATE_MESSAGE));
s = Stream_New((BYTE*)buffer->pvBuffer, buffer->cbBuffer);
if (!s)
return SEC_E_INTERNAL_ERROR;
if (ntlm_read_message_header(s, (NTLM_MESSAGE_HEADER*)message) < 0)
{
Stream_Free(s, FALSE);
return SEC_E_INVALID_TOKEN;
}
if (message->MessageType != MESSAGE_TYPE_NEGOTIATE)
{
Stream_Free(s, FALSE);
return SEC_E_INVALID_TOKEN;
}
if (Stream_GetRemainingLength(s) < 4)
{
Stream_Free(s, FALSE);
return SEC_E_INVALID_TOKEN;
}
Stream_Read_UINT32(s, message->NegotiateFlags); /* NegotiateFlags (4 bytes) */
if (!((message->NegotiateFlags & NTLMSSP_REQUEST_TARGET) &&
(message->NegotiateFlags & NTLMSSP_NEGOTIATE_NTLM) &&
(message->NegotiateFlags & NTLMSSP_NEGOTIATE_UNICODE)))
{
Stream_Free(s, FALSE);
return SEC_E_INVALID_TOKEN;
}
context->NegotiateFlags = message->NegotiateFlags;
/* only set if NTLMSSP_NEGOTIATE_DOMAIN_SUPPLIED is set */
if (ntlm_read_message_fields(s, &(message->DomainName)) < 0) /* DomainNameFields (8 bytes) */
{
Stream_Free(s, FALSE);
return SEC_E_INVALID_TOKEN;
}
/* only set if NTLMSSP_NEGOTIATE_WORKSTATION_SUPPLIED is set */
if (ntlm_read_message_fields(s, &(message->Workstation)) < 0) /* WorkstationFields (8 bytes) */
{
Stream_Free(s, FALSE);
return SEC_E_INVALID_TOKEN;
}
if (message->NegotiateFlags & NTLMSSP_NEGOTIATE_VERSION)
{
if (ntlm_read_version_info(s, &(message->Version)) < 0) /* Version (8 bytes) */
{
Stream_Free(s, FALSE);
return SEC_E_INVALID_TOKEN;
}
}
length = Stream_GetPosition(s);
buffer->cbBuffer = length;
if (!sspi_SecBufferAlloc(&context->NegotiateMessage, length))
{
Stream_Free(s, FALSE);
return SEC_E_INTERNAL_ERROR;
}
CopyMemory(context->NegotiateMessage.pvBuffer, buffer->pvBuffer, buffer->cbBuffer);
context->NegotiateMessage.BufferType = buffer->BufferType;
#ifdef WITH_DEBUG_NTLM
WLog_DBG(TAG, "NEGOTIATE_MESSAGE (length = %" PRIu32 ")", context->NegotiateMessage.cbBuffer);
winpr_HexDump(TAG, WLOG_DEBUG, context->NegotiateMessage.pvBuffer,
context->NegotiateMessage.cbBuffer);
ntlm_print_negotiate_flags(message->NegotiateFlags);
if (message->NegotiateFlags & NTLMSSP_NEGOTIATE_VERSION)
ntlm_print_version_info(&(message->Version));
#endif
context->state = NTLM_STATE_CHALLENGE;
Stream_Free(s, FALSE);
return SEC_I_CONTINUE_NEEDED;
}
SECURITY_STATUS ntlm_write_NegotiateMessage(NTLM_CONTEXT* context, PSecBuffer buffer)
{
wStream* s;
size_t length;
NTLM_NEGOTIATE_MESSAGE* message;
message = &context->NEGOTIATE_MESSAGE;
ZeroMemory(message, sizeof(NTLM_NEGOTIATE_MESSAGE));
s = Stream_New((BYTE*)buffer->pvBuffer, buffer->cbBuffer);
if (!s)
return SEC_E_INTERNAL_ERROR;
ntlm_populate_message_header((NTLM_MESSAGE_HEADER*)message, MESSAGE_TYPE_NEGOTIATE);
if (context->NTLMv2)
{
message->NegotiateFlags |= NTLMSSP_NEGOTIATE_56;
message->NegotiateFlags |= NTLMSSP_NEGOTIATE_VERSION;
message->NegotiateFlags |= NTLMSSP_NEGOTIATE_LM_KEY;
message->NegotiateFlags |= NTLMSSP_NEGOTIATE_OEM;
}
message->NegotiateFlags |= NTLMSSP_NEGOTIATE_KEY_EXCH;
message->NegotiateFlags |= NTLMSSP_NEGOTIATE_128;
message->NegotiateFlags |= NTLMSSP_NEGOTIATE_EXTENDED_SESSION_SECURITY;
message->NegotiateFlags |= NTLMSSP_NEGOTIATE_ALWAYS_SIGN;
message->NegotiateFlags |= NTLMSSP_NEGOTIATE_NTLM;
message->NegotiateFlags |= NTLMSSP_NEGOTIATE_SIGN;
message->NegotiateFlags |= NTLMSSP_REQUEST_TARGET;
message->NegotiateFlags |= NTLMSSP_NEGOTIATE_UNICODE;
if (context->confidentiality)
message->NegotiateFlags |= NTLMSSP_NEGOTIATE_SEAL;
if (context->SendVersionInfo)
message->NegotiateFlags |= NTLMSSP_NEGOTIATE_VERSION;
if (message->NegotiateFlags & NTLMSSP_NEGOTIATE_VERSION)
ntlm_get_version_info(&(message->Version));
context->NegotiateFlags = message->NegotiateFlags;
/* Message Header (12 bytes) */
ntlm_write_message_header(s, (NTLM_MESSAGE_HEADER*)message);
Stream_Write_UINT32(s, message->NegotiateFlags); /* NegotiateFlags (4 bytes) */
/* only set if NTLMSSP_NEGOTIATE_DOMAIN_SUPPLIED is set */
/* DomainNameFields (8 bytes) */
ntlm_write_message_fields(s, &(message->DomainName));
/* only set if NTLMSSP_NEGOTIATE_WORKSTATION_SUPPLIED is set */
/* WorkstationFields (8 bytes) */
ntlm_write_message_fields(s, &(message->Workstation));
if (message->NegotiateFlags & NTLMSSP_NEGOTIATE_VERSION)
ntlm_write_version_info(s, &(message->Version));
length = Stream_GetPosition(s);
buffer->cbBuffer = length;
if (!sspi_SecBufferAlloc(&context->NegotiateMessage, length))
{
Stream_Free(s, FALSE);
return SEC_E_INTERNAL_ERROR;
}
CopyMemory(context->NegotiateMessage.pvBuffer, buffer->pvBuffer, buffer->cbBuffer);
context->NegotiateMessage.BufferType = buffer->BufferType;
#ifdef WITH_DEBUG_NTLM
WLog_DBG(TAG, "NEGOTIATE_MESSAGE (length = %d)", length);
winpr_HexDump(TAG, WLOG_DEBUG, Stream_Buffer(s), length);
if (message->NegotiateFlags & NTLMSSP_NEGOTIATE_VERSION)
ntlm_print_version_info(&(message->Version));
#endif
context->state = NTLM_STATE_CHALLENGE;
Stream_Free(s, FALSE);
return SEC_I_CONTINUE_NEEDED;
}
SECURITY_STATUS ntlm_read_ChallengeMessage(NTLM_CONTEXT* context, PSecBuffer buffer)
{
wStream* s;
int length;
PBYTE StartOffset;
PBYTE PayloadOffset;
NTLM_AV_PAIR* AvTimestamp;
NTLM_CHALLENGE_MESSAGE* message;
ntlm_generate_client_challenge(context);
message = &context->CHALLENGE_MESSAGE;
ZeroMemory(message, sizeof(NTLM_CHALLENGE_MESSAGE));
s = Stream_New((BYTE*)buffer->pvBuffer, buffer->cbBuffer);
if (!s)
return SEC_E_INTERNAL_ERROR;
StartOffset = Stream_Pointer(s);
if (ntlm_read_message_header(s, (NTLM_MESSAGE_HEADER*)message) < 0)
{
Stream_Free(s, FALSE);
return SEC_E_INVALID_TOKEN;
}
if (message->MessageType != MESSAGE_TYPE_CHALLENGE)
{
Stream_Free(s, FALSE);
return SEC_E_INVALID_TOKEN;
}
if (ntlm_read_message_fields(s, &(message->TargetName)) < 0) /* TargetNameFields (8 bytes) */
{
Stream_Free(s, FALSE);
return SEC_E_INVALID_TOKEN;
}
if (Stream_GetRemainingLength(s) < 4)
{
Stream_Free(s, FALSE);
return SEC_E_INVALID_TOKEN;
}
Stream_Read_UINT32(s, message->NegotiateFlags); /* NegotiateFlags (4 bytes) */
context->NegotiateFlags = message->NegotiateFlags;
if (Stream_GetRemainingLength(s) < 8)
{
Stream_Free(s, FALSE);
return SEC_E_INVALID_TOKEN;
}
Stream_Read(s, message->ServerChallenge, 8); /* ServerChallenge (8 bytes) */
CopyMemory(context->ServerChallenge, message->ServerChallenge, 8);
if (Stream_GetRemainingLength(s) < 8)
{
Stream_Free(s, FALSE);
return SEC_E_INVALID_TOKEN;
}
Stream_Read(s, message->Reserved, 8); /* Reserved (8 bytes), should be ignored */
if (ntlm_read_message_fields(s, &(message->TargetInfo)) < 0) /* TargetInfoFields (8 bytes) */
{
Stream_Free(s, FALSE);
return SEC_E_INVALID_TOKEN;
}
if (context->NegotiateFlags & NTLMSSP_NEGOTIATE_VERSION)
{
if (ntlm_read_version_info(s, &(message->Version)) < 0) /* Version (8 bytes) */
{
Stream_Free(s, FALSE);
return SEC_E_INVALID_TOKEN;
}
}
/* Payload (variable) */
PayloadOffset = Stream_Pointer(s);
if (message->TargetName.Len > 0)
{
if (ntlm_read_message_fields_buffer(s, &(message->TargetName)) < 0)
{
Stream_Free(s, FALSE);
return SEC_E_INTERNAL_ERROR;
}
}
if (message->TargetInfo.Len > 0)
{
size_t cbAvTimestamp;
if (ntlm_read_message_fields_buffer(s, &(message->TargetInfo)) < 0)
{
Stream_Free(s, FALSE);
return SEC_E_INTERNAL_ERROR;
}
context->ChallengeTargetInfo.pvBuffer = message->TargetInfo.Buffer;
context->ChallengeTargetInfo.cbBuffer = message->TargetInfo.Len;
AvTimestamp = ntlm_av_pair_get((NTLM_AV_PAIR*)message->TargetInfo.Buffer,
message->TargetInfo.Len, MsvAvTimestamp, &cbAvTimestamp);
if (AvTimestamp)
{
PBYTE ptr = ntlm_av_pair_get_value_pointer(AvTimestamp);
if (!ptr)
return SEC_E_INTERNAL_ERROR;
if (context->NTLMv2)
context->UseMIC = TRUE;
CopyMemory(context->ChallengeTimestamp, ptr, 8);
}
}
length = (PayloadOffset - StartOffset) + message->TargetName.Len + message->TargetInfo.Len;
if (!sspi_SecBufferAlloc(&context->ChallengeMessage, length))
{
Stream_Free(s, FALSE);
return SEC_E_INTERNAL_ERROR;
}
CopyMemory(context->ChallengeMessage.pvBuffer, StartOffset, length);
#ifdef WITH_DEBUG_NTLM
WLog_DBG(TAG, "CHALLENGE_MESSAGE (length = %d)", length);
winpr_HexDump(TAG, WLOG_DEBUG, context->ChallengeMessage.pvBuffer,
context->ChallengeMessage.cbBuffer);
ntlm_print_negotiate_flags(context->NegotiateFlags);
if (context->NegotiateFlags & NTLMSSP_NEGOTIATE_VERSION)
ntlm_print_version_info(&(message->Version));
ntlm_print_message_fields(&(message->TargetName), "TargetName");
ntlm_print_message_fields(&(message->TargetInfo), "TargetInfo");
if (context->ChallengeTargetInfo.cbBuffer > 0)
{
WLog_DBG(TAG, "ChallengeTargetInfo (%" PRIu32 "):", context->ChallengeTargetInfo.cbBuffer);
ntlm_print_av_pair_list(context->ChallengeTargetInfo.pvBuffer,
context->ChallengeTargetInfo.cbBuffer);
}
#endif
/* AV_PAIRs */
if (context->NTLMv2)
{
if (ntlm_construct_authenticate_target_info(context) < 0)
{
Stream_Free(s, FALSE);
return SEC_E_INTERNAL_ERROR;
}
sspi_SecBufferFree(&context->ChallengeTargetInfo);
context->ChallengeTargetInfo.pvBuffer = context->AuthenticateTargetInfo.pvBuffer;
context->ChallengeTargetInfo.cbBuffer = context->AuthenticateTargetInfo.cbBuffer;
}
ntlm_generate_timestamp(context); /* Timestamp */
if (ntlm_compute_lm_v2_response(context) < 0) /* LmChallengeResponse */
{
Stream_Free(s, FALSE);
return SEC_E_INTERNAL_ERROR;
}
if (ntlm_compute_ntlm_v2_response(context) < 0) /* NtChallengeResponse */
{
Stream_Free(s, FALSE);
return SEC_E_INTERNAL_ERROR;
}
ntlm_generate_key_exchange_key(context); /* KeyExchangeKey */
ntlm_generate_random_session_key(context); /* RandomSessionKey */
ntlm_generate_exported_session_key(context); /* ExportedSessionKey */
ntlm_encrypt_random_session_key(context); /* EncryptedRandomSessionKey */
/* Generate signing keys */
ntlm_generate_client_signing_key(context);
ntlm_generate_server_signing_key(context);
/* Generate sealing keys */
ntlm_generate_client_sealing_key(context);
ntlm_generate_server_sealing_key(context);
/* Initialize RC4 seal state using client sealing key */
ntlm_init_rc4_seal_states(context);
#ifdef WITH_DEBUG_NTLM
WLog_DBG(TAG, "ClientChallenge");
winpr_HexDump(TAG, WLOG_DEBUG, context->ClientChallenge, 8);
WLog_DBG(TAG, "ServerChallenge");
winpr_HexDump(TAG, WLOG_DEBUG, context->ServerChallenge, 8);
WLog_DBG(TAG, "SessionBaseKey");
winpr_HexDump(TAG, WLOG_DEBUG, context->SessionBaseKey, 16);
WLog_DBG(TAG, "KeyExchangeKey");
winpr_HexDump(TAG, WLOG_DEBUG, context->KeyExchangeKey, 16);
WLog_DBG(TAG, "ExportedSessionKey");
winpr_HexDump(TAG, WLOG_DEBUG, context->ExportedSessionKey, 16);
WLog_DBG(TAG, "RandomSessionKey");
winpr_HexDump(TAG, WLOG_DEBUG, context->RandomSessionKey, 16);
WLog_DBG(TAG, "ClientSigningKey");
winpr_HexDump(TAG, WLOG_DEBUG, context->ClientSigningKey, 16);
WLog_DBG(TAG, "ClientSealingKey");
winpr_HexDump(TAG, WLOG_DEBUG, context->ClientSealingKey, 16);
WLog_DBG(TAG, "ServerSigningKey");
winpr_HexDump(TAG, WLOG_DEBUG, context->ServerSigningKey, 16);
WLog_DBG(TAG, "ServerSealingKey");
winpr_HexDump(TAG, WLOG_DEBUG, context->ServerSealingKey, 16);
WLog_DBG(TAG, "Timestamp");
winpr_HexDump(TAG, WLOG_DEBUG, context->Timestamp, 8);
#endif
context->state = NTLM_STATE_AUTHENTICATE;
ntlm_free_message_fields_buffer(&(message->TargetName));
Stream_Free(s, FALSE);
return SEC_I_CONTINUE_NEEDED;
}
SECURITY_STATUS ntlm_write_ChallengeMessage(NTLM_CONTEXT* context, PSecBuffer buffer)
{
wStream* s;
size_t length;
UINT32 PayloadOffset;
NTLM_CHALLENGE_MESSAGE* message;
message = &context->CHALLENGE_MESSAGE;
ZeroMemory(message, sizeof(NTLM_CHALLENGE_MESSAGE));
s = Stream_New((BYTE*)buffer->pvBuffer, buffer->cbBuffer);
if (!s)
return SEC_E_INTERNAL_ERROR;
ntlm_get_version_info(&(message->Version)); /* Version */
ntlm_generate_server_challenge(context); /* Server Challenge */
ntlm_generate_timestamp(context); /* Timestamp */
if (ntlm_construct_challenge_target_info(context) < 0) /* TargetInfo */
{
Stream_Free(s, FALSE);
return SEC_E_INTERNAL_ERROR;
}
CopyMemory(message->ServerChallenge, context->ServerChallenge, 8); /* ServerChallenge */
message->NegotiateFlags = context->NegotiateFlags;
ntlm_populate_message_header((NTLM_MESSAGE_HEADER*)message, MESSAGE_TYPE_CHALLENGE);
/* Message Header (12 bytes) */
ntlm_write_message_header(s, (NTLM_MESSAGE_HEADER*)message);
if (message->NegotiateFlags & NTLMSSP_REQUEST_TARGET)
{
message->TargetName.Len = (UINT16)context->TargetName.cbBuffer;
message->TargetName.Buffer = (PBYTE)context->TargetName.pvBuffer;
}
message->NegotiateFlags |= NTLMSSP_NEGOTIATE_TARGET_INFO;
if (message->NegotiateFlags & NTLMSSP_NEGOTIATE_TARGET_INFO)
{
message->TargetInfo.Len = (UINT16)context->ChallengeTargetInfo.cbBuffer;
message->TargetInfo.Buffer = (PBYTE)context->ChallengeTargetInfo.pvBuffer;
}
PayloadOffset = 48;
if (message->NegotiateFlags & NTLMSSP_NEGOTIATE_VERSION)
PayloadOffset += 8;
message->TargetName.BufferOffset = PayloadOffset;
message->TargetInfo.BufferOffset = message->TargetName.BufferOffset + message->TargetName.Len;
/* TargetNameFields (8 bytes) */
ntlm_write_message_fields(s, &(message->TargetName));
Stream_Write_UINT32(s, message->NegotiateFlags); /* NegotiateFlags (4 bytes) */
Stream_Write(s, message->ServerChallenge, 8); /* ServerChallenge (8 bytes) */
Stream_Write(s, message->Reserved, 8); /* Reserved (8 bytes), should be ignored */
/* TargetInfoFields (8 bytes) */
ntlm_write_message_fields(s, &(message->TargetInfo));
if (message->NegotiateFlags & NTLMSSP_NEGOTIATE_VERSION)
ntlm_write_version_info(s, &(message->Version)); /* Version (8 bytes) */
/* Payload (variable) */
if (message->NegotiateFlags & NTLMSSP_REQUEST_TARGET)
ntlm_write_message_fields_buffer(s, &(message->TargetName));
if (message->NegotiateFlags & NTLMSSP_NEGOTIATE_TARGET_INFO)
ntlm_write_message_fields_buffer(s, &(message->TargetInfo));
length = Stream_GetPosition(s);
buffer->cbBuffer = length;
if (!sspi_SecBufferAlloc(&context->ChallengeMessage, length))
{
Stream_Free(s, FALSE);
return SEC_E_INTERNAL_ERROR;
}
CopyMemory(context->ChallengeMessage.pvBuffer, Stream_Buffer(s), length);
#ifdef WITH_DEBUG_NTLM
WLog_DBG(TAG, "CHALLENGE_MESSAGE (length = %d)", length);
winpr_HexDump(TAG, WLOG_DEBUG, context->ChallengeMessage.pvBuffer,
context->ChallengeMessage.cbBuffer);
ntlm_print_negotiate_flags(message->NegotiateFlags);
if (message->NegotiateFlags & NTLMSSP_NEGOTIATE_VERSION)
ntlm_print_version_info(&(message->Version));
ntlm_print_message_fields(&(message->TargetName), "TargetName");
ntlm_print_message_fields(&(message->TargetInfo), "TargetInfo");
#endif
context->state = NTLM_STATE_AUTHENTICATE;
Stream_Free(s, FALSE);
return SEC_I_CONTINUE_NEEDED;
}
SECURITY_STATUS ntlm_read_AuthenticateMessage(NTLM_CONTEXT* context, PSecBuffer buffer)
{
SECURITY_STATUS status = SEC_E_INVALID_TOKEN;
wStream* s;
size_t length;
UINT32 flags = 0;
NTLM_AV_PAIR* AvFlags = NULL;
UINT32 PayloadBufferOffset;
NTLM_AUTHENTICATE_MESSAGE* message;
SSPI_CREDENTIALS* credentials = context->credentials;
message = &context->AUTHENTICATE_MESSAGE;
ZeroMemory(message, sizeof(NTLM_AUTHENTICATE_MESSAGE));
s = Stream_New((BYTE*)buffer->pvBuffer, buffer->cbBuffer);
if (!s)
return SEC_E_INTERNAL_ERROR;
if (ntlm_read_message_header(s, (NTLM_MESSAGE_HEADER*)message) < 0)
goto fail;
if (message->MessageType != MESSAGE_TYPE_AUTHENTICATE)
goto fail;
if (ntlm_read_message_fields(s, &(message->LmChallengeResponse)) <
0) /* LmChallengeResponseFields (8 bytes) */
goto fail;
if (ntlm_read_message_fields(s, &(message->NtChallengeResponse)) <
0) /* NtChallengeResponseFields (8 bytes) */
goto fail;
if (ntlm_read_message_fields(s, &(message->DomainName)) < 0) /* DomainNameFields (8 bytes) */
goto fail;
if (ntlm_read_message_fields(s, &(message->UserName)) < 0) /* UserNameFields (8 bytes) */
goto fail;
if (ntlm_read_message_fields(s, &(message->Workstation)) < 0) /* WorkstationFields (8 bytes) */
goto fail;
if (ntlm_read_message_fields(s, &(message->EncryptedRandomSessionKey)) <
0) /* EncryptedRandomSessionKeyFields (8 bytes) */
goto fail;
if (Stream_GetRemainingLength(s) < 4)
goto fail;
Stream_Read_UINT32(s, message->NegotiateFlags); /* NegotiateFlags (4 bytes) */
context->NegotiateKeyExchange =
(message->NegotiateFlags & NTLMSSP_NEGOTIATE_KEY_EXCH) ? TRUE : FALSE;
if ((context->NegotiateKeyExchange && !message->EncryptedRandomSessionKey.Len) ||
(!context->NegotiateKeyExchange && message->EncryptedRandomSessionKey.Len))
goto fail;
if (message->NegotiateFlags & NTLMSSP_NEGOTIATE_VERSION)
{
if (ntlm_read_version_info(s, &(message->Version)) < 0) /* Version (8 bytes) */
goto fail;
}
PayloadBufferOffset = Stream_GetPosition(s);
status = SEC_E_INTERNAL_ERROR;
if (ntlm_read_message_fields_buffer(s, &(message->DomainName)) < 0) /* DomainName */
goto fail;
if (ntlm_read_message_fields_buffer(s, &(message->UserName)) < 0) /* UserName */
goto fail;
if (ntlm_read_message_fields_buffer(s, &(message->Workstation)) < 0) /* Workstation */
goto fail;
if (ntlm_read_message_fields_buffer(s, &(message->LmChallengeResponse)) <
0) /* LmChallengeResponse */
goto fail;
if (ntlm_read_message_fields_buffer(s, &(message->NtChallengeResponse)) <
0) /* NtChallengeResponse */
goto fail;
if (message->NtChallengeResponse.Len > 0)
{
int rc;
size_t cbAvFlags;
wStream* snt =
Stream_New(message->NtChallengeResponse.Buffer, message->NtChallengeResponse.Len);
if (!snt)
goto fail;
status = SEC_E_INVALID_TOKEN;
rc = ntlm_read_ntlm_v2_response(snt, &(context->NTLMv2Response));
Stream_Free(snt, FALSE);
if (rc < 0)
goto fail;
status = SEC_E_INTERNAL_ERROR;
context->NtChallengeResponse.pvBuffer = message->NtChallengeResponse.Buffer;
context->NtChallengeResponse.cbBuffer = message->NtChallengeResponse.Len;
sspi_SecBufferFree(&(context->ChallengeTargetInfo));
context->ChallengeTargetInfo.pvBuffer = (void*)context->NTLMv2Response.Challenge.AvPairs;
context->ChallengeTargetInfo.cbBuffer = message->NtChallengeResponse.Len - (28 + 16);
CopyMemory(context->ClientChallenge, context->NTLMv2Response.Challenge.ClientChallenge, 8);
AvFlags =
ntlm_av_pair_get(context->NTLMv2Response.Challenge.AvPairs,
context->NTLMv2Response.Challenge.cbAvPairs, MsvAvFlags, &cbAvFlags);
if (AvFlags)
Data_Read_UINT32(ntlm_av_pair_get_value_pointer(AvFlags), flags);
}
if (ntlm_read_message_fields_buffer(s, &(message->EncryptedRandomSessionKey)) <
0) /* EncryptedRandomSessionKey */
goto fail;
if (message->EncryptedRandomSessionKey.Len > 0)
{
if (message->EncryptedRandomSessionKey.Len != 16)
goto fail;
CopyMemory(context->EncryptedRandomSessionKey, message->EncryptedRandomSessionKey.Buffer,
16);
}
length = Stream_GetPosition(s);
if (!sspi_SecBufferAlloc(&context->AuthenticateMessage, length))
goto fail;
CopyMemory(context->AuthenticateMessage.pvBuffer, Stream_Buffer(s), length);
buffer->cbBuffer = length;
Stream_SetPosition(s, PayloadBufferOffset);
if (flags & MSV_AV_FLAGS_MESSAGE_INTEGRITY_CHECK)
{
context->MessageIntegrityCheckOffset = (UINT32)Stream_GetPosition(s);
status = SEC_E_INVALID_TOKEN;
if (Stream_GetRemainingLength(s) < 16)
goto fail;
Stream_Read(s, message->MessageIntegrityCheck, 16);
}
status = SEC_E_INTERNAL_ERROR;
#ifdef WITH_DEBUG_NTLM
WLog_DBG(TAG, "AUTHENTICATE_MESSAGE (length = %" PRIu32 ")",
context->AuthenticateMessage.cbBuffer);
winpr_HexDump(TAG, WLOG_DEBUG, context->AuthenticateMessage.pvBuffer,
context->AuthenticateMessage.cbBuffer);
if (message->NegotiateFlags & NTLMSSP_NEGOTIATE_VERSION)
ntlm_print_version_info(&(message->Version));
ntlm_print_message_fields(&(message->DomainName), "DomainName");
ntlm_print_message_fields(&(message->UserName), "UserName");
ntlm_print_message_fields(&(message->Workstation), "Workstation");
ntlm_print_message_fields(&(message->LmChallengeResponse), "LmChallengeResponse");
ntlm_print_message_fields(&(message->NtChallengeResponse), "NtChallengeResponse");
ntlm_print_message_fields(&(message->EncryptedRandomSessionKey), "EncryptedRandomSessionKey");
ntlm_print_av_pair_list(context->NTLMv2Response.Challenge.AvPairs,
context->NTLMv2Response.Challenge.cbAvPairs);
if (flags & MSV_AV_FLAGS_MESSAGE_INTEGRITY_CHECK)
{
WLog_DBG(TAG, "MessageIntegrityCheck:");
winpr_HexDump(TAG, WLOG_DEBUG, message->MessageIntegrityCheck, 16);
}
#endif
if (message->UserName.Len > 0)
{
credentials->identity.User = (UINT16*)malloc(message->UserName.Len);
if (!credentials->identity.User)
goto fail;
CopyMemory(credentials->identity.User, message->UserName.Buffer, message->UserName.Len);
credentials->identity.UserLength = message->UserName.Len / 2;
}
if (message->DomainName.Len > 0)
{
credentials->identity.Domain = (UINT16*)malloc(message->DomainName.Len);
if (!credentials->identity.Domain)
goto fail;
CopyMemory(credentials->identity.Domain, message->DomainName.Buffer,
message->DomainName.Len);
credentials->identity.DomainLength = message->DomainName.Len / 2;
}
Stream_Free(s, FALSE);
/* Computations beyond this point require the NTLM hash of the password */
context->state = NTLM_STATE_COMPLETION;
return SEC_I_COMPLETE_NEEDED;
fail:
Stream_Free(s, FALSE);
return status;
}
/**
* Send NTLMSSP AUTHENTICATE_MESSAGE.\n
* AUTHENTICATE_MESSAGE @msdn{cc236643}
* @param NTLM context
* @param buffer
*/
SECURITY_STATUS ntlm_write_AuthenticateMessage(NTLM_CONTEXT* context, PSecBuffer buffer)
{
wStream* s;
size_t length;
UINT32 PayloadBufferOffset;
NTLM_AUTHENTICATE_MESSAGE* message;
SSPI_CREDENTIALS* credentials = context->credentials;
message = &context->AUTHENTICATE_MESSAGE;
ZeroMemory(message, sizeof(NTLM_AUTHENTICATE_MESSAGE));
s = Stream_New((BYTE*)buffer->pvBuffer, buffer->cbBuffer);
if (!s)
return SEC_E_INTERNAL_ERROR;
if (context->NTLMv2)
{
message->NegotiateFlags |= NTLMSSP_NEGOTIATE_56;
if (context->SendVersionInfo)
message->NegotiateFlags |= NTLMSSP_NEGOTIATE_VERSION;
}
if (context->UseMIC)
message->NegotiateFlags |= NTLMSSP_NEGOTIATE_TARGET_INFO;
if (context->SendWorkstationName)
message->NegotiateFlags |= NTLMSSP_NEGOTIATE_WORKSTATION_SUPPLIED;
if (context->confidentiality)
message->NegotiateFlags |= NTLMSSP_NEGOTIATE_SEAL;
if (context->CHALLENGE_MESSAGE.NegotiateFlags & NTLMSSP_NEGOTIATE_KEY_EXCH)
message->NegotiateFlags |= NTLMSSP_NEGOTIATE_KEY_EXCH;
message->NegotiateFlags |= NTLMSSP_NEGOTIATE_128;
message->NegotiateFlags |= NTLMSSP_NEGOTIATE_EXTENDED_SESSION_SECURITY;
message->NegotiateFlags |= NTLMSSP_NEGOTIATE_ALWAYS_SIGN;
message->NegotiateFlags |= NTLMSSP_NEGOTIATE_NTLM;
message->NegotiateFlags |= NTLMSSP_NEGOTIATE_SIGN;
message->NegotiateFlags |= NTLMSSP_REQUEST_TARGET;
message->NegotiateFlags |= NTLMSSP_NEGOTIATE_UNICODE;
if (message->NegotiateFlags & NTLMSSP_NEGOTIATE_VERSION)
ntlm_get_version_info(&(message->Version));
if (message->NegotiateFlags & NTLMSSP_NEGOTIATE_WORKSTATION_SUPPLIED)
{
message->Workstation.Len = context->Workstation.Length;
message->Workstation.Buffer = (BYTE*)context->Workstation.Buffer;
}
if (credentials->identity.DomainLength > 0)
{
message->NegotiateFlags |= NTLMSSP_NEGOTIATE_DOMAIN_SUPPLIED;
message->DomainName.Len = (UINT16)credentials->identity.DomainLength * 2;
message->DomainName.Buffer = (BYTE*)credentials->identity.Domain;
}
message->UserName.Len = (UINT16)credentials->identity.UserLength * 2;
message->UserName.Buffer = (BYTE*)credentials->identity.User;
message->LmChallengeResponse.Len = (UINT16)context->LmChallengeResponse.cbBuffer;
message->LmChallengeResponse.Buffer = (BYTE*)context->LmChallengeResponse.pvBuffer;
message->NtChallengeResponse.Len = (UINT16)context->NtChallengeResponse.cbBuffer;
message->NtChallengeResponse.Buffer = (BYTE*)context->NtChallengeResponse.pvBuffer;
if (message->NegotiateFlags & NTLMSSP_NEGOTIATE_KEY_EXCH)
{
message->EncryptedRandomSessionKey.Len = 16;
message->EncryptedRandomSessionKey.Buffer = context->EncryptedRandomSessionKey;
}
PayloadBufferOffset = 64;
if (message->NegotiateFlags & NTLMSSP_NEGOTIATE_VERSION)
PayloadBufferOffset += 8; /* Version (8 bytes) */
if (context->UseMIC)
PayloadBufferOffset += 16; /* Message Integrity Check (16 bytes) */
message->DomainName.BufferOffset = PayloadBufferOffset;
message->UserName.BufferOffset = message->DomainName.BufferOffset + message->DomainName.Len;
message->Workstation.BufferOffset = message->UserName.BufferOffset + message->UserName.Len;
message->LmChallengeResponse.BufferOffset =
message->Workstation.BufferOffset + message->Workstation.Len;
message->NtChallengeResponse.BufferOffset =
message->LmChallengeResponse.BufferOffset + message->LmChallengeResponse.Len;
message->EncryptedRandomSessionKey.BufferOffset =
message->NtChallengeResponse.BufferOffset + message->NtChallengeResponse.Len;
ntlm_populate_message_header((NTLM_MESSAGE_HEADER*)message, MESSAGE_TYPE_AUTHENTICATE);
ntlm_write_message_header(s, (NTLM_MESSAGE_HEADER*)message); /* Message Header (12 bytes) */
ntlm_write_message_fields(
s, &(message->LmChallengeResponse)); /* LmChallengeResponseFields (8 bytes) */
ntlm_write_message_fields(
s, &(message->NtChallengeResponse)); /* NtChallengeResponseFields (8 bytes) */
ntlm_write_message_fields(s, &(message->DomainName)); /* DomainNameFields (8 bytes) */
ntlm_write_message_fields(s, &(message->UserName)); /* UserNameFields (8 bytes) */
ntlm_write_message_fields(s, &(message->Workstation)); /* WorkstationFields (8 bytes) */
ntlm_write_message_fields(
s, &(message->EncryptedRandomSessionKey)); /* EncryptedRandomSessionKeyFields (8 bytes) */
Stream_Write_UINT32(s, message->NegotiateFlags); /* NegotiateFlags (4 bytes) */
if (message->NegotiateFlags & NTLMSSP_NEGOTIATE_VERSION)
ntlm_write_version_info(s, &(message->Version)); /* Version (8 bytes) */
if (context->UseMIC)
{
context->MessageIntegrityCheckOffset = (UINT32)Stream_GetPosition(s);
Stream_Zero(s, 16); /* Message Integrity Check (16 bytes) */
}
if (message->NegotiateFlags & NTLMSSP_NEGOTIATE_DOMAIN_SUPPLIED)
ntlm_write_message_fields_buffer(s, &(message->DomainName)); /* DomainName */
ntlm_write_message_fields_buffer(s, &(message->UserName)); /* UserName */
if (message->NegotiateFlags & NTLMSSP_NEGOTIATE_WORKSTATION_SUPPLIED)
ntlm_write_message_fields_buffer(s, &(message->Workstation)); /* Workstation */
ntlm_write_message_fields_buffer(s, &(message->LmChallengeResponse)); /* LmChallengeResponse */
ntlm_write_message_fields_buffer(s, &(message->NtChallengeResponse)); /* NtChallengeResponse */
if (message->NegotiateFlags & NTLMSSP_NEGOTIATE_KEY_EXCH)
ntlm_write_message_fields_buffer(
s, &(message->EncryptedRandomSessionKey)); /* EncryptedRandomSessionKey */
length = Stream_GetPosition(s);
if (!sspi_SecBufferAlloc(&context->AuthenticateMessage, length))
{
Stream_Free(s, FALSE);
return SEC_E_INTERNAL_ERROR;
}
CopyMemory(context->AuthenticateMessage.pvBuffer, Stream_Buffer(s), length);
buffer->cbBuffer = length;
if (context->UseMIC)
{
/* Message Integrity Check */
ntlm_compute_message_integrity_check(context, message->MessageIntegrityCheck, 16);
Stream_SetPosition(s, context->MessageIntegrityCheckOffset);
Stream_Write(s, message->MessageIntegrityCheck, 16);
Stream_SetPosition(s, length);
}
#ifdef WITH_DEBUG_NTLM
WLog_DBG(TAG, "AUTHENTICATE_MESSAGE (length = %d)", length);
winpr_HexDump(TAG, WLOG_DEBUG, Stream_Buffer(s), length);
ntlm_print_negotiate_flags(message->NegotiateFlags);
if (message->NegotiateFlags & NTLMSSP_NEGOTIATE_VERSION)
ntlm_print_version_info(&(message->Version));
if (context->AuthenticateTargetInfo.cbBuffer > 0)
{
WLog_DBG(TAG,
"AuthenticateTargetInfo (%" PRIu32 "):", context->AuthenticateTargetInfo.cbBuffer);
ntlm_print_av_pair_list(context->AuthenticateTargetInfo.pvBuffer,
context->AuthenticateTargetInfo.cbBuffer);
}
ntlm_print_message_fields(&(message->DomainName), "DomainName");
ntlm_print_message_fields(&(message->UserName), "UserName");
ntlm_print_message_fields(&(message->Workstation), "Workstation");
ntlm_print_message_fields(&(message->LmChallengeResponse), "LmChallengeResponse");
ntlm_print_message_fields(&(message->NtChallengeResponse), "NtChallengeResponse");
ntlm_print_message_fields(&(message->EncryptedRandomSessionKey), "EncryptedRandomSessionKey");
if (context->UseMIC)
{
WLog_DBG(TAG, "MessageIntegrityCheck (length = 16)");
winpr_HexDump(TAG, WLOG_DEBUG, message->MessageIntegrityCheck, 16);
}
#endif
context->state = NTLM_STATE_FINAL;
Stream_Free(s, FALSE);
return SEC_I_COMPLETE_NEEDED;
}
SECURITY_STATUS ntlm_server_AuthenticateComplete(NTLM_CONTEXT* context)
{
UINT32 flags = 0;
size_t cbAvFlags;
NTLM_AV_PAIR* AvFlags = NULL;
NTLM_AUTHENTICATE_MESSAGE* message;
BYTE messageIntegrityCheck[16];
if (!context)
return SEC_E_INVALID_PARAMETER;
if (context->state != NTLM_STATE_COMPLETION)
return SEC_E_OUT_OF_SEQUENCE;
message = &context->AUTHENTICATE_MESSAGE;
AvFlags = ntlm_av_pair_get(context->NTLMv2Response.Challenge.AvPairs,
context->NTLMv2Response.Challenge.cbAvPairs, MsvAvFlags, &cbAvFlags);
if (AvFlags)
Data_Read_UINT32(ntlm_av_pair_get_value_pointer(AvFlags), flags);
if (ntlm_compute_lm_v2_response(context) < 0) /* LmChallengeResponse */
return SEC_E_INTERNAL_ERROR;
if (ntlm_compute_ntlm_v2_response(context) < 0) /* NtChallengeResponse */
return SEC_E_INTERNAL_ERROR;
/* KeyExchangeKey */
ntlm_generate_key_exchange_key(context);
/* EncryptedRandomSessionKey */
ntlm_decrypt_random_session_key(context);
/* ExportedSessionKey */
ntlm_generate_exported_session_key(context);
if (flags & MSV_AV_FLAGS_MESSAGE_INTEGRITY_CHECK)
{
ZeroMemory(
&((PBYTE)context->AuthenticateMessage.pvBuffer)[context->MessageIntegrityCheckOffset],
16);
ntlm_compute_message_integrity_check(context, messageIntegrityCheck,
sizeof(messageIntegrityCheck));
CopyMemory(
&((PBYTE)context->AuthenticateMessage.pvBuffer)[context->MessageIntegrityCheckOffset],
message->MessageIntegrityCheck, 16);
if (memcmp(messageIntegrityCheck, message->MessageIntegrityCheck, 16) != 0)
{
WLog_ERR(TAG, "Message Integrity Check (MIC) verification failed!");
#ifdef WITH_DEBUG_NTLM
WLog_ERR(TAG, "Expected MIC:");
winpr_HexDump(TAG, WLOG_ERROR, messageIntegrityCheck, sizeof(messageIntegrityCheck));
WLog_ERR(TAG, "Actual MIC:");
winpr_HexDump(TAG, WLOG_ERROR, message->MessageIntegrityCheck,
sizeof(message->MessageIntegrityCheck));
#endif
return SEC_E_MESSAGE_ALTERED;
}
}
else
{
/* no mic message was present
https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-nlmp/f9e6fbc4-a953-4f24-b229-ccdcc213b9ec
the mic is optional, as not supported in Windows NT, Windows 2000, Windows XP, and
Windows Server 2003 and, as it seems, in the NTLMv2 implementation of Qt5.
now check the NtProofString, to detect if the entered client password matches the
expected password.
*/
#ifdef WITH_DEBUG_NTLM
WLog_DBG(TAG, "No MIC present, using NtProofString for verification.");
#endif
if (memcmp(context->NTLMv2Response.Response, context->NtProofString, 16) != 0)
{
WLog_ERR(TAG, "NtProofString verification failed!");
#ifdef WITH_DEBUG_NTLM
WLog_ERR(TAG, "Expected NtProofString:");
winpr_HexDump(TAG, WLOG_ERROR, context->NtProofString, sizeof(context->NtProofString));
WLog_ERR(TAG, "Actual NtProofString:");
winpr_HexDump(TAG, WLOG_ERROR, context->NTLMv2Response.Response,
sizeof(context->NTLMv2Response));
#endif
return SEC_E_LOGON_DENIED;
}
}
/* Generate signing keys */
ntlm_generate_client_signing_key(context);
ntlm_generate_server_signing_key(context);
/* Generate sealing keys */
ntlm_generate_client_sealing_key(context);
ntlm_generate_server_sealing_key(context);
/* Initialize RC4 seal state */
ntlm_init_rc4_seal_states(context);
#ifdef WITH_DEBUG_NTLM
WLog_DBG(TAG, "ClientChallenge");
winpr_HexDump(TAG, WLOG_DEBUG, context->ClientChallenge, 8);
WLog_DBG(TAG, "ServerChallenge");
winpr_HexDump(TAG, WLOG_DEBUG, context->ServerChallenge, 8);
WLog_DBG(TAG, "SessionBaseKey");
winpr_HexDump(TAG, WLOG_DEBUG, context->SessionBaseKey, 16);
WLog_DBG(TAG, "KeyExchangeKey");
winpr_HexDump(TAG, WLOG_DEBUG, context->KeyExchangeKey, 16);
WLog_DBG(TAG, "ExportedSessionKey");
winpr_HexDump(TAG, WLOG_DEBUG, context->ExportedSessionKey, 16);
WLog_DBG(TAG, "RandomSessionKey");
winpr_HexDump(TAG, WLOG_DEBUG, context->RandomSessionKey, 16);
WLog_DBG(TAG, "ClientSigningKey");
winpr_HexDump(TAG, WLOG_DEBUG, context->ClientSigningKey, 16);
WLog_DBG(TAG, "ClientSealingKey");
winpr_HexDump(TAG, WLOG_DEBUG, context->ClientSealingKey, 16);
WLog_DBG(TAG, "ServerSigningKey");
winpr_HexDump(TAG, WLOG_DEBUG, context->ServerSigningKey, 16);
WLog_DBG(TAG, "ServerSealingKey");
winpr_HexDump(TAG, WLOG_DEBUG, context->ServerSealingKey, 16);
WLog_DBG(TAG, "Timestamp");
winpr_HexDump(TAG, WLOG_DEBUG, context->Timestamp, 8);
#endif
context->state = NTLM_STATE_FINAL;
ntlm_free_message_fields_buffer(&(message->DomainName));
ntlm_free_message_fields_buffer(&(message->UserName));
ntlm_free_message_fields_buffer(&(message->Workstation));
ntlm_free_message_fields_buffer(&(message->LmChallengeResponse));
ntlm_free_message_fields_buffer(&(message->NtChallengeResponse));
ntlm_free_message_fields_buffer(&(message->EncryptedRandomSessionKey));
return SEC_E_OK;
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/good_3944_0 |
crossvul-cpp_data_bad_3181_0 | /* radare - LGPL - Copyright 2011-2016 - pancake */
#include <r_cons.h>
#include <r_types.h>
#include <r_util.h>
#include <r_lib.h>
#include <r_bin.h>
#include "dex/dex.h"
#define r_hash_adler32 __adler32
#include "../../hash/adler32.c"
extern struct r_bin_dbginfo_t r_bin_dbginfo_dex;
#define DEBUG_PRINTF 0
#if DEBUG_PRINTF
#define dprintf eprintf
#else
#define dprintf if (0)eprintf
#endif
static bool dexdump = false;
static Sdb *mdb = NULL;
static Sdb *cdb = NULL; // TODO: remove if it is not used
static char *getstr(RBinDexObj *bin, int idx) {
ut8 buf[6];
ut64 len;
int uleblen;
if (!bin || idx < 0 || idx >= bin->header.strings_size ||
!bin->strings) {
return NULL;
}
if (bin->strings[idx] >= bin->size) {
return NULL;
}
if (r_buf_read_at (bin->b, bin->strings[idx], buf, sizeof (buf)) < 1) {
return NULL;
}
uleblen = r_uleb128 (buf, sizeof (buf), &len) - buf;
if (!uleblen || uleblen >= bin->size) {
return NULL;
}
if (!len || len >= bin->size) {
return NULL;
}
// TODO: improve this ugly fix
char c = 'a';
while (c) {
ut64 offset = bin->strings[idx] + uleblen + len;
if (offset >= bin->size || offset < len) {
return NULL;
}
r_buf_read_at (bin->b, offset, (ut8*)&c, 1);
len++;
}
if ((int)len > 0 && len < R_BIN_SIZEOF_STRINGS) {
char *str = calloc (1, len + 1);
if (str) {
r_buf_read_at (bin->b, (bin->strings[idx]) + uleblen,
(ut8 *)str, len);
str[len] = 0;
return str;
}
}
return NULL;
}
static int countOnes(ut32 val) {
int count = 0;
val = val - ((val >> 1) & 0x55555555);
val = (val & 0x33333333) + ((val >> 2) & 0x33333333);
count = (((val + (val >> 4)) & 0x0F0F0F0F) * 0x01010101) >> 24;
return count;
}
typedef enum {
kAccessForClass = 0,
kAccessForMethod = 1,
kAccessForField = 2,
kAccessForMAX
} AccessFor;
static char *createAccessFlagStr(ut32 flags, AccessFor forWhat) {
#define NUM_FLAGS 18
static const char* kAccessStrings[kAccessForMAX][NUM_FLAGS] = {
{
/* class, inner class */
"PUBLIC", /* 0x0001 */
"PRIVATE", /* 0x0002 */
"PROTECTED", /* 0x0004 */
"STATIC", /* 0x0008 */
"FINAL", /* 0x0010 */
"?", /* 0x0020 */
"?", /* 0x0040 */
"?", /* 0x0080 */
"?", /* 0x0100 */
"INTERFACE", /* 0x0200 */
"ABSTRACT", /* 0x0400 */
"?", /* 0x0800 */
"SYNTHETIC", /* 0x1000 */
"ANNOTATION", /* 0x2000 */
"ENUM", /* 0x4000 */
"?", /* 0x8000 */
"VERIFIED", /* 0x10000 */
"OPTIMIZED", /* 0x20000 */
},
{
/* method */
"PUBLIC", /* 0x0001 */
"PRIVATE", /* 0x0002 */
"PROTECTED", /* 0x0004 */
"STATIC", /* 0x0008 */
"FINAL", /* 0x0010 */
"SYNCHRONIZED", /* 0x0020 */
"BRIDGE", /* 0x0040 */
"VARARGS", /* 0x0080 */
"NATIVE", /* 0x0100 */
"?", /* 0x0200 */
"ABSTRACT", /* 0x0400 */
"STRICT", /* 0x0800 */
"SYNTHETIC", /* 0x1000 */
"?", /* 0x2000 */
"?", /* 0x4000 */
"MIRANDA", /* 0x8000 */
"CONSTRUCTOR", /* 0x10000 */
"DECLARED_SYNCHRONIZED", /* 0x20000 */
},
{
/* field */
"PUBLIC", /* 0x0001 */
"PRIVATE", /* 0x0002 */
"PROTECTED", /* 0x0004 */
"STATIC", /* 0x0008 */
"FINAL", /* 0x0010 */
"?", /* 0x0020 */
"VOLATILE", /* 0x0040 */
"TRANSIENT", /* 0x0080 */
"?", /* 0x0100 */
"?", /* 0x0200 */
"?", /* 0x0400 */
"?", /* 0x0800 */
"SYNTHETIC", /* 0x1000 */
"?", /* 0x2000 */
"ENUM", /* 0x4000 */
"?", /* 0x8000 */
"?", /* 0x10000 */
"?", /* 0x20000 */
},
};
const int kLongest = 21;
int i, count;
char* str;
char* cp;
count = countOnes(flags);
// XXX check if this allocation is safe what if all the arithmetic
// produces a huge number????
cp = str = (char*) malloc (count * (kLongest + 1) + 1);
for (i = 0; i < NUM_FLAGS; i++) {
if (flags & 0x01) {
const char* accessStr = kAccessStrings[forWhat][i];
int len = strlen(accessStr);
if (cp != str) {
*cp++ = ' ';
}
memcpy(cp, accessStr, len);
cp += len;
}
flags >>= 1;
}
*cp = '\0';
return str;
}
static char *dex_type_descriptor(RBinDexObj *bin, int type_idx) {
if (type_idx < 0 || type_idx >= bin->header.types_size) {
return NULL;
}
return getstr (bin, bin->types[type_idx].descriptor_id);
}
static char *dex_method_signature(RBinDexObj *bin, int method_idx) {
ut32 proto_id, params_off, type_id, list_size;
char *r, *return_type = NULL, *signature = NULL, *buff = NULL;
ut8 *bufptr;
ut16 type_idx;
int pos = 0, i, size = 1;
if (method_idx < 0 || method_idx >= bin->header.method_size) {
return NULL;
}
proto_id = bin->methods[method_idx].proto_id;
if (proto_id >= bin->header.prototypes_size) {
return NULL;
}
params_off = bin->protos[proto_id].parameters_off;
if (params_off >= bin->size) {
return NULL;
}
type_id = bin->protos[proto_id].return_type_id;
if (type_id >= bin->header.types_size ) {
return NULL;
}
return_type = getstr (bin, bin->types[type_id].descriptor_id);
if (!return_type) {
return NULL;
}
if (!params_off) {
return r_str_newf ("()%s", return_type);;
}
bufptr = bin->b->buf;
// size of the list, in entries
list_size = r_read_le32 (bufptr + params_off);
//XXX again list_size is user controlled huge loop
for (i = 0; i < list_size; i++) {
int buff_len = 0;
if (params_off + 4 + (i * 2) >= bin->size) {
break;
}
type_idx = r_read_le16 (bufptr + params_off + 4 + (i * 2));
if (type_idx < 0 ||
type_idx >=
bin->header.types_size || type_idx >= bin->size) {
break;
}
buff = getstr (bin, bin->types[type_idx].descriptor_id);
if (!buff) {
break;
}
buff_len = strlen (buff);
size += buff_len + 1;
signature = realloc (signature, size);
strcpy (signature + pos, buff);
pos += buff_len;
signature[pos] = '\0';
}
r = r_str_newf ("(%s)%s", signature, return_type);
free (buff);
free (signature);
return r;
}
static RList *dex_method_signature2(RBinDexObj *bin, int method_idx) {
ut32 proto_id, params_off, list_size;
char *buff = NULL;
ut8 *bufptr;
ut16 type_idx;
int i;
RList *params = r_list_newf (free);
if (!params) {
return NULL;
}
if (method_idx < 0 || method_idx >= bin->header.method_size) {
goto out_error;
}
proto_id = bin->methods[method_idx].proto_id;
if (proto_id >= bin->header.prototypes_size) {
goto out_error;
}
params_off = bin->protos[proto_id].parameters_off;
if (params_off >= bin->size) {
goto out_error;
}
if (!params_off) {
return params;
}
bufptr = bin->b->buf;
// size of the list, in entries
list_size = r_read_le32 (bufptr + params_off);
//XXX list_size tainted it may produce huge loop
for (i = 0; i < list_size; i++) {
ut64 of = params_off + 4 + (i * 2);
if (of >= bin->size || of < params_off) {
break;
}
type_idx = r_read_le16 (bufptr + of);
if (type_idx >= bin->header.types_size ||
type_idx > bin->size) {
break;
}
buff = getstr (bin, bin->types[type_idx].descriptor_id);
if (!buff) {
break;
}
r_list_append (params, buff);
}
return params;
out_error:
r_list_free (params);
return NULL;
}
// TODO: fix this, now has more registers that it should
// https://github.com/android/platform_dalvik/blob/0641c2b4836fae3ee8daf6c0af45c316c84d5aeb/libdex/DexDebugInfo.cpp#L312
// https://github.com/android/platform_dalvik/blob/0641c2b4836fae3ee8daf6c0af45c316c84d5aeb/libdex/DexDebugInfo.cpp#L141
static void dex_parse_debug_item(RBinFile *binfile, RBinDexObj *bin,
RBinDexClass *c, int MI, int MA, int paddr, int ins_size,
int insns_size, char *class_name, int regsz,
int debug_info_off) {
struct r_bin_t *rbin = binfile->rbin;
const ut8 *p4 = r_buf_get_at (binfile->buf, debug_info_off, NULL);
const ut8 *p4_end = p4 + binfile->buf->length - debug_info_off;
ut64 line_start;
ut64 parameters_size;
ut64 param_type_idx;
ut16 argReg = regsz - ins_size;
ut64 source_file_idx = c->source_file;
RList *params, *debug_positions, *emitted_debug_locals = NULL;
bool keep = true;
if (argReg > regsz) {
return; // this return breaks tests
}
p4 = r_uleb128 (p4, p4_end - p4, &line_start);
p4 = r_uleb128 (p4, p4_end - p4, ¶meters_size);
// TODO: check when we should use source_file
// The state machine consists of five registers
ut32 address = 0;
ut32 line = line_start;
if (!(debug_positions = r_list_newf ((RListFree)free))) {
return;
}
if (!(emitted_debug_locals = r_list_newf ((RListFree)free))) {
r_list_free (debug_positions);
return;
}
struct dex_debug_local_t debug_locals[regsz];
memset (debug_locals, 0, sizeof (struct dex_debug_local_t) * regsz);
if (!(MA & 0x0008)) {
debug_locals[argReg].name = "this";
debug_locals[argReg].descriptor = r_str_newf("%s;", class_name);
debug_locals[argReg].startAddress = 0;
debug_locals[argReg].signature = NULL;
debug_locals[argReg].live = true;
argReg++;
}
if (!(params = dex_method_signature2 (bin, MI))) {
r_list_free (debug_positions);
r_list_free (emitted_debug_locals);
return;
}
RListIter *iter = r_list_iterator (params);
char *name;
char *type;
int reg;
r_list_foreach (params, iter, type) {
if ((argReg >= regsz) || !type || parameters_size <= 0) {
r_list_free (debug_positions);
r_list_free (params);
r_list_free (emitted_debug_locals);
return;
}
p4 = r_uleb128 (p4, p4_end - p4, ¶m_type_idx); // read uleb128p1
param_type_idx -= 1;
name = getstr (bin, param_type_idx);
reg = argReg;
switch (type[0]) {
case 'D':
case 'J':
argReg += 2;
break;
default:
argReg += 1;
break;
}
if (name) {
debug_locals[reg].name = name;
debug_locals[reg].descriptor = type;
debug_locals[reg].signature = NULL;
debug_locals[reg].startAddress = address;
debug_locals[reg].live = true;
}
--parameters_size;
}
ut8 opcode = *(p4++) & 0xff;
while (keep) {
switch (opcode) {
case 0x0: // DBG_END_SEQUENCE
keep = false;
break;
case 0x1: // DBG_ADVANCE_PC
{
ut64 addr_diff;
p4 = r_uleb128 (p4, p4_end - p4, &addr_diff);
address += addr_diff;
}
break;
case 0x2: // DBG_ADVANCE_LINE
{
st64 line_diff = r_sleb128 (&p4, p4_end);
line += line_diff;
}
break;
case 0x3: // DBG_START_LOCAL
{
ut64 register_num;
ut64 name_idx;
ut64 type_idx;
p4 = r_uleb128 (p4, p4_end - p4, ®ister_num);
p4 = r_uleb128 (p4, p4_end - p4, &name_idx);
name_idx -= 1;
p4 = r_uleb128 (p4, p4_end - p4, &type_idx);
type_idx -= 1;
if (register_num >= regsz) {
r_list_free (debug_positions);
r_list_free (params);
return;
}
// Emit what was previously there, if anything
// emitLocalCbIfLive
if (debug_locals[register_num].live) {
struct dex_debug_local_t *local = malloc (
sizeof (struct dex_debug_local_t));
if (!local) {
keep = false;
break;
}
local->name = debug_locals[register_num].name;
local->descriptor = debug_locals[register_num].descriptor;
local->startAddress = debug_locals[register_num].startAddress;
local->signature = debug_locals[register_num].signature;
local->live = true;
local->reg = register_num;
local->endAddress = address;
r_list_append (emitted_debug_locals, local);
}
debug_locals[register_num].name = getstr (bin, name_idx);
debug_locals[register_num].descriptor = dex_type_descriptor (bin, type_idx);
debug_locals[register_num].startAddress = address;
debug_locals[register_num].signature = NULL;
debug_locals[register_num].live = true;
//eprintf("DBG_START_LOCAL %x %x %x\n", register_num, name_idx, type_idx);
}
break;
case 0x4: //DBG_START_LOCAL_EXTENDED
{
ut64 register_num;
ut64 name_idx;
ut64 type_idx;
ut64 sig_idx;
p4 = r_uleb128 (p4, p4_end - p4, ®ister_num);
p4 = r_uleb128 (p4, p4_end - p4, &name_idx);
name_idx -= 1;
p4 = r_uleb128 (p4, p4_end - p4, &type_idx);
type_idx -= 1;
p4 = r_uleb128 (p4, p4_end - p4, &sig_idx);
sig_idx -= 1;
if (register_num >= regsz) {
r_list_free (debug_positions);
r_list_free (params);
return;
}
// Emit what was previously there, if anything
// emitLocalCbIfLive
if (debug_locals[register_num].live) {
struct dex_debug_local_t *local = malloc (
sizeof (struct dex_debug_local_t));
if (!local) {
keep = false;
break;
}
local->name = debug_locals[register_num].name;
local->descriptor = debug_locals[register_num].descriptor;
local->startAddress = debug_locals[register_num].startAddress;
local->signature = debug_locals[register_num].signature;
local->live = true;
local->reg = register_num;
local->endAddress = address;
r_list_append (emitted_debug_locals, local);
}
debug_locals[register_num].name = getstr (bin, name_idx);
debug_locals[register_num].descriptor = dex_type_descriptor (bin, type_idx);
debug_locals[register_num].startAddress = address;
debug_locals[register_num].signature = getstr (bin, sig_idx);
debug_locals[register_num].live = true;
}
break;
case 0x5: // DBG_END_LOCAL
{
ut64 register_num;
p4 = r_uleb128 (p4, p4_end - p4, ®ister_num);
// emitLocalCbIfLive
if (debug_locals[register_num].live) {
struct dex_debug_local_t *local = malloc (
sizeof (struct dex_debug_local_t));
if (!local) {
keep = false;
break;
}
local->name = debug_locals[register_num].name;
local->descriptor = debug_locals[register_num].descriptor;
local->startAddress = debug_locals[register_num].startAddress;
local->signature = debug_locals[register_num].signature;
local->live = true;
local->reg = register_num;
local->endAddress = address;
r_list_append (emitted_debug_locals, local);
}
debug_locals[register_num].live = false;
}
break;
case 0x6: // DBG_RESTART_LOCAL
{
ut64 register_num;
p4 = r_uleb128 (p4, p4_end - p4, ®ister_num);
if (!debug_locals[register_num].live) {
debug_locals[register_num].startAddress = address;
debug_locals[register_num].live = true;
}
}
break;
case 0x7: //DBG_SET_PROLOGUE_END
break;
case 0x8: //DBG_SET_PROLOGUE_BEGIN
break;
case 0x9:
{
p4 = r_uleb128 (p4, p4_end - p4, &source_file_idx);
source_file_idx--;
}
break;
default:
{
int adjusted_opcode = opcode - 0x0a;
address += (adjusted_opcode / 15);
line += -4 + (adjusted_opcode % 15);
struct dex_debug_position_t *position =
malloc (sizeof (struct dex_debug_position_t));
if (!position) {
keep = false;
break;
}
position->source_file_idx = source_file_idx;
position->address = address;
position->line = line;
r_list_append (debug_positions, position);
}
break;
}
opcode = *(p4++) & 0xff;
}
if (!binfile->sdb_addrinfo) {
binfile->sdb_addrinfo = sdb_new0 ();
}
char *fileline;
char offset[64];
char *offset_ptr;
RListIter *iter1;
struct dex_debug_position_t *pos;
r_list_foreach (debug_positions, iter1, pos) {
fileline = r_str_newf ("%s|%"PFMT64d, getstr (bin, pos->source_file_idx), pos->line);
offset_ptr = sdb_itoa (pos->address + paddr, offset, 16);
sdb_set (binfile->sdb_addrinfo, offset_ptr, fileline, 0);
sdb_set (binfile->sdb_addrinfo, fileline, offset_ptr, 0);
}
if (!dexdump) {
r_list_free (debug_positions);
r_list_free (emitted_debug_locals);
r_list_free (params);
return;
}
RListIter *iter2;
struct dex_debug_position_t *position;
rbin->cb_printf (" positions :\n");
r_list_foreach (debug_positions, iter2, position) {
rbin->cb_printf (" 0x%04llx line=%llu\n",
position->address, position->line);
}
rbin->cb_printf (" locals :\n");
RListIter *iter3;
struct dex_debug_local_t *local;
r_list_foreach (emitted_debug_locals, iter3, local) {
if (local->signature) {
rbin->cb_printf (
" 0x%04x - 0x%04x reg=%d %s %s %s\n",
local->startAddress, local->endAddress,
local->reg, local->name, local->descriptor,
local->signature);
} else {
rbin->cb_printf (
" 0x%04x - 0x%04x reg=%d %s %s\n",
local->startAddress, local->endAddress,
local->reg, local->name, local->descriptor);
}
}
for (reg = 0; reg < regsz; reg++) {
if (debug_locals[reg].live) {
if (debug_locals[reg].signature) {
rbin->cb_printf (
" 0x%04x - 0x%04x reg=%d %s %s "
"%s\n",
debug_locals[reg].startAddress,
insns_size, reg, debug_locals[reg].name,
debug_locals[reg].descriptor,
debug_locals[reg].signature);
} else {
rbin->cb_printf (
" 0x%04x - 0x%04x reg=%d %s %s"
"\n",
debug_locals[reg].startAddress,
insns_size, reg, debug_locals[reg].name,
debug_locals[reg].descriptor);
}
}
}
r_list_free (debug_positions);
r_list_free (emitted_debug_locals);
r_list_free (params);
}
static int check (RBinFile *arch);
static int check_bytes (const ut8 *buf, ut64 length);
static Sdb *get_sdb (RBinObject *o) {
if (!o || !o->bin_obj) {
return NULL;
}
struct r_bin_dex_obj_t *bin = (struct r_bin_dex_obj_t *) o->bin_obj;
if (bin->kv) {
return bin->kv;
}
return NULL;
}
static void *load_bytes(RBinFile *arch, const ut8 *buf, ut64 sz, ut64 loadaddr, Sdb *sdb){
void *res = NULL;
RBuffer *tbuf = NULL;
if (!buf || !sz || sz == UT64_MAX) {
return NULL;
}
tbuf = r_buf_new ();
if (!tbuf) {
return NULL;
}
r_buf_set_bytes (tbuf, buf, sz);
res = r_bin_dex_new_buf (tbuf);
r_buf_free (tbuf);
return res;
}
static int load(RBinFile *arch) {
const ut8 *bytes = arch ? r_buf_buffer (arch->buf) : NULL;
ut64 sz = arch ? r_buf_size (arch->buf): 0;
if (!arch || !arch->o) {
return false;
}
arch->o->bin_obj = load_bytes (arch, bytes, sz, arch->o->loadaddr, arch->sdb);
return arch->o->bin_obj ? true: false;
}
static ut64 baddr(RBinFile *arch) {
return 0;
}
static int check(RBinFile *arch) {
const ut8 *bytes = arch ? r_buf_buffer (arch->buf) : NULL;
ut64 sz = arch ? r_buf_size (arch->buf): 0;
return check_bytes (bytes, sz);
}
static int check_bytes(const ut8 *buf, ut64 length) {
if (!buf || length < 8) {
return false;
}
// Non-extended opcode dex file
if (!memcmp (buf, "dex\n035\0", 8)) {
return true;
}
// Extended (jumnbo) opcode dex file, ICS+ only (sdk level 14+)
if (!memcmp (buf, "dex\n036\0", 8)) {
return true;
}
// M3 (Nov-Dec 07)
if (!memcmp (buf, "dex\n009\0", 8)) {
return true;
}
// M5 (Feb-Mar 08)
if (!memcmp (buf, "dex\n009\0", 8)) {
return true;
}
// Default fall through, should still be a dex file
if (!memcmp (buf, "dex\n", 4)) {
return true;
}
return false;
}
static RBinInfo *info(RBinFile *arch) {
RBinHash *h;
RBinInfo *ret = R_NEW0 (RBinInfo);
if (!ret) {
return NULL;
}
ret->file = arch->file? strdup (arch->file): NULL;
ret->type = strdup ("DEX CLASS");
ret->has_va = false;
ret->bclass = r_bin_dex_get_version (arch->o->bin_obj);
ret->rclass = strdup ("class");
ret->os = strdup ("linux");
ret->subsystem = strdup ("any");
ret->machine = strdup ("Dalvik VM");
h = &ret->sum[0];
h->type = "sha1";
h->len = 20;
h->addr = 12;
h->from = 12;
h->to = arch->buf->length-32;
memcpy (h->buf, arch->buf->buf+12, 20);
h = &ret->sum[1];
h->type = "adler32";
h->len = 4;
h->addr = 0x8;
h->from = 12;
h->to = arch->buf->length-h->from;
h = &ret->sum[2];
h->type = 0;
memcpy (h->buf, arch->buf->buf + 8, 4);
{
ut32 *fc = (ut32 *)(arch->buf->buf + 8);
ut32 cc = __adler32 (arch->buf->buf + 12, arch->buf->length - 12);
if (*fc != cc) {
eprintf ("# adler32 checksum doesn't match. Type this to fix it:\n");
eprintf ("wx `#sha1 $s-32 @32` @12 ; wx `#adler32 $s-12 @12` @8\n");
}
}
ret->arch = strdup ("dalvik");
ret->lang = "dalvik";
ret->bits = 32;
ret->big_endian = 0;
ret->dbg_info = 0; //1 | 4 | 8; /* Stripped | LineNums | Syms */
return ret;
}
static RList *strings(RBinFile *arch) {
struct r_bin_dex_obj_t *bin = NULL;
RBinString *ptr = NULL;
RList *ret = NULL;
int i, len;
ut8 buf[6];
ut64 off;
if (!arch || !arch->o) {
return NULL;
}
bin = (struct r_bin_dex_obj_t *) arch->o->bin_obj;
if (!bin || !bin->strings) {
return NULL;
}
if (bin->header.strings_size > bin->size) {
bin->strings = NULL;
return NULL;
}
if (!(ret = r_list_newf (free))) {
return NULL;
}
for (i = 0; i < bin->header.strings_size; i++) {
if (!(ptr = R_NEW0 (RBinString))) {
break;
}
if (bin->strings[i] > bin->size || bin->strings[i] + 6 > bin->size) {
goto out_error;
}
r_buf_read_at (bin->b, bin->strings[i], (ut8*)&buf, 6);
len = dex_read_uleb128 (buf);
if (len > 1 && len < R_BIN_SIZEOF_STRINGS) {
ptr->string = malloc (len + 1);
if (!ptr->string) {
goto out_error;
}
off = bin->strings[i] + dex_uleb128_len (buf);
if (off + len >= bin->size || off + len < len) {
free (ptr->string);
goto out_error;
}
r_buf_read_at (bin->b, off, (ut8*)ptr->string, len);
ptr->string[len] = 0;
ptr->vaddr = ptr->paddr = bin->strings[i];
ptr->size = len;
ptr->length = len;
ptr->ordinal = i+1;
r_list_append (ret, ptr);
} else {
free (ptr);
}
}
return ret;
out_error:
r_list_free (ret);
free (ptr);
return NULL;
}
static char *dex_method_name(RBinDexObj *bin, int idx) {
if (idx < 0 || idx >= bin->header.method_size) {
return NULL;
}
int cid = bin->methods[idx].class_id;
if (cid < 0 || cid >= bin->header.strings_size) {
return NULL;
}
int tid = bin->methods[idx].name_id;
if (tid < 0 || tid >= bin->header.strings_size) {
return NULL;
}
return getstr (bin, tid);
}
static char *dex_class_name_byid(RBinDexObj *bin, int cid) {
int tid;
if (!bin || !bin->types) {
return NULL;
}
if (cid < 0 || cid >= bin->header.types_size) {
return NULL;
}
tid = bin->types[cid].descriptor_id;
return getstr (bin, tid);
}
static char *dex_class_name(RBinDexObj *bin, RBinDexClass *c) {
return dex_class_name_byid (bin, c->class_id);
}
static char *dex_field_name(RBinDexObj *bin, int fid) {
int cid, tid, type_id;
if (!bin || !bin->fields) {
return NULL;
}
if (fid < 0 || fid >= bin->header.fields_size) {
return NULL;
}
cid = bin->fields[fid].class_id;
if (cid < 0 || cid >= bin->header.types_size) {
return NULL;
}
type_id = bin->fields[fid].type_id;
if (type_id < 0 || type_id >= bin->header.types_size) {
return NULL;
}
tid = bin->fields[fid].name_id;
return r_str_newf ("%s->%s %s", getstr (bin, bin->types[cid].descriptor_id),
getstr (bin, tid), getstr (bin, bin->types[type_id].descriptor_id));
}
static char *dex_method_fullname(RBinDexObj *bin, int method_idx) {
if (!bin || !bin->types) {
return NULL;
}
if (method_idx < 0 || method_idx >= bin->header.method_size) {
return NULL;
}
int cid = bin->methods[method_idx].class_id;
if (cid < 0 || cid >= bin->header.types_size) {
return NULL;
}
char *name = dex_method_name (bin, method_idx);
char *class_name = dex_class_name_byid (bin, cid);
class_name = r_str_replace (class_name, ";", "", 0); //TODO: move to func
char *signature = dex_method_signature (bin, method_idx);
char *flagname = r_str_newf ("%s.%s%s", class_name, name, signature);
free (name);
free (class_name);
free (signature);
return flagname;
}
static ut64 dex_get_type_offset(RBinFile *arch, int type_idx) {
RBinDexObj *bin = (RBinDexObj*) arch->o->bin_obj;
if (!bin || !bin->types) {
return 0;
}
if (type_idx < 0 || type_idx >= bin->header.types_size) {
return 0;
}
return bin->header.types_offset + type_idx * 0x04; //&bin->types[type_idx];
}
static void __r_bin_class_free(RBinClass *p) {
r_list_free (p->methods);
r_list_free (p->fields);
r_bin_class_free (p);
}
static char *dex_class_super_name(RBinDexObj *bin, RBinDexClass *c) {
int cid, tid;
if (!bin || !c || !bin->types) {
return NULL;
}
cid = c->super_class;
if (cid < 0 || cid >= bin->header.types_size) {
return NULL;
}
tid = bin->types[cid].descriptor_id;
return getstr (bin, tid);
}
static const ut8 *parse_dex_class_fields(RBinFile *binfile, RBinDexObj *bin,
RBinDexClass *c, RBinClass *cls,
const ut8 *p, const ut8 *p_end,
int *sym_count, ut64 fields_count,
bool is_sfield) {
struct r_bin_t *rbin = binfile->rbin;
ut64 lastIndex = 0;
ut8 ff[sizeof (DexField)] = {0};
int total, i, tid;
DexField field;
const char* type_str;
for (i = 0; i < fields_count; i++) {
ut64 fieldIndex, accessFlags;
p = r_uleb128 (p, p_end - p, &fieldIndex); // fieldIndex
p = r_uleb128 (p, p_end - p, &accessFlags); // accessFlags
fieldIndex += lastIndex;
total = bin->header.fields_offset + (sizeof (DexField) * fieldIndex);
if (total >= bin->size || total < bin->header.fields_offset) {
break;
}
if (r_buf_read_at (binfile->buf, total, ff,
sizeof (DexField)) != sizeof (DexField)) {
break;
}
field.class_id = r_read_le16 (ff);
field.type_id = r_read_le16 (ff + 2);
field.name_id = r_read_le32 (ff + 4);
char *fieldName = getstr (bin, field.name_id);
if (field.type_id >= bin->header.types_size) {
break;
}
tid = bin->types[field.type_id].descriptor_id;
type_str = getstr (bin, tid);
RBinSymbol *sym = R_NEW0 (RBinSymbol);
if (is_sfield) {
sym->name = r_str_newf ("%s.sfield_%s:%s", cls->name,
fieldName, type_str);
sym->type = r_str_const ("STATIC");
} else {
sym->name = r_str_newf ("%s.ifield_%s:%s", cls->name,
fieldName, type_str);
sym->type = r_str_const ("FIELD");
}
sym->name = r_str_replace (sym->name, "method.", "", 0);
//sym->name = r_str_replace (sym->name, ";", "", 0);
sym->paddr = sym->vaddr = total;
sym->ordinal = (*sym_count)++;
if (dexdump) {
const char *accessStr = createAccessFlagStr (
accessFlags, kAccessForField);
rbin->cb_printf (" #%d : (in %s;)\n", i,
cls->name);
rbin->cb_printf (" name : '%s'\n", fieldName);
rbin->cb_printf (" type : '%s'\n", type_str);
rbin->cb_printf (" access : 0x%04x (%s)\n",
(unsigned int)accessFlags, accessStr);
}
r_list_append (bin->methods_list, sym);
r_list_append (cls->fields, sym);
lastIndex = fieldIndex;
}
return p;
}
// TODO: refactor this method
// XXX it needs a lot of love!!!
static const ut8 *parse_dex_class_method(RBinFile *binfile, RBinDexObj *bin,
RBinDexClass *c, RBinClass *cls,
const ut8 *p, const ut8 *p_end,
int *sym_count, ut64 DM, int *methods,
bool is_direct) {
struct r_bin_t *rbin = binfile->rbin;
ut8 ff2[16] = {0};
ut8 ff3[8] = {0};
int i;
ut64 omi = 0;
bool catchAll;
ut16 regsz, ins_size, outs_size, tries_size;
ut16 handler_off, start_addr, insn_count;
ut32 debug_info_off, insns_size;
const ut8 *encoded_method_addr;
for (i = 0; i < DM; i++) {
encoded_method_addr = p;
char *method_name, *flag_name;
ut64 MI, MA, MC;
p = r_uleb128 (p, p_end - p, &MI);
MI += omi;
omi = MI;
p = r_uleb128 (p, p_end - p, &MA);
p = r_uleb128 (p, p_end - p, &MC);
// TODO: MOVE CHECKS OUTSIDE!
if (MI < bin->header.method_size) {
if (methods) {
methods[MI] = 1;
}
}
method_name = dex_method_name (bin, MI);
char *signature = dex_method_signature (bin, MI);
if (!method_name) {
method_name = strdup ("unknown");
}
flag_name = r_str_newf ("%s.method.%s%s", cls->name,
method_name, signature);
if (!flag_name) {
R_FREE (method_name);
R_FREE (signature);
continue;
}
// TODO: check size
// ut64 prolog_size = 2 + 2 + 2 + 2 + 4 + 4;
ut64 v2, handler_type, handler_addr;
int t;
if (MC > 0) {
// TODO: parse debug info
// XXX why binfile->buf->base???
if (MC + 16 >= bin->size || MC + 16 < MC) {
R_FREE (method_name);
R_FREE (flag_name);
R_FREE (signature);
continue;
}
if (r_buf_read_at (binfile->buf,
binfile->buf->base + MC, ff2,
16) < 1) {
R_FREE (method_name);
R_FREE (flag_name);
R_FREE (signature);
continue;
}
regsz = r_read_le16 (ff2);
ins_size = r_read_le16 (ff2 + 2);
outs_size = r_read_le16 (ff2 + 4);
tries_size = r_read_le16 (ff2 + 6);
debug_info_off = r_read_le32 (ff2 + 8);
insns_size = r_read_le32 (ff2 + 12);
int padd = 0;
if (tries_size > 0 && insns_size % 2) {
padd = 2;
}
t = 16 + 2 * insns_size + padd;
}
if (dexdump) {
const char* accessStr = createAccessFlagStr (MA, kAccessForMethod);
rbin->cb_printf (" #%d : (in %s;)\n", i, cls->name);
rbin->cb_printf (" name : '%s'\n", method_name);
rbin->cb_printf (" type : '%s'\n", signature);
rbin->cb_printf (" access : 0x%04x (%s)\n",
(unsigned int)MA, accessStr);
}
if (MC > 0) {
if (dexdump) {
rbin->cb_printf (" code -\n");
rbin->cb_printf (" registers : %d\n", regsz);
rbin->cb_printf (" ins : %d\n", ins_size);
rbin->cb_printf (" outs : %d\n", outs_size);
rbin->cb_printf (
" insns size : %d 16-bit code "
"units\n",
insns_size);
}
if (tries_size > 0) {
if (dexdump) {
rbin->cb_printf (" catches : %d\n", tries_size);
}
int j, m = 0;
//XXX bucle controlled by tainted variable it could produces huge loop
for (j = 0; j < tries_size; ++j) {
ut64 offset = MC + t + j * 8;
if (offset >= bin->size || offset < MC) {
R_FREE (signature);
break;
}
if (r_buf_read_at (
binfile->buf,
binfile->buf->base + offset,
ff3, 8) < 1) {
// free (method_name);
R_FREE (signature);
break;
}
start_addr = r_read_le32 (ff3);
insn_count = r_read_le16 (ff3 + 4);
handler_off = r_read_le16 (ff3 + 6);
char* s = NULL;
if (dexdump) {
rbin->cb_printf (
" 0x%04x - "
"0x%04x\n",
start_addr,
(start_addr +
insn_count));
}
const ut8 *p3, *p3_end;
//XXX tries_size is tainted and oob here
int off = MC + t + tries_size * 8 + handler_off;
if (off >= bin->size || off < tries_size) {
R_FREE (signature);
break;
}
p3 = r_buf_get_at (binfile->buf, off, NULL);
p3_end = p3 + binfile->buf->length - off;
st64 size = r_sleb128 (&p3, p3_end);
if (size <= 0) {
catchAll = true;
size = -size;
} else {
catchAll = false;
}
for (m = 0; m < size; m++) {
p3 = r_uleb128 (p3, p3_end - p3, &handler_type);
p3 = r_uleb128 (p3, p3_end - p3, &handler_addr);
if (handler_type > 0 &&
handler_type <
bin->header.types_size) {
s = getstr (bin, bin->types[handler_type].descriptor_id);
if (dexdump) {
rbin->cb_printf (
" %s "
"-> 0x%04llx\n",
s,
handler_addr);
}
} else {
if (dexdump) {
rbin->cb_printf (
" "
"(error) -> "
"0x%04llx\n",
handler_addr);
}
}
}
if (catchAll) {
p3 = r_uleb128 (p3, p3_end - p3, &v2);
if (dexdump) {
rbin->cb_printf (
" "
"<any> -> "
"0x%04llx\n",
v2);
}
}
}
} else {
if (dexdump) {
rbin->cb_printf (
" catches : "
"(none)\n");
}
}
} else {
if (dexdump) {
rbin->cb_printf (
" code : (none)\n");
}
}
if (*flag_name) {
RBinSymbol *sym = R_NEW0 (RBinSymbol);
sym->name = flag_name;
// is_direct is no longer used
// if method has code *addr points to code
// otherwise it points to the encoded method
if (MC > 0) {
sym->type = r_str_const ("FUNC");
sym->paddr = MC;// + 0x10;
sym->vaddr = MC;// + 0x10;
} else {
sym->type = r_str_const ("METH");
sym->paddr = encoded_method_addr - binfile->buf->buf;
sym->vaddr = encoded_method_addr - binfile->buf->buf;
}
if ((MA & 0x1) == 0x1) {
sym->bind = r_str_const ("GLOBAL");
} else {
sym->bind = r_str_const ("LOCAL");
}
sym->ordinal = (*sym_count)++;
if (MC > 0) {
if (r_buf_read_at (binfile->buf, binfile->buf->base + MC, ff2, 16) < 1) {
R_FREE (sym);
R_FREE (signature);
continue;
}
//ut16 regsz = r_read_le16 (ff2);
//ut16 ins_size = r_read_le16 (ff2 + 2);
//ut16 outs_size = r_read_le16 (ff2 + 4);
ut16 tries_size = r_read_le16 (ff2 + 6);
//ut32 debug_info_off = r_read_le32 (ff2 + 8);
ut32 insns_size = r_read_le32 (ff2 + 12);
ut64 prolog_size = 2 + 2 + 2 + 2 + 4 + 4;
if (tries_size > 0) {
//prolog_size += 2 + 8*tries_size; // we need to parse all so the catch info...
}
// TODO: prolog_size
sym->paddr = MC + prolog_size;// + 0x10;
sym->vaddr = MC + prolog_size;// + 0x10;
//if (is_direct) {
sym->size = insns_size * 2;
//}
//eprintf("%s (0x%x-0x%x) size=%d\nregsz=%d\ninsns_size=%d\nouts_size=%d\ntries_size=%d\ninsns_size=%d\n", flag_name, sym->vaddr, sym->vaddr+sym->size, prolog_size, regsz, ins_size, outs_size, tries_size, insns_size);
r_list_append (bin->methods_list, sym);
r_list_append (cls->methods, sym);
if (bin->code_from > sym->paddr) {
bin->code_from = sym->paddr;
}
if (bin->code_to < sym->paddr) {
bin->code_to = sym->paddr;
}
if (!mdb) {
mdb = sdb_new0 ();
}
sdb_num_set (mdb, sdb_fmt (0, "method.%d", MI), sym->paddr, 0);
// -----------------
// WORK IN PROGRESS
// -----------------
if (0) {
if (MA & 0x10000) { //ACC_CONSTRUCTOR
if (!cdb) {
cdb = sdb_new0 ();
}
sdb_num_set (cdb, sdb_fmt (0, "%d", c->class_id), sym->paddr, 0);
}
}
} else {
sym->size = 0;
r_list_append (bin->methods_list, sym);
r_list_append (cls->methods, sym);
}
if (MC > 0 && debug_info_off > 0 && bin->header.data_offset < debug_info_off &&
debug_info_off < bin->header.data_offset + bin->header.data_size) {
dex_parse_debug_item (binfile, bin, c, MI, MA, sym->paddr, ins_size,
insns_size, cls->name, regsz, debug_info_off);
} else if (MC > 0) {
if (dexdump) {
rbin->cb_printf (" positions :\n");
rbin->cb_printf (" locals :\n");
}
}
} else {
R_FREE (flag_name);
}
R_FREE (signature);
R_FREE (method_name);
}
return p;
}
static void parse_class(RBinFile *binfile, RBinDexObj *bin, RBinDexClass *c,
int class_index, int *methods, int *sym_count) {
struct r_bin_t *rbin = binfile->rbin;
char *class_name;
int z;
const ut8 *p, *p_end;
if (!c) {
return;
}
class_name = dex_class_name (bin, c);
class_name = r_str_replace (class_name, ";", "", 0); //TODO: move to func
if (!class_name || !*class_name) {
return;
}
RBinClass *cls = R_NEW0 (RBinClass);
if (!cls) {
return;
}
cls->name = class_name;
cls->index = class_index;
cls->addr = bin->header.class_offset + class_index * DEX_CLASS_SIZE;
cls->methods = r_list_new ();
if (!cls->methods) {
free (cls);
return;
}
cls->fields = r_list_new ();
if (!cls->fields) {
r_list_free (cls->methods);
free (cls);
return;
}
r_list_append (bin->classes_list, cls);
if (dexdump) {
rbin->cb_printf (" Class descriptor : '%s;'\n", class_name);
rbin->cb_printf (
" Access flags : 0x%04x (%s)\n", c->access_flags,
createAccessFlagStr (c->access_flags, kAccessForClass));
rbin->cb_printf (" Superclass : '%s'\n",
dex_class_super_name (bin, c));
rbin->cb_printf (" Interfaces -\n");
}
if (c->interfaces_offset > 0 &&
bin->header.data_offset < c->interfaces_offset &&
c->interfaces_offset <
bin->header.data_offset + bin->header.data_size) {
p = r_buf_get_at (binfile->buf, c->interfaces_offset, NULL);
int types_list_size = r_read_le32 (p);
if (types_list_size < 0 || types_list_size >= bin->header.types_size ) {
return;
}
for (z = 0; z < types_list_size; z++) {
int t = r_read_le16 (p + 4 + z * 2);
if (t > 0 && t < bin->header.types_size ) {
int tid = bin->types[t].descriptor_id;
if (dexdump) {
rbin->cb_printf (
" #%d : '%s'\n",
z, getstr (bin, tid));
}
}
}
}
// TODO: this is quite ugly
if (!c || !c->class_data_offset) {
if (dexdump) {
rbin->cb_printf (
" Static fields -\n Instance fields "
"-\n Direct methods -\n Virtual methods "
"-\n");
}
} else {
// TODO: move to func, def or inline
// class_data_offset => [class_offset, class_defs_off+class_defs_size*32]
if (bin->header.class_offset > c->class_data_offset ||
c->class_data_offset <
bin->header.class_offset +
bin->header.class_size * DEX_CLASS_SIZE) {
return;
}
p = r_buf_get_at (binfile->buf, c->class_data_offset, NULL);
p_end = p + binfile->buf->length - c->class_data_offset;
//XXX check for NULL!!
c->class_data = (struct dex_class_data_item_t *)malloc (
sizeof (struct dex_class_data_item_t));
p = r_uleb128 (p, p_end - p, &c->class_data->static_fields_size);
p = r_uleb128 (p, p_end - p, &c->class_data->instance_fields_size);
p = r_uleb128 (p, p_end - p, &c->class_data->direct_methods_size);
p = r_uleb128 (p, p_end - p, &c->class_data->virtual_methods_size);
if (dexdump) {
rbin->cb_printf (" Static fields -\n");
}
p = parse_dex_class_fields (
binfile, bin, c, cls, p, p_end, sym_count,
c->class_data->static_fields_size, true);
if (dexdump) {
rbin->cb_printf (" Instance fields -\n");
}
p = parse_dex_class_fields (
binfile, bin, c, cls, p, p_end, sym_count,
c->class_data->instance_fields_size, false);
if (dexdump) {
rbin->cb_printf (" Direct methods -\n");
}
p = parse_dex_class_method (
binfile, bin, c, cls, p, p_end, sym_count,
c->class_data->direct_methods_size, methods, true);
if (dexdump) {
rbin->cb_printf (" Virtual methods -\n");
}
p = parse_dex_class_method (
binfile, bin, c, cls, p, p_end, sym_count,
c->class_data->virtual_methods_size, methods, false);
}
if (dexdump) {
char *source_file = getstr (bin, c->source_file);
if (!source_file) {
rbin->cb_printf (
" source_file_idx : %d (unknown)\n\n",
c->source_file);
} else {
rbin->cb_printf (" source_file_idx : %d (%s)\n\n",
c->source_file, source_file);
}
}
// TODO:!!!!
// FIX: FREE BEFORE ALLOCATE!!!
//free (class_name);
}
static bool is_class_idx_in_code_classes(RBinDexObj *bin, int class_idx) {
int i;
for (i = 0; i < bin->header.class_size; i++) {
if (class_idx == bin->classes[i].class_id) {
return true;
}
}
return false;
}
static int dex_loadcode(RBinFile *arch, RBinDexObj *bin) {
struct r_bin_t *rbin = arch->rbin;
int i;
int *methods = NULL;
int sym_count = 0;
// doublecheck??
if (!bin || bin->methods_list) {
return false;
}
bin->code_from = UT64_MAX;
bin->code_to = 0;
bin->methods_list = r_list_newf ((RListFree)free);
if (!bin->methods_list) {
return false;
}
bin->imports_list = r_list_newf ((RListFree)free);
if (!bin->imports_list) {
r_list_free (bin->methods_list);
return false;
}
bin->classes_list = r_list_newf ((RListFree)__r_bin_class_free);
if (!bin->classes_list) {
r_list_free (bin->methods_list);
r_list_free (bin->imports_list);
return false;
}
if (bin->header.method_size>bin->size) {
bin->header.method_size = 0;
return false;
}
/* WrapDown the header sizes to avoid huge allocations */
bin->header.method_size = R_MIN (bin->header.method_size, bin->size);
bin->header.class_size = R_MIN (bin->header.class_size, bin->size);
bin->header.strings_size = R_MIN (bin->header.strings_size, bin->size);
// TODO: is this posible after R_MIN ??
if (bin->header.strings_size > bin->size) {
eprintf ("Invalid strings size\n");
return false;
}
if (bin->classes) {
ut64 amount = sizeof (int) * bin->header.method_size;
if (amount > UT32_MAX || amount < bin->header.method_size) {
return false;
}
methods = calloc (1, amount + 1);
for (i = 0; i < bin->header.class_size; i++) {
char *super_name, *class_name;
struct dex_class_t *c = &bin->classes[i];
class_name = dex_class_name (bin, c);
super_name = dex_class_super_name (bin, c);
if (dexdump) {
rbin->cb_printf ("Class #%d -\n", i);
}
parse_class (arch, bin, c, i, methods, &sym_count);
free (class_name);
free (super_name);
}
}
if (methods) {
int import_count = 0;
int sym_count = bin->methods_list->length;
for (i = 0; i < bin->header.method_size; i++) {
int len = 0;
if (methods[i]) {
continue;
}
if (bin->methods[i].class_id > bin->header.types_size - 1) {
continue;
}
if (is_class_idx_in_code_classes(bin, bin->methods[i].class_id)) {
continue;
}
char *class_name = getstr (
bin, bin->types[bin->methods[i].class_id]
.descriptor_id);
if (!class_name) {
free (class_name);
continue;
}
len = strlen (class_name);
if (len < 1) {
continue;
}
class_name[len - 1] = 0; // remove last char ";"
char *method_name = dex_method_name (bin, i);
char *signature = dex_method_signature (bin, i);
if (method_name && *method_name) {
RBinImport *imp = R_NEW0 (RBinImport);
imp->name = r_str_newf ("%s.method.%s%s", class_name, method_name, signature);
imp->type = r_str_const ("FUNC");
imp->bind = r_str_const ("NONE");
imp->ordinal = import_count++;
r_list_append (bin->imports_list, imp);
RBinSymbol *sym = R_NEW0 (RBinSymbol);
sym->name = r_str_newf ("imp.%s", imp->name);
sym->type = r_str_const ("FUNC");
sym->bind = r_str_const ("NONE");
//XXX so damn unsafe check buffer boundaries!!!!
//XXX use r_buf API!!
sym->paddr = sym->vaddr = bin->b->base + bin->header.method_offset + (sizeof (struct dex_method_t) * i) ;
sym->ordinal = sym_count++;
r_list_append (bin->methods_list, sym);
sdb_num_set (mdb, sdb_fmt (0, "method.%d", i), sym->paddr, 0);
}
free (method_name);
free (signature);
free (class_name);
}
free (methods);
}
return true;
}
static RList* imports(RBinFile *arch) {
RBinDexObj *bin = (RBinDexObj*) arch->o->bin_obj;
if (!bin) {
return NULL;
}
if (bin && bin->imports_list) {
return bin->imports_list;
}
dex_loadcode (arch, bin);
return bin->imports_list;
}
static RList *methods(RBinFile *arch) {
RBinDexObj *bin;
if (!arch || !arch->o || !arch->o->bin_obj) {
return NULL;
}
bin = (RBinDexObj*) arch->o->bin_obj;
if (!bin->methods_list) {
dex_loadcode (arch, bin);
}
return bin->methods_list;
}
static RList *classes(RBinFile *arch) {
RBinDexObj *bin;
if (!arch || !arch->o || !arch->o->bin_obj) {
return NULL;
}
bin = (RBinDexObj*) arch->o->bin_obj;
if (!bin->classes_list) {
dex_loadcode (arch, bin);
}
return bin->classes_list;
}
static bool already_entry(RList *entries, ut64 vaddr) {
RBinAddr *e;
RListIter *iter;
r_list_foreach (entries, iter, e) {
if (e->vaddr == vaddr) {
return true;
}
}
return false;
}
static RList *entries(RBinFile *arch) {
RListIter *iter;
RBinDexObj *bin;
RBinSymbol *m;
RBinAddr *ptr;
RList *ret;
if (!arch || !arch->o || !arch->o->bin_obj) {
return NULL;
}
bin = (RBinDexObj*) arch->o->bin_obj;
ret = r_list_newf ((RListFree)free);
if (!bin->methods_list) {
dex_loadcode (arch, bin);
}
// STEP 1. ".onCreate(Landroid/os/Bundle;)V"
r_list_foreach (bin->methods_list, iter, m) {
if (strlen (m->name) > 30 && m->bind &&
!strcmp(m->bind, "GLOBAL") &&
!strcmp (m->name + strlen (m->name) - 31,
".onCreate(Landroid/os/Bundle;)V")) {
if (!already_entry (ret, m->paddr)) {
if ((ptr = R_NEW0 (RBinAddr))) {
ptr->paddr = ptr->vaddr = m->paddr;
r_list_append (ret, ptr);
}
}
}
}
// STEP 2. ".main([Ljava/lang/String;)V"
if (r_list_empty (ret)) {
r_list_foreach (bin->methods_list, iter, m) {
if (strlen (m->name) > 26 &&
!strcmp (m->name + strlen (m->name) - 27,
".main([Ljava/lang/String;)V")) {
if (!already_entry (ret, m->paddr)) {
if ((ptr = R_NEW0 (RBinAddr))) {
ptr->paddr = ptr->vaddr = m->paddr;
r_list_append (ret, ptr);
}
}
}
}
}
// STEP 3. NOTHING FOUND POINT TO CODE_INIT
if (r_list_empty (ret)) {
if (!already_entry (ret, bin->code_from)) {
ptr = R_NEW0 (RBinAddr);
if (ptr) {
ptr->paddr = ptr->vaddr = bin->code_from;
r_list_append (ret, ptr);
}
}
}
return ret;
}
static ut64 offset_of_method_idx(RBinFile *arch, struct r_bin_dex_obj_t *dex, int idx) {
ut64 off = dex->header.method_offset + idx;
off = sdb_num_get (mdb, sdb_fmt (0, "method.%d", idx), 0);
return (ut64) off;
}
// TODO: change all return type for all getoffset
static int getoffset(RBinFile *arch, int type, int idx) {
struct r_bin_dex_obj_t *dex = arch->o->bin_obj;
switch (type) {
case 'm': // methods
// TODO: ADD CHECK
return offset_of_method_idx (arch, dex, idx);
case 'o': // objects
break;
case 's': // strings
if (dex->header.strings_size > idx) {
if (dex->strings) return dex->strings[idx];
}
break;
case 't': // type
return dex_get_type_offset (arch, idx);
case 'c': // class
return dex_get_type_offset (arch, idx);
//return sdb_num_get (cdb, sdb_fmt (0, "%d", idx), 0);
}
return -1;
}
static char *getname(RBinFile *arch, int type, int idx) {
struct r_bin_dex_obj_t *dex = arch->o->bin_obj;
switch (type) {
case 'm': // methods
return dex_method_fullname (dex, idx);
case 'c': // classes
return dex_class_name_byid (dex, idx);
case 'f': // fields
return dex_field_name (dex, idx);
}
return NULL;
}
static RList *sections(RBinFile *arch) {
struct r_bin_dex_obj_t *bin = arch->o->bin_obj;
RList *ml = methods (arch);
RBinSection *ptr = NULL;
int ns, fsymsz = 0;
RList *ret = NULL;
RListIter *iter;
RBinSymbol *m;
int fsym = 0;
r_list_foreach (ml, iter, m) {
if (!fsym || m->paddr < fsym) {
fsym = m->paddr;
}
ns = m->paddr + m->size;
if (ns > arch->buf->length) {
continue;
}
if (ns > fsymsz) {
fsymsz = ns;
}
}
if (!fsym) {
return NULL;
}
if (!(ret = r_list_new ())) {
return NULL;
}
ret->free = free;
if ((ptr = R_NEW0 (RBinSection))) {
strcpy (ptr->name, "header");
ptr->size = ptr->vsize = sizeof (struct dex_header_t);
ptr->paddr= ptr->vaddr = 0;
ptr->srwx = R_BIN_SCN_READABLE | R_BIN_SCN_MAP;
ptr->add = true;
r_list_append (ret, ptr);
}
if ((ptr = R_NEW0 (RBinSection))) {
strcpy (ptr->name, "constpool");
//ptr->size = ptr->vsize = fsym;
ptr->paddr= ptr->vaddr = sizeof (struct dex_header_t);
ptr->size = bin->code_from - ptr->vaddr; // fix size
ptr->srwx = R_BIN_SCN_READABLE | R_BIN_SCN_MAP;
ptr->add = true;
r_list_append (ret, ptr);
}
if ((ptr = R_NEW0 (RBinSection))) {
strcpy (ptr->name, "code");
ptr->vaddr = ptr->paddr = bin->code_from; //ptr->vaddr = fsym;
ptr->size = bin->code_to - ptr->paddr;
ptr->srwx = R_BIN_SCN_READABLE | R_BIN_SCN_EXECUTABLE | R_BIN_SCN_MAP;
ptr->add = true;
r_list_append (ret, ptr);
}
if ((ptr = R_NEW0 (RBinSection))) {
//ut64 sz = arch ? r_buf_size (arch->buf): 0;
strcpy (ptr->name, "data");
ptr->paddr = ptr->vaddr = fsymsz+fsym;
if (ptr->vaddr > arch->buf->length) {
ptr->paddr = ptr->vaddr = bin->code_to;
ptr->size = ptr->vsize = arch->buf->length - ptr->vaddr;
} else {
ptr->size = ptr->vsize = arch->buf->length - ptr->vaddr;
// hacky workaround
//dprintf ("Hack\n");
//ptr->size = ptr->vsize = 1024;
}
ptr->srwx = R_BIN_SCN_READABLE | R_BIN_SCN_MAP; //|2;
ptr->add = true;
r_list_append (ret, ptr);
}
return ret;
}
static void header(RBinFile *arch) {
struct r_bin_dex_obj_t *bin = arch->o->bin_obj;
struct r_bin_t *rbin = arch->rbin;
rbin->cb_printf ("DEX file header:\n");
rbin->cb_printf ("magic : 'dex\\n035\\0'\n");
rbin->cb_printf ("checksum : %x\n", bin->header.checksum);
rbin->cb_printf ("signature : %02x%02x...%02x%02x\n", bin->header.signature[0], bin->header.signature[1], bin->header.signature[18], bin->header.signature[19]);
rbin->cb_printf ("file_size : %d\n", bin->header.size);
rbin->cb_printf ("header_size : %d\n", bin->header.header_size);
rbin->cb_printf ("link_size : %d\n", bin->header.linksection_size);
rbin->cb_printf ("link_off : %d (0x%06x)\n", bin->header.linksection_offset, bin->header.linksection_offset);
rbin->cb_printf ("string_ids_size : %d\n", bin->header.strings_size);
rbin->cb_printf ("string_ids_off : %d (0x%06x)\n", bin->header.strings_offset, bin->header.strings_offset);
rbin->cb_printf ("type_ids_size : %d\n", bin->header.types_size);
rbin->cb_printf ("type_ids_off : %d (0x%06x)\n", bin->header.types_offset, bin->header.types_offset);
rbin->cb_printf ("proto_ids_size : %d\n", bin->header.prototypes_size);
rbin->cb_printf ("proto_ids_off : %d (0x%06x)\n", bin->header.prototypes_offset, bin->header.prototypes_offset);
rbin->cb_printf ("field_ids_size : %d\n", bin->header.fields_size);
rbin->cb_printf ("field_ids_off : %d (0x%06x)\n", bin->header.fields_offset, bin->header.fields_offset);
rbin->cb_printf ("method_ids_size : %d\n", bin->header.method_size);
rbin->cb_printf ("method_ids_off : %d (0x%06x)\n", bin->header.method_offset, bin->header.method_offset);
rbin->cb_printf ("class_defs_size : %d\n", bin->header.class_size);
rbin->cb_printf ("class_defs_off : %d (0x%06x)\n", bin->header.class_offset, bin->header.class_offset);
rbin->cb_printf ("data_size : %d\n", bin->header.data_size);
rbin->cb_printf ("data_off : %d (0x%06x)\n\n", bin->header.data_offset, bin->header.data_offset);
// TODO: print information stored in the RBIN not this ugly fix
dexdump = true;
bin->methods_list = NULL;
dex_loadcode (arch, bin);
dexdump = false;
}
static ut64 size(RBinFile *arch) {
int ret;
ut32 off = 0, len = 0;
ut8 u32s[sizeof (ut32)] = {0};
ret = r_buf_read_at (arch->buf, 108, u32s, 4);
if (ret != 4) {
return 0;
}
off = r_read_le32 (u32s);
ret = r_buf_read_at (arch->buf, 104, u32s, 4);
if (ret != 4) {
return 0;
}
len = r_read_le32 (u32s);
return off + len;
}
RBinPlugin r_bin_plugin_dex = {
.name = "dex",
.desc = "dex format bin plugin",
.license = "LGPL3",
.get_sdb = &get_sdb,
.load = &load,
.load_bytes = &load_bytes,
.check = &check,
.check_bytes = &check_bytes,
.baddr = &baddr,
.entries = entries,
.classes = classes,
.sections = sections,
.symbols = methods,
.imports = imports,
.strings = strings,
.info = &info,
.header = &header,
.size = &size,
.get_offset = &getoffset,
.get_name = &getname,
.dbginfo = &r_bin_dbginfo_dex,
};
#ifndef CORELIB
RLibStruct radare_plugin = {
.type = R_LIB_TYPE_BIN,
.data = &r_bin_plugin_dex,
.version = R2_VERSION
};
#endif
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_3181_0 |
crossvul-cpp_data_bad_351_15 | /*
* PKCS15 emulation layer for Italian CNS.
*
* Copyright (C) 2008, Emanuele Pucciarelli <ep@acm.org>
* Many snippets have been taken out from other PKCS15 emulation layer
* modules in this directory; their copyright is their authors'.
*
* 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
*/
/*
* Specifications for the development of this driver come from:
* http://www.servizidemografici.interno.it/sitoCNSD/documentazioneRicerca.do?metodo=contenutoDocumento&servizio=documentazione&ID_DOCUMENTO=1043
*/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#ifdef ENABLE_OPENSSL
#include <openssl/x509.h>
#include <openssl/x509v3.h>
#endif
#include "internal.h"
#include "pkcs15.h"
#include "log.h"
#include "cards.h"
#include "itacns.h"
#include "common/compat_strlcpy.h"
#include "common/compat_strlcat.h"
#ifdef ENABLE_OPENSSL
#include <openssl/x509.h>
#include <openssl/x509v3.h>
#endif
int sc_pkcs15emu_itacns_init_ex(sc_pkcs15_card_t *, struct sc_aid *, sc_pkcs15emu_opt_t *);
static const char path_serial[] = "10001003";
/* Manufacturers */
const char * itacns_mask_manufacturers[] = {
"Unknown",
"Kaitech",
"Gemplus",
"Ghirlanda",
"Giesecke & Devrient",
"Oberthur Card Systems",
"Orga",
"Axalto",
"Siemens",
"STIncard",
"GEP",
"EPS Corp",
"Athena"
};
const char * iso7816_ic_manufacturers[] = {
"Unknown",
"Motorola",
"STMicroelectronics",
"Hitachi",
"NXP Semiconductors",
"Infineon",
"Cylinc",
"Texas Instruments",
"Fujitsu",
"Matsushita",
"NEC",
"Oki",
"Toshiba",
"Mitsubishi",
"Samsung",
"Hynix",
"LG",
"Emosyn-EM",
"INSIDE",
"ORGA",
"SHARP",
"ATMEL",
"EM Microelectronic-Marin",
"KSW Microtec",
"ZMD",
"XICOR",
"Sony",
"Malaysia Microelectronic Solutions",
"Emosyn",
"Shanghai Fudan",
"Magellan",
"Melexis",
"Renesas",
"TAGSYS",
"Transcore",
"Shanghai belling",
"Masktech",
"Innovision",
"Hitachi",
"Cypak",
"Ricoh",
"ASK",
"Unicore",
"Dallas",
"Impinj",
"RightPlug Alliance",
"Broadcom",
"MStar",
"BeeDar",
"RFIDsec",
"Schweizer Electronic",
"AMIC Technology",
"Mikron",
"Fraunhofer",
"IDS Microchip",
"Kovio",
"HMT Microelectronic",
"Silicon Craft",
"Advanced Film Device",
"Nitecrest",
"Verayo",
"HID Gloval",
"Productivity Engineering",
"Austriamicrosystems",
"Gemalto"
};
/* Data files */
static const struct {
const char *label;
const char *path;
int cie_only;
} itacns_data_files[] = {
{ "EF_DatiProcessore", "3F0010001002", 0 },
{ "EF_IDCarta", "3F0010001003", 0 },
{ "EF_DatiSistema", "3F0010001004", 1 },
{ "EF_DatiPersonali", "3F0011001102", 0 },
{ "EF_DatiPersonali_Annotazioni", "3F0011001103", 1 },
{ "EF_Impronte", "3F0011001104", 1 },
{ "EF_Foto", "3F0011001104", 1 },
{ "EF_DatiPersonaliAggiuntivi", "3F0012001201", 0 },
{ "EF_MemoriaResidua", "3F0012001202", 0 },
{ "EF_ServiziInstallati", "3F0012001203", 0 },
{ "EF_INST_FILE", "3F0012004142", 0 },
{ "EF_CardStatus", "3F003F02", 0 },
{ "EF_GDO", "3F002F02", 0 },
{ "EF_RootInstFile", "3F000405", 0 }
};
/*
* Utility functions
*/
static void set_string(char **strp, const char *value)
{
if (*strp)
free(*strp);
*strp = value ? strdup(value) : NULL;
}
static int loadFile(const sc_pkcs15_card_t *p15card, const sc_path_t *path,
u8 *buf, const size_t buflen)
{
int sc_res;
SC_FUNC_CALLED(p15card->card->ctx, 1);
sc_res = sc_select_file(p15card->card, path, NULL);
if(sc_res != SC_SUCCESS)
return sc_res;
sc_res = sc_read_binary(p15card->card, 0, buf, buflen, 0);
return sc_res;
}
/*
* The following functions add objects to the card emulator.
*/
static int itacns_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,
int *ext_info_ok, int *key_usage, int *x_key_usage)
{
int r;
/* const char *label = "Certificate"; */
sc_pkcs15_cert_info_t info;
sc_pkcs15_object_t obj;
#ifdef ENABLE_OPENSSL
X509 *x509;
sc_pkcs15_cert_t *cert;
#endif
SC_FUNC_CALLED(p15card->card->ctx, 1);
if(type != SC_PKCS15_TYPE_CERT_X509) {
sc_debug(p15card->card->ctx, SC_LOG_DEBUG_NORMAL,
"Cannot add a certificate of a type other than X.509");
return 1;
}
*ext_info_ok = 0;
memset(&info, 0, sizeof(info));
memset(&obj, 0, sizeof(obj));
info.id = *id;
info.authority = authority;
if (path)
info.path = *path;
strlcpy(obj.label, label, sizeof(obj.label));
obj.flags = obj_flags;
r = sc_pkcs15emu_add_x509_cert(p15card, &obj, &info);
SC_TEST_RET(p15card->card->ctx, SC_LOG_DEBUG_NORMAL, r,
"Could not add X.509 certificate");
/* If we have OpenSSL, read keyUsage */
#ifdef ENABLE_OPENSSL
r = sc_pkcs15_read_certificate(p15card, &info, &cert);
SC_TEST_RET(p15card->card->ctx, SC_LOG_DEBUG_NORMAL, r,
"Could not read X.509 certificate");
{
const u8 *throwaway = cert->data.value;
x509 = d2i_X509(NULL, &throwaway, cert->data.len);
}
sc_pkcs15_free_certificate(cert);
if (!x509) return SC_SUCCESS;
X509_check_purpose(x509, -1, 0);
if(X509_get_extension_flags(x509) & EXFLAG_KUSAGE) {
*ext_info_ok = 1;
*key_usage = X509_get_key_usage(x509);
*x_key_usage = X509_get_extended_key_usage(x509);
}
OPENSSL_free(x509);
return SC_SUCCESS;
#else /* ENABLE_OPENSSL */
return SC_SUCCESS;
#endif /* ENABLE_OPENSSL */
}
static int itacns_add_pubkey(sc_pkcs15_card_t *p15card,
const sc_path_t *path, const sc_pkcs15_id_t *id, const char *label,
int usage, int ref, int obj_flags, int *modulus_len_out)
{
int r;
sc_pkcs15_pubkey_info_t info;
sc_pkcs15_object_t obj;
SC_FUNC_CALLED(p15card->card->ctx, 1);
memset(&info, 0, sizeof(info));
memset(&obj, 0, sizeof(obj));
info.id = *id;
if (path)
info.path = *path;
info.usage = usage;
info.key_reference = ref;
strlcpy(obj.label, label, sizeof(obj.label));
obj.flags = obj_flags;
/*
* This is hard-coded, unless unforeseen versions of the CNS
* turn up sometime.
*/
info.modulus_length = 1024;
*modulus_len_out = info.modulus_length;
r = sc_pkcs15emu_add_rsa_pubkey(p15card, &obj, &info);
SC_TEST_RET(p15card->card->ctx, SC_LOG_DEBUG_NORMAL, r,
"Could not add pub key");
return r;
}
static int itacns_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;
sc_pkcs15_object_t obj;
SC_FUNC_CALLED(p15card->card->ctx, 1);
if(type != SC_PKCS15_TYPE_PRKEY_RSA) {
sc_debug(p15card->card->ctx, SC_LOG_DEBUG_NORMAL,
"Cannot add a private key of a type other than RSA");
return 1;
}
memset(&info, 0, sizeof(info));
memset(&obj, 0, sizeof(obj));
info.id = *id;
info.modulus_length = modulus_length;
info.usage = usage;
info.native = 1;
info.key_reference = ref;
if (path)
info.path = *path;
obj.flags = obj_flags;
strlcpy(obj.label, label, sizeof(obj.label));
if (auth_id != NULL)
obj.auth_id = *auth_id;
return sc_pkcs15emu_add_rsa_prkey(p15card, &obj, &info);
}
static int itacns_add_pin(sc_pkcs15_card_t *p15card,
char *label,
int id,
int auth_id,
int reference,
sc_path_t *path,
int flags)
{
struct sc_pkcs15_auth_info pin_info;
struct sc_pkcs15_object pin_obj;
SC_FUNC_CALLED(p15card->card->ctx, 1);
memset(&pin_info, 0, sizeof(pin_info));
pin_info.auth_type = SC_PKCS15_PIN_AUTH_TYPE_PIN;
pin_info.auth_id.len = 1;
pin_info.auth_id.value[0] = id;
pin_info.attrs.pin.reference = reference;
pin_info.attrs.pin.flags = flags;
pin_info.attrs.pin.type = SC_PKCS15_PIN_TYPE_ASCII_NUMERIC;
pin_info.attrs.pin.min_length = 5;
pin_info.attrs.pin.stored_length = 8;
pin_info.attrs.pin.max_length = 8;
pin_info.attrs.pin.pad_char = 0xff;
pin_info.logged_in = SC_PIN_STATE_UNKNOWN;
if(path)
pin_info.path = *path;
memset(&pin_obj, 0, sizeof(pin_obj));
strlcpy(pin_obj.label, label, sizeof(pin_obj.label));
pin_obj.flags = SC_PKCS15_CO_FLAG_PRIVATE |
(auth_id ? SC_PKCS15_CO_FLAG_MODIFIABLE : 0);
if (auth_id) {
pin_obj.auth_id.len = 1;
pin_obj.auth_id.value[0] = auth_id;
} else
pin_obj.auth_id.len = 0;
return sc_pkcs15emu_add_pin_obj(p15card, &pin_obj, &pin_info);
}
static int hextoint(char *src, unsigned int len)
{
char hex[16];
char *end;
int res;
if(len >= sizeof(hex))
return -1;
strncpy(hex, src, len+1);
hex[len] = '\0';
res = strtol(hex, &end, 0x10);
if(end != (char*)&hex[len])
return -1;
return res;
}
static int get_name_from_EF_DatiPersonali(unsigned char *EFdata,
char name[], int name_len)
{
/*
* Bytes 0-5 contain the ASCII encoding of the following TLV
* structure's total size, in base 16.
*/
const unsigned int EF_personaldata_maxlen = 400;
const unsigned int tlv_length_size = 6;
char *file = (char*)&EFdata[tlv_length_size];
int file_size = hextoint((char*)EFdata, tlv_length_size);
enum {
f_issuer_code = 0,
f_issuing_date,
f_expiry_date,
f_last_name,
f_first_name,
f_birth_date,
f_sex,
f_height,
f_codice_fiscale,
f_citizenship_code,
f_birth_township_code,
f_birth_country,
f_birth_certificate,
f_residence_township_code,
f_residence_address,
f_expat_notes
};
/* Read the fields up to f_first_name */
struct {
int len;
char value[256];
} fields[f_first_name+1];
int i=0; /* offset inside the file */
int f; /* field number */
if(file_size < 0)
return -1;
/*
* This shouldn't happen, but let us be protected against wrong
* or malicious cards
*/
if(file_size > (int)EF_personaldata_maxlen - (int)tlv_length_size)
file_size = EF_personaldata_maxlen - tlv_length_size;
memset(fields, 0, sizeof(fields));
for(f=0; f<f_first_name+1; f++) {
int field_size;
/* Don't read beyond the allocated buffer */
if(i > file_size)
return -1;
field_size = hextoint((char*) &file[i], 2);
if((field_size < 0) || (field_size+i > file_size))
return -1;
i += 2;
if(field_size >= (int)sizeof(fields[f].value))
return -1;
fields[f].len = field_size;
strncpy(fields[f].value, &file[i], field_size);
fields[f].value[field_size] = '\0';
i += field_size;
}
if (fields[f_first_name].len + fields[f_last_name].len + 1 >= name_len)
return -1;
/* the lengths are already checked that they will fit in buffer */
snprintf(name, name_len, "%.*s %.*s",
fields[f_first_name].len, fields[f_first_name].value,
fields[f_last_name].len, fields[f_last_name].value);
return 0;
}
static int itacns_add_data_files(sc_pkcs15_card_t *p15card)
{
const size_t array_size =
sizeof(itacns_data_files)/sizeof(itacns_data_files[0]);
unsigned int i;
int rv;
sc_pkcs15_data_t *p15_personaldata = NULL;
sc_pkcs15_data_info_t dinfo;
struct sc_pkcs15_object *objs[32];
struct sc_pkcs15_data_info *cinfo;
for(i=0; i < array_size; i++) {
sc_path_t path;
sc_pkcs15_data_info_t data;
sc_pkcs15_object_t obj;
if (itacns_data_files[i].cie_only &&
p15card->card->type != SC_CARD_TYPE_ITACNS_CIE_V2)
continue;
sc_format_path(itacns_data_files[i].path, &path);
memset(&data, 0, sizeof(data));
memset(&obj, 0, sizeof(obj));
strlcpy(data.app_label, itacns_data_files[i].label,
sizeof(data.app_label));
strlcpy(obj.label, itacns_data_files[i].label,
sizeof(obj.label));
data.path = path;
rv = sc_pkcs15emu_add_data_object(p15card, &obj, &data);
SC_TEST_RET(p15card->card->ctx, SC_LOG_DEBUG_NORMAL, rv,
"Could not add data file");
}
/*
* If we got this far, we can read the Personal Data file and glean
* the user's full name. Thus we can use it to put together a
* user-friendlier card name.
*/
memset(&dinfo, 0, sizeof(dinfo));
strcpy(dinfo.app_label, "EF_DatiPersonali");
/* Find EF_DatiPersonali */
rv = sc_pkcs15_get_objects(p15card, SC_PKCS15_TYPE_DATA_OBJECT,
objs, 32);
if(rv < 0) {
sc_debug(p15card->card->ctx, SC_LOG_DEBUG_NORMAL,
"Data enumeration failed");
return SC_SUCCESS;
}
for(i=0; i<32; i++) {
cinfo = (struct sc_pkcs15_data_info *) objs[i]->data;
if(!strcmp("EF_DatiPersonali", objs[i]->label))
break;
}
if(i>=32) {
sc_debug(p15card->card->ctx, SC_LOG_DEBUG_NORMAL,
"Could not find EF_DatiPersonali: "
"keeping generic card name");
return SC_SUCCESS;
}
rv = sc_pkcs15_read_data_object(p15card, cinfo, &p15_personaldata);
if (rv) {
sc_debug(p15card->card->ctx, SC_LOG_DEBUG_NORMAL,
"Could not read EF_DatiPersonali: "
"keeping generic card name");
}
{
char fullname[160];
if(get_name_from_EF_DatiPersonali(p15_personaldata->data,
fullname, sizeof(fullname))) {
sc_debug(p15card->card->ctx, SC_LOG_DEBUG_NORMAL,
"Could not parse EF_DatiPersonali: "
"keeping generic card name");
sc_pkcs15_free_data_object(p15_personaldata);
return SC_SUCCESS;
}
set_string(&p15card->tokeninfo->label, fullname);
}
sc_pkcs15_free_data_object(p15_personaldata);
return SC_SUCCESS;
}
static int itacns_add_keyset(sc_pkcs15_card_t *p15card,
const char *label, int sec_env, sc_pkcs15_id_t *cert_id,
const char *pubkey_path, const char *prkey_path,
unsigned int pubkey_usage_flags, unsigned int prkey_usage_flags,
u8 pin_ref)
{
int r;
sc_path_t path;
sc_path_t *private_path = NULL;
char pinlabel[16];
int fake_puk_authid, pin_flags;
/* This is hard-coded, for the time being. */
int modulus_length = 1024;
/* Public key; not really needed */
/* FIXME: set usage according to the certificate. */
if (pubkey_path) {
sc_format_path(pubkey_path, &path);
r = itacns_add_pubkey(p15card, &path, cert_id, label,
pubkey_usage_flags, sec_env, 0, &modulus_length);
SC_TEST_RET(p15card->card->ctx, SC_LOG_DEBUG_NORMAL, r,
"Could not add public key");
}
/*
* FIXME: usage should be inferred from the X.509 certificate, and not
* from whether the key needs Secure Messaging.
*/
if (prkey_path) {
sc_format_path(prkey_path, &path);
private_path = &path;
}
r = itacns_add_prkey(p15card, cert_id, label, SC_PKCS15_TYPE_PRKEY_RSA,
modulus_length,
prkey_usage_flags,
private_path, sec_env, cert_id, SC_PKCS15_CO_FLAG_PRIVATE);
SC_TEST_RET(p15card->card->ctx, SC_LOG_DEBUG_NORMAL, r,
"Could not add private key");
/* PIN and PUK */
strlcpy(pinlabel, "PIN ", sizeof(pinlabel));
strlcat(pinlabel, label, sizeof(pinlabel));
/* We are making up ID 0x90+ to link the PIN and the PUK. */
fake_puk_authid = 0x90 + pin_ref;
pin_flags = SC_PKCS15_PIN_FLAG_CASE_SENSITIVE
| SC_PKCS15_PIN_FLAG_INITIALIZED;
r = itacns_add_pin(p15card, pinlabel, sec_env, fake_puk_authid, pin_ref,
private_path, pin_flags);
SC_TEST_RET(p15card->card->ctx, SC_LOG_DEBUG_NORMAL, r,
"Could not add PIN");
strlcpy(pinlabel, "PUK ", sizeof(pinlabel));
strlcat(pinlabel, label, sizeof(pinlabel));
/*
* Looking at pkcs15-tcos.c and pkcs15-framework.c, it seems that the
* right thing to do here is to define a PUK as a SO PIN. Can anybody
* comment on this?
*/
pin_flags |= SC_PKCS15_PIN_FLAG_UNBLOCKING_PIN
| SC_PKCS15_PIN_FLAG_UNBLOCK_DISABLED;
r = itacns_add_pin(p15card, pinlabel, fake_puk_authid, 0, pin_ref+1,
private_path, pin_flags);
SC_TEST_RET(p15card->card->ctx, SC_LOG_DEBUG_NORMAL, r,
"Could not add PUK");
return 0;
}
/*
* itacns_check_and_add_keyset() checks for the existence and correctness
* of an X.509 certificate. If it is all right, it adds the related keys;
* otherwise it aborts.
*/
static int itacns_check_and_add_keyset(sc_pkcs15_card_t *p15card,
const char *label, int sec_env, size_t cert_offset,
const char *cert_path, const char *pubkey_path, const char *prkey_path,
u8 pin_ref, int *found_certificates)
{
int r;
sc_path_t path;
sc_pkcs15_id_t cert_id;
int ext_info_ok;
int ku = 0, xku = 0;
int pubkey_usage_flags = 0, prkey_usage_flags = 0;
cert_id.len = 1;
cert_id.value[0] = sec_env;
*found_certificates = 0;
/* Certificate */
if (!cert_path) {
sc_debug(p15card->card->ctx, SC_LOG_DEBUG_NORMAL,
"We cannot use keys without a matching certificate");
return SC_ERROR_NOT_SUPPORTED;
}
sc_format_path(cert_path, &path);
r = sc_select_file(p15card->card, &path, NULL);
if (r == SC_ERROR_FILE_NOT_FOUND)
return 0;
if (r != SC_SUCCESS) {
sc_debug(p15card->card->ctx, SC_LOG_DEBUG_NORMAL,
"Could not find certificate for %s", label);
return r;
}
/*
* Infocamere 1204 (and others?) store a more complex structure. We
* are going to read the first bytes to guess its length, and invoke
* itacns_add_cert so that it only reads the certificate.
*/
if (cert_offset) {
u8 certlen[3];
r = loadFile(p15card, &path, certlen, sizeof(certlen));
SC_TEST_RET(p15card->card->ctx, SC_LOG_DEBUG_NORMAL, r,
"Could not read certificate file");
path.index = cert_offset;
path.count = (certlen[1] << 8) + certlen[2];
/* If those bytes are 00, then we are probably dealing with an
* empty file. */
if (path.count == 0)
return 0;
}
r = itacns_add_cert(p15card, SC_PKCS15_TYPE_CERT_X509, 0,
&path, &cert_id, label, 0, &ext_info_ok, &ku, &xku);
if (r == SC_ERROR_INVALID_ASN1_OBJECT)
return 0;
SC_TEST_RET(p15card->card->ctx, SC_LOG_DEBUG_NORMAL, r,
"Could not add certificate");
(*found_certificates)++;
/* Set usage flags */
if(ext_info_ok) {
#ifdef ENABLE_OPENSSL
if (ku & KU_DIGITAL_SIGNATURE) {
pubkey_usage_flags |= SC_PKCS15_PRKEY_USAGE_VERIFY;
prkey_usage_flags |= SC_PKCS15_PRKEY_USAGE_SIGN;
}
if (ku & KU_NON_REPUDIATION) {
pubkey_usage_flags |= SC_PKCS15_PRKEY_USAGE_VERIFY;
prkey_usage_flags |= SC_PKCS15_PRKEY_USAGE_NONREPUDIATION;
}
if (ku & KU_KEY_ENCIPHERMENT || ku & KU_KEY_AGREEMENT
|| xku & XKU_SSL_CLIENT) {
pubkey_usage_flags |= SC_PKCS15_PRKEY_USAGE_WRAP;
prkey_usage_flags |= SC_PKCS15_PRKEY_USAGE_UNWRAP;
}
if (ku & KU_DATA_ENCIPHERMENT || xku & XKU_SMIME) {
pubkey_usage_flags |= SC_PKCS15_PRKEY_USAGE_ENCRYPT;
prkey_usage_flags |= SC_PKCS15_PRKEY_USAGE_DECRYPT;
}
#else /* ENABLE_OPENSSL */
sc_debug(p15card->card->ctx, SC_LOG_DEBUG_NORMAL,
"Extended certificate info retrieved without OpenSSL. "
"How is this possible?");
return SC_ERROR_INTERNAL;
#endif /* ENABLE_OPENSSL */
} else {
/* Certificate info not retrieved; fall back onto defaults */
pubkey_usage_flags =
SC_PKCS15_PRKEY_USAGE_VERIFY
| SC_PKCS15_PRKEY_USAGE_WRAP;
prkey_usage_flags =
SC_PKCS15_PRKEY_USAGE_SIGN
| SC_PKCS15_PRKEY_USAGE_UNWRAP;
}
r = itacns_add_keyset(p15card, label, sec_env, &cert_id,
pubkey_path, prkey_path, pubkey_usage_flags, prkey_usage_flags,
pin_ref);
SC_TEST_RET(p15card->card->ctx, SC_LOG_DEBUG_NORMAL, r,
"Could not add keys for this certificate");
return r;
}
/* Initialization. */
static int itacns_init(sc_pkcs15_card_t *p15card)
{
int r;
sc_path_t path;
int certificate_count = 0;
int found_certs;
int card_is_cie_v1, cns0_secenv;
SC_FUNC_CALLED(p15card->card->ctx, 1);
set_string(&p15card->tokeninfo->label, p15card->card->name);
if(p15card->card->drv_data) {
unsigned int mask_code, ic_code;
char buffer[256];
itacns_drv_data_t *data =
(itacns_drv_data_t*) p15card->card->drv_data;
mask_code = data->mask_manufacturer_code;
if (mask_code >= sizeof(itacns_mask_manufacturers)
/sizeof(itacns_mask_manufacturers[0]))
mask_code = 0;
ic_code = data->ic_manufacturer_code;
if (ic_code >= sizeof(iso7816_ic_manufacturers)
/sizeof(iso7816_ic_manufacturers[0]))
ic_code = 0;
snprintf(buffer, sizeof(buffer), "IC: %s; mask: %s",
iso7816_ic_manufacturers[ic_code],
itacns_mask_manufacturers[mask_code]);
set_string(&p15card->tokeninfo->manufacturer_id, buffer);
}
/* Read and set serial */
{
u8 serial[17];
int bytes;
sc_format_path(path_serial, &path);
bytes = loadFile(p15card, &path, serial, 16);
if (bytes < 0) return bytes;
if (bytes > 16) return -1;
serial[bytes] = '\0';
set_string(&p15card->tokeninfo->serial_number, (char*)serial);
}
/* Is the card a CIE v1? */
card_is_cie_v1 =
(p15card->card->type == SC_CARD_TYPE_ITACNS_CIE_V1)
|| (p15card->card->type == SC_CARD_TYPE_CARDOS_CIE_V1);
cns0_secenv = (card_is_cie_v1 ? 0x31 : 0x01);
/* If it's a Siemens CIE v1 card, set algo flags accordingly. */
if (card_is_cie_v1) {
int i;
for (i = 0; i < p15card->card->algorithm_count; i++) {
sc_algorithm_info_t *info =
&p15card->card->algorithms[i];
if (info->algorithm != SC_ALGORITHM_RSA)
continue;
info->flags &= ~(SC_ALGORITHM_RSA_RAW
| SC_ALGORITHM_RSA_HASH_NONE);
info->flags |= (SC_ALGORITHM_RSA_PAD_PKCS1
| SC_ALGORITHM_RSA_HASHES);
}
}
/* Data files */
r = itacns_add_data_files(p15card);
SC_TEST_RET(p15card->card->ctx, SC_LOG_DEBUG_NORMAL, r,
"Could not add data files");
/*** Certificate and keys. ***/
/* Standard CNS */
r = itacns_check_and_add_keyset(p15card, "CNS0", cns0_secenv,
0, "3F0011001101", "3F003F01", NULL,
0x10, &found_certs);
SC_TEST_RET(p15card->card->ctx, SC_LOG_DEBUG_NORMAL, r,
"Could not add CNS0");
certificate_count += found_certs;
/* Infocamere 1204 */
r = itacns_check_and_add_keyset(p15card, "CNS01", 0x21,
5, "3F002FFF8228", NULL, "3F002FFF0000",
0x10, &found_certs);
SC_TEST_RET(p15card->card->ctx, SC_LOG_DEBUG_NORMAL, r,
"Could not add CNS01");
certificate_count += found_certs;
/* Digital signature */
r = itacns_check_and_add_keyset(p15card, "CNS1", 0x10,
0, "3F0014009010", "3F00140081108010", "3F0014008110",
0x1a, &found_certs);
SC_TEST_RET(p15card->card->ctx, SC_LOG_DEBUG_NORMAL, r,
"Could not add CNS1");
certificate_count += found_certs;
/* Did we find anything? */
if (certificate_count == 0)
sc_debug(p15card->card->ctx, SC_LOG_DEBUG_VERBOSE,
"Warning: no certificates found!");
/* Back to Master File */
sc_format_path("3F00", &path);
r = sc_select_file(p15card->card, &path, NULL);
SC_TEST_RET(p15card->card->ctx, SC_LOG_DEBUG_NORMAL, r,
"Could not select master file again");
return r;
}
int sc_pkcs15emu_itacns_init_ex(sc_pkcs15_card_t *p15card, struct sc_aid *aid,
sc_pkcs15emu_opt_t *opts)
{
sc_card_t *card = p15card->card;
SC_FUNC_CALLED(card->ctx, 1);
/* Check card */
if (!(opts && opts->flags & SC_PKCS15EMU_FLAGS_NO_CHECK)) {
if (! (
(card->type > SC_CARD_TYPE_ITACNS_BASE &&
card->type < SC_CARD_TYPE_ITACNS_BASE + 1000)
|| card->type == SC_CARD_TYPE_CARDOS_CIE_V1)
)
return SC_ERROR_WRONG_CARD;
}
/* Init card */
return itacns_init(p15card);
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_351_15 |
crossvul-cpp_data_bad_2861_0 | /* radare - LGPL - Copyright 2017 - pancake, cgvwzq */
// http://webassembly.org/docs/binary-encoding/#module-structure
#include <stdio.h>
#include <string.h>
#include <stdint.h>
#include <stdarg.h>
#include <sys/types.h>
#include "../../bin/format/wasm/wasm.h"
typedef enum {
// Control flow operators
WASM_OP_TRAP = 0x00,
WASM_OP_NOP,
WASM_OP_BLOCK,
WASM_OP_LOOP,
WASM_OP_IF,
WASM_OP_ELSE,
WASM_OP_END = 0x0b,
WASM_OP_BR,
WASM_OP_BRIF,
WASM_OP_BRTABLE,
WASM_OP_RETURN,
// Call operators
WASM_OP_CALL = 0x10,
WASM_OP_CALLINDIRECT,
// Parametric operators
WASM_OP_DROP = 0x1a,
WASM_OP_SELECT,
// Variable access
WASM_OP_GETLOCAL = 0x20,
WASM_OP_SETLOCAL,
WASM_OP_TEELOCAL,
WASM_OP_GETGLOBAL,
WASM_OP_SETGLOBAL,
// Memory-related operators
WASM_OP_I32LOAD = 0x28,
WASM_OP_I64LOAD,
WASM_OP_F32LOAD,
WASM_OP_F64LOAD,
WASM_OP_I32LOAD8S,
WASM_OP_I32LOAD8U,
WASM_OP_I32LOAD16S,
WASM_OP_I32LOAD16U,
WASM_OP_I64LOAD8S,
WASM_OP_I64LOAD8U,
WASM_OP_I64LOAD16S,
WASM_OP_I64LOAD16U,
WASM_OP_I64LOAD32S,
WASM_OP_I64LOAD32U,
WASM_OP_I32STORE,
WASM_OP_I64STORE,
WASM_OP_F32STORE,
WASM_OP_F64STORE,
WASM_OP_I32STORE8,
WASM_OP_I32STORE16,
WASM_OP_I64STORE8,
WASM_OP_I64STORE16,
WASM_OP_I64STORE32,
WASM_OP_CURRENTMEMORY,
WASM_OP_GROWMEMORY,
// Constants
WASM_OP_I32CONST,
WASM_OP_I64CONST,
WASM_OP_F32CONST,
WASM_OP_F64CONST,
// Comparison operators
WASM_OP_I32EQZ,
WASM_OP_I32EQ,
WASM_OP_I32NE,
WASM_OP_I32LTS,
WASM_OP_I32LTU,
WASM_OP_I32GTS,
WASM_OP_I32GTU,
WASM_OP_I32LES,
WASM_OP_I32LEU,
WASM_OP_I32GES,
WASM_OP_I32GEU,
WASM_OP_I64EQZ,
WASM_OP_I64EQ,
WASM_OP_I64NE,
WASM_OP_I64LTS,
WASM_OP_I64LTU,
WASM_OP_I64GTS,
WASM_OP_I64GTU,
WASM_OP_I64LES,
WASM_OP_I64LEU,
WASM_OP_I64GES,
WASM_OP_I64GEU,
WASM_OP_F32EQ,
WASM_OP_F32NE,
WASM_OP_F32LT,
WASM_OP_F32GT,
WASM_OP_F32LE,
WASM_OP_F32GE,
WASM_OP_F64EQ,
WASM_OP_F64NE,
WASM_OP_F64LT,
WASM_OP_F64GT,
WASM_OP_F64LE,
WASM_OP_F64GE,
// Numeric operators
WASM_OP_I32CLZ,
WASM_OP_I32CTZ,
WASM_OP_I32POPCNT,
WASM_OP_I32ADD,
WASM_OP_I32SUB,
WASM_OP_I32MUL,
WASM_OP_I32DIVS,
WASM_OP_I32DIVU,
WASM_OP_I32REMS,
WASM_OP_I32REMU,
WASM_OP_I32AND,
WASM_OP_I32OR,
WASM_OP_I32XOR,
WASM_OP_I32SHL,
WASM_OP_I32SHRS,
WASM_OP_I32SHRU,
WASM_OP_I32ROTL,
WASM_OP_I32ROTR,
WASM_OP_I64CLZ,
WASM_OP_I64CTZ,
WASM_OP_I64POPCNT,
WASM_OP_I64ADD,
WASM_OP_I64SUB,
WASM_OP_I64MUL,
WASM_OP_I64DIVS,
WASM_OP_I64DIVU,
WASM_OP_I64REMS,
WASM_OP_I64REMU,
WASM_OP_I64AND,
WASM_OP_I64OR,
WASM_OP_I64XOR,
WASM_OP_I64SHL,
WASM_OP_I64SHRS,
WASM_OP_I64SHRU,
WASM_OP_I64ROTL,
WASM_OP_I64ROTR,
WASM_OP_F32ABS,
WASM_OP_F32NEG,
WASM_OP_F32CEIL,
WASM_OP_F32FLOOR,
WASM_OP_F32TRUNC,
WASM_OP_F32NEAREST,
WASM_OP_F32SQRT,
WASM_OP_F32ADD,
WASM_OP_F32SUB,
WASM_OP_F32MUL,
WASM_OP_F32DIV,
WASM_OP_F32MIN,
WASM_OP_F32MAX,
WASM_OP_F32COPYSIGN,
WASM_OP_F64ABS,
WASM_OP_F64NEG,
WASM_OP_F64CEIL,
WASM_OP_F64FLOOR,
WASM_OP_F64TRUNC,
WASM_OP_F64NEAREST,
WASM_OP_F64SQRT,
WASM_OP_F64ADD,
WASM_OP_F64SUB,
WASM_OP_F64MUL,
WASM_OP_F64DIV,
WASM_OP_F64MIN,
WASM_OP_F64MAX,
WASM_OP_F64COPYSIGN,
// Conversions
WASM_OP_I32WRAPI64,
WASM_OP_I32TRUNCSF32,
WASM_OP_I32TRUNCUF32,
WASM_OP_I32TRUNCSF64,
WASM_OP_I32TRUNCUF64,
WASM_OP_I64EXTENDSI32,
WASM_OP_I64EXTENDUI32,
WASM_OP_I64TRUNCSF32,
WASM_OP_I64TRUNCUF32,
WASM_OP_I64TRUNCSF64,
WASM_OP_I64TRUNCUF64,
WASM_OP_F32CONVERTSI32,
WASM_OP_F32CONVERTUI32,
WASM_OP_F32CONVERTSI64,
WASM_OP_F32CONVERTUI64,
WASM_OP_F32DEMOTEF64,
WASM_OP_F64CONVERTSI32,
WASM_OP_F64CONVERTUI32,
WASM_OP_F64CONVERTSI64,
WASM_OP_F64CONVERTUI64,
WASM_OP_F64PROMOTEF32,
// Reinterpretations
WASM_OP_I32REINTERPRETF32,
WASM_OP_I64REINTERPRETF64,
WASM_OP_F32REINTERPRETI32,
WASM_OP_F64REINTERPRETI64,
// Extensions
// ...
} WasmOpCodes;
typedef struct {
WasmOpCodes op;
int len;
char txt[R_ASM_BUFSIZE];
} WasmOp;
typedef struct {
const char *txt;
size_t min, max;
} WasmOpDef;
static WasmOpDef opcodes[256] = {
[WASM_OP_TRAP] = { "trap", 1, 1 },
[WASM_OP_NOP] = { "nop", 1, 1 },
[WASM_OP_BLOCK] = { "block", 2, 2 },
[WASM_OP_LOOP] = { "loop", 2, 2 },
[WASM_OP_IF] = { "if", 2, 2 },
[WASM_OP_ELSE] = { "else", 1, 1 },
[WASM_OP_END] = { "end", 1, 1 },
[WASM_OP_BR] = { "br", 2, 2 },
[WASM_OP_BRIF] = { "br_if", 2, 2 },
[WASM_OP_BRTABLE] = { "brtable", 3, 0 },
[WASM_OP_RETURN] = { "return", 1, 1 },
[WASM_OP_CALL] = { "call" , 2, 2 },
[WASM_OP_CALLINDIRECT] = { "call_indirect", 3, 3 },
[WASM_OP_DROP] = { "drop", 1, 1 },
[WASM_OP_SELECT] = { "select", 1, 1 },
[WASM_OP_GETLOCAL] = { "get_local", 2, 2 },
[WASM_OP_SETLOCAL] = { "set_local", 2, 2 },
[WASM_OP_TEELOCAL] = { "tee_local", 2, 2 },
[WASM_OP_GETGLOBAL] = { "get_global", 2, 2 },
[WASM_OP_SETGLOBAL] = { "set_global", 2, 2 },
[WASM_OP_I32LOAD] = { "i32.load", 3, 3 },
[WASM_OP_I64LOAD] = { "i64.load", 3, 3 },
[WASM_OP_F32LOAD] = { "f32.load", 3, 3 },
[WASM_OP_F64LOAD] = { "f64.load", 3, 3 },
[WASM_OP_I32LOAD8S] = { "i32.load8_s", 3, 3 },
[WASM_OP_I32LOAD8U] = { "i32.load8_u", 3, 3 },
[WASM_OP_I32LOAD16S] = { "i32.load16_s", 3, 3 },
[WASM_OP_I32LOAD16U] = { "i32.load_16_u", 3, 3 },
[WASM_OP_I64LOAD8S] = { "i64.load8_s", 3, 3 },
[WASM_OP_I64LOAD8U] = { "i64.load8_u", 3, 3 },
[WASM_OP_I64LOAD16S] = { "i64.load16_s", 3, 3 },
[WASM_OP_I64LOAD16U] = { "i64.load16_u", 3, 3 },
[WASM_OP_I64LOAD32S] = { "i64.load32_s", 3, 3 },
[WASM_OP_I64LOAD32U] = { "i64.load32_u", 3, 3 },
[WASM_OP_I32STORE] = { "i32.store", 3, 3 },
[WASM_OP_I64STORE] = { "i64.store", 3, 3 },
[WASM_OP_F32STORE] = { "f32.store", 3, 3 },
[WASM_OP_F64STORE] = { "f64.store", 3, 3 },
[WASM_OP_I32STORE8] = { "i32.store8", 3, 3 },
[WASM_OP_I32STORE16] = { "i32.store16", 3, 3 },
[WASM_OP_I64STORE8] = { "i64.store8", 3, 3 },
[WASM_OP_I64STORE16] = { "i64.store16", 3, 3 },
[WASM_OP_I64STORE32] = { "i64.store32", 3, 3 },
[WASM_OP_CURRENTMEMORY] = { "current_memory", 2, 2 },
[WASM_OP_GROWMEMORY] = { "grow_memory", 2, 2 },
[WASM_OP_I32CONST] = { "i32.const", 2, 2 },
[WASM_OP_I64CONST] = { "i64.const", 2, 2 },
[WASM_OP_F32CONST] = { "f32.const", 2, 2 },
[WASM_OP_F64CONST] = { "f64.const", 2, 2 },
[WASM_OP_I32EQZ] = { "i32.eqz", 1, 1 },
[WASM_OP_I32EQ] = { "i32.eq", 1, 1 },
[WASM_OP_I32NE] = { "i32.ne", 1, 1},
[WASM_OP_I32LTS] = { "i32.lt_s", 1, 1 },
[WASM_OP_I32LTU] = { "i32.lt_u", 1, 1 },
[WASM_OP_I32GTS] = { "i32.gt_s", 1, 1 },
[WASM_OP_I32GTU] = { "i32.gt_u", 1, 1 },
[WASM_OP_I32LES] = { "i32.le_s", 1, 1 },
[WASM_OP_I32LEU] = { "i32.le_u", 1, 1 },
[WASM_OP_I32GES] = { "i32.ge_s", 1, 1 },
[WASM_OP_I32GEU] = { "i32.ge_u", 1, 1 },
[WASM_OP_I64EQZ] = { "i64.eqz", 1, 1 },
[WASM_OP_I64EQ] = {" i64.eq", 1, 1 },
[WASM_OP_I64NE] = {" i64.ne", 1, 1 },
[WASM_OP_I64LTS] = { "i64.lt_s", 1, 1 },
[WASM_OP_I64LTU] = { "i64.lt_u", 1, 1 },
[WASM_OP_I64GTS] = { "i64.gt_s", 1, 1 },
[WASM_OP_I64GTU] = { "i64.gt_u", 1, 1 },
[WASM_OP_I64LES] = { "i64.le_s", 1, 1 },
[WASM_OP_I64LEU] = { "i64.le_u", 1, 1 },
[WASM_OP_I64GES] = { "i64.ge_s", 1, 1 },
[WASM_OP_I64GEU] = { "i64.ge_u", 1, 1 },
[WASM_OP_F32EQ] = { "f32.eq", 1, 1 },
[WASM_OP_F32NE] = { "f32.ne", 1, 1 },
[WASM_OP_F32LT] = { "f32.lt", 1, 1 },
[WASM_OP_F32GT] = { "f32.gt", 1, 1 },
[WASM_OP_F32LE] = { "f32.le", 1, 1 },
[WASM_OP_F32GE] = { "f32.ge", 1, 1 },
[WASM_OP_F64EQ] = { "f64.eq", 1, 1 },
[WASM_OP_F64NE] = { "f64.ne", 1, 1 },
[WASM_OP_F64LT] = { "f64.lt", 1, 1 },
[WASM_OP_F64GT] = { "f64.gt", 1, 1 },
[WASM_OP_F64LE] = { "f64.le", 1, 1 },
[WASM_OP_F64GE] = { "f64.ge", 1, 1 },
[WASM_OP_I32CLZ] = { "i32.clz", 1, 1 },
[WASM_OP_I32CTZ] = { "i32.ctz", 1, 1 },
[WASM_OP_I32POPCNT] = { "i32.popcnt", 1, 1 },
[WASM_OP_I32ADD] = { "i32.add", 1, 1 },
[WASM_OP_I32SUB] = { "i32.sub", 1, 1 },
[WASM_OP_I32MUL] = { "i32.mul", 1, 1 },
[WASM_OP_I32DIVS] = { "i32.div_s", 1, 1 },
[WASM_OP_I32DIVU] = { "i32.div_u", 1, 1 },
[WASM_OP_I32REMS] = { "i32.rem_s", 1, 1 },
[WASM_OP_I32REMU] = { "i32.rem_u", 1, 1 },
[WASM_OP_I32AND] = { "i32.and", 1, 1 },
[WASM_OP_I32OR] = { "i32.or", 1, 1 },
[WASM_OP_I32XOR] = { "i32.xor", 1, 1 },
[WASM_OP_I32SHL] = { "i32.shl", 1, 1 },
[WASM_OP_I32SHRS] = { "i32.shr_s", 1, 1 },
[WASM_OP_I32SHRU] = { "i32.shr_u", 1, 1 },
[WASM_OP_I32ROTL] = { "i32.rotl", 1, 1 },
[WASM_OP_I32ROTR] = { "i32.rotr", 1, 1 },
[WASM_OP_I64CLZ] = { "i64.clz", 1, 1 },
[WASM_OP_I64CTZ] = { "i64.ctz", 1, 1 },
[WASM_OP_I64POPCNT] = { "i64.popcnt", 1, 1 },
[WASM_OP_I64ADD] = { "i64.add", 1, 1 },
[WASM_OP_I64SUB] = { "i64.sub", 1, 1 },
[WASM_OP_I64MUL] = { "i64.mul", 1, 1 },
[WASM_OP_I64DIVS] = { "i64.div_s", 1, 1 },
[WASM_OP_I64DIVU] = { "i64.div_u", 1, 1 },
[WASM_OP_I64REMS] = { "i64.rem_s", 1, 1 },
[WASM_OP_I64REMU] = { "i64.rem_u", 1, 1 },
[WASM_OP_I64AND] = { "i64.and", 1, 1 },
[WASM_OP_I64OR] = { "i64.or", 1, 1 },
[WASM_OP_I64XOR] = { "i64.xor", 1, 1 },
[WASM_OP_I64SHL] = { "i64.shl", 1, 1 },
[WASM_OP_I64SHRS] = { "i64.shr_s", 1, 1 },
[WASM_OP_I64SHRU] = { "i64.shr_u", 1, 1 },
[WASM_OP_I64ROTL] = { "i64.rotl", 1, 1 },
[WASM_OP_I64ROTR] = { "i64.rotr", 1, 1 },
[WASM_OP_F32ABS] = { "f32.abs", 1, 1 },
[WASM_OP_F32NEG] = { "f32.neg", 1, 1 },
[WASM_OP_F32CEIL] = { "f32.ceil", 1, 1 },
[WASM_OP_F32FLOOR] = { "f32.floor", 1, 1 },
[WASM_OP_F32TRUNC] = { "f32.trunc", 1, 1 },
[WASM_OP_F32NEAREST] = { "f32.nearest", 1, 1 },
[WASM_OP_F32SQRT] = { "f32.sqrt", 1, 1 },
[WASM_OP_F32ADD] = { "f32.add", 1, 1 },
[WASM_OP_F32SUB] = { "f32.sub", 1, 1 },
[WASM_OP_F32MUL] = { "f32.mul", 1, 1 },
[WASM_OP_F32DIV] = { "f32.div", 1, 1 },
[WASM_OP_F32MIN] = { "f32.min", 1, 1 },
[WASM_OP_F32MAX] = { "f32.max", 1, 1 },
[WASM_OP_F32COPYSIGN] = {" f32.copysign", 1, 1 },
[WASM_OP_F64ABS] = { "f64.abs", 1, 1 },
[WASM_OP_F64NEG] = { "f64.neg", 1, 1 },
[WASM_OP_F64CEIL] = { "f64.ceil", 1, 1 },
[WASM_OP_F64FLOOR] = { "f64.floor", 1, 1 },
[WASM_OP_F64TRUNC] = { "f64.trunc", 1, 1 },
[WASM_OP_F64NEAREST] = { "f64.nearest", 1, 1 },
[WASM_OP_F64SQRT] = { "f64.sqrt", 1, 1 },
[WASM_OP_F64ADD] = { "f64.add", 1, 1 },
[WASM_OP_F64SUB] = { "f64.sub", 1, 1 },
[WASM_OP_F64MUL] = { "f64.mul", 1, 1 },
[WASM_OP_F64DIV] = { "f64.div", 1, 1 },
[WASM_OP_F64MIN] = { "f64.min", 1, 1 },
[WASM_OP_F64MAX] = { "f64.max", 1, 1 },
[WASM_OP_F64COPYSIGN] = { "f64.copysign", 1, 1 },
[WASM_OP_I32WRAPI64] = { "i32.wrap/i64", 1, 1 },
[WASM_OP_I32TRUNCSF32] = { "i32.trunc_s/f32", 1, 1 },
[WASM_OP_I32TRUNCUF32] = { "i32.trunc_u/f32", 1, 1 },
[WASM_OP_I32TRUNCSF64] = { "i32.trunc_s/f64", 1, 1 },
[WASM_OP_I32TRUNCUF64] = { "i32.trunc_u/f64", 1, 1 },
[WASM_OP_I64EXTENDSI32] = { "i64.extend_s/i32", 1, 1 },
[WASM_OP_I64EXTENDUI32] = { "i64.extend_u/i32", 1, 1 },
[WASM_OP_I64TRUNCSF32] = { "i64.trunc_s/f32", 1, 1 },
[WASM_OP_I64TRUNCUF32] = { "i64.trunc_u/f32", 1, 1 },
[WASM_OP_I64TRUNCSF64] = { "i64.trunc_s/f64", 1, 1 },
[WASM_OP_I64TRUNCUF64] = { "i64.trunc_u/f64", 1, 1 },
[WASM_OP_F32CONVERTSI32] = { "f32.convert_s/i32", 1, 1 },
[WASM_OP_F32CONVERTUI32] = { "f32.convert_u/i32", 1, 1 },
[WASM_OP_F32CONVERTSI64] = { "f32.convert_s/i64", 1, 1 },
[WASM_OP_F32CONVERTUI64] = { "f32.convert_u/i64", 1, 1 },
[WASM_OP_F32DEMOTEF64] = { "f32.demote/f64", 1, 1 },
[WASM_OP_F64CONVERTSI32] = { "f64.convert_s/i32", 1, 1 },
[WASM_OP_F64CONVERTUI32] = { "f64.convert_u/i32", 1, 1 },
[WASM_OP_F64CONVERTSI64] = { "f64.convert_s/i64", 1, 1 },
[WASM_OP_F64CONVERTUI64] = { "f64.convert_u/i64", 1, 1 },
[WASM_OP_F64PROMOTEF32] = { "f64.promote/f32", 1, 1 },
[WASM_OP_I32REINTERPRETF32] = { "i32.reinterpret/f32", 1, 1 },
[WASM_OP_I64REINTERPRETF64] = { "i64.reinterpret/f64", 1, 1 },
[WASM_OP_F32REINTERPRETI32] = { "f32.reinterpret/i32", 1, 1 },
[WASM_OP_F64REINTERPRETI64] = { "f64/reinterpret/i64", 1, 1 }
};
int wasm_asm(const char *str, unsigned char *buf, int buf_len) {
// TODO: add immediates assembly
int i = 0, len = -1;
char tmp[R_ASM_BUFSIZE];
while (str[i] != ' ' && i < buf_len) {
tmp[i] = str[i];
i++;
}
tmp[i] = 0;
for (i = 0; i < 0xff; i++) {
WasmOpDef *opdef = &opcodes[i];
if (opdef->txt) {
if (!strcmp (opdef->txt, tmp)) {
buf[0] = i;
return 1;
}
}
}
return len;
}
int wasm_dis(WasmOp *op, const unsigned char *buf, int buf_len) {
op->len = 1;
op->op = buf[0];
if (op->op > 0xbf) return 1;
// add support for extension opcodes (SIMD + atomics)
WasmOpDef *opdef = &opcodes[op->op];
switch (op->op) {
case WASM_OP_TRAP:
case WASM_OP_NOP:
case WASM_OP_ELSE:
case WASM_OP_RETURN:
case WASM_OP_DROP:
case WASM_OP_SELECT:
case WASM_OP_I32EQZ:
case WASM_OP_I32EQ:
case WASM_OP_I32NE:
case WASM_OP_I32LTS:
case WASM_OP_I32LTU:
case WASM_OP_I32GTS:
case WASM_OP_I32GTU:
case WASM_OP_I32LES:
case WASM_OP_I32LEU:
case WASM_OP_I32GES:
case WASM_OP_I32GEU:
case WASM_OP_I64EQZ:
case WASM_OP_I64EQ:
case WASM_OP_I64NE:
case WASM_OP_I64LTS:
case WASM_OP_I64LTU:
case WASM_OP_I64GTS:
case WASM_OP_I64GTU:
case WASM_OP_I64LES:
case WASM_OP_I64LEU:
case WASM_OP_I64GES:
case WASM_OP_I64GEU:
case WASM_OP_F32EQ:
case WASM_OP_F32NE:
case WASM_OP_F32LT:
case WASM_OP_F32GT:
case WASM_OP_F32LE:
case WASM_OP_F32GE:
case WASM_OP_F64EQ:
case WASM_OP_F64NE:
case WASM_OP_F64LT:
case WASM_OP_F64GT:
case WASM_OP_F64LE:
case WASM_OP_F64GE:
case WASM_OP_I32CLZ:
case WASM_OP_I32CTZ:
case WASM_OP_I32POPCNT:
case WASM_OP_I32ADD:
case WASM_OP_I32SUB:
case WASM_OP_I32MUL:
case WASM_OP_I32DIVS:
case WASM_OP_I32DIVU:
case WASM_OP_I32REMS:
case WASM_OP_I32REMU:
case WASM_OP_I32AND:
case WASM_OP_I32OR:
case WASM_OP_I32XOR:
case WASM_OP_I32SHL:
case WASM_OP_I32SHRS:
case WASM_OP_I32SHRU:
case WASM_OP_I32ROTL:
case WASM_OP_I32ROTR:
case WASM_OP_I64CLZ:
case WASM_OP_I64CTZ:
case WASM_OP_I64POPCNT:
case WASM_OP_I64ADD:
case WASM_OP_I64SUB:
case WASM_OP_I64MUL:
case WASM_OP_I64DIVS:
case WASM_OP_I64DIVU:
case WASM_OP_I64REMS:
case WASM_OP_I64REMU:
case WASM_OP_I64AND:
case WASM_OP_I64OR:
case WASM_OP_I64XOR:
case WASM_OP_I64SHL:
case WASM_OP_I64SHRS:
case WASM_OP_I64SHRU:
case WASM_OP_I64ROTL:
case WASM_OP_I64ROTR:
case WASM_OP_F32ABS:
case WASM_OP_F32NEG:
case WASM_OP_F32CEIL:
case WASM_OP_F32FLOOR:
case WASM_OP_F32TRUNC:
case WASM_OP_F32NEAREST:
case WASM_OP_F32SQRT:
case WASM_OP_F32ADD:
case WASM_OP_F32SUB:
case WASM_OP_F32MUL:
case WASM_OP_F32DIV:
case WASM_OP_F32MIN:
case WASM_OP_F32MAX:
case WASM_OP_F32COPYSIGN:
case WASM_OP_F64ABS:
case WASM_OP_F64NEG:
case WASM_OP_F64CEIL:
case WASM_OP_F64FLOOR:
case WASM_OP_F64TRUNC:
case WASM_OP_F64NEAREST:
case WASM_OP_F64SQRT:
case WASM_OP_F64ADD:
case WASM_OP_F64SUB:
case WASM_OP_F64MUL:
case WASM_OP_F64DIV:
case WASM_OP_F64MIN:
case WASM_OP_F64MAX:
case WASM_OP_F64COPYSIGN:
case WASM_OP_I32WRAPI64:
case WASM_OP_I32TRUNCSF32:
case WASM_OP_I32TRUNCUF32:
case WASM_OP_I32TRUNCSF64:
case WASM_OP_I32TRUNCUF64:
case WASM_OP_I64EXTENDSI32:
case WASM_OP_I64EXTENDUI32:
case WASM_OP_I64TRUNCSF32:
case WASM_OP_I64TRUNCUF32:
case WASM_OP_I64TRUNCSF64:
case WASM_OP_I64TRUNCUF64:
case WASM_OP_F32CONVERTSI32:
case WASM_OP_F32CONVERTUI32:
case WASM_OP_F32CONVERTSI64:
case WASM_OP_F32CONVERTUI64:
case WASM_OP_F32DEMOTEF64:
case WASM_OP_F64CONVERTSI32:
case WASM_OP_F64CONVERTUI32:
case WASM_OP_F64CONVERTSI64:
case WASM_OP_F64CONVERTUI64:
case WASM_OP_F64PROMOTEF32:
case WASM_OP_I32REINTERPRETF32:
case WASM_OP_I64REINTERPRETF64:
case WASM_OP_F32REINTERPRETI32:
case WASM_OP_F64REINTERPRETI64:
case WASM_OP_END:
{
snprintf (op->txt, R_ASM_BUFSIZE, "%s", opdef->txt);
}
break;
case WASM_OP_BLOCK:
case WASM_OP_LOOP:
case WASM_OP_IF:
{
st32 val = 0;
size_t n = read_i32_leb128 (buf + 1, buf + buf_len, &val);
if (!(n > 0 && n < buf_len)) goto err;
switch (0x80 - val) {
case R_BIN_WASM_VALUETYPE_EMPTY:
snprintf (op->txt, R_ASM_BUFSIZE, "%s", opdef->txt);
break;
case R_BIN_WASM_VALUETYPE_i32:
snprintf (op->txt, R_ASM_BUFSIZE, "%s (result i32)", opdef->txt);
break;
case R_BIN_WASM_VALUETYPE_i64:
snprintf (op->txt, R_ASM_BUFSIZE, "%s (result i64)", opdef->txt);
break;
case R_BIN_WASM_VALUETYPE_f32:
snprintf (op->txt, R_ASM_BUFSIZE, "%s (result f32)", opdef->txt);
break;
case R_BIN_WASM_VALUETYPE_f64:
snprintf (op->txt, R_ASM_BUFSIZE, "%s (result f64)", opdef->txt);
break;
default:
snprintf (op->txt, R_ASM_BUFSIZE, "%s (result ?)", opdef->txt);
break;
}
op->len += n;
}
break;
case WASM_OP_BR:
case WASM_OP_BRIF:
case WASM_OP_CALL:
{
ut32 val = 0;
size_t n = read_u32_leb128 (buf + 1, buf + buf_len, &val);
if (!(n > 0 && n < buf_len)) goto err;
snprintf (op->txt, R_ASM_BUFSIZE, "%s %d", opdef->txt, val);
op->len += n;
}
break;
case WASM_OP_BRTABLE:
{
ut32 count = 0, *table = NULL, def = 0;
size_t n = read_u32_leb128 (buf + 1, buf + buf_len, &count);
if (!(n > 0 && n < buf_len)) goto err;
if (!(table = calloc (count, sizeof (ut32)))) goto err;
int i = 0;
op->len += n;
for (i = 0; i < count; i++) {
n = read_u32_leb128 (buf + op->len, buf + buf_len, &table[i]);
if (!(op->len + n <= buf_len)) goto beach;
op->len += n;
}
n = read_u32_leb128 (buf + op->len, buf + buf_len, &def);
if (!(n > 0 && n + op->len < buf_len)) goto beach;
op->len += n;
snprintf (op->txt, R_ASM_BUFSIZE, "%s %d ", opdef->txt, count);
for (i = 0; i < count && strlen (op->txt) < R_ASM_BUFSIZE; i++) {
snprintf (op->txt + strlen (op->txt), R_ASM_BUFSIZE, "%d ", table[i]);
}
snprintf (op->txt + strlen (op->txt), R_ASM_BUFSIZE, "%d", def);
free (table);
break;
beach:
free (table);
goto err;
}
break;
case WASM_OP_CALLINDIRECT:
{
ut32 val = 0, reserved = 0;
size_t n = read_u32_leb128 (buf + 1, buf + buf_len, &val);
if (!(n > 0 && n < buf_len)) goto err;
op->len += n;
n = read_u32_leb128 (buf + op->len, buf + buf_len, &reserved);
if (!(n == 1 && op->len + n <= buf_len)) goto err;
reserved &= 0x1;
snprintf (op->txt, R_ASM_BUFSIZE, "%s %d %d", opdef->txt, val, reserved);
op->len += n;
}
break;
case WASM_OP_GETLOCAL:
case WASM_OP_SETLOCAL:
case WASM_OP_TEELOCAL:
case WASM_OP_GETGLOBAL:
case WASM_OP_SETGLOBAL:
{
ut32 val = 0;
size_t n = read_u32_leb128 (buf + 1, buf + buf_len, &val);
if (!(n > 0 && n < buf_len)) goto err;
snprintf (op->txt, R_ASM_BUFSIZE, "%s %d", opdef->txt, val);
op->len += n;
}
break;
case WASM_OP_I32LOAD:
case WASM_OP_I64LOAD:
case WASM_OP_F32LOAD:
case WASM_OP_F64LOAD:
case WASM_OP_I32LOAD8S:
case WASM_OP_I32LOAD8U:
case WASM_OP_I32LOAD16S:
case WASM_OP_I32LOAD16U:
case WASM_OP_I64LOAD8S:
case WASM_OP_I64LOAD8U:
case WASM_OP_I64LOAD16S:
case WASM_OP_I64LOAD16U:
case WASM_OP_I64LOAD32S:
case WASM_OP_I64LOAD32U:
case WASM_OP_I32STORE:
case WASM_OP_I64STORE:
case WASM_OP_F32STORE:
case WASM_OP_F64STORE:
case WASM_OP_I32STORE8:
case WASM_OP_I32STORE16:
case WASM_OP_I64STORE8:
case WASM_OP_I64STORE16:
case WASM_OP_I64STORE32:
{
ut32 flag = 0, offset = 0;
size_t n = read_u32_leb128 (buf + 1, buf + buf_len, &flag);
if (!(n > 0 && n < buf_len)) goto err;
op->len += n;
n = read_u32_leb128 (buf + op->len, buf + buf_len, &offset);
if (!(n > 0 && op->len + n <= buf_len)) goto err;
snprintf (op->txt, R_ASM_BUFSIZE, "%s %d %d", opdef->txt, flag, offset);
op->len += n;
}
break;
case WASM_OP_CURRENTMEMORY:
case WASM_OP_GROWMEMORY:
{
ut32 reserved = 0;
size_t n = read_u32_leb128 (buf + 1, buf + buf_len, &reserved);
if (!(n == 1 && n < buf_len)) goto err;
reserved &= 0x1;
snprintf (op->txt, R_ASM_BUFSIZE, "%s %d", opdef->txt, reserved);
op->len += n;
}
break;
case WASM_OP_I32CONST:
{
st32 val = 0;
size_t n = read_i32_leb128 (buf + 1, buf + buf_len, &val);
if (!(n > 0 && n < buf_len)) goto err;
snprintf (op->txt, R_ASM_BUFSIZE, "%s %" PFMT32d, opdef->txt, val);
op->len += n;
}
break;
case WASM_OP_I64CONST:
{
st64 val = 0;
size_t n = read_i64_leb128 (buf + 1, buf + buf_len, &val);
if (!(n > 0 && n < buf_len)) goto err;
snprintf (op->txt, R_ASM_BUFSIZE, "%s %" PFMT64d, opdef->txt, val);
op->len += n;
}
break;
case WASM_OP_F32CONST:
{
ut32 val = 0;
size_t n = read_u32_leb128 (buf + 1, buf + buf_len, &val);
if (!(n > 0 && n < buf_len)) goto err;
long double d = (long double)val;
snprintf (op->txt, R_ASM_BUFSIZE, "%s %" LDBLFMT, opdef->txt, d);
op->len += n;
}
break;
case WASM_OP_F64CONST:
{
ut64 val = 0;
size_t n = read_u64_leb128 (buf + 1, buf + buf_len, &val);
if (!(n > 0 && n < buf_len)) goto err;
long double d = (long double)val;
snprintf (op->txt, R_ASM_BUFSIZE, "%s %" LDBLFMT, opdef->txt, d);
op->len += n;
}
break;
default:
goto err;
}
return op->len;
err:
op->len = 1;
snprintf (op->txt, R_ASM_BUFSIZE, "invalid");
return op->len;
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_2861_0 |
crossvul-cpp_data_good_259_0 | /*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that: (1) source code
* distributions retain the above copyright notice and this paragraph
* in its entirety, and (2) distributions including binary code include
* the above copyright notice and this paragraph in its entirety in
* the documentation or other materials provided with the distribution.
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND
* WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, WITHOUT
* LIMITATION, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE.
*
* Original code by Hannes Gredler (hannes@gredler.at)
* and Steinar Haug (sthaug@nethelp.no)
*/
/* \summary: Label Distribution Protocol (LDP) printer */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <netdissect-stdinc.h>
#include "netdissect.h"
#include "extract.h"
#include "addrtoname.h"
#include "l2vpn.h"
#include "af.h"
static const char tstr[] = " [|LDP]";
/*
* ldp common header
*
* 0 1 2 3
* 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Version | PDU Length |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | LDP Identifier |
* + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*
*/
struct ldp_common_header {
uint8_t version[2];
uint8_t pdu_length[2];
uint8_t lsr_id[4];
uint8_t label_space[2];
};
#define LDP_VERSION 1
/*
* ldp message header
*
* 0 1 2 3
* 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* |U| Message Type | Message Length |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Message ID |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | |
* + +
* | Mandatory Parameters |
* + +
* | |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | |
* + +
* | Optional Parameters |
* + +
* | |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*/
struct ldp_msg_header {
uint8_t type[2];
uint8_t length[2];
uint8_t id[4];
};
#define LDP_MASK_MSG_TYPE(x) ((x)&0x7fff)
#define LDP_MASK_U_BIT(x) ((x)&0x8000)
#define LDP_MSG_NOTIF 0x0001
#define LDP_MSG_HELLO 0x0100
#define LDP_MSG_INIT 0x0200
#define LDP_MSG_KEEPALIVE 0x0201
#define LDP_MSG_ADDRESS 0x0300
#define LDP_MSG_ADDRESS_WITHDRAW 0x0301
#define LDP_MSG_LABEL_MAPPING 0x0400
#define LDP_MSG_LABEL_REQUEST 0x0401
#define LDP_MSG_LABEL_WITHDRAW 0x0402
#define LDP_MSG_LABEL_RELEASE 0x0403
#define LDP_MSG_LABEL_ABORT_REQUEST 0x0404
#define LDP_VENDOR_PRIVATE_MIN 0x3e00
#define LDP_VENDOR_PRIVATE_MAX 0x3eff
#define LDP_EXPERIMENTAL_MIN 0x3f00
#define LDP_EXPERIMENTAL_MAX 0x3fff
static const struct tok ldp_msg_values[] = {
{ LDP_MSG_NOTIF, "Notification" },
{ LDP_MSG_HELLO, "Hello" },
{ LDP_MSG_INIT, "Initialization" },
{ LDP_MSG_KEEPALIVE, "Keepalive" },
{ LDP_MSG_ADDRESS, "Address" },
{ LDP_MSG_ADDRESS_WITHDRAW, "Address Withdraw" },
{ LDP_MSG_LABEL_MAPPING, "Label Mapping" },
{ LDP_MSG_LABEL_REQUEST, "Label Request" },
{ LDP_MSG_LABEL_WITHDRAW, "Label Withdraw" },
{ LDP_MSG_LABEL_RELEASE, "Label Release" },
{ LDP_MSG_LABEL_ABORT_REQUEST, "Label Abort Request" },
{ 0, NULL}
};
#define LDP_MASK_TLV_TYPE(x) ((x)&0x3fff)
#define LDP_MASK_F_BIT(x) ((x)&0x4000)
#define LDP_TLV_FEC 0x0100
#define LDP_TLV_ADDRESS_LIST 0x0101
#define LDP_TLV_ADDRESS_LIST_AFNUM_LEN 2
#define LDP_TLV_HOP_COUNT 0x0103
#define LDP_TLV_PATH_VECTOR 0x0104
#define LDP_TLV_GENERIC_LABEL 0x0200
#define LDP_TLV_ATM_LABEL 0x0201
#define LDP_TLV_FR_LABEL 0x0202
#define LDP_TLV_STATUS 0x0300
#define LDP_TLV_EXTD_STATUS 0x0301
#define LDP_TLV_RETURNED_PDU 0x0302
#define LDP_TLV_RETURNED_MSG 0x0303
#define LDP_TLV_COMMON_HELLO 0x0400
#define LDP_TLV_IPV4_TRANSPORT_ADDR 0x0401
#define LDP_TLV_CONFIG_SEQ_NUMBER 0x0402
#define LDP_TLV_IPV6_TRANSPORT_ADDR 0x0403
#define LDP_TLV_COMMON_SESSION 0x0500
#define LDP_TLV_ATM_SESSION_PARM 0x0501
#define LDP_TLV_FR_SESSION_PARM 0x0502
#define LDP_TLV_FT_SESSION 0x0503
#define LDP_TLV_LABEL_REQUEST_MSG_ID 0x0600
#define LDP_TLV_MTU 0x0601 /* rfc 3988 */
static const struct tok ldp_tlv_values[] = {
{ LDP_TLV_FEC, "FEC" },
{ LDP_TLV_ADDRESS_LIST, "Address List" },
{ LDP_TLV_HOP_COUNT, "Hop Count" },
{ LDP_TLV_PATH_VECTOR, "Path Vector" },
{ LDP_TLV_GENERIC_LABEL, "Generic Label" },
{ LDP_TLV_ATM_LABEL, "ATM Label" },
{ LDP_TLV_FR_LABEL, "Frame-Relay Label" },
{ LDP_TLV_STATUS, "Status" },
{ LDP_TLV_EXTD_STATUS, "Extended Status" },
{ LDP_TLV_RETURNED_PDU, "Returned PDU" },
{ LDP_TLV_RETURNED_MSG, "Returned Message" },
{ LDP_TLV_COMMON_HELLO, "Common Hello Parameters" },
{ LDP_TLV_IPV4_TRANSPORT_ADDR, "IPv4 Transport Address" },
{ LDP_TLV_CONFIG_SEQ_NUMBER, "Configuration Sequence Number" },
{ LDP_TLV_IPV6_TRANSPORT_ADDR, "IPv6 Transport Address" },
{ LDP_TLV_COMMON_SESSION, "Common Session Parameters" },
{ LDP_TLV_ATM_SESSION_PARM, "ATM Session Parameters" },
{ LDP_TLV_FR_SESSION_PARM, "Frame-Relay Session Parameters" },
{ LDP_TLV_FT_SESSION, "Fault-Tolerant Session Parameters" },
{ LDP_TLV_LABEL_REQUEST_MSG_ID, "Label Request Message ID" },
{ LDP_TLV_MTU, "MTU" },
{ 0, NULL}
};
#define LDP_FEC_WILDCARD 0x01
#define LDP_FEC_PREFIX 0x02
#define LDP_FEC_HOSTADDRESS 0x03
/* From RFC 4906; should probably be updated to RFC 4447 (e.g., VC -> PW) */
#define LDP_FEC_MARTINI_VC 0x80
static const struct tok ldp_fec_values[] = {
{ LDP_FEC_WILDCARD, "Wildcard" },
{ LDP_FEC_PREFIX, "Prefix" },
{ LDP_FEC_HOSTADDRESS, "Host address" },
{ LDP_FEC_MARTINI_VC, "Martini VC" },
{ 0, NULL}
};
#define LDP_FEC_MARTINI_IFPARM_MTU 0x01
#define LDP_FEC_MARTINI_IFPARM_DESC 0x03
#define LDP_FEC_MARTINI_IFPARM_VCCV 0x0c
static const struct tok ldp_fec_martini_ifparm_values[] = {
{ LDP_FEC_MARTINI_IFPARM_MTU, "MTU" },
{ LDP_FEC_MARTINI_IFPARM_DESC, "Description" },
{ LDP_FEC_MARTINI_IFPARM_VCCV, "VCCV" },
{ 0, NULL}
};
/* draft-ietf-pwe3-vccv-04.txt */
static const struct tok ldp_fec_martini_ifparm_vccv_cc_values[] = {
{ 0x01, "PWE3 control word" },
{ 0x02, "MPLS Router Alert Label" },
{ 0x04, "MPLS inner label TTL = 1" },
{ 0, NULL}
};
/* draft-ietf-pwe3-vccv-04.txt */
static const struct tok ldp_fec_martini_ifparm_vccv_cv_values[] = {
{ 0x01, "ICMP Ping" },
{ 0x02, "LSP Ping" },
{ 0x04, "BFD" },
{ 0, NULL}
};
static u_int ldp_pdu_print(netdissect_options *, register const u_char *);
/*
* ldp tlv header
*
* 0 1 2 3
* 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* |U|F| Type | Length |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | |
* | Value |
* ~ ~
* | |
* | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*/
#define TLV_TCHECK(minlen) \
ND_TCHECK2(*tptr, minlen); if (tlv_tlen < minlen) goto badtlv;
static int
ldp_tlv_print(netdissect_options *ndo,
register const u_char *tptr,
u_short msg_tlen)
{
struct ldp_tlv_header {
uint8_t type[2];
uint8_t length[2];
};
const struct ldp_tlv_header *ldp_tlv_header;
u_short tlv_type,tlv_len,tlv_tlen,af,ft_flags;
u_char fec_type;
u_int ui,vc_info_len, vc_info_tlv_type, vc_info_tlv_len,idx;
char buf[100];
int i;
ldp_tlv_header = (const struct ldp_tlv_header *)tptr;
ND_TCHECK(*ldp_tlv_header);
tlv_len=EXTRACT_16BITS(ldp_tlv_header->length);
if (tlv_len + 4 > msg_tlen) {
ND_PRINT((ndo, "\n\t\t TLV contents go past end of message"));
return 0;
}
tlv_tlen=tlv_len;
tlv_type=LDP_MASK_TLV_TYPE(EXTRACT_16BITS(ldp_tlv_header->type));
/* FIXME vendor private / experimental check */
ND_PRINT((ndo, "\n\t %s TLV (0x%04x), length: %u, Flags: [%s and %s forward if unknown]",
tok2str(ldp_tlv_values,
"Unknown",
tlv_type),
tlv_type,
tlv_len,
LDP_MASK_U_BIT(EXTRACT_16BITS(&ldp_tlv_header->type)) ? "continue processing" : "ignore",
LDP_MASK_F_BIT(EXTRACT_16BITS(&ldp_tlv_header->type)) ? "do" : "don't"));
tptr+=sizeof(struct ldp_tlv_header);
switch(tlv_type) {
case LDP_TLV_COMMON_HELLO:
TLV_TCHECK(4);
ND_PRINT((ndo, "\n\t Hold Time: %us, Flags: [%s Hello%s]",
EXTRACT_16BITS(tptr),
(EXTRACT_16BITS(tptr+2)&0x8000) ? "Targeted" : "Link",
(EXTRACT_16BITS(tptr+2)&0x4000) ? ", Request for targeted Hellos" : ""));
break;
case LDP_TLV_IPV4_TRANSPORT_ADDR:
TLV_TCHECK(4);
ND_PRINT((ndo, "\n\t IPv4 Transport Address: %s", ipaddr_string(ndo, tptr)));
break;
case LDP_TLV_IPV6_TRANSPORT_ADDR:
TLV_TCHECK(16);
ND_PRINT((ndo, "\n\t IPv6 Transport Address: %s", ip6addr_string(ndo, tptr)));
break;
case LDP_TLV_CONFIG_SEQ_NUMBER:
TLV_TCHECK(4);
ND_PRINT((ndo, "\n\t Sequence Number: %u", EXTRACT_32BITS(tptr)));
break;
case LDP_TLV_ADDRESS_LIST:
TLV_TCHECK(LDP_TLV_ADDRESS_LIST_AFNUM_LEN);
af = EXTRACT_16BITS(tptr);
tptr+=LDP_TLV_ADDRESS_LIST_AFNUM_LEN;
tlv_tlen -= LDP_TLV_ADDRESS_LIST_AFNUM_LEN;
ND_PRINT((ndo, "\n\t Address Family: %s, addresses",
tok2str(af_values, "Unknown (%u)", af)));
switch (af) {
case AFNUM_INET:
while(tlv_tlen >= sizeof(struct in_addr)) {
ND_TCHECK2(*tptr, sizeof(struct in_addr));
ND_PRINT((ndo, " %s", ipaddr_string(ndo, tptr)));
tlv_tlen-=sizeof(struct in_addr);
tptr+=sizeof(struct in_addr);
}
break;
case AFNUM_INET6:
while(tlv_tlen >= sizeof(struct in6_addr)) {
ND_TCHECK2(*tptr, sizeof(struct in6_addr));
ND_PRINT((ndo, " %s", ip6addr_string(ndo, tptr)));
tlv_tlen-=sizeof(struct in6_addr);
tptr+=sizeof(struct in6_addr);
}
break;
default:
/* unknown AF */
break;
}
break;
case LDP_TLV_COMMON_SESSION:
TLV_TCHECK(8);
ND_PRINT((ndo, "\n\t Version: %u, Keepalive: %us, Flags: [Downstream %s, Loop Detection %s]",
EXTRACT_16BITS(tptr), EXTRACT_16BITS(tptr+2),
(EXTRACT_16BITS(tptr+6)&0x8000) ? "On Demand" : "Unsolicited",
(EXTRACT_16BITS(tptr+6)&0x4000) ? "Enabled" : "Disabled"
));
break;
case LDP_TLV_FEC:
TLV_TCHECK(1);
fec_type = *tptr;
ND_PRINT((ndo, "\n\t %s FEC (0x%02x)",
tok2str(ldp_fec_values, "Unknown", fec_type),
fec_type));
tptr+=1;
tlv_tlen-=1;
switch(fec_type) {
case LDP_FEC_WILDCARD:
break;
case LDP_FEC_PREFIX:
TLV_TCHECK(2);
af = EXTRACT_16BITS(tptr);
tptr+=LDP_TLV_ADDRESS_LIST_AFNUM_LEN;
tlv_tlen-=LDP_TLV_ADDRESS_LIST_AFNUM_LEN;
if (af == AFNUM_INET) {
i=decode_prefix4(ndo, tptr, tlv_tlen, buf, sizeof(buf));
if (i == -2)
goto trunc;
if (i == -3)
ND_PRINT((ndo, ": IPv4 prefix (goes past end of TLV)"));
else if (i == -1)
ND_PRINT((ndo, ": IPv4 prefix (invalid length)"));
else
ND_PRINT((ndo, ": IPv4 prefix %s", buf));
}
else if (af == AFNUM_INET6) {
i=decode_prefix6(ndo, tptr, tlv_tlen, buf, sizeof(buf));
if (i == -2)
goto trunc;
if (i == -3)
ND_PRINT((ndo, ": IPv4 prefix (goes past end of TLV)"));
else if (i == -1)
ND_PRINT((ndo, ": IPv6 prefix (invalid length)"));
else
ND_PRINT((ndo, ": IPv6 prefix %s", buf));
}
else
ND_PRINT((ndo, ": Address family %u prefix", af));
break;
case LDP_FEC_HOSTADDRESS:
break;
case LDP_FEC_MARTINI_VC:
/*
* We assume the type was supposed to be one of the MPLS
* Pseudowire Types.
*/
TLV_TCHECK(7);
vc_info_len = *(tptr+2);
/*
* According to RFC 4908, the VC info Length field can be zero,
* in which case not only are there no interface parameters,
* there's no VC ID.
*/
if (vc_info_len == 0) {
ND_PRINT((ndo, ": %s, %scontrol word, group-ID %u, VC-info-length: %u",
tok2str(mpls_pw_types_values, "Unknown", EXTRACT_16BITS(tptr)&0x7fff),
EXTRACT_16BITS(tptr)&0x8000 ? "" : "no ",
EXTRACT_32BITS(tptr+3),
vc_info_len));
break;
}
/* Make sure we have the VC ID as well */
TLV_TCHECK(11);
ND_PRINT((ndo, ": %s, %scontrol word, group-ID %u, VC-ID %u, VC-info-length: %u",
tok2str(mpls_pw_types_values, "Unknown", EXTRACT_16BITS(tptr)&0x7fff),
EXTRACT_16BITS(tptr)&0x8000 ? "" : "no ",
EXTRACT_32BITS(tptr+3),
EXTRACT_32BITS(tptr+7),
vc_info_len));
if (vc_info_len < 4) {
/* minimum 4, for the VC ID */
ND_PRINT((ndo, " (invalid, < 4"));
return(tlv_len+4); /* Type & Length fields not included */
}
vc_info_len -= 4; /* subtract out the VC ID, giving the length of the interface parameters */
/* Skip past the fixed information and the VC ID */
tptr+=11;
tlv_tlen-=11;
TLV_TCHECK(vc_info_len);
while (vc_info_len > 2) {
vc_info_tlv_type = *tptr;
vc_info_tlv_len = *(tptr+1);
if (vc_info_tlv_len < 2)
break;
if (vc_info_len < vc_info_tlv_len)
break;
ND_PRINT((ndo, "\n\t\tInterface Parameter: %s (0x%02x), len %u",
tok2str(ldp_fec_martini_ifparm_values,"Unknown",vc_info_tlv_type),
vc_info_tlv_type,
vc_info_tlv_len));
switch(vc_info_tlv_type) {
case LDP_FEC_MARTINI_IFPARM_MTU:
ND_PRINT((ndo, ": %u", EXTRACT_16BITS(tptr+2)));
break;
case LDP_FEC_MARTINI_IFPARM_DESC:
ND_PRINT((ndo, ": "));
for (idx = 2; idx < vc_info_tlv_len; idx++)
safeputchar(ndo, *(tptr + idx));
break;
case LDP_FEC_MARTINI_IFPARM_VCCV:
ND_PRINT((ndo, "\n\t\t Control Channels (0x%02x) = [%s]",
*(tptr+2),
bittok2str(ldp_fec_martini_ifparm_vccv_cc_values, "none", *(tptr+2))));
ND_PRINT((ndo, "\n\t\t CV Types (0x%02x) = [%s]",
*(tptr+3),
bittok2str(ldp_fec_martini_ifparm_vccv_cv_values, "none", *(tptr+3))));
break;
default:
print_unknown_data(ndo, tptr+2, "\n\t\t ", vc_info_tlv_len-2);
break;
}
vc_info_len -= vc_info_tlv_len;
tptr += vc_info_tlv_len;
}
break;
}
break;
case LDP_TLV_GENERIC_LABEL:
TLV_TCHECK(4);
ND_PRINT((ndo, "\n\t Label: %u", EXTRACT_32BITS(tptr) & 0xfffff));
break;
case LDP_TLV_STATUS:
TLV_TCHECK(8);
ui = EXTRACT_32BITS(tptr);
tptr+=4;
ND_PRINT((ndo, "\n\t Status: 0x%02x, Flags: [%s and %s forward]",
ui&0x3fffffff,
ui&0x80000000 ? "Fatal error" : "Advisory Notification",
ui&0x40000000 ? "do" : "don't"));
ui = EXTRACT_32BITS(tptr);
tptr+=4;
if (ui)
ND_PRINT((ndo, ", causing Message ID: 0x%08x", ui));
break;
case LDP_TLV_FT_SESSION:
TLV_TCHECK(12);
ft_flags = EXTRACT_16BITS(tptr);
ND_PRINT((ndo, "\n\t Flags: [%sReconnect, %sSave State, %sAll-Label Protection, %s Checkpoint, %sRe-Learn State]",
ft_flags&0x8000 ? "" : "No ",
ft_flags&0x8 ? "" : "Don't ",
ft_flags&0x4 ? "" : "No ",
ft_flags&0x2 ? "Sequence Numbered Label" : "All Labels",
ft_flags&0x1 ? "" : "Don't "));
/* 16 bits (FT Flags) + 16 bits (Reserved) */
tptr+=4;
ui = EXTRACT_32BITS(tptr);
if (ui)
ND_PRINT((ndo, ", Reconnect Timeout: %ums", ui));
tptr+=4;
ui = EXTRACT_32BITS(tptr);
if (ui)
ND_PRINT((ndo, ", Recovery Time: %ums", ui));
break;
case LDP_TLV_MTU:
TLV_TCHECK(2);
ND_PRINT((ndo, "\n\t MTU: %u", EXTRACT_16BITS(tptr)));
break;
/*
* FIXME those are the defined TLVs that lack a decoder
* you are welcome to contribute code ;-)
*/
case LDP_TLV_HOP_COUNT:
case LDP_TLV_PATH_VECTOR:
case LDP_TLV_ATM_LABEL:
case LDP_TLV_FR_LABEL:
case LDP_TLV_EXTD_STATUS:
case LDP_TLV_RETURNED_PDU:
case LDP_TLV_RETURNED_MSG:
case LDP_TLV_ATM_SESSION_PARM:
case LDP_TLV_FR_SESSION_PARM:
case LDP_TLV_LABEL_REQUEST_MSG_ID:
default:
if (ndo->ndo_vflag <= 1)
print_unknown_data(ndo, tptr, "\n\t ", tlv_tlen);
break;
}
return(tlv_len+4); /* Type & Length fields not included */
trunc:
ND_PRINT((ndo, "%s", tstr));
return 0;
badtlv:
ND_PRINT((ndo, "\n\t\t TLV contents go past end of TLV"));
return(tlv_len+4); /* Type & Length fields not included */
}
void
ldp_print(netdissect_options *ndo,
register const u_char *pptr, register u_int len)
{
u_int processed;
while (len > (sizeof(struct ldp_common_header) + sizeof(struct ldp_msg_header))) {
processed = ldp_pdu_print(ndo, pptr);
if (processed == 0)
return;
if (len < processed) {
ND_PRINT((ndo, " [remaining length %u < %u]", len, processed));
ND_PRINT((ndo, "%s", istr));
break;
}
len -= processed;
pptr += processed;
}
}
static u_int
ldp_pdu_print(netdissect_options *ndo,
register const u_char *pptr)
{
const struct ldp_common_header *ldp_com_header;
const struct ldp_msg_header *ldp_msg_header;
const u_char *tptr,*msg_tptr;
u_short tlen;
u_short pdu_len,msg_len,msg_type,msg_tlen;
int hexdump,processed;
ldp_com_header = (const struct ldp_common_header *)pptr;
ND_TCHECK(*ldp_com_header);
/*
* Sanity checking of the header.
*/
if (EXTRACT_16BITS(&ldp_com_header->version) != LDP_VERSION) {
ND_PRINT((ndo, "%sLDP version %u packet not supported",
(ndo->ndo_vflag < 1) ? "" : "\n\t",
EXTRACT_16BITS(&ldp_com_header->version)));
return 0;
}
pdu_len = EXTRACT_16BITS(&ldp_com_header->pdu_length);
if (pdu_len < sizeof(const struct ldp_common_header)-4) {
/* length too short */
ND_PRINT((ndo, "%sLDP, pdu-length: %u (too short, < %u)",
(ndo->ndo_vflag < 1) ? "" : "\n\t",
pdu_len,
(u_int)(sizeof(const struct ldp_common_header)-4)));
return 0;
}
/* print the LSR-ID, label-space & length */
ND_PRINT((ndo, "%sLDP, Label-Space-ID: %s:%u, pdu-length: %u",
(ndo->ndo_vflag < 1) ? "" : "\n\t",
ipaddr_string(ndo, &ldp_com_header->lsr_id),
EXTRACT_16BITS(&ldp_com_header->label_space),
pdu_len));
/* bail out if non-verbose */
if (ndo->ndo_vflag < 1)
return 0;
/* ok they seem to want to know everything - lets fully decode it */
tptr = pptr + sizeof(const struct ldp_common_header);
tlen = pdu_len - (sizeof(const struct ldp_common_header)-4); /* Type & Length fields not included */
while(tlen>0) {
/* did we capture enough for fully decoding the msg header ? */
ND_TCHECK2(*tptr, sizeof(struct ldp_msg_header));
ldp_msg_header = (const struct ldp_msg_header *)tptr;
msg_len=EXTRACT_16BITS(ldp_msg_header->length);
msg_type=LDP_MASK_MSG_TYPE(EXTRACT_16BITS(ldp_msg_header->type));
if (msg_len < sizeof(struct ldp_msg_header)-4) {
/* length too short */
/* FIXME vendor private / experimental check */
ND_PRINT((ndo, "\n\t %s Message (0x%04x), length: %u (too short, < %u)",
tok2str(ldp_msg_values,
"Unknown",
msg_type),
msg_type,
msg_len,
(u_int)(sizeof(struct ldp_msg_header)-4)));
return 0;
}
/* FIXME vendor private / experimental check */
ND_PRINT((ndo, "\n\t %s Message (0x%04x), length: %u, Message ID: 0x%08x, Flags: [%s if unknown]",
tok2str(ldp_msg_values,
"Unknown",
msg_type),
msg_type,
msg_len,
EXTRACT_32BITS(&ldp_msg_header->id),
LDP_MASK_U_BIT(EXTRACT_16BITS(&ldp_msg_header->type)) ? "continue processing" : "ignore"));
msg_tptr=tptr+sizeof(struct ldp_msg_header);
msg_tlen=msg_len-(sizeof(struct ldp_msg_header)-4); /* Type & Length fields not included */
/* did we capture enough for fully decoding the message ? */
ND_TCHECK2(*tptr, msg_len);
hexdump=FALSE;
switch(msg_type) {
case LDP_MSG_NOTIF:
case LDP_MSG_HELLO:
case LDP_MSG_INIT:
case LDP_MSG_KEEPALIVE:
case LDP_MSG_ADDRESS:
case LDP_MSG_LABEL_MAPPING:
case LDP_MSG_ADDRESS_WITHDRAW:
case LDP_MSG_LABEL_WITHDRAW:
while(msg_tlen >= 4) {
processed = ldp_tlv_print(ndo, msg_tptr, msg_tlen);
if (processed == 0)
break;
msg_tlen-=processed;
msg_tptr+=processed;
}
break;
/*
* FIXME those are the defined messages that lack a decoder
* you are welcome to contribute code ;-)
*/
case LDP_MSG_LABEL_REQUEST:
case LDP_MSG_LABEL_RELEASE:
case LDP_MSG_LABEL_ABORT_REQUEST:
default:
if (ndo->ndo_vflag <= 1)
print_unknown_data(ndo, msg_tptr, "\n\t ", msg_tlen);
break;
}
/* do we want to see an additionally hexdump ? */
if (ndo->ndo_vflag > 1 || hexdump==TRUE)
print_unknown_data(ndo, tptr+sizeof(struct ldp_msg_header), "\n\t ",
msg_len);
tptr += msg_len+4;
tlen -= msg_len+4;
}
return pdu_len+4;
trunc:
ND_PRINT((ndo, "%s", tstr));
return 0;
}
/*
* Local Variables:
* c-style: whitesmith
* c-basic-offset: 8
* End:
*/
| ./CrossVul/dataset_final_sorted/CWE-125/c/good_259_0 |
crossvul-cpp_data_bad_144_0 | /* radare - LGPL - Copyright 2008-2017 nibble, pancake, inisider */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <r_types.h>
#include <r_util.h>
#include "pe.h"
#include <time.h>
#define PE_IMAGE_FILE_MACHINE_RPI2 452
#define MAX_METADATA_STRING_LENGTH 256
#define bprintf if(bin->verbose) eprintf
#define COFF_SYMBOL_SIZE 18
struct SCV_NB10_HEADER;
typedef struct {
ut8 signature[4];
ut32 offset;
ut32 timestamp;
ut32 age;
ut8* file_name;
void (* free)(struct SCV_NB10_HEADER* cv_nb10_header);
} SCV_NB10_HEADER;
typedef struct {
ut32 data1;
ut16 data2;
ut16 data3;
ut8 data4[8];
} SGUID;
struct SCV_RSDS_HEADER;
typedef struct {
ut8 signature[4];
SGUID guid;
ut32 age;
ut8* file_name;
void (* free)(struct SCV_RSDS_HEADER* rsds_hdr);
} SCV_RSDS_HEADER;
static inline int is_thumb(struct PE_(r_bin_pe_obj_t)* bin) {
return bin->nt_headers->optional_header.AddressOfEntryPoint & 1;
}
static inline int is_arm(struct PE_(r_bin_pe_obj_t)* bin) {
switch (bin->nt_headers->file_header.Machine) {
case PE_IMAGE_FILE_MACHINE_RPI2: // 462
case PE_IMAGE_FILE_MACHINE_ARM:
case PE_IMAGE_FILE_MACHINE_THUMB:
return 1;
}
return 0;
}
struct r_bin_pe_addr_t *PE_(check_msvcseh) (struct PE_(r_bin_pe_obj_t) *bin) {
struct r_bin_pe_addr_t* entry;
ut8 b[512];
int n = 0;
if (!bin || !bin->b) {
return 0LL;
}
entry = PE_(r_bin_pe_get_entrypoint) (bin);
ZERO_FILL (b);
if (r_buf_read_at (bin->b, entry->paddr, b, sizeof (b)) < 0) {
bprintf ("Warning: Cannot read entry at 0x%08"PFMT64x "\n", entry->paddr);
free (entry);
return NULL;
}
// MSVC SEH
// E8 13 09 00 00 call 0x44C388
// E9 05 00 00 00 jmp 0x44BA7F
if (b[0] == 0xe8 && b[5] == 0xe9) {
const st32 jmp_dst = r_read_ble32 (b + 6, bin->big_endian);
entry->paddr += (5 + 5 + jmp_dst);
entry->vaddr += (5 + 5 + jmp_dst);
if (r_buf_read_at (bin->b, entry->paddr, b, sizeof (b)) > 0) {
// case1:
// from des address of jmp search for 68 xx xx xx xx e8 and test xx xx xx xx = imagebase
// 68 00 00 40 00 push 0x400000
// E8 3E F9 FF FF call 0x44B4FF
ut32 imageBase = bin->nt_headers->optional_header.ImageBase;
for (n = 0; n < sizeof (b) - 6; n++) {
const ut32 tmp_imgbase = r_read_ble32 (b + n + 1, bin->big_endian);
if (b[n] == 0x68 && tmp_imgbase == imageBase && b[n + 5] == 0xe8) {
const st32 call_dst = r_read_ble32 (b + n + 6, bin->big_endian);
entry->paddr += (n + 5 + 5 + call_dst);
entry->vaddr += (n + 5 + 5 + call_dst);
return entry;
}
}
//case2:
// from des address of jmp search for 50 FF xx FF xx E8
//50 push eax
//FF 37 push dword ptr[edi]
//FF 36 push dword ptr[esi]
//E8 6F FC FF FF call _main
for (n = 0; n < sizeof (b) - 6; n++) {
if (b[n] == 0x50 && b[n+1] == 0xff && b[n + 3] == 0xff && b[n + 5] == 0xe8) {
const st32 call_dst = r_read_ble32 (b + n + 6, bin->big_endian);
entry->paddr += (n + 5 + 5 + call_dst);
entry->vaddr += (n + 5 + 5 + call_dst);
return entry;
}
}
//case3:
//50 push eax
//FF 35 0C E2 40 00 push xxxxxxxx
//FF 35 08 E2 40 00 push xxxxxxxx
//E8 2B FD FF FF call _main
for (n = 0; n < sizeof (b) - 20; n++) {
if (b[n] == 0x50 && b[n + 1] == 0xff && b[n + 7] == 0xff && b[n + 13] == 0xe8) {
const st32 call_dst = r_read_ble32 (b + n + 14, bin->big_endian);
entry->paddr += (n + 5 + 13 + call_dst);
entry->vaddr += (n + 5 + 13 + call_dst);
return entry;
}
}
//case4:
//50 push eax
//57 push edi
//FF 36 push dword ptr[esi]
//E8 D9 FD FF FF call _main
for (n = 0; n < sizeof (b) - 5; n++) {
if (b[n] == 0x50 && b[n + 1] == 0x57 && b[n + 2] == 0xff && b[n + 4] == 0xe8) {
const st32 call_dst = r_read_ble32 (b + n + 5, bin->big_endian);
entry->paddr += (n + 5 + 4 + call_dst);
entry->vaddr += (n + 5 + 4 + call_dst);
return entry;
}
}
}
}
// MSVC AMD64
// 48 83 EC 28 sub rsp, 0x28
// E8 xx xx xx xx call xxxxxxxx
// 48 83 C4 28 add rsp, 0x28
// E9 xx xx xx xx jmp xxxxxxxx
if (b[4] == 0xe8 && b[13] == 0xe9) {
//const st32 jmp_dst = b[14] | (b[15] << 8) | (b[16] << 16) | (b[17] << 24);
const st32 jmp_dst = r_read_ble32 (b + 14, bin->big_endian);
entry->paddr += (5 + 13 + jmp_dst);
entry->vaddr += (5 + 13 + jmp_dst);
if (r_buf_read_at (bin->b, entry->paddr, b, sizeof (b)) > 0) {
// from des address of jmp, search for 4C ... 48 ... 8B ... E8
// 4C 8B C0 mov r8, rax
// 48 8B 17 mov rdx, qword [rdi]
// 8B 0B mov ecx, dword [rbx]
// E8 xx xx xx xx call main
for (n = 0; n < sizeof (b) - 13; n++) {
if (b[n] == 0x4c && b[n + 3] == 0x48 && b[n + 6] == 0x8b && b[n + 8] == 0xe8) {
const st32 call_dst = r_read_ble32 (b + n + 9, bin->big_endian);
entry->paddr += (n + 5 + 8 + call_dst);
entry->vaddr += (n + 5 + 8 + call_dst);
return entry;
}
}
}
}
//Microsoft Visual-C
// 50 push eax
// FF 75 9C push dword [ebp - local_64h]
// 56 push esi
// 56 push esi
// FF 15 CC C0 44 00 call dword [sym.imp.KERNEL32.dll_GetModuleHandleA]
// 50 push eax
// E8 DB DA 00 00 call main
// 89 45 A0 mov dword [ebp - local_60h], eax
// 50 push eax
// E8 2D 00 00 00 call 0x4015a6
if (b[188] == 0x50 && b[201] == 0xe8) {
const st32 call_dst = r_read_ble32 (b + 202, bin->big_endian);
entry->paddr += (201 + 5 + call_dst);
entry->vaddr += (201 + 5 + call_dst);
return entry;
}
if (b[292] == 0x50 && b[303] == 0xe8) {
const st32 call_dst = r_read_ble32 (b + 304, bin->big_endian);
entry->paddr += (303 + 5 + call_dst);
entry->vaddr += (303 + 5 + call_dst);
return entry;
}
free (entry);
return NULL;
}
struct r_bin_pe_addr_t *PE_(check_mingw) (struct PE_(r_bin_pe_obj_t) *bin) {
struct r_bin_pe_addr_t* entry;
int sw = 0;
ut8 b[1024];
int n = 0;
if (!bin || !bin->b) {
return 0LL;
}
entry = PE_(r_bin_pe_get_entrypoint) (bin);
ZERO_FILL (b);
if (r_buf_read_at (bin->b, entry->paddr, b, sizeof (b)) < 0) {
bprintf ("Warning: Cannot read entry at 0x%08"PFMT64x "\n", entry->paddr);
free (entry);
return NULL;
}
// mingw
//55 push ebp
//89 E5 mov ebp, esp
//83 EC 08 sub esp, 8
//C7 04 24 01 00 00 00 mov dword ptr[esp], 1
//FF 15 C8 63 41 00 call ds : __imp____set_app_type
//E8 B8 FE FF FF call ___mingw_CRTStartup
if (b[0] == 0x55 && b[1] == 0x89 && b[3] == 0x83 && b[6] == 0xc7 && b[13] == 0xff && b[19] == 0xe8) {
const st32 jmp_dst = (st32) r_read_le32 (&b[20]);
entry->paddr += (5 + 19 + jmp_dst);
entry->vaddr += (5 + 19 + jmp_dst);
sw = 1;
}
//83 EC 1C sub esp, 1Ch
//C7 04 24 01 00 00 00 mov[esp + 1Ch + var_1C], 1
//FF 15 F8 60 40 00 call ds : __imp____set_app_type
//E8 6B FD FF FF call ___mingw_CRTStartup
if (b[0] == 0x83 && b[3] == 0xc7 && b[10] == 0xff && b[16] == 0xe8) {
const st32 jmp_dst = (st32) r_read_le32 (&b[17]);
entry->paddr += (5 + 16 + jmp_dst);
entry->vaddr += (5 + 16 + jmp_dst);
sw = 1;
}
//83 EC 0C sub esp, 0Ch
//C7 05 F4 0A 81 00 00 00 00 00 mov ds : _mingw_app_type, 0
//ED E8 3E AD 24 00 call ___security_init_cookie
//F2 83 C4 0C add esp, 0Ch
//F5 E9 86 FC FF FF jmp ___tmainCRTStartup
if (b[0] == 0x83 && b[3] == 0xc7 && b[13] == 0xe8 && b[18] == 0x83 && b[21] == 0xe9) {
const st32 jmp_dst = (st32) r_read_le32 (&b[22]);
entry->paddr += (5 + 21 + jmp_dst);
entry->vaddr += (5 + 21 + jmp_dst);
sw = 1;
}
if (sw) {
if (r_buf_read_at (bin->b, entry->paddr, b, sizeof (b)) > 0) {
// case1:
// from des address of call search for a1 xx xx xx xx 89 xx xx e8 xx xx xx xx
//A1 04 50 44 00 mov eax, ds:dword_445004
//89 04 24 mov[esp + 28h + lpTopLevelExceptionFilter], eax
//E8 A3 01 00 00 call sub_4013EE
// ut32 imageBase = bin->nt_headers->optional_header.ImageBase;
for (n = 0; n < sizeof (b) - 12; n++) {
if (b[n] == 0xa1 && b[n + 5] == 0x89 && b[n + 8] == 0xe8) {
const st32 call_dst = (st32) r_read_le32 (&b[n + 9]);
entry->paddr += (n + 5 + 8 + call_dst);
entry->vaddr += (n + 5 + 8 + call_dst);
return entry;
}
}
}
}
free (entry);
return NULL;
}
struct r_bin_pe_addr_t *PE_(check_unknow) (struct PE_(r_bin_pe_obj_t) *bin) {
struct r_bin_pe_addr_t *entry;
if (!bin || !bin->b) {
return 0LL;
}
ut8 *b = calloc (1, 512);
if (!b) {
return NULL;
}
entry = PE_ (r_bin_pe_get_entrypoint) (bin);
// option2: /x 8bff558bec83ec20
if (r_buf_read_at (bin->b, entry->paddr, b, 512) < 1) {
bprintf ("Warning: Cannot read entry at 0x%08"PFMT64x"\n", entry->paddr);
free (entry);
free (b);
return NULL;
}
/* Decode the jmp instruction, this gets the address of the 'main'
function for PE produced by a compiler whose name someone forgot to
write down. */
// this is dirty only a single byte check, can return false positives
if (b[367] == 0xe8) {
const st32 jmp_dst = (st32) r_read_le32 (&b[368]);
entry->paddr += 367 + 5 + jmp_dst;
entry->vaddr += 367 + 5 + jmp_dst;
free (b);
return entry;
}
int i;
for (i = 0; i < 512 - 16 ; i++) {
// 5. ff 15 .. .. .. .. 50 e8 [main]
if (!memcmp (b + i, "\xff\x15", 2)) {
if (b[i+6] == 0x50) {
if (b[i+7] == 0xe8) {
const st32 call_dst = (st32) r_read_le32 (&b[i + 8]);
entry->paddr = entry->vaddr - entry->paddr;
entry->vaddr += (i + 7 + 5 + (long)call_dst);
entry->paddr += entry->vaddr;
free (b);
return entry;
}
}
}
}
free (entry);
free (b);
return NULL;
}
struct r_bin_pe_addr_t *PE_(r_bin_pe_get_main_vaddr)(struct PE_(r_bin_pe_obj_t) *bin) {
struct r_bin_pe_addr_t *winmain = PE_(check_msvcseh) (bin);
if (!winmain) {
winmain = PE_(check_mingw) (bin);
if (!winmain) {
winmain = PE_(check_unknow) (bin);
}
}
return winmain;
}
#define RBinPEObj struct PE_(r_bin_pe_obj_t)
static PE_DWord bin_pe_rva_to_paddr(RBinPEObj* bin, PE_DWord rva) {
PE_DWord section_base;
int i, section_size;
for (i = 0; i < bin->num_sections; i++) {
section_base = bin->section_header[i].VirtualAddress;
section_size = bin->section_header[i].Misc.VirtualSize;
if (rva >= section_base && rva < section_base + section_size) {
return bin->section_header[i].PointerToRawData + (rva - section_base);
}
}
return rva;
}
ut64 PE_(r_bin_pe_get_image_base)(struct PE_(r_bin_pe_obj_t)* bin) {
ut64 imageBase = 0;
if (!bin || !bin->nt_headers) {
return 0LL;
}
imageBase = bin->nt_headers->optional_header.ImageBase;
if (!imageBase) {
//this should only happens with messed up binaries
//XXX this value should be user defined by bin.baddr
//but from here we can not access config API
imageBase = 0x10000;
}
return imageBase;
}
static PE_DWord bin_pe_rva_to_va(RBinPEObj* bin, PE_DWord rva) {
return PE_(r_bin_pe_get_image_base) (bin) + rva;
}
static PE_DWord bin_pe_va_to_rva(RBinPEObj* bin, PE_DWord va) {
ut64 imageBase = PE_(r_bin_pe_get_image_base) (bin);
if (va < imageBase) {
return va;
}
return va - imageBase;
}
static char* resolveModuleOrdinal(Sdb* sdb, const char* module, int ordinal) {
Sdb* db = sdb;
char* foo = sdb_get (db, sdb_fmt ("%d", ordinal), 0);
if (foo && *foo) {
return foo;
} else {
free (foo); // should never happen
}
return NULL;
}
static int bin_pe_parse_imports(struct PE_(r_bin_pe_obj_t)* bin,
struct r_bin_pe_import_t** importp, int* nimp,
const char* dll_name,
PE_DWord OriginalFirstThunk,
PE_DWord FirstThunk) {
char import_name[PE_NAME_LENGTH + 1];
char name[PE_NAME_LENGTH + 1];
PE_Word import_hint, import_ordinal = 0;
PE_DWord import_table = 0, off = 0;
int i = 0, len;
Sdb* db = NULL;
char* sdb_module = NULL;
char* symname;
char* filename;
char* symdllname = NULL;
if (!dll_name || *dll_name == '0') {
return 0;
}
if (!(off = bin_pe_rva_to_paddr (bin, OriginalFirstThunk)) &&
!(off = bin_pe_rva_to_paddr (bin, FirstThunk))) {
return 0;
}
do {
if (import_ordinal >= UT16_MAX) {
break;
}
if (off + i * sizeof(PE_DWord) > bin->size) {
break;
}
len = r_buf_read_at (bin->b, off + i * sizeof (PE_DWord), (ut8*) &import_table, sizeof (PE_DWord));
if (len != sizeof (PE_DWord)) {
bprintf ("Warning: read (import table)\n");
goto error;
} else if (import_table) {
if (import_table & ILT_MASK1) {
import_ordinal = import_table & ILT_MASK2;
import_hint = 0;
snprintf (import_name, PE_NAME_LENGTH, "%s_Ordinal_%i", dll_name, import_ordinal);
free (symdllname);
strncpy (name, dll_name, sizeof (name) - 1);
name[sizeof(name) - 1] = 0;
symdllname = strdup (name);
// remove the trailling ".dll"
size_t len = strlen (symdllname);
r_str_case (symdllname, 0);
len = len < 4? 0: len - 4;
symdllname[len] = 0;
if (!sdb_module || strcmp (symdllname, sdb_module)) {
sdb_free (db);
if (db) {
sdb_free (db);
}
db = NULL;
free (sdb_module);
sdb_module = strdup (symdllname);
filename = sdb_fmt ("%s.sdb", symdllname);
if (r_file_exists (filename)) {
db = sdb_new (NULL, filename, 0);
} else {
#if __WINDOWS__
char invoke_dir[MAX_PATH];
if (r_sys_get_src_dir_w32 (invoke_dir)) {
filename = sdb_fmt ("%s\\share\\radare2\\"R2_VERSION "\\format\\dll\\%s.sdb", invoke_dir, symdllname);
} else {
filename = sdb_fmt ("share/radare2/"R2_VERSION "/format/dll/%s.sdb", symdllname);
}
#else
const char *dirPrefix = r_sys_prefix (NULL);
filename = sdb_fmt ("%s/share/radare2/" R2_VERSION "/format/dll/%s.sdb", dirPrefix, symdllname);
#endif
if (r_file_exists (filename)) {
db = sdb_new (NULL, filename, 0);
}
}
}
if (db) {
symname = resolveModuleOrdinal (db, symdllname, import_ordinal);
if (symname) {
snprintf (import_name, PE_NAME_LENGTH, "%s_%s", dll_name, symname);
R_FREE (symname);
}
} else {
bprintf ("Cannot find %s\n", filename);
}
} else {
import_ordinal++;
const ut64 off = bin_pe_rva_to_paddr (bin, import_table);
if (off > bin->size || (off + sizeof (PE_Word)) > bin->size) {
bprintf ("Warning: off > bin->size\n");
goto error;
}
len = r_buf_read_at (bin->b, off, (ut8*) &import_hint, sizeof (PE_Word));
if (len != sizeof (PE_Word)) {
bprintf ("Warning: read import hint at 0x%08"PFMT64x "\n", off);
goto error;
}
name[0] = '\0';
len = r_buf_read_at (bin->b, off + sizeof(PE_Word), (ut8*) name, PE_NAME_LENGTH);
if (len < 1) {
bprintf ("Warning: read (import name)\n");
goto error;
} else if (!*name) {
break;
}
name[PE_NAME_LENGTH] = '\0';
snprintf (import_name, PE_NAME_LENGTH, "%s_%s", dll_name, name);
}
if (!(*importp = realloc (*importp, (*nimp + 1) * sizeof(struct r_bin_pe_import_t)))) {
r_sys_perror ("realloc (import)");
goto error;
}
memcpy ((*importp)[*nimp].name, import_name, PE_NAME_LENGTH);
(*importp)[*nimp].name[PE_NAME_LENGTH] = '\0';
(*importp)[*nimp].vaddr = bin_pe_rva_to_va (bin, FirstThunk + i * sizeof (PE_DWord));
(*importp)[*nimp].paddr = bin_pe_rva_to_paddr (bin, FirstThunk) + i * sizeof(PE_DWord);
(*importp)[*nimp].hint = import_hint;
(*importp)[*nimp].ordinal = import_ordinal;
(*importp)[*nimp].last = 0;
(*nimp)++;
i++;
}
} while (import_table);
if (db) {
sdb_free (db);
db = NULL;
}
free (symdllname);
free (sdb_module);
return i;
error:
if (db) {
sdb_free (db);
db = NULL;
}
free (symdllname);
free (sdb_module);
return false;
}
static char *_time_stamp_to_str(ut32 timeStamp) {
#ifdef _MSC_VER
time_t rawtime;
struct tm *tminfo;
rawtime = (time_t)timeStamp;
tminfo = localtime (&rawtime);
//tminfo = gmtime (&rawtime);
return r_str_trim (strdup (asctime (tminfo)));
#else
struct my_timezone {
int tz_minuteswest; /* minutes west of Greenwich */
int tz_dsttime; /* type of DST correction */
} tz;
struct timeval tv;
int gmtoff;
time_t ts = (time_t) timeStamp;
gettimeofday (&tv, (void*) &tz);
gmtoff = (int) (tz.tz_minuteswest * 60); // in seconds
ts += (time_t)gmtoff;
return r_str_trim (strdup (ctime (&ts)));
#endif
}
static int bin_pe_init_hdr(struct PE_(r_bin_pe_obj_t)* bin) {
if (!(bin->dos_header = malloc (sizeof(PE_(image_dos_header))))) {
r_sys_perror ("malloc (dos header)");
return false;
}
if (r_buf_read_at (bin->b, 0, (ut8*) bin->dos_header, sizeof(PE_(image_dos_header))) == -1) {
bprintf ("Warning: read (dos header)\n");
return false;
}
sdb_num_set (bin->kv, "pe_dos_header.offset", 0, 0);
sdb_set (bin->kv, "pe_dos_header.format", "[2]zwwwwwwwwwwwww[4]www[10]wx"
" e_magic e_cblp e_cp e_crlc e_cparhdr e_minalloc e_maxalloc"
" e_ss e_sp e_csum e_ip e_cs e_lfarlc e_ovno e_res e_oemid"
" e_oeminfo e_res2 e_lfanew", 0);
if (bin->dos_header->e_lfanew > (unsigned int) bin->size) {
bprintf ("Invalid e_lfanew field\n");
return false;
}
if (!(bin->nt_headers = malloc (sizeof (PE_(image_nt_headers))))) {
r_sys_perror ("malloc (nt header)");
return false;
}
bin->nt_header_offset = bin->dos_header->e_lfanew;
if (r_buf_read_at (bin->b, bin->dos_header->e_lfanew, (ut8*) bin->nt_headers, sizeof (PE_(image_nt_headers))) < -1) {
bprintf ("Warning: read (dos header)\n");
return false;
}
sdb_set (bin->kv, "pe_magic.cparse", "enum pe_magic { IMAGE_NT_OPTIONAL_HDR32_MAGIC=0x10b, IMAGE_NT_OPTIONAL_HDR64_MAGIC=0x20b, IMAGE_ROM_OPTIONAL_HDR_MAGIC=0x107 };", 0);
sdb_set (bin->kv, "pe_subsystem.cparse", "enum pe_subsystem { IMAGE_SUBSYSTEM_UNKNOWN=0, IMAGE_SUBSYSTEM_NATIVE=1, IMAGE_SUBSYSTEM_WINDOWS_GUI=2, "
" IMAGE_SUBSYSTEM_WINDOWS_CUI=3, IMAGE_SUBSYSTEM_OS2_CUI=5, IMAGE_SUBSYSTEM_POSIX_CUI=7, IMAGE_SUBSYSTEM_WINDOWS_CE_GUI=9, "
" IMAGE_SUBSYSTEM_EFI_APPLICATION=10, IMAGE_SUBSYSTEM_EFI_BOOT_SERVICE_DRIVER=11, IMAGE_SUBSYSTEM_EFI_RUNTIME_DRIVER=12, "
" IMAGE_SUBSYSTEM_EFI_ROM=13, IMAGE_SUBSYSTEM_XBOX=14, IMAGE_SUBSYSTEM_WINDOWS_BOOT_APPLICATION=16 };", 0);
sdb_set (bin->kv, "pe_dllcharacteristics.cparse", "enum pe_dllcharacteristics { IMAGE_LIBRARY_PROCESS_INIT=0x0001, IMAGE_LIBRARY_PROCESS_TERM=0x0002, "
" IMAGE_LIBRARY_THREAD_INIT=0x0004, IMAGE_LIBRARY_THREAD_TERM=0x0008, IMAGE_DLLCHARACTERISTICS_HIGH_ENTROPY_VA=0x0020, "
" IMAGE_DLLCHARACTERISTICS_DYNAMIC_BASE=0x0040, IMAGE_DLLCHARACTERISTICS_FORCE_INTEGRITY=0x0080, "
" IMAGE_DLLCHARACTERISTICS_NX_COMPAT=0x0100, IMAGE_DLLCHARACTERISTICS_NO_ISOLATION=0x0200,IMAGE_DLLCHARACTERISTICS_NO_SEH=0x0400, "
" IMAGE_DLLCHARACTERISTICS_NO_BIND=0x0800, IMAGE_DLLCHARACTERISTICS_APPCONTAINER=0x1000, IMAGE_DLLCHARACTERISTICS_WDM_DRIVER=0x2000, "
" IMAGE_DLLCHARACTERISTICS_GUARD_CF=0x4000, IMAGE_DLLCHARACTERISTICS_TERMINAL_SERVER_AWARE=0x8000};", 0);
#if R_BIN_PE64
sdb_num_set (bin->kv, "pe_nt_image_headers64.offset", bin->dos_header->e_lfanew, 0);
sdb_set (bin->kv, "pe_nt_image_headers64.format", "[4]z?? signature (pe_image_file_header)fileHeader (pe_image_optional_header64)optionalHeader", 0);
sdb_set (bin->kv, "pe_image_optional_header64.format", "[2]Ebbxxxxxqxxwwwwwwxxxx[2]E[2]Bqqqqxx[16]?"
" (pe_magic)magic majorLinkerVersion minorLinkerVersion sizeOfCode sizeOfInitializedData"
" sizeOfUninitializedData addressOfEntryPoint baseOfCode imageBase"
" sectionAlignment fileAlignment majorOperatingSystemVersion minorOperatingSystemVersion"
" majorImageVersion minorImageVersion majorSubsystemVersion minorSubsystemVersion"
" win32VersionValue sizeOfImage sizeOfHeaders checkSum (pe_subsystem)subsystem (pe_dllcharacteristics)dllCharacteristics"
" sizeOfStackReserve sizeOfStackCommit sizeOfHeapReserve sizeOfHeapCommit loaderFlags"
" numberOfRvaAndSizes (pe_image_data_directory)dataDirectory", 0);
#else
sdb_num_set (bin->kv, "pe_nt_image_headers32.offset", bin->dos_header->e_lfanew, 0);
sdb_set (bin->kv, "pe_nt_image_headers32.format", "[4]z?? signature (pe_image_file_header)fileHeader (pe_image_optional_header32)optionalHeader", 0);
sdb_set (bin->kv, "pe_image_optional_header32.format", "[2]Ebbxxxxxxxxxwwwwwwxxxx[2]E[2]Bxxxxxx[16]?"
" (pe_magic)magic majorLinkerVersion minorLinkerVersion sizeOfCode sizeOfInitializedData"
" sizeOfUninitializedData addressOfEntryPoint baseOfCode baseOfData imageBase"
" sectionAlignment fileAlignment majorOperatingSystemVersion minorOperatingSystemVersion"
" majorImageVersion minorImageVersion majorSubsystemVersion minorSubsystemVersion"
" win32VersionValue sizeOfImage sizeOfHeaders checkSum (pe_subsystem)subsystem (pe_dllcharacteristics)dllCharacteristics"
" sizeOfStackReserve sizeOfStackCommit sizeOfHeapReserve sizeOfHeapCommit loaderFlags numberOfRvaAndSizes"
" (pe_image_data_directory)dataDirectory", 0);
#endif
sdb_set (bin->kv, "pe_machine.cparse", "enum pe_machine { IMAGE_FILE_MACHINE_I386=0x014c, IMAGE_FILE_MACHINE_IA64=0x0200, IMAGE_FILE_MACHINE_AMD64=0x8664 };", 0);
sdb_set (bin->kv, "pe_characteristics.cparse", "enum pe_characteristics { "
" IMAGE_FILE_RELOCS_STRIPPED=0x0001, IMAGE_FILE_EXECUTABLE_IMAGE=0x0002, IMAGE_FILE_LINE_NUMS_STRIPPED=0x0004, "
" IMAGE_FILE_LOCAL_SYMS_STRIPPED=0x0008, IMAGE_FILE_AGGRESIVE_WS_TRIM=0x0010, IMAGE_FILE_LARGE_ADDRESS_AWARE=0x0020, "
" IMAGE_FILE_BYTES_REVERSED_LO=0x0080, IMAGE_FILE_32BIT_MACHINE=0x0100, IMAGE_FILE_DEBUG_STRIPPED=0x0200, "
" IMAGE_FILE_REMOVABLE_RUN_FROM_SWAP=0x0400, IMAGE_FILE_NET_RUN_FROM_SWAP=0x0800, IMAGE_FILE_SYSTEM=0x1000, "
" IMAGE_FILE_DLL=0x2000, IMAGE_FILE_UP_SYSTEM_ONLY=0x4000, IMAGE_FILE_BYTES_REVERSED_HI=0x8000 };", 0);
sdb_set (bin->kv, "pe_image_file_header.format", "[2]Ewtxxw[2]B"
" (pe_machine)machine numberOfSections timeDateStamp pointerToSymbolTable"
" numberOfSymbols sizeOfOptionalHeader (pe_characteristics)characteristics", 0);
sdb_set (bin->kv, "pe_image_data_directory.format", "xx virtualAddress size",0);
// adding compile time to the SDB
{
sdb_num_set (bin->kv, "image_file_header.TimeDateStamp", bin->nt_headers->file_header.TimeDateStamp, 0);
char *timestr = _time_stamp_to_str (bin->nt_headers->file_header.TimeDateStamp);
sdb_set_owned (bin->kv, "image_file_header.TimeDateStamp_string", timestr, 0);
}
bin->optional_header = &bin->nt_headers->optional_header;
bin->data_directory = (PE_(image_data_directory*)) & bin->optional_header->DataDirectory;
if (strncmp ((char*) &bin->dos_header->e_magic, "MZ", 2) ||
(strncmp ((char*) &bin->nt_headers->Signature, "PE", 2) &&
/* Check also for Phar Lap TNT DOS extender PL executable */
strncmp ((char*) &bin->nt_headers->Signature, "PL", 2))) {
return false;
}
return true;
}
typedef struct {
ut64 shortname;
ut32 value;
ut16 secnum;
ut16 symtype;
ut8 symclass;
ut8 numaux;
} SymbolRecord;
static struct r_bin_pe_export_t* parse_symbol_table(struct PE_(r_bin_pe_obj_t)* bin, struct r_bin_pe_export_t* exports, int sz) {
ut64 sym_tbl_off, num = 0;
const int srsz = COFF_SYMBOL_SIZE; // symbol record size
struct r_bin_pe_section_t* sections;
struct r_bin_pe_export_t* exp;
int bufsz, i, shsz;
SymbolRecord* sr;
ut64 text_off = 0LL;
ut64 text_rva = 0LL;
int textn = 0;
int exports_sz;
int symctr = 0;
char* buf;
if (!bin || !bin->nt_headers) {
return NULL;
}
sym_tbl_off = bin->nt_headers->file_header.PointerToSymbolTable;
num = bin->nt_headers->file_header.NumberOfSymbols;
shsz = bufsz = num * srsz;
if (bufsz < 1 || bufsz > bin->size) {
return NULL;
}
buf = calloc (num, srsz);
if (!buf) {
return NULL;
}
exports_sz = sizeof(struct r_bin_pe_export_t) * num;
if (exports) {
int osz = sz;
sz += exports_sz;
exports = realloc (exports, sz);
if (!exports) {
free (buf);
return NULL;
}
exp = (struct r_bin_pe_export_t*) (((const ut8*) exports) + osz);
} else {
sz = exports_sz;
exports = malloc (sz);
exp = exports;
}
sections = PE_(r_bin_pe_get_sections) (bin);
for (i = 0; i < bin->num_sections; i++) {
//XXX search by section with +x permission since the section can be left blank
if (!strcmp ((char*) sections[i].name, ".text")) {
text_rva = sections[i].vaddr;
text_off = sections[i].paddr;
textn = i + 1;
}
}
free (sections);
symctr = 0;
if (r_buf_read_at (bin->b, sym_tbl_off, (ut8*) buf, bufsz)) {
for (i = 0; i < shsz; i += srsz) {
sr = (SymbolRecord*) (buf + i);
//bprintf ("SECNUM %d\n", sr->secnum);
if (sr->secnum == textn) {
if (sr->symtype == 32) {
char shortname[9];
memcpy (shortname, &sr->shortname, 8);
shortname[8] = 0;
if (*shortname) {
strncpy ((char*) exp[symctr].name, shortname, PE_NAME_LENGTH - 1);
} else {
char* longname, name[128];
ut32* idx = (ut32*) (buf + i + 4);
if (r_buf_read_at (bin->b, sym_tbl_off + *idx + shsz, (ut8*) name, 128)) { // == 128) {
longname = name;
name[sizeof(name) - 1] = 0;
strncpy ((char*) exp[symctr].name, longname, PE_NAME_LENGTH - 1);
} else {
sprintf ((char*) exp[symctr].name, "unk_%d", symctr);
}
}
exp[symctr].name[PE_NAME_LENGTH] = 0;
exp[symctr].vaddr = bin_pe_rva_to_va (bin, text_rva + sr->value);
exp[symctr].paddr = text_off + sr->value;
exp[symctr].ordinal = symctr;
exp[symctr].forwarder[0] = 0;
exp[symctr].last = 0;
symctr++;
}
}
} // for
} // if read ok
exp[symctr].last = 1;
free (buf);
return exports;
}
static int bin_pe_init_sections(struct PE_(r_bin_pe_obj_t)* bin) {
bin->num_sections = bin->nt_headers->file_header.NumberOfSections;
int sections_size;
if (bin->num_sections < 1) {
return true;
}
sections_size = sizeof (PE_(image_section_header)) * bin->num_sections;
if (sections_size > bin->size) {
sections_size = bin->size;
bin->num_sections = bin->size / sizeof (PE_(image_section_header));
// massage this to make corkami happy
//bprintf ("Invalid NumberOfSections value\n");
//goto out_error;
}
if (!(bin->section_header = malloc (sections_size))) {
r_sys_perror ("malloc (section header)");
goto out_error;
}
bin->section_header_offset = bin->dos_header->e_lfanew + 4 + sizeof (PE_(image_file_header)) +
bin->nt_headers->file_header.SizeOfOptionalHeader;
if (r_buf_read_at (bin->b, bin->section_header_offset,
(ut8*) bin->section_header, sections_size) == -1) {
bprintf ("Warning: read (sections)\n");
R_FREE (bin->section_header);
goto out_error;
}
#if 0
Each symbol table entry includes a name, storage class, type, value and section number.Short names (8 characters or fewer) are stored directly in the symbol table;
longer names are stored as an paddr into the string table at the end of the COFF object.
================================================================
COFF SYMBOL TABLE RECORDS (18 BYTES)
================================================================
record
paddr
struct symrec {
union {
char string[8]; // short name
struct {
ut32 seros;
ut32 stridx;
} stridx;
} name;
ut32 value;
ut16 secnum;
ut16 symtype;
ut8 symclass;
ut8 numaux;
}
------------------------------------------------------ -
0 | 8 - char symbol name |
| or 32 - bit zeroes followed by 32 - bit |
| index into string table |
------------------------------------------------------ -
8 | symbol value |
------------------------------------------------------ -
0Ch | section number | symbol type |
------------------------------------------------------ -
10h | sym class | num aux |
-------------------------- -
12h
#endif
return true;
out_error:
bin->num_sections = 0;
return false;
}
int PE_(bin_pe_get_claimed_checksum)(struct PE_(r_bin_pe_obj_t)* bin) {
if (!bin || !bin->optional_header) {
return 0;
}
return bin->optional_header->CheckSum;
}
int PE_(bin_pe_get_actual_checksum)(struct PE_(r_bin_pe_obj_t)* bin) {
int i, j, checksum_offset = 0;
ut8* buf = NULL;
ut64 computed_cs = 0;
int remaining_bytes;
int shift;
ut32 cur;
if (!bin || !bin->nt_header_offset) {
return 0;
}
buf = bin->b->buf;
checksum_offset = bin->nt_header_offset + 4 + sizeof(PE_(image_file_header)) + 0x40;
for (i = 0; i < bin->size / 4; i++) {
cur = r_read_le32 (&buf[i * 4]);
// skip the checksum bytes
if (i * 4 == checksum_offset) {
continue;
}
computed_cs = (computed_cs & 0xFFFFFFFF) + cur + (computed_cs >> 32);
if (computed_cs >> 32) {
computed_cs = (computed_cs & 0xFFFFFFFF) + (computed_cs >> 32);
}
}
// add resultant bytes to checksum
remaining_bytes = bin->size % 4;
i = i * 4;
if (remaining_bytes != 0) {
cur = buf[i];
shift = 8;
for (j = 1; j < remaining_bytes; j++, shift += 8) {
cur |= buf[i + j] << shift;
}
computed_cs = (computed_cs & 0xFFFFFFFF) + cur + (computed_cs >> 32);
if (computed_cs >> 32) {
computed_cs = (computed_cs & 0xFFFFFFFF) + (computed_cs >> 32);
}
}
// 32bits -> 16bits
computed_cs = (computed_cs & 0xFFFF) + (computed_cs >> 16);
computed_cs = (computed_cs) + (computed_cs >> 16);
computed_cs = (computed_cs & 0xFFFF);
// add filesize
computed_cs += bin->size;
return computed_cs;
}
static void computeOverlayOffset(ut64 offset, ut64 size, ut64 file_size, ut64* largest_offset, ut64* largest_size) {
if (offset + size <= file_size && offset + size > (*largest_offset + *largest_size)) {
*largest_offset = offset;
*largest_size = size;
}
}
/* Inspired from https://github.com/erocarrera/pefile/blob/master/pefile.py#L5425 */
int PE_(bin_pe_get_overlay)(struct PE_(r_bin_pe_obj_t)* bin, ut64* size) {
ut64 largest_offset = 0;
ut64 largest_size = 0;
*size = 0;
int i;
if (!bin) {
return 0;
}
if (bin->optional_header) {
computeOverlayOffset (
bin->nt_header_offset+4+sizeof(bin->nt_headers->file_header),
bin->nt_headers->file_header.SizeOfOptionalHeader,
bin->size,
&largest_offset,
&largest_size);
}
struct r_bin_pe_section_t *sects = NULL;
sects = PE_(r_bin_pe_get_sections) (bin);
for (i = 0; !sects[i].last; i++) {
computeOverlayOffset(
sects[i].paddr,
sects[i].size,
bin->size,
&largest_offset,
&largest_size
);
}
if (bin->optional_header) {
for (i = 0; i < PE_IMAGE_DIRECTORY_ENTRIES; i++) {
if (i == PE_IMAGE_DIRECTORY_ENTRY_SECURITY) {
continue;
}
computeOverlayOffset (
bin_pe_rva_to_paddr (bin, bin->data_directory[i].VirtualAddress),
bin->data_directory[i].Size,
bin->size,
&largest_offset,
&largest_size);
}
}
if ((ut64) bin->size > largest_offset + largest_size) {
*size = bin->size - largest_offset - largest_size;
free (sects);
return largest_offset + largest_size;
}
free (sects);
return 0;
}
static int bin_pe_read_metadata_string(char* to, char* from) {
int covered = 0;
while (covered < MAX_METADATA_STRING_LENGTH) {
to[covered] = from[covered];
if (from[covered] == '\0') {
covered += 1;
break;
}
covered++;
}
while (covered % 4 != 0) { covered++; }
return covered;
}
static int bin_pe_init_metadata_hdr(struct PE_(r_bin_pe_obj_t)* bin) {
PE_DWord metadata_directory = bin->clr_hdr? bin_pe_rva_to_paddr (bin, bin->clr_hdr->MetaDataDirectoryAddress): 0;
PE_(image_metadata_header) * metadata = R_NEW0 (PE_(image_metadata_header));
int rr;
if (!metadata) {
return 0;
}
if (!metadata_directory) {
free (metadata);
return 0;
}
rr = r_buf_fread_at (bin->b, metadata_directory,
(ut8*) metadata, bin->big_endian? "1I2S": "1i2s", 1);
if (rr < 1) {
goto fail;
}
rr = r_buf_fread_at (bin->b, metadata_directory + 8,
(ut8*) (&metadata->Reserved), bin->big_endian? "1I": "1i", 1);
if (rr < 1) {
goto fail;
}
rr = r_buf_fread_at (bin->b, metadata_directory + 12,
(ut8*) (&metadata->VersionStringLength), bin->big_endian? "1I": "1i", 1);
if (rr < 1) {
goto fail;
}
eprintf ("Metadata Signature: 0x%"PFMT64x" 0x%"PFMT64x" %d\n",
(ut64)metadata_directory, (ut64)metadata->Signature, (int)metadata->VersionStringLength);
// read the version string
int len = metadata->VersionStringLength; // XXX: dont trust this length
if (len > 0) {
metadata->VersionString = calloc (1, len + 1);
if (!metadata->VersionString) {
goto fail;
}
rr = r_buf_read_at (bin->b, metadata_directory + 16, (ut8*)(metadata->VersionString), len);
if (rr != len) {
eprintf ("Warning: read (metadata header) - cannot parse version string\n");
free (metadata->VersionString);
free (metadata);
return 0;
}
eprintf (".NET Version: %s\n", metadata->VersionString);
}
// read the header after the string
rr = r_buf_fread_at (bin->b, metadata_directory + 16 + metadata->VersionStringLength,
(ut8*) (&metadata->Flags), bin->big_endian? "2S": "2s", 1);
if (rr < 1) {
goto fail;
}
eprintf ("Number of Metadata Streams: %d\n", metadata->NumberOfStreams);
bin->metadata_header = metadata;
// read metadata streams
int start_of_stream = metadata_directory + 20 + metadata->VersionStringLength;
PE_(image_metadata_stream) * stream;
PE_(image_metadata_stream) **streams = calloc (sizeof (PE_(image_metadata_stream)*), metadata->NumberOfStreams);
if (!streams) {
goto fail;
}
int count = 0;
while (count < metadata->NumberOfStreams) {
stream = R_NEW0 (PE_(image_metadata_stream));
if (!stream) {
free (streams);
goto fail;
}
if (r_buf_fread_at (bin->b, start_of_stream, (ut8*) stream, bin->big_endian? "2I": "2i", 1) < 1) {
free (stream);
free (streams);
goto fail;
}
eprintf ("DirectoryAddress: %x Size: %x\n", stream->Offset, stream->Size);
char* stream_name = calloc (1, MAX_METADATA_STRING_LENGTH + 1);
if (!stream_name) {
free (stream);
free (streams);
goto fail;
}
if (r_buf_size (bin->b) < (start_of_stream + 8 + MAX_METADATA_STRING_LENGTH)) {
free (stream_name);
free (stream);
free (streams);
goto fail;
}
int c = bin_pe_read_metadata_string (stream_name,
(char *)(bin->b->buf + start_of_stream + 8));
if (c == 0) {
free (stream_name);
free (stream);
free (streams);
goto fail;
}
eprintf ("Stream name: %s %d\n", stream_name, c);
stream->Name = stream_name;
streams[count] = stream;
start_of_stream += 8 + c;
count += 1;
}
bin->streams = streams;
return 1;
fail:
eprintf ("Warning: read (metadata header)\n");
free (metadata);
return 0;
}
static int bin_pe_init_overlay(struct PE_(r_bin_pe_obj_t)* bin) {
ut64 pe_overlay_size;
ut64 pe_overlay_offset = PE_(bin_pe_get_overlay) (bin, &pe_overlay_size);
if (pe_overlay_offset) {
sdb_num_set (bin->kv, "pe_overlay.offset", pe_overlay_offset, 0);
sdb_num_set (bin->kv, "pe_overlay.size", pe_overlay_size, 0);
}
return 0;
}
static int bin_pe_init_clr_hdr(struct PE_(r_bin_pe_obj_t)* bin) {
PE_(image_data_directory) * clr_dir = &bin->data_directory[PE_IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR];
PE_DWord image_clr_hdr_paddr = bin_pe_rva_to_paddr (bin, clr_dir->VirtualAddress);
// int clr_dir_size = clr_dir? clr_dir->Size: 0;
PE_(image_clr_header) * clr_hdr = R_NEW0 (PE_(image_clr_header));
int rr, len = sizeof (PE_(image_clr_header));
if (!clr_hdr) {
return 0;
}
rr = r_buf_read_at (bin->b, image_clr_hdr_paddr, (ut8*) (clr_hdr), len);
// printf("%x\n", clr_hdr->HeaderSize);
if (clr_hdr->HeaderSize != 0x48) {
// probably not a .NET binary
// 64bit?
free (clr_hdr);
return 0;
}
if (rr != len) {
free (clr_hdr);
return 0;
}
bin->clr_hdr = clr_hdr;
return 1;
}
static int bin_pe_init_imports(struct PE_(r_bin_pe_obj_t)* bin) {
PE_(image_data_directory) * data_dir_import = &bin->data_directory[PE_IMAGE_DIRECTORY_ENTRY_IMPORT];
PE_(image_data_directory) * data_dir_delay_import = &bin->data_directory[PE_IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT];
PE_DWord import_dir_paddr = bin_pe_rva_to_paddr (bin, data_dir_import->VirtualAddress);
PE_DWord import_dir_offset = bin_pe_rva_to_paddr (bin, data_dir_import->VirtualAddress);
PE_DWord delay_import_dir_offset = data_dir_delay_import
? bin_pe_rva_to_paddr (bin, data_dir_delay_import->VirtualAddress)
: 0;
PE_(image_import_directory) * import_dir = NULL;
PE_(image_import_directory) * new_import_dir = NULL;
PE_(image_import_directory) * curr_import_dir = NULL;
PE_(image_delay_import_directory) * delay_import_dir = NULL;
PE_(image_delay_import_directory) * curr_delay_import_dir = NULL;
int dir_size = sizeof(PE_(image_import_directory));
int delay_import_size = sizeof(PE_(image_delay_import_directory));
int indx = 0;
int rr, count = 0;
int import_dir_size = data_dir_import->Size;
int delay_import_dir_size = data_dir_delay_import->Size;
/// HACK to modify import size because of begin 0.. this may report wrong info con corkami tests
if (!import_dir_size) {
// asume 1 entry for each
import_dir_size = data_dir_import->Size = 0xffff;
}
if (!delay_import_dir_size) {
// asume 1 entry for each
delay_import_dir_size = data_dir_delay_import->Size = 0xffff;
}
int maxidsz = R_MIN ((PE_DWord) bin->size, import_dir_offset + import_dir_size);
maxidsz -= import_dir_offset;
if (maxidsz < 0) {
maxidsz = 0;
}
//int maxcount = maxidsz/ sizeof (struct r_bin_pe_import_t);
free (bin->import_directory);
bin->import_directory = NULL;
if (import_dir_paddr != 0) {
if (import_dir_size < 1 || import_dir_size > maxidsz) {
bprintf ("Warning: Invalid import directory size: 0x%x is now 0x%x\n", import_dir_size, maxidsz);
import_dir_size = maxidsz;
}
bin->import_directory_offset = import_dir_offset;
count = 0;
do {
indx++;
if (((2 + indx) * dir_size) > import_dir_size) {
break; //goto fail;
}
new_import_dir = (PE_(image_import_directory)*)realloc (import_dir, ((1 + indx) * dir_size));
if (!new_import_dir) {
r_sys_perror ("malloc (import directory)");
free (import_dir);
import_dir = NULL;
break; //
// goto fail;
}
import_dir = new_import_dir;
new_import_dir = NULL;
curr_import_dir = import_dir + (indx - 1);
if (r_buf_read_at (bin->b, import_dir_offset + (indx - 1) * dir_size, (ut8*) (curr_import_dir), dir_size) < 1) {
bprintf ("Warning: read (import directory)\n");
free (import_dir);
import_dir = NULL;
break; //return false;
}
count++;
} while (curr_import_dir->FirstThunk != 0 || curr_import_dir->Name != 0 ||
curr_import_dir->TimeDateStamp != 0 || curr_import_dir->Characteristics != 0 ||
curr_import_dir->ForwarderChain != 0);
bin->import_directory = import_dir;
bin->import_directory_size = import_dir_size;
}
indx = 0;
if (bin->b->length > 0) {
if ((delay_import_dir_offset != 0) && (delay_import_dir_offset < (ut32) bin->b->length)) {
ut64 off;
bin->delay_import_directory_offset = delay_import_dir_offset;
do {
indx++;
off = indx * delay_import_size;
if (off >= bin->b->length) {
bprintf ("Warning: Cannot find end of import symbols\n");
break;
}
delay_import_dir = (PE_(image_delay_import_directory)*)realloc (
delay_import_dir, (indx * delay_import_size) + 1);
if (delay_import_dir == 0) {
r_sys_perror ("malloc (delay import directory)");
free (delay_import_dir);
return false;
}
curr_delay_import_dir = delay_import_dir + (indx - 1);
rr = r_buf_read_at (bin->b, delay_import_dir_offset + (indx - 1) * delay_import_size,
(ut8*) (curr_delay_import_dir), dir_size);
if (rr != dir_size) {
bprintf ("Warning: read (delay import directory)\n");
goto fail;
}
} while (curr_delay_import_dir->Name != 0);
bin->delay_import_directory = delay_import_dir;
}
}
return true;
fail:
free (import_dir);
import_dir = NULL;
bin->import_directory = import_dir;
free (delay_import_dir);
return false;
}
static int bin_pe_init_exports(struct PE_(r_bin_pe_obj_t)* bin) {
PE_(image_data_directory) * data_dir_export = &bin->data_directory[PE_IMAGE_DIRECTORY_ENTRY_EXPORT];
PE_DWord export_dir_paddr = bin_pe_rva_to_paddr (bin, data_dir_export->VirtualAddress);
if (!export_dir_paddr) {
// This export-dir-paddr should only appear in DLL files
// bprintf ("Warning: Cannot find the paddr of the export directory\n");
return false;
}
// sdb_setn (DB, "hdr.exports_directory", export_dir_paddr);
// bprintf ("Pexports paddr at 0x%"PFMT64x"\n", export_dir_paddr);
if (!(bin->export_directory = malloc (sizeof(PE_(image_export_directory))))) {
r_sys_perror ("malloc (export directory)");
return false;
}
if (r_buf_read_at (bin->b, export_dir_paddr, (ut8*) bin->export_directory, sizeof (PE_(image_export_directory))) == -1) {
bprintf ("Warning: read (export directory)\n");
free (bin->export_directory);
bin->export_directory = NULL;
return false;
}
return true;
}
static void _free_resources(r_pe_resource *rs) {
if (rs) {
free (rs->timestr);
free (rs->data);
free (rs->type);
free (rs->language);
free (rs);
}
}
static int bin_pe_init_resource(struct PE_(r_bin_pe_obj_t)* bin) {
PE_(image_data_directory) * resource_dir = &bin->data_directory[PE_IMAGE_DIRECTORY_ENTRY_RESOURCE];
PE_DWord resource_dir_paddr = bin_pe_rva_to_paddr (bin, resource_dir->VirtualAddress);
if (!resource_dir_paddr) {
return false;
}
bin->resources = r_list_newf ((RListFree)_free_resources);
if (!bin->resources) {
return false;
}
if (!(bin->resource_directory = malloc (sizeof(*bin->resource_directory)))) {
r_sys_perror ("malloc (resource directory)");
return false;
}
if (r_buf_read_at (bin->b, resource_dir_paddr, (ut8*) bin->resource_directory,
sizeof (*bin->resource_directory)) != sizeof (*bin->resource_directory)) {
bprintf ("Warning: read (resource directory)\n");
free (bin->resource_directory);
bin->resource_directory = NULL;
return false;
}
bin->resource_directory_offset = resource_dir_paddr;
return true;
}
static void bin_pe_store_tls_callbacks(struct PE_(r_bin_pe_obj_t)* bin, PE_DWord callbacks) {
PE_DWord paddr, haddr;
int count = 0;
PE_DWord addressOfTLSCallback = 1;
char* key;
while (addressOfTLSCallback != 0) {
if (r_buf_read_at (bin->b, callbacks, (ut8*) &addressOfTLSCallback, sizeof(addressOfTLSCallback)) != sizeof (addressOfTLSCallback)) {
bprintf ("Warning: read (tls_callback)\n");
return;
}
if (!addressOfTLSCallback) {
break;
}
if (bin->optional_header->SizeOfImage) {
int rva_callback = bin_pe_va_to_rva (bin, (PE_DWord) addressOfTLSCallback);
if (rva_callback > bin->optional_header->SizeOfImage) {
break;
}
}
key = sdb_fmt ("pe.tls_callback%d_vaddr", count);
sdb_num_set (bin->kv, key, addressOfTLSCallback, 0);
key = sdb_fmt ("pe.tls_callback%d_paddr", count);
paddr = bin_pe_rva_to_paddr (bin, bin_pe_va_to_rva (bin, (PE_DWord) addressOfTLSCallback));
sdb_num_set (bin->kv, key, paddr, 0);
key = sdb_fmt ("pe.tls_callback%d_haddr", count);
haddr = callbacks;
sdb_num_set (bin->kv, key, haddr, 0);
count++;
callbacks += sizeof (addressOfTLSCallback);
}
}
static int bin_pe_init_tls(struct PE_(r_bin_pe_obj_t)* bin) {
PE_(image_tls_directory) * image_tls_directory;
PE_(image_data_directory) * data_dir_tls = &bin->data_directory[PE_IMAGE_DIRECTORY_ENTRY_TLS];
PE_DWord tls_paddr = bin_pe_rva_to_paddr (bin, data_dir_tls->VirtualAddress);
image_tls_directory = R_NEW0 (PE_(image_tls_directory));
if (r_buf_read_at (bin->b, tls_paddr, (ut8*) image_tls_directory, sizeof (PE_(image_tls_directory))) != sizeof (PE_(image_tls_directory))) {
bprintf ("Warning: read (image_tls_directory)\n");
free (image_tls_directory);
return 0;
}
bin->tls_directory = image_tls_directory;
if (!image_tls_directory->AddressOfCallBacks) {
return 0;
}
if (image_tls_directory->EndAddressOfRawData < image_tls_directory->StartAddressOfRawData) {
return 0;
}
PE_DWord callbacks_paddr = bin_pe_rva_to_paddr (bin, bin_pe_va_to_rva (bin,
(PE_DWord) image_tls_directory->AddressOfCallBacks));
bin_pe_store_tls_callbacks (bin, callbacks_paddr);
return 0;
}
static void free_Var(Var* var) {
if (var) {
free (var->szKey);
free (var->Value);
free (var);
}
}
static void free_VarFileInfo(VarFileInfo* varFileInfo) {
if (varFileInfo) {
free (varFileInfo->szKey);
if (varFileInfo->Children) {
ut32 children = 0;
for (; children < varFileInfo->numOfChildren; children++) {
free_Var (varFileInfo->Children[children]);
}
free (varFileInfo->Children);
}
free (varFileInfo);
}
}
static void free_String(String* string) {
if (string) {
free (string->szKey);
free (string->Value);
free (string);
}
}
static void free_StringTable(StringTable* stringTable) {
if (stringTable) {
free (stringTable->szKey);
if (stringTable->Children) {
ut32 childrenST = 0;
for (; childrenST < stringTable->numOfChildren; childrenST++) {
free_String (stringTable->Children[childrenST]);
}
free (stringTable->Children);
}
free (stringTable);
}
}
static void free_StringFileInfo(StringFileInfo* stringFileInfo) {
if (stringFileInfo) {
free (stringFileInfo->szKey);
if (stringFileInfo->Children) {
ut32 childrenSFI = 0;
for (; childrenSFI < stringFileInfo->numOfChildren; childrenSFI++) {
free_StringTable (stringFileInfo->Children[childrenSFI]);
}
free (stringFileInfo->Children);
}
free (stringFileInfo);
}
}
#define align32(x) x = ((x & 0x3) == 0)? x: (x & ~0x3) + 0x4;
static void free_VS_VERSIONINFO(PE_VS_VERSIONINFO* vs_VersionInfo) {
if (vs_VersionInfo) {
free (vs_VersionInfo->szKey);
free (vs_VersionInfo->Value);
free_VarFileInfo (vs_VersionInfo->varFileInfo);
free_StringFileInfo (vs_VersionInfo->stringFileInfo);
free (vs_VersionInfo);
}
}
void PE_(free_VS_VERSIONINFO)(PE_VS_VERSIONINFO * vs_VersionInfo) {
free_VS_VERSIONINFO (vs_VersionInfo);
}
static Var* Pe_r_bin_pe_parse_var(struct PE_(r_bin_pe_obj_t)* bin, PE_DWord* curAddr) {
Var* var = calloc (1, sizeof(*var));
if (!var) {
bprintf ("Warning: calloc (Var)\n");
return NULL;
}
if (r_buf_read_at (bin->b, *curAddr, (ut8*) &var->wLength, sizeof(var->wLength)) != sizeof(var->wLength)) {
bprintf ("Warning: read (Var wLength)\n");
free_Var (var);
return NULL;
}
*curAddr += sizeof(var->wLength);
if (r_buf_read_at (bin->b, *curAddr, (ut8*) &var->wValueLength, sizeof(var->wValueLength)) != sizeof(var->wValueLength)) {
bprintf ("Warning: read (Var wValueLength)\n");
free_Var (var);
return NULL;
}
*curAddr += sizeof(var->wValueLength);
if (r_buf_read_at (bin->b, *curAddr, (ut8*) &var->wType, sizeof(var->wType)) != sizeof(var->wType)) {
bprintf ("Warning: read (Var wType)\n");
free_Var (var);
return NULL;
}
*curAddr += sizeof(var->wType);
if (var->wType != 0 && var->wType != 1) {
bprintf ("Warning: check (Var wType)\n");
free_Var (var);
return NULL;
}
var->szKey = (ut16*) malloc (UT16_ALIGN (TRANSLATION_UTF_16_LEN)); //L"Translation"
if (!var->szKey) {
bprintf ("Warning: malloc (Var szKey)\n");
free_Var (var);
return NULL;
}
if (r_buf_read_at (bin->b, *curAddr, (ut8*) var->szKey, TRANSLATION_UTF_16_LEN) < 1) {
bprintf ("Warning: read (Var szKey)\n");
free_Var (var);
return NULL;
}
*curAddr += TRANSLATION_UTF_16_LEN;
if (memcmp (var->szKey, TRANSLATION_UTF_16, TRANSLATION_UTF_16_LEN)) {
bprintf ("Warning: check (Var szKey)\n");
free_Var (var);
return NULL;
}
align32 (*curAddr);
var->numOfValues = var->wValueLength / 4;
if (!var->numOfValues) {
bprintf ("Warning: check (Var numOfValues)\n");
free_Var (var);
return NULL;
}
var->Value = (ut32*) malloc (var->wValueLength);
if (!var->Value) {
bprintf ("Warning: malloc (Var Value)\n");
free_Var (var);
return NULL;
}
if (r_buf_read_at (bin->b, *curAddr, (ut8*) var->Value, var->wValueLength) != var->wValueLength) {
bprintf ("Warning: read (Var Value)\n");
free_Var (var);
return NULL;
}
*curAddr += var->wValueLength;
return var;
}
static VarFileInfo* Pe_r_bin_pe_parse_var_file_info(struct PE_(r_bin_pe_obj_t)* bin, PE_DWord* curAddr) {
VarFileInfo* varFileInfo = calloc (1, sizeof(*varFileInfo));
if (!varFileInfo) {
bprintf ("Warning: calloc (VarFileInfo)\n");
return NULL;
}
PE_DWord startAddr = *curAddr;
if (r_buf_read_at (bin->b, *curAddr, (ut8*) &varFileInfo->wLength, sizeof(varFileInfo->wLength)) != sizeof(varFileInfo->wLength)) {
bprintf ("Warning: read (VarFileInfo wLength)\n");
free_VarFileInfo (varFileInfo);
return NULL;
}
*curAddr += sizeof(varFileInfo->wLength);
if (r_buf_read_at (bin->b, *curAddr, (ut8*) &varFileInfo->wValueLength, sizeof(varFileInfo->wValueLength)) != sizeof(varFileInfo->wValueLength)) {
bprintf ("Warning: read (VarFileInfo wValueLength)\n");
free_VarFileInfo (varFileInfo);
return NULL;
}
*curAddr += sizeof(varFileInfo->wValueLength);
if (varFileInfo->wValueLength != 0) {
bprintf ("Warning: check (VarFileInfo wValueLength)\n");
free_VarFileInfo (varFileInfo);
return NULL;
}
if (r_buf_read_at (bin->b, *curAddr, (ut8*) &varFileInfo->wType, sizeof(varFileInfo->wType)) != sizeof(varFileInfo->wType)) {
bprintf ("Warning: read (VarFileInfo wType)\n");
free_VarFileInfo (varFileInfo);
return NULL;
}
*curAddr += sizeof(varFileInfo->wType);
if (varFileInfo->wType && varFileInfo->wType != 1) {
bprintf ("Warning: check (VarFileInfo wType)\n");
free_VarFileInfo (varFileInfo);
return NULL;
}
varFileInfo->szKey = (ut16*) malloc (UT16_ALIGN (VARFILEINFO_UTF_16_LEN )); //L"VarFileInfo"
if (!varFileInfo->szKey) {
bprintf ("Warning: malloc (VarFileInfo szKey)\n");
free_VarFileInfo (varFileInfo);
return NULL;
}
if (r_buf_read_at (bin->b, *curAddr, (ut8*) varFileInfo->szKey, VARFILEINFO_UTF_16_LEN) != VARFILEINFO_UTF_16_LEN) {
bprintf ("Warning: read (VarFileInfo szKey)\n");
free_VarFileInfo (varFileInfo);
return NULL;
}
*curAddr += VARFILEINFO_UTF_16_LEN;
if (memcmp (varFileInfo->szKey, VARFILEINFO_UTF_16, VARFILEINFO_UTF_16_LEN)) {
bprintf ("Warning: check (VarFileInfo szKey)\n");
free_VarFileInfo (varFileInfo);
return NULL;
}
align32 (*curAddr);
while (startAddr + varFileInfo->wLength > *curAddr) {
Var** tmp = (Var**) realloc (varFileInfo->Children, (varFileInfo->numOfChildren + 1) * sizeof(*varFileInfo->Children));
if (!tmp) {
bprintf ("Warning: realloc (VarFileInfo Children)\n");
free_VarFileInfo (varFileInfo);
return NULL;
}
varFileInfo->Children = tmp;
if (!(varFileInfo->Children[varFileInfo->numOfChildren] = Pe_r_bin_pe_parse_var (bin, curAddr))) {
bprintf ("Warning: bad parsing Var\n");
free_VarFileInfo (varFileInfo);
return NULL;
}
varFileInfo->numOfChildren++;
align32 (*curAddr);
}
return varFileInfo;
}
static String* Pe_r_bin_pe_parse_string(struct PE_(r_bin_pe_obj_t)* bin, PE_DWord* curAddr) {
String* string = calloc (1, sizeof(*string));
PE_DWord begAddr = *curAddr;
int len_value = 0;
int i = 0;
if (!string) {
bprintf ("Warning: calloc (String)\n");
return NULL;
}
if (begAddr > bin->size || begAddr + sizeof(string->wLength) > bin->size) {
free_String (string);
return NULL;
}
if (r_buf_read_at (bin->b, *curAddr, (ut8*) &string->wLength, sizeof(string->wLength)) != sizeof(string->wLength)) {
bprintf ("Warning: read (String wLength)\n");
goto out_error;
}
*curAddr += sizeof(string->wLength);
if (*curAddr > bin->size || *curAddr + sizeof(string->wValueLength) > bin->size) {
goto out_error;
}
if (r_buf_read_at (bin->b, *curAddr, (ut8*) &string->wValueLength, sizeof(string->wValueLength)) != sizeof(string->wValueLength)) {
bprintf ("Warning: read (String wValueLength)\n");
goto out_error;
}
*curAddr += sizeof(string->wValueLength);
if (*curAddr > bin->size || *curAddr + sizeof(string->wType) > bin->size) {
goto out_error;
}
if (r_buf_read_at (bin->b, *curAddr, (ut8*) &string->wType, sizeof(string->wType)) != sizeof(string->wType)) {
bprintf ("Warning: read (String wType)\n");
goto out_error;
}
*curAddr += sizeof(string->wType);
if (string->wType != 0 && string->wType != 1) {
bprintf ("Warning: check (String wType)\n");
goto out_error;
}
for (i = 0; *curAddr < begAddr + string->wLength; ++i, *curAddr += sizeof (ut16)) {
ut16 utf16_char;
if (*curAddr > bin->size || *curAddr + sizeof (ut16) > bin->size) {
goto out_error;
}
if (r_buf_read_at (bin->b, *curAddr, (ut8*) &utf16_char, sizeof (ut16)) != sizeof (ut16)) {
bprintf ("Warning: check (String szKey)\n");
goto out_error;
}
string->szKey = (ut16*) realloc (string->szKey, (i + 1) * sizeof (ut16));
string->szKey[i] = utf16_char;
string->wKeyLen += sizeof (ut16);
if (!utf16_char) {
*curAddr += sizeof (ut16);
break;
}
}
align32 (*curAddr);
len_value = R_MIN (string->wValueLength * 2, string->wLength - (*curAddr - begAddr));
string->wValueLength = len_value;
if (len_value < 0) {
len_value = 0;
}
string->Value = (ut16*) calloc (len_value + 1, 1);
if (!string->Value) {
bprintf ("Warning: malloc (String Value)\n");
goto out_error;
}
if (*curAddr > bin->size || *curAddr + len_value > bin->size) {
goto out_error;
}
if (r_buf_read_at (bin->b, *curAddr, (ut8*) string->Value, len_value) != len_value) {
bprintf ("Warning: read (String Value)\n");
goto out_error;
}
*curAddr += len_value;
return string;
out_error:
free_String (string);
return NULL;
}
static StringTable* Pe_r_bin_pe_parse_string_table(struct PE_(r_bin_pe_obj_t)* bin, PE_DWord* curAddr) {
StringTable* stringTable = calloc (1, sizeof(*stringTable));
if (!stringTable) {
bprintf ("Warning: calloc (stringTable)\n");
return NULL;
}
PE_DWord startAddr = *curAddr;
if (r_buf_read_at (bin->b, *curAddr, (ut8*) &stringTable->wLength, sizeof(stringTable->wLength)) != sizeof(stringTable->wLength)) {
bprintf ("Warning: read (StringTable wLength)\n");
free_StringTable (stringTable);
return NULL;
}
*curAddr += sizeof(stringTable->wLength);
if (r_buf_read_at (bin->b, *curAddr, (ut8*) &stringTable->wValueLength, sizeof(stringTable->wValueLength)) != sizeof(stringTable->wValueLength)) {
bprintf ("Warning: read (StringTable wValueLength)\n");
free_StringTable (stringTable);
return NULL;
}
*curAddr += sizeof(stringTable->wValueLength);
if (stringTable->wValueLength) {
bprintf ("Warning: check (StringTable wValueLength)\n");
free_StringTable (stringTable);
return NULL;
}
if (r_buf_read_at (bin->b, *curAddr, (ut8*) &stringTable->wType, sizeof(stringTable->wType)) != sizeof(stringTable->wType)) {
bprintf ("Warning: read (StringTable wType)\n");
free_StringTable (stringTable);
return NULL;
}
*curAddr += sizeof(stringTable->wType);
if (stringTable->wType && stringTable->wType != 1) {
bprintf ("Warning: check (StringTable wType)\n");
free_StringTable (stringTable);
return NULL;
}
stringTable->szKey = (ut16*) malloc (UT16_ALIGN (EIGHT_HEX_DIG_UTF_16_LEN)); //EIGHT_HEX_DIG_UTF_16_LEN
if (!stringTable->szKey) {
bprintf ("Warning: malloc (stringTable szKey)\n");
free_StringTable (stringTable);
return NULL;
}
if (r_buf_read_at (bin->b, *curAddr, (ut8*) stringTable->szKey, EIGHT_HEX_DIG_UTF_16_LEN) != EIGHT_HEX_DIG_UTF_16_LEN) {
bprintf ("Warning: read (StringTable szKey)\n");
free_StringTable (stringTable);
return NULL;
}
*curAddr += EIGHT_HEX_DIG_UTF_16_LEN;
align32 (*curAddr);
while (startAddr + stringTable->wLength > *curAddr) {
String** tmp = (String**) realloc (stringTable->Children, (stringTable->numOfChildren + 1) * sizeof(*stringTable->Children));
if (!tmp) {
bprintf ("Warning: realloc (StringTable Children)\n");
free_StringTable (stringTable);
return NULL;
}
stringTable->Children = tmp;
if (!(stringTable->Children[stringTable->numOfChildren] = Pe_r_bin_pe_parse_string (bin, curAddr))) {
bprintf ("Warning: bad parsing String\n");
free_StringTable (stringTable);
return NULL;
}
stringTable->numOfChildren++;
align32 (*curAddr);
}
if (!stringTable->numOfChildren) {
bprintf ("Warning: check (StringTable numOfChildren)\n");
free_StringTable (stringTable);
return NULL;
}
return stringTable;
}
static StringFileInfo* Pe_r_bin_pe_parse_string_file_info(struct PE_(r_bin_pe_obj_t)* bin, PE_DWord* curAddr) {
StringFileInfo* stringFileInfo = calloc (1, sizeof(*stringFileInfo));
if (!stringFileInfo) {
bprintf ("Warning: calloc (StringFileInfo)\n");
return NULL;
}
PE_DWord startAddr = *curAddr;
if (r_buf_read_at (bin->b, *curAddr, (ut8*) &stringFileInfo->wLength, sizeof(stringFileInfo->wLength)) != sizeof(stringFileInfo->wLength)) {
bprintf ("Warning: read (StringFileInfo wLength)\n");
free_StringFileInfo (stringFileInfo);
return NULL;
}
*curAddr += sizeof(stringFileInfo->wLength);
if (r_buf_read_at (bin->b, *curAddr, (ut8*) &stringFileInfo->wValueLength, sizeof(stringFileInfo->wValueLength)) != sizeof(stringFileInfo->wValueLength)) {
bprintf ("Warning: read (StringFileInfo wValueLength)\n");
free_StringFileInfo (stringFileInfo);
return NULL;
}
*curAddr += sizeof(stringFileInfo->wValueLength);
if (stringFileInfo->wValueLength) {
bprintf ("Warning: check (StringFileInfo wValueLength)\n");
free_StringFileInfo (stringFileInfo);
return NULL;
}
if (r_buf_read_at (bin->b, *curAddr, (ut8*) &stringFileInfo->wType, sizeof(stringFileInfo->wType)) != sizeof(stringFileInfo->wType)) {
bprintf ("Warning: read (StringFileInfo wType)\n");
free_StringFileInfo (stringFileInfo);
return NULL;
}
*curAddr += sizeof(stringFileInfo->wType);
if (stringFileInfo->wType && stringFileInfo->wType != 1) {
bprintf ("Warning: check (StringFileInfo wType)\n");
free_StringFileInfo (stringFileInfo);
return NULL;
}
stringFileInfo->szKey = (ut16*) malloc (UT16_ALIGN (STRINGFILEINFO_UTF_16_LEN)); //L"StringFileInfo"
if (!stringFileInfo->szKey) {
bprintf ("Warning: malloc (StringFileInfo szKey)\n");
free_StringFileInfo (stringFileInfo);
return NULL;
}
if (r_buf_read_at (bin->b, *curAddr, (ut8*) stringFileInfo->szKey, STRINGFILEINFO_UTF_16_LEN) != STRINGFILEINFO_UTF_16_LEN) {
bprintf ("Warning: read (StringFileInfo szKey)\n");
free_StringFileInfo (stringFileInfo);
return NULL;
}
*curAddr += STRINGFILEINFO_UTF_16_LEN;
if (memcmp (stringFileInfo->szKey, STRINGFILEINFO_UTF_16, STRINGFILEINFO_UTF_16_LEN) != 0) {
bprintf ("Warning: check (StringFileInfo szKey)\n");
free_StringFileInfo (stringFileInfo);
return NULL;
}
align32 (*curAddr);
while (startAddr + stringFileInfo->wLength > *curAddr) {
StringTable** tmp = (StringTable**) realloc (stringFileInfo->Children, (stringFileInfo->numOfChildren + 1) * sizeof(*stringFileInfo->Children));
if (!tmp) {
bprintf ("Warning: realloc (StringFileInfo Children)\n");
free_StringFileInfo (stringFileInfo);
return NULL;
}
stringFileInfo->Children = tmp;
if (!(stringFileInfo->Children[stringFileInfo->numOfChildren] = Pe_r_bin_pe_parse_string_table (bin, curAddr))) {
bprintf ("Warning: bad parsing StringTable\n");
free_StringFileInfo (stringFileInfo);
return NULL;
}
stringFileInfo->numOfChildren++;
align32 (*curAddr);
}
if (!stringFileInfo->numOfChildren) {
bprintf ("Warning: check (StringFileInfo numOfChildren)\n");
free_StringFileInfo (stringFileInfo);
return NULL;
}
return stringFileInfo;
}
#define EXIT_ON_OVERFLOW(S)\
if (curAddr > bin->size || curAddr + (S) > bin->size) { \
goto out_error; }
static PE_VS_VERSIONINFO* Pe_r_bin_pe_parse_version_info(struct PE_(r_bin_pe_obj_t)* bin, PE_DWord version_info_paddr) {
ut32 sz;
PE_VS_VERSIONINFO* vs_VersionInfo = calloc (1, sizeof(PE_VS_VERSIONINFO));
if (!vs_VersionInfo) {
return NULL;
}
PE_DWord startAddr = version_info_paddr;
PE_DWord curAddr = version_info_paddr;
//align32(curAddr); // XXX: do we really need this? Because in msdn
//wLength is The length, in bytes, of the VS_VERSIONINFO structure.
//This length does not include any padding that aligns any subsequent
//version resource data on a 32-bit boundary.
//Mb we are in subsequent version resource data and not aligned.
sz = sizeof(ut16);
EXIT_ON_OVERFLOW (sz);
if (r_buf_read_at (bin->b, curAddr, (ut8*) &vs_VersionInfo->wLength, sz) != sz) {
bprintf ("Warning: read (VS_VERSIONINFO wLength)\n");
goto out_error;
}
curAddr += sz;
EXIT_ON_OVERFLOW (sz);
if (r_buf_read_at (bin->b, curAddr, (ut8*) &vs_VersionInfo->wValueLength, sz) != sz) {
bprintf ("Warning: read (VS_VERSIONINFO wValueLength)\n");
goto out_error;
}
curAddr += sz;
EXIT_ON_OVERFLOW (sz);
if (r_buf_read_at (bin->b, curAddr, (ut8*) &vs_VersionInfo->wType, sz) != sz) {
bprintf ("Warning: read (VS_VERSIONINFO wType)\n");
goto out_error;
}
curAddr += sz;
if (vs_VersionInfo->wType && vs_VersionInfo->wType != 1) {
bprintf ("Warning: check (VS_VERSIONINFO wType)\n");
goto out_error;
}
vs_VersionInfo->szKey = (ut16*) malloc (UT16_ALIGN (VS_VERSION_INFO_UTF_16_LEN)); //L"VS_VERSION_INFO"
if (!vs_VersionInfo->szKey) {
bprintf ("Warning: malloc (VS_VERSIONINFO szKey)\n");
goto out_error;
}
sz = VS_VERSION_INFO_UTF_16_LEN;
EXIT_ON_OVERFLOW (sz);
if (r_buf_read_at (bin->b, curAddr, (ut8*) vs_VersionInfo->szKey, sz) != sz) {
bprintf ("Warning: read (VS_VERSIONINFO szKey)\n");
goto out_error;
}
curAddr += sz;
if (memcmp (vs_VersionInfo->szKey, VS_VERSION_INFO_UTF_16, sz)) {
goto out_error;
}
align32 (curAddr);
if (vs_VersionInfo->wValueLength) {
if (vs_VersionInfo->wValueLength != sizeof (*vs_VersionInfo->Value)) {
bprintf ("Warning: check (VS_VERSIONINFO wValueLength != sizeof PE_VS_FIXEDFILEINFO)\n");
goto out_error;
}
vs_VersionInfo->Value = (PE_VS_FIXEDFILEINFO*) malloc (sizeof(*vs_VersionInfo->Value));
if (!vs_VersionInfo->Value) {
bprintf ("Warning: malloc (VS_VERSIONINFO Value)\n");
goto out_error;
}
sz = sizeof(PE_VS_FIXEDFILEINFO);
EXIT_ON_OVERFLOW (sz);
if (r_buf_read_at (bin->b, curAddr, (ut8*) vs_VersionInfo->Value, sz) != sz) {
bprintf ("Warning: read (VS_VERSIONINFO Value)\n");
goto out_error;
}
if (vs_VersionInfo->Value->dwSignature != 0xFEEF04BD) {
bprintf ("Warning: check (PE_VS_FIXEDFILEINFO signature) 0x%08x\n", vs_VersionInfo->Value->dwSignature);
goto out_error;
}
curAddr += sz;
align32 (curAddr);
}
if (startAddr + vs_VersionInfo->wLength > curAddr) {
char t = '\0';
if (curAddr + 3 * sizeof(ut16) > bin->size || curAddr + 3 + sizeof(ut64) + 1 > bin->size) {
goto out_error;
}
if (r_buf_read_at (bin->b, curAddr + 3 * sizeof(ut16), (ut8*) &t, 1) != 1) {
bprintf ("Warning: read (VS_VERSIONINFO Children V or S)\n");
goto out_error;
}
if (!(t == 'S' || t == 'V')) {
bprintf ("Warning: bad type (VS_VERSIONINFO Children)\n");
goto out_error;
}
if (t == 'S') {
if (!(vs_VersionInfo->stringFileInfo = Pe_r_bin_pe_parse_string_file_info (bin, &curAddr))) {
bprintf ("Warning: bad parsing (VS_VERSIONINFO StringFileInfo)\n");
goto out_error;
}
}
if (t == 'V') {
if (!(vs_VersionInfo->varFileInfo = Pe_r_bin_pe_parse_var_file_info (bin, &curAddr))) {
bprintf ("Warning: bad parsing (VS_VERSIONINFO VarFileInfo)\n");
goto out_error;
}
}
align32 (curAddr);
if (startAddr + vs_VersionInfo->wLength > curAddr) {
if (t == 'V') {
if (!(vs_VersionInfo->stringFileInfo = Pe_r_bin_pe_parse_string_file_info (bin, &curAddr))) {
bprintf ("Warning: bad parsing (VS_VERSIONINFO StringFileInfo)\n");
goto out_error;
}
} else if (t == 'S') {
if (!(vs_VersionInfo->varFileInfo = Pe_r_bin_pe_parse_var_file_info (bin, &curAddr))) {
bprintf ("Warning: bad parsing (VS_VERSIONINFO VarFileInfo)\n");
goto out_error;
}
}
if (startAddr + vs_VersionInfo->wLength > curAddr) {
bprintf ("Warning: bad parsing (VS_VERSIONINFO wLength left)\n");
goto out_error;
}
}
}
return vs_VersionInfo;
out_error:
free_VS_VERSIONINFO (vs_VersionInfo);
return NULL;
}
static Sdb* Pe_r_bin_store_var(Var* var) {
unsigned int i = 0;
char key[20];
Sdb* sdb = NULL;
if (var) {
sdb = sdb_new0 ();
if (sdb) {
for (; i < var->numOfValues; i++) {
snprintf (key, 20, "%d", i);
sdb_num_set (sdb, key, var->Value[i], 0);
}
}
}
return sdb;
}
static Sdb* Pe_r_bin_store_var_file_info(VarFileInfo* varFileInfo) {
char key[20];
unsigned int i = 0;
if (!varFileInfo) {
return NULL;
}
Sdb* sdb = sdb_new0 ();
if (!sdb) {
return NULL;
}
for (; i < varFileInfo->numOfChildren; i++) {
snprintf (key, 20, "var%d", i);
sdb_ns_set (sdb, key, Pe_r_bin_store_var (varFileInfo->Children[i]));
}
return sdb;
}
static Sdb* Pe_r_bin_store_string(String* string) {
Sdb* sdb = NULL;
char* encodedVal = NULL, * encodedKey = NULL;
if (!string) {
return NULL;
}
sdb = sdb_new0 ();
if (!sdb) {
return NULL;
}
encodedKey = sdb_encode ((unsigned char*) string->szKey, string->wKeyLen);
if (!encodedKey) {
sdb_free (sdb);
return NULL;
}
encodedVal = sdb_encode ((unsigned char*) string->Value, string->wValueLength);
if (!encodedVal) {
free (encodedKey);
sdb_free (sdb);
return NULL;
}
sdb_set (sdb, "key", encodedKey, 0);
sdb_set (sdb, "value", encodedVal, 0);
free (encodedKey);
free (encodedVal);
return sdb;
}
static Sdb* Pe_r_bin_store_string_table(StringTable* stringTable) {
char key[20];
char* encodedKey = NULL;
int i = 0;
Sdb* sdb = NULL;
if (!stringTable) {
return NULL;
}
sdb = sdb_new0 ();
if (!sdb) {
return NULL;
}
encodedKey = sdb_encode ((unsigned char*) stringTable->szKey, EIGHT_HEX_DIG_UTF_16_LEN);
if (!encodedKey) {
sdb_free (sdb);
return NULL;
}
sdb_set (sdb, "key", encodedKey, 0);
free (encodedKey);
for (; i < stringTable->numOfChildren; i++) {
snprintf (key, 20, "string%d", i);
sdb_ns_set (sdb, key, Pe_r_bin_store_string (stringTable->Children[i]));
}
return sdb;
}
static Sdb* Pe_r_bin_store_string_file_info(StringFileInfo* stringFileInfo) {
char key[30];
int i = 0;
Sdb* sdb = NULL;
if (!stringFileInfo) {
return NULL;
}
sdb = sdb_new0 ();
if (!sdb) {
return NULL;
}
for (; i < stringFileInfo->numOfChildren; i++) {
snprintf (key, 30, "stringtable%d", i);
sdb_ns_set (sdb, key, Pe_r_bin_store_string_table (stringFileInfo->Children[i]));
}
return sdb;
}
static Sdb* Pe_r_bin_store_fixed_file_info(PE_VS_FIXEDFILEINFO* vs_fixedFileInfo) {
Sdb* sdb = NULL;
if (!vs_fixedFileInfo) {
return NULL;
}
sdb = sdb_new0 ();
if (!sdb) {
return NULL;
}
sdb_num_set (sdb, "Signature", vs_fixedFileInfo->dwSignature, 0);
sdb_num_set (sdb, "StrucVersion", vs_fixedFileInfo->dwStrucVersion, 0);
sdb_num_set (sdb, "FileVersionMS", vs_fixedFileInfo->dwFileVersionMS, 0);
sdb_num_set (sdb, "FileVersionLS", vs_fixedFileInfo->dwFileVersionLS, 0);
sdb_num_set (sdb, "ProductVersionMS", vs_fixedFileInfo->dwProductVersionMS, 0);
sdb_num_set (sdb, "ProductVersionLS", vs_fixedFileInfo->dwProductVersionLS, 0);
sdb_num_set (sdb, "FileFlagsMask", vs_fixedFileInfo->dwFileFlagsMask, 0);
sdb_num_set (sdb, "FileFlags", vs_fixedFileInfo->dwFileFlags, 0);
sdb_num_set (sdb, "FileOS", vs_fixedFileInfo->dwFileOS, 0);
sdb_num_set (sdb, "FileType", vs_fixedFileInfo->dwFileType, 0);
sdb_num_set (sdb, "FileSubtype", vs_fixedFileInfo->dwFileSubtype, 0);
sdb_num_set (sdb, "FileDateMS", vs_fixedFileInfo->dwFileDateMS, 0);
sdb_num_set (sdb, "FileDateLS", vs_fixedFileInfo->dwFileDateLS, 0);
return sdb;
}
static Sdb* Pe_r_bin_store_resource_version_info(PE_VS_VERSIONINFO* vs_VersionInfo) {
Sdb* sdb = NULL;
if (!vs_VersionInfo) {
return NULL;
}
sdb = sdb_new0 ();
if (!sdb) {
return NULL;
}
if (vs_VersionInfo->Value) {
sdb_ns_set (sdb, "fixed_file_info", Pe_r_bin_store_fixed_file_info (vs_VersionInfo->Value));
}
if (vs_VersionInfo->varFileInfo) {
sdb_ns_set (sdb, "var_file_info", Pe_r_bin_store_var_file_info (vs_VersionInfo->varFileInfo));
}
if (vs_VersionInfo->stringFileInfo) {
sdb_ns_set (sdb, "string_file_info", Pe_r_bin_store_string_file_info (vs_VersionInfo->stringFileInfo));
}
return sdb;
}
static char* _resource_lang_str(int id) {
switch(id) {
case 0x00: return "LANG_NEUTRAL";
case 0x7f: return "LANG_INVARIANT";
case 0x36: return "LANG_AFRIKAANS";
case 0x1c: return "LANG_ALBANIAN ";
case 0x01: return "LANG_ARABIC";
case 0x2b: return "LANG_ARMENIAN";
case 0x4d: return "LANG_ASSAMESE";
case 0x2c: return "LANG_AZERI";
case 0x2d: return "LANG_BASQUE";
case 0x23: return "LANG_BELARUSIAN";
case 0x45: return "LANG_BENGALI";
case 0x02: return "LANG_BULGARIAN";
case 0x03: return "LANG_CATALAN";
case 0x04: return "LANG_CHINESE";
case 0x1a: return "LANG_CROATIAN";
case 0x05: return "LANG_CZECH";
case 0x06: return "LANG_DANISH";
case 0x65: return "LANG_DIVEHI";
case 0x13: return "LANG_DUTCH";
case 0x09: return "LANG_ENGLISH";
case 0x25: return "LANG_ESTONIAN";
case 0x38: return "LANG_FAEROESE";
case 0x29: return "LANG_FARSI";
case 0x0b: return "LANG_FINNISH";
case 0x0c: return "LANG_FRENCH";
case 0x56: return "LANG_GALICIAN";
case 0x37: return "LANG_GEORGIAN";
case 0x07: return "LANG_GERMAN";
case 0x08: return "LANG_GREEK";
case 0x47: return "LANG_GUJARATI";
case 0x0d: return "LANG_HEBREW";
case 0x39: return "LANG_HINDI";
case 0x0e: return "LANG_HUNGARIAN";
case 0x0f: return "LANG_ICELANDIC";
case 0x21: return "LANG_INDONESIAN";
case 0x10: return "LANG_ITALIAN";
case 0x11: return "LANG_JAPANESE";
case 0x4b: return "LANG_KANNADA";
case 0x60: return "LANG_KASHMIRI";
case 0x3f: return "LANG_KAZAK";
case 0x57: return "LANG_KONKANI";
case 0x12: return "LANG_KOREAN";
case 0x40: return "LANG_KYRGYZ";
case 0x26: return "LANG_LATVIAN";
case 0x27: return "LANG_LITHUANIAN";
case 0x2f: return "LANG_MACEDONIAN";
case 0x3e: return "LANG_MALAY";
case 0x4c: return "LANG_MALAYALAM";
case 0x58: return "LANG_MANIPURI";
case 0x4e: return "LANG_MARATHI";
case 0x50: return "LANG_MONGOLIAN";
case 0x61: return "LANG_NEPALI";
case 0x14: return "LANG_NORWEGIAN";
case 0x48: return "LANG_ORIYA";
case 0x15: return "LANG_POLISH";
case 0x16: return "LANG_PORTUGUESE";
case 0x46: return "LANG_PUNJABI";
case 0x18: return "LANG_ROMANIAN";
case 0x19: return "LANG_RUSSIAN";
case 0x4f: return "LANG_SANSKRIT";
case 0x59: return "LANG_SINDHI";
case 0x1b: return "LANG_SLOVAK";
case 0x24: return "LANG_SLOVENIAN";
case 0x0a: return "LANG_SPANISH ";
case 0x41: return "LANG_SWAHILI";
case 0x1d: return "LANG_SWEDISH";
case 0x5a: return "LANG_SYRIAC";
case 0x49: return "LANG_TAMIL";
case 0x44: return "LANG_TATAR";
case 0x4a: return "LANG_TELUGU";
case 0x1e: return "LANG_THAI";
case 0x1f: return "LANG_TURKISH";
case 0x22: return "LANG_UKRAINIAN";
case 0x20: return "LANG_URDU";
case 0x43: return "LANG_UZBEK";
case 0x2a: return "LANG_VIETNAMESE";
case 0x3c: return "LANG_GAELIC";
case 0x3a: return "LANG_MALTESE";
case 0x28: return "LANG_MAORI";
case 0x17: return "LANG_RHAETO_ROMANCE";
case 0x3b: return "LANG_SAAMI";
case 0x2e: return "LANG_SORBIAN";
case 0x30: return "LANG_SUTU";
case 0x31: return "LANG_TSONGA";
case 0x32: return "LANG_TSWANA";
case 0x33: return "LANG_VENDA";
case 0x34: return "LANG_XHOSA";
case 0x35: return "LANG_ZULU";
case 0x8f: return "LANG_ESPERANTO";
case 0x90: return "LANG_WALON";
case 0x91: return "LANG_CORNISH";
case 0x92: return "LANG_WELSH";
case 0x93: return "LANG_BRETON";
default: return "UNKNOWN";
}
}
static char* _resource_type_str(int type) {
switch (type) {
case 1: return "CURSOR";
case 2: return "BITMAP";
case 3: return "ICON";
case 4: return "MENU";
case 5: return "DIALOG";
case 6: return "STRING";
case 7: return "FONTDIR";
case 8: return "FONT";
case 9: return "ACCELERATOR";
case 10: return "RCDATA";
case 11: return "MESSAGETABLE";
case 12: return "GROUP_CURSOR";
case 14: return "GROUP_ICON";
case 16: return "VERSION";
case 17: return "DLGINCLUDE";
case 19: return "PLUGPLAY";
case 20: return "VXD";
case 21: return "ANICURSOR";
case 22: return "ANIICON";
case 23: return "HTML";
case 24: return "MANIFEST";
default: return "UNKNOWN";
}
}
static void _parse_resource_directory(struct PE_(r_bin_pe_obj_t) *bin, Pe_image_resource_directory *dir, ut64 offDir, int type, int id, SdbHash *dirs) {
int index = 0;
ut32 totalRes = dir->NumberOfNamedEntries + dir->NumberOfIdEntries;
ut64 rsrc_base = bin->resource_directory_offset;
ut64 off;
if (totalRes > R_PE_MAX_RESOURCES) {
return;
}
for (index = 0; index < totalRes; index++) {
Pe_image_resource_directory_entry entry;
off = rsrc_base + offDir + sizeof(*dir) + index * sizeof(entry);
char *key = sdb_fmt ("0x%08"PFMT64x, off);
if (sdb_ht_find (dirs, key, NULL)) {
break;
}
sdb_ht_insert (dirs, key, "1");
if (off > bin->size || off + sizeof (entry) > bin->size) {
break;
}
if (r_buf_read_at (bin->b, off, (ut8*)&entry, sizeof(entry)) < 1) {
eprintf ("Warning: read resource entry\n");
break;
}
if (entry.u2.s.DataIsDirectory) {
//detect here malicious file trying to making us infinite loop
Pe_image_resource_directory identEntry;
off = rsrc_base + entry.u2.s.OffsetToDirectory;
int len = r_buf_read_at (bin->b, off, (ut8*) &identEntry, sizeof (identEntry));
if (len < 1 || len != sizeof (Pe_image_resource_directory)) {
eprintf ("Warning: parsing resource directory\n");
}
_parse_resource_directory (bin, &identEntry,
entry.u2.s.OffsetToDirectory, type, entry.u1.Id, dirs);
continue;
}
Pe_image_resource_data_entry *data = R_NEW0 (Pe_image_resource_data_entry);
if (!data) {
break;
}
off = rsrc_base + entry.u2.OffsetToData;
if (off > bin->size || off + sizeof (data) > bin->size) {
free (data);
break;
}
if (r_buf_read_at (bin->b, off, (ut8*)data, sizeof (*data)) != sizeof (*data)) {
eprintf ("Warning: read (resource data entry)\n");
free (data);
break;
}
if (type == PE_RESOURCE_ENTRY_VERSION) {
char key[64];
int counter = 0;
Sdb *sdb = sdb_new0 ();
if (!sdb) {
free (data);
sdb_free (sdb);
continue;
}
PE_DWord data_paddr = bin_pe_rva_to_paddr (bin, data->OffsetToData);
if (!data_paddr) {
bprintf ("Warning: bad RVA in resource data entry\n");
free (data);
sdb_free (sdb);
continue;
}
PE_DWord cur_paddr = data_paddr;
if ((cur_paddr & 0x3) != 0) {
bprintf ("Warning: not aligned version info address\n");
free (data);
sdb_free (sdb);
continue;
}
while (cur_paddr < (data_paddr + data->Size) && cur_paddr < bin->size) {
PE_VS_VERSIONINFO* vs_VersionInfo = Pe_r_bin_pe_parse_version_info (bin, cur_paddr);
if (vs_VersionInfo) {
snprintf (key, 30, "VS_VERSIONINFO%d", counter++);
sdb_ns_set (sdb, key, Pe_r_bin_store_resource_version_info (vs_VersionInfo));
} else {
break;
}
if (vs_VersionInfo->wLength < 1) {
// Invalid version length
break;
}
cur_paddr += vs_VersionInfo->wLength;
free_VS_VERSIONINFO (vs_VersionInfo);
align32 (cur_paddr);
}
sdb_ns_set (bin->kv, "vs_version_info", sdb);
}
r_pe_resource *rs = R_NEW0 (r_pe_resource);
if (!rs) {
free (data);
break;
}
rs->timestr = _time_stamp_to_str (dir->TimeDateStamp);
rs->type = strdup (_resource_type_str (type));
rs->language = strdup (_resource_lang_str (entry.u1.Name & 0x3ff));
rs->data = data;
rs->name = id;
r_list_append (bin->resources, rs);
}
}
static void _store_resource_sdb(struct PE_(r_bin_pe_obj_t) *bin) {
RListIter *iter;
r_pe_resource *rs;
int index = 0;
ut64 vaddr = 0;
char *key;
Sdb *sdb = sdb_new0 ();
if (!sdb) {
return;
}
r_list_foreach (bin->resources, iter, rs) {
key = sdb_fmt ("resource.%d.timestr", index);
sdb_set (sdb, key, rs->timestr, 0);
key = sdb_fmt ("resource.%d.vaddr", index);
vaddr = bin_pe_rva_to_va (bin, rs->data->OffsetToData);
sdb_num_set (sdb, key, vaddr, 0);
key = sdb_fmt ("resource.%d.name", index);
sdb_num_set (sdb, key, rs->name, 0);
key = sdb_fmt ("resource.%d.size", index);
sdb_num_set (sdb, key, rs->data->Size, 0);
key = sdb_fmt ("resource.%d.type", index);
sdb_set (sdb, key, rs->type, 0);
key = sdb_fmt ("resource.%d.language", index);
sdb_set (sdb, key, rs->language, 0);
index++;
}
sdb_ns_set (bin->kv, "pe_resource", sdb);
}
R_API void PE_(bin_pe_parse_resource)(struct PE_(r_bin_pe_obj_t) *bin) {
int index = 0;
ut64 off = 0, rsrc_base = bin->resource_directory_offset;
Pe_image_resource_directory *rs_directory = bin->resource_directory;
ut32 curRes = 0;
int totalRes = 0;
SdbHash *dirs = sdb_ht_new (); //to avoid infinite loops
if (!dirs) {
return;
}
if (!rs_directory) {
sdb_ht_free (dirs);
return;
}
curRes = rs_directory->NumberOfNamedEntries;
totalRes = curRes + rs_directory->NumberOfIdEntries;
if (totalRes > R_PE_MAX_RESOURCES) {
eprintf ("Error parsing resource directory\n");
sdb_ht_free (dirs);
return;
}
for (index = 0; index < totalRes; index++) {
Pe_image_resource_directory_entry typeEntry;
off = rsrc_base + sizeof (*rs_directory) + index * sizeof (typeEntry);
sdb_ht_insert (dirs, sdb_fmt ("0x%08"PFMT64x, off), "1");
if (off > bin->size || off + sizeof(typeEntry) > bin->size) {
break;
}
if (r_buf_read_at (bin->b, off, (ut8*)&typeEntry, sizeof(typeEntry)) < 1) {
eprintf ("Warning: read resource directory entry\n");
break;
}
if (typeEntry.u2.s.DataIsDirectory) {
Pe_image_resource_directory identEntry;
off = rsrc_base + typeEntry.u2.s.OffsetToDirectory;
int len = r_buf_read_at (bin->b, off, (ut8*)&identEntry, sizeof(identEntry));
if (len < 1 || len != sizeof (identEntry)) {
eprintf ("Warning: parsing resource directory\n");
}
_parse_resource_directory (bin, &identEntry, typeEntry.u2.s.OffsetToDirectory, typeEntry.u1.Id, 0, dirs);
}
}
sdb_ht_free (dirs);
_store_resource_sdb (bin);
}
static void bin_pe_get_certificate(struct PE_ (r_bin_pe_obj_t) * bin) {
ut64 size, vaddr;
ut8 *data = NULL;
int len;
if (!bin || !bin->nt_headers) {
return;
}
bin->cms = NULL;
size = bin->data_directory[PE_IMAGE_DIRECTORY_ENTRY_SECURITY].Size;
vaddr = bin->data_directory[PE_IMAGE_DIRECTORY_ENTRY_SECURITY].VirtualAddress;
data = calloc (1, size);
if (!data) {
return;
}
if (vaddr > bin->size || vaddr + size > bin->size) {
bprintf ("vaddr greater than the file\n");
free (data);
return;
}
//skipping useless header..
len = r_buf_read_at (bin->b, vaddr + 8, data, size - 8);
if (len < 1) {
R_FREE (data);
return;
}
bin->cms = r_pkcs7_parse_cms (data, size);
bin->is_signed = bin->cms != NULL;
R_FREE (data);
}
static int bin_pe_init(struct PE_(r_bin_pe_obj_t)* bin) {
bin->dos_header = NULL;
bin->nt_headers = NULL;
bin->section_header = NULL;
bin->export_directory = NULL;
bin->import_directory = NULL;
bin->resource_directory = NULL;
bin->delay_import_directory = NULL;
bin->optional_header = NULL;
bin->data_directory = NULL;
bin->big_endian = 0;
if (!bin_pe_init_hdr (bin)) {
eprintf ("Warning: File is not PE\n");
return false;
}
if (!bin_pe_init_sections (bin)) {
eprintf ("Warning: Cannot initialize sections\n");
return false;
}
bin_pe_init_imports (bin);
bin_pe_init_exports (bin);
bin_pe_init_resource (bin);
bin_pe_get_certificate(bin);
bin->big_endian = PE_(r_bin_pe_is_big_endian) (bin);
bin_pe_init_tls (bin);
bin_pe_init_clr_hdr (bin);
bin_pe_init_metadata_hdr (bin);
bin_pe_init_overlay (bin);
PE_(bin_pe_parse_resource) (bin);
bin->relocs = NULL;
return true;
}
char* PE_(r_bin_pe_get_arch)(struct PE_(r_bin_pe_obj_t)* bin) {
char* arch;
if (!bin || !bin->nt_headers) {
return strdup ("x86");
}
switch (bin->nt_headers->file_header.Machine) {
case PE_IMAGE_FILE_MACHINE_ALPHA:
case PE_IMAGE_FILE_MACHINE_ALPHA64:
arch = strdup ("alpha");
break;
case PE_IMAGE_FILE_MACHINE_RPI2: // 462
case PE_IMAGE_FILE_MACHINE_ARM:
case PE_IMAGE_FILE_MACHINE_THUMB:
arch = strdup ("arm");
break;
case PE_IMAGE_FILE_MACHINE_M68K:
arch = strdup ("m68k");
break;
case PE_IMAGE_FILE_MACHINE_MIPS16:
case PE_IMAGE_FILE_MACHINE_MIPSFPU:
case PE_IMAGE_FILE_MACHINE_MIPSFPU16:
case PE_IMAGE_FILE_MACHINE_WCEMIPSV2:
arch = strdup ("mips");
break;
case PE_IMAGE_FILE_MACHINE_POWERPC:
case PE_IMAGE_FILE_MACHINE_POWERPCFP:
arch = strdup ("ppc");
break;
case PE_IMAGE_FILE_MACHINE_EBC:
arch = strdup ("ebc");
break;
case PE_IMAGE_FILE_MACHINE_ARM64:
arch = strdup ("arm");
break;
default:
arch = strdup ("x86");
}
return arch;
}
struct r_bin_pe_addr_t* PE_(r_bin_pe_get_entrypoint)(struct PE_(r_bin_pe_obj_t)* bin) {
struct r_bin_pe_addr_t* entry = NULL;
static bool debug = false;
PE_DWord pe_entry;
int i;
ut64 base_addr = PE_(r_bin_pe_get_image_base) (bin);
if (!bin || !bin->optional_header) {
return NULL;
}
if (!(entry = malloc (sizeof (struct r_bin_pe_addr_t)))) {
r_sys_perror ("malloc (entrypoint)");
return NULL;
}
pe_entry = bin->optional_header->AddressOfEntryPoint;
entry->vaddr = bin_pe_rva_to_va (bin, pe_entry);
entry->paddr = bin_pe_rva_to_paddr (bin, pe_entry);
// haddr is the address of AddressOfEntryPoint in header.
entry->haddr = bin->dos_header->e_lfanew + 4 + sizeof (PE_(image_file_header)) + 16;
if (entry->paddr >= bin->size) {
struct r_bin_pe_section_t* sections = PE_(r_bin_pe_get_sections) (bin);
ut64 paddr = 0;
if (!debug) {
bprintf ("Warning: Invalid entrypoint ... "
"trying to fix it but i do not promise nothing\n");
}
for (i = 0; i < bin->num_sections; i++) {
if (sections[i].flags & PE_IMAGE_SCN_MEM_EXECUTE) {
entry->paddr = sections[i].paddr;
entry->vaddr = sections[i].vaddr + base_addr;
paddr = 1;
break;
}
}
if (!paddr) {
ut64 min_off = -1;
for (i = 0; i < bin->num_sections; i++) {
//get the lowest section's paddr
if (sections[i].paddr < min_off) {
entry->paddr = sections[i].paddr;
entry->vaddr = sections[i].vaddr + base_addr;
min_off = sections[i].paddr;
}
}
if (min_off == -1) {
//no section just a hack to try to fix entrypoint
//maybe doesn't work always
int sa = R_MAX (bin->optional_header->SectionAlignment, 0x1000);
entry->paddr = pe_entry & ((sa << 1) - 1);
entry->vaddr = entry->paddr + base_addr;
}
}
free (sections);
}
if (!entry->paddr) {
if (!debug) {
bprintf ("Warning: NULL entrypoint\n");
}
struct r_bin_pe_section_t* sections = PE_(r_bin_pe_get_sections) (bin);
for (i = 0; i < bin->num_sections; i++) {
//If there is a section with x without w perm is a good candidate to be the entrypoint
if (sections[i].flags & PE_IMAGE_SCN_MEM_EXECUTE && !(sections[i].flags & PE_IMAGE_SCN_MEM_WRITE)) {
entry->paddr = sections[i].paddr;
entry->vaddr = sections[i].vaddr + base_addr;
break;
}
}
free (sections);
}
if (is_arm (bin) && entry->vaddr & 1) {
entry->vaddr--;
if (entry->paddr & 1) {
entry->paddr--;
}
}
if (!debug) {
debug = true;
}
return entry;
}
struct r_bin_pe_export_t* PE_(r_bin_pe_get_exports)(struct PE_(r_bin_pe_obj_t)* bin) {
struct r_bin_pe_export_t* exp, * exports = NULL;
PE_Word function_ordinal;
PE_VWord functions_paddr, names_paddr, ordinals_paddr, function_rva, name_vaddr, name_paddr;
char function_name[PE_NAME_LENGTH + 1], forwarder_name[PE_NAME_LENGTH + 1];
char dll_name[PE_NAME_LENGTH + 1], export_name[256];
PE_(image_data_directory) * data_dir_export;
PE_VWord export_dir_rva;
int n,i, export_dir_size;
st64 exports_sz = 0;
if (!bin || !bin->data_directory) {
return NULL;
}
data_dir_export = &bin->data_directory[PE_IMAGE_DIRECTORY_ENTRY_EXPORT];
export_dir_rva = data_dir_export->VirtualAddress;
export_dir_size = data_dir_export->Size;
if (bin->export_directory) {
if (bin->export_directory->NumberOfFunctions + 1 <
bin->export_directory->NumberOfFunctions) {
// avoid integer overflow
return NULL;
}
exports_sz = (bin->export_directory->NumberOfFunctions + 1) * sizeof (struct r_bin_pe_export_t);
// we cant exit with export_sz > bin->size, us r_bin_pe_export_t is 256+256+8+8+8+4 bytes is easy get over file size
// to avoid fuzzing we can abort on export_directory->NumberOfFunctions>0xffff
if (exports_sz < 0 || bin->export_directory->NumberOfFunctions + 1 > 0xffff) {
return NULL;
}
if (!(exports = malloc (exports_sz))) {
return NULL;
}
if (r_buf_read_at (bin->b, bin_pe_rva_to_paddr (bin, bin->export_directory->Name), (ut8*) dll_name, PE_NAME_LENGTH) < 1) {
bprintf ("Warning: read (dll name)\n");
free (exports);
return NULL;
}
functions_paddr = bin_pe_rva_to_paddr (bin, bin->export_directory->AddressOfFunctions);
names_paddr = bin_pe_rva_to_paddr (bin, bin->export_directory->AddressOfNames);
ordinals_paddr = bin_pe_rva_to_paddr (bin, bin->export_directory->AddressOfOrdinals);
for (i = 0; i < bin->export_directory->NumberOfFunctions; i++) {
// get vaddr from AddressOfFunctions array
int ret = r_buf_read_at (bin->b, functions_paddr + i * sizeof(PE_VWord), (ut8*) &function_rva, sizeof(PE_VWord));
if (ret < 1) {
break;
}
// have exports by name?
if (bin->export_directory->NumberOfNames != 0) {
// search for value of i into AddressOfOrdinals
name_vaddr = 0;
for (n = 0; n < bin->export_directory->NumberOfNames; n++) {
ret = r_buf_read_at (bin->b, ordinals_paddr + n * sizeof(PE_Word), (ut8*) &function_ordinal, sizeof (PE_Word));
if (ret < 1) {
break;
}
// if exist this index into AddressOfOrdinals
if (i == function_ordinal) {
// get the VA of export name from AddressOfNames
r_buf_read_at (bin->b, names_paddr + n * sizeof (PE_VWord), (ut8*) &name_vaddr, sizeof (PE_VWord));
break;
}
}
// have an address into name_vaddr?
if (name_vaddr) {
// get the name of the Export
name_paddr = bin_pe_rva_to_paddr (bin, name_vaddr);
if (r_buf_read_at (bin->b, name_paddr, (ut8*) function_name, PE_NAME_LENGTH) < 1) {
bprintf ("Warning: read (function name)\n");
exports[i].last = 1;
return exports;
}
} else { // No name export, get the ordinal
snprintf (function_name, PE_NAME_LENGTH, "Ordinal_%i", i + 1);
}
}else { // if dont export by name exist, get the ordinal taking in mind the Base value.
function_ordinal = i + bin->export_directory->Base;
snprintf (function_name, PE_NAME_LENGTH, "Ordinal_%i", function_ordinal);
}
// check if VA are into export directory, this mean a forwarder export
if (function_rva >= export_dir_rva && function_rva < (export_dir_rva + export_dir_size)) {
// if forwarder, the VA point to Forwarded name
if (r_buf_read_at (bin->b, bin_pe_rva_to_paddr (bin, function_rva), (ut8*) forwarder_name, PE_NAME_LENGTH) < 1) {
exports[i].last = 1;
return exports;
}
} else { // no forwarder export
snprintf (forwarder_name, PE_NAME_LENGTH, "NONE");
}
dll_name[PE_NAME_LENGTH] = '\0';
function_name[PE_NAME_LENGTH] = '\0';
snprintf (export_name, sizeof (export_name) - 1, "%s_%s", dll_name, function_name);
exports[i].vaddr = bin_pe_rva_to_va (bin, function_rva);
exports[i].paddr = bin_pe_rva_to_paddr (bin, function_rva);
exports[i].ordinal = function_ordinal;
memcpy (exports[i].forwarder, forwarder_name, PE_NAME_LENGTH);
exports[i].forwarder[PE_NAME_LENGTH] = '\0';
memcpy (exports[i].name, export_name, PE_NAME_LENGTH);
exports[i].name[PE_NAME_LENGTH] = '\0';
exports[i].last = 0;
}
exports[i].last = 1;
}
exp = parse_symbol_table (bin, exports, exports_sz - 1);
if (exp) {
exports = exp;
}
return exports;
}
static void free_rsdr_hdr(SCV_RSDS_HEADER* rsds_hdr) {
R_FREE (rsds_hdr->file_name);
}
static void init_rsdr_hdr(SCV_RSDS_HEADER* rsds_hdr) {
memset (rsds_hdr, 0, sizeof (SCV_RSDS_HEADER));
rsds_hdr->free = (void (*)(struct SCV_RSDS_HEADER*))free_rsdr_hdr;
}
static void free_cv_nb10_header(SCV_NB10_HEADER* cv_nb10_header) {
R_FREE (cv_nb10_header->file_name);
}
static void init_cv_nb10_header(SCV_NB10_HEADER* cv_nb10_header) {
memset (cv_nb10_header, 0, sizeof (SCV_NB10_HEADER));
cv_nb10_header->free = (void (*)(struct SCV_NB10_HEADER*))free_cv_nb10_header;
}
static bool get_rsds(ut8* dbg_data, int dbg_data_len, SCV_RSDS_HEADER* res) {
const int rsds_sz = 4 + sizeof (SGUID) + 4;
if (dbg_data_len < rsds_sz) {
return false;
}
memcpy (res, dbg_data, rsds_sz);
res->file_name = (ut8*) strdup ((const char*) dbg_data + rsds_sz);
return true;
}
static void get_nb10(ut8* dbg_data, SCV_NB10_HEADER* res) {
const int nb10sz = 16;
memcpy (res, dbg_data, nb10sz);
res->file_name = (ut8*) strdup ((const char*) dbg_data + nb10sz);
}
static int get_debug_info(struct PE_(r_bin_pe_obj_t)* bin, PE_(image_debug_directory_entry)* dbg_dir_entry, ut8* dbg_data, int dbg_data_len, SDebugInfo* res) {
#define SIZEOF_FILE_NAME 255
int i = 0;
const char* basename;
if (!dbg_data) {
return 0;
}
switch (dbg_dir_entry->Type) {
case IMAGE_DEBUG_TYPE_CODEVIEW:
if (!strncmp ((char*) dbg_data, "RSDS", 4)) {
SCV_RSDS_HEADER rsds_hdr;
init_rsdr_hdr (&rsds_hdr);
if (!get_rsds (dbg_data, dbg_data_len, &rsds_hdr)) {
bprintf ("Warning: Cannot read PE debug info\n");
return 0;
}
snprintf (res->guidstr, GUIDSTR_LEN,
"%08x%04x%04x%02x%02x%02x%02x%02x%02x%02x%02x%x",
rsds_hdr.guid.data1,
rsds_hdr.guid.data2,
rsds_hdr.guid.data3,
rsds_hdr.guid.data4[0],
rsds_hdr.guid.data4[1],
rsds_hdr.guid.data4[2],
rsds_hdr.guid.data4[3],
rsds_hdr.guid.data4[4],
rsds_hdr.guid.data4[5],
rsds_hdr.guid.data4[6],
rsds_hdr.guid.data4[7],
rsds_hdr.age);
basename = r_file_basename ((char*) rsds_hdr.file_name);
strncpy (res->file_name, (const char*)
basename, sizeof (res->file_name));
res->file_name[sizeof (res->file_name) - 1] = 0;
rsds_hdr.free ((struct SCV_RSDS_HEADER*) &rsds_hdr);
} else if (strncmp ((const char*) dbg_data, "NB10", 4) == 0) {
SCV_NB10_HEADER nb10_hdr;
init_cv_nb10_header (&nb10_hdr);
get_nb10 (dbg_data, &nb10_hdr);
snprintf (res->guidstr, sizeof (res->guidstr),
"%x%x", nb10_hdr.timestamp, nb10_hdr.age);
strncpy (res->file_name, (const char*)
nb10_hdr.file_name, sizeof(res->file_name) - 1);
res->file_name[sizeof (res->file_name) - 1] = 0;
nb10_hdr.free ((struct SCV_NB10_HEADER*) &nb10_hdr);
} else {
bprintf ("CodeView section not NB10 or RSDS\n");
return 0;
}
break;
default:
//bprintf("get_debug_info(): not supported type\n");
return 0;
}
while (i < 33) {
res->guidstr[i] = toupper ((int) res->guidstr[i]);
i++;
}
return 1;
}
int PE_(r_bin_pe_get_debug_data)(struct PE_(r_bin_pe_obj_t)* bin, SDebugInfo* res) {
PE_(image_debug_directory_entry)* img_dbg_dir_entry = NULL;
PE_(image_data_directory) * dbg_dir;
PE_DWord dbg_dir_offset;
ut8* dbg_data = 0;
int result = 0;
if (!bin) {
return 0;
}
dbg_dir = &bin->nt_headers->optional_header.DataDirectory[6 /*IMAGE_DIRECTORY_ENTRY_DEBUG*/];
dbg_dir_offset = bin_pe_rva_to_paddr (bin, dbg_dir->VirtualAddress);
if ((int) dbg_dir_offset < 0 || dbg_dir_offset >= bin->size) {
return false;
}
if (dbg_dir_offset >= bin->b->length) {
return false;
}
img_dbg_dir_entry = (PE_(image_debug_directory_entry)*)(bin->b->buf + dbg_dir_offset);
if ((bin->b->length - dbg_dir_offset) < sizeof (PE_(image_debug_directory_entry))) {
return false;
}
if (img_dbg_dir_entry) {
ut32 dbg_data_poff = R_MIN (img_dbg_dir_entry->PointerToRawData, bin->b->length);
int dbg_data_len = R_MIN (img_dbg_dir_entry->SizeOfData, bin->b->length - dbg_data_poff);
if (dbg_data_len < 1) {
return false;
}
dbg_data = (ut8*) calloc (1, dbg_data_len + 1);
if (dbg_data) {
r_buf_read_at (bin->b, dbg_data_poff, dbg_data, dbg_data_len);
result = get_debug_info (bin, img_dbg_dir_entry, dbg_data, dbg_data_len, res);
R_FREE (dbg_data);
}
}
return result;
}
struct r_bin_pe_import_t* PE_(r_bin_pe_get_imports)(struct PE_(r_bin_pe_obj_t)* bin) {
struct r_bin_pe_import_t* imps, * imports = NULL;
char dll_name[PE_NAME_LENGTH + 1];
int nimp = 0;
ut64 off; //used to cache value
PE_DWord dll_name_offset = 0;
PE_DWord paddr = 0;
PE_DWord import_func_name_offset;
PE_(image_import_directory) * curr_import_dir = NULL;
PE_(image_delay_import_directory) * curr_delay_import_dir = 0;
if (!bin) {
return NULL;
}
if (bin->import_directory_offset >= bin->size) {
return NULL;
}
if (bin->import_directory_offset + 32 >= bin->size) {
return NULL;
}
off = bin->import_directory_offset;
if (off < bin->size && off > 0) {
void* last;
if (off + sizeof(PE_(image_import_directory)) > bin->size) {
return NULL;
}
curr_import_dir = (PE_(image_import_directory)*)(bin->b->buf + bin->import_directory_offset);
dll_name_offset = curr_import_dir->Name;
if (bin->import_directory_size < 1) {
return NULL;
}
if (off + bin->import_directory_size > bin->size) {
//why chopping instead of returning and cleaning?
bprintf ("Warning: read (import directory too big)\n");
bin->import_directory_size = bin->size - bin->import_directory_offset;
}
last = (char*) curr_import_dir + bin->import_directory_size;
while ((void*) (curr_import_dir + 1) <= last && (
curr_import_dir->FirstThunk != 0 || curr_import_dir->Name != 0 ||
curr_import_dir->TimeDateStamp != 0 || curr_import_dir->Characteristics != 0 ||
curr_import_dir->ForwarderChain != 0)) {
int rr;
dll_name_offset = curr_import_dir->Name;
paddr = bin_pe_rva_to_paddr (bin, dll_name_offset);
if (paddr > bin->size) {
goto beach;
}
if (paddr + PE_NAME_LENGTH > bin->size) {
rr = r_buf_read_at (bin->b, paddr, (ut8*) dll_name, bin->size - paddr);
if (rr != bin->size - paddr) {
goto beach;
}
dll_name[bin->size - paddr] = '\0';
}else {
rr = r_buf_read_at (bin->b, paddr, (ut8*) dll_name, PE_NAME_LENGTH);
if (rr != PE_NAME_LENGTH) {
goto beach;
}
dll_name[PE_NAME_LENGTH] = '\0';
}
if (!bin_pe_parse_imports (bin, &imports, &nimp, dll_name,
curr_import_dir->Characteristics,
curr_import_dir->FirstThunk)) {
break;
}
curr_import_dir++;
}
}
off = bin->delay_import_directory_offset;
if (off < bin->size && off > 0) {
if (off + sizeof(PE_(image_delay_import_directory)) > bin->size) {
goto beach;
}
curr_delay_import_dir = (PE_(image_delay_import_directory)*)(bin->b->buf + off);
if (!curr_delay_import_dir->Attributes) {
dll_name_offset = bin_pe_rva_to_paddr (bin,
curr_delay_import_dir->Name - PE_(r_bin_pe_get_image_base)(bin));
import_func_name_offset = curr_delay_import_dir->DelayImportNameTable -
PE_(r_bin_pe_get_image_base)(bin);
} else {
dll_name_offset = bin_pe_rva_to_paddr (bin, curr_delay_import_dir->Name);
import_func_name_offset = curr_delay_import_dir->DelayImportNameTable;
}
while ((curr_delay_import_dir->Name != 0) && (curr_delay_import_dir->DelayImportAddressTable !=0)) {
if (dll_name_offset > bin->size || dll_name_offset + PE_NAME_LENGTH > bin->size) {
goto beach;
}
int rr = r_buf_read_at (bin->b, dll_name_offset, (ut8*) dll_name, PE_NAME_LENGTH);
if (rr < 5) {
goto beach;
}
dll_name[PE_NAME_LENGTH] = '\0';
if (!bin_pe_parse_imports (bin, &imports, &nimp, dll_name, import_func_name_offset,
curr_delay_import_dir->DelayImportAddressTable)) {
break;
}
if ((char*) (curr_delay_import_dir + 2) > (char*) (bin->b->buf + bin->size)) {
goto beach;
}
curr_delay_import_dir++;
}
}
beach:
if (nimp) {
imps = realloc (imports, (nimp + 1) * sizeof(struct r_bin_pe_import_t));
if (!imps) {
r_sys_perror ("realloc (import)");
return NULL;
}
imports = imps;
imports[nimp].last = 1;
}
return imports;
}
struct r_bin_pe_lib_t* PE_(r_bin_pe_get_libs)(struct PE_(r_bin_pe_obj_t)* bin) {
if (!bin) {
return NULL;
}
struct r_bin_pe_lib_t* libs = NULL;
PE_(image_import_directory) * curr_import_dir = NULL;
PE_(image_delay_import_directory) * curr_delay_import_dir = NULL;
PE_DWord name_off = 0;
SdbHash* lib_map = NULL;
ut64 off; //cache value
int index = 0;
int len = 0;
int max_libs = 20;
libs = calloc (max_libs + 1, sizeof(struct r_bin_pe_lib_t));
if (!libs) {
r_sys_perror ("malloc (libs)");
return NULL;
}
if (bin->import_directory_offset + bin->import_directory_size > bin->size) {
bprintf ("import directory offset bigger than file\n");
goto out_error;
}
lib_map = sdb_ht_new ();
off = bin->import_directory_offset;
if (off < bin->size && off > 0) {
void* last = NULL;
// normal imports
if (off + sizeof (PE_(image_import_directory)) > bin->size) {
goto out_error;
}
curr_import_dir = (PE_(image_import_directory)*)(bin->b->buf + off);
last = (char*) curr_import_dir + bin->import_directory_size;
while ((void*) (curr_import_dir + 1) <= last && (
curr_import_dir->FirstThunk || curr_import_dir->Name ||
curr_import_dir->TimeDateStamp || curr_import_dir->Characteristics ||
curr_import_dir->ForwarderChain)) {
name_off = bin_pe_rva_to_paddr (bin, curr_import_dir->Name);
len = r_buf_read_at (bin->b, name_off, (ut8*) libs[index].name, PE_STRING_LENGTH);
if (!libs[index].name[0]) { // minimum string length
goto next;
}
if (len < 2 || libs[index].name[0] == 0) { // minimum string length
bprintf ("Warning: read (libs - import dirs) %d\n", len);
break;
}
libs[index].name[len - 1] = '\0';
r_str_case (libs[index].name, 0);
if (!sdb_ht_find (lib_map, libs[index].name, NULL)) {
sdb_ht_insert (lib_map, libs[index].name, "a");
libs[index++].last = 0;
if (index >= max_libs) {
libs = realloc (libs, (max_libs * 2) * sizeof (struct r_bin_pe_lib_t));
if (!libs) {
r_sys_perror ("realloc (libs)");
goto out_error;
}
max_libs *= 2;
}
}
next:
curr_import_dir++;
}
}
off = bin->delay_import_directory_offset;
if (off < bin->size && off > 0) {
if (off + sizeof(PE_(image_delay_import_directory)) > bin->size) {
goto out_error;
}
curr_delay_import_dir = (PE_(image_delay_import_directory)*)(bin->b->buf + off);
while (curr_delay_import_dir->Name != 0 && curr_delay_import_dir->DelayImportNameTable != 0) {
name_off = bin_pe_rva_to_paddr (bin, curr_delay_import_dir->Name);
if (name_off > bin->size || name_off + PE_STRING_LENGTH > bin->size) {
goto out_error;
}
len = r_buf_read_at (bin->b, name_off, (ut8*) libs[index].name, PE_STRING_LENGTH);
if (len != PE_STRING_LENGTH) {
bprintf ("Warning: read (libs - delay import dirs)\n");
break;
}
libs[index].name[len - 1] = '\0';
r_str_case (libs[index].name, 0);
if (!sdb_ht_find (lib_map, libs[index].name, NULL)) {
sdb_ht_insert (lib_map, libs[index].name, "a");
libs[index++].last = 0;
if (index >= max_libs) {
libs = realloc (libs, (max_libs * 2) * sizeof (struct r_bin_pe_lib_t));
if (!libs) {
sdb_ht_free (lib_map);
r_sys_perror ("realloc (libs)");
return NULL;
}
max_libs *= 2;
}
}
curr_delay_import_dir++;
if ((const ut8*) (curr_delay_import_dir + 1) >= (const ut8*) (bin->b->buf + bin->size)) {
break;
}
}
}
sdb_ht_free (lib_map);
libs[index].last = 1;
return libs;
out_error:
sdb_ht_free (lib_map);
free (libs);
return NULL;
}
int PE_(r_bin_pe_get_image_size)(struct PE_(r_bin_pe_obj_t)* bin) {
return bin->nt_headers->optional_header.SizeOfImage;
}
// TODO: make it const! like in elf
char* PE_(r_bin_pe_get_machine)(struct PE_(r_bin_pe_obj_t)* bin) {
char* machine = NULL;
if (bin && bin->nt_headers) {
switch (bin->nt_headers->file_header.Machine) {
case PE_IMAGE_FILE_MACHINE_ALPHA: machine = "Alpha"; break;
case PE_IMAGE_FILE_MACHINE_ALPHA64: machine = "Alpha 64"; break;
case PE_IMAGE_FILE_MACHINE_AM33: machine = "AM33"; break;
case PE_IMAGE_FILE_MACHINE_AMD64: machine = "AMD 64"; break;
case PE_IMAGE_FILE_MACHINE_ARM: machine = "ARM"; break;
case PE_IMAGE_FILE_MACHINE_CEE: machine = "CEE"; break;
case PE_IMAGE_FILE_MACHINE_CEF: machine = "CEF"; break;
case PE_IMAGE_FILE_MACHINE_EBC: machine = "EBC"; break;
case PE_IMAGE_FILE_MACHINE_I386: machine = "i386"; break;
case PE_IMAGE_FILE_MACHINE_IA64: machine = "ia64"; break;
case PE_IMAGE_FILE_MACHINE_M32R: machine = "M32R"; break;
case PE_IMAGE_FILE_MACHINE_M68K: machine = "M68K"; break;
case PE_IMAGE_FILE_MACHINE_MIPS16: machine = "Mips 16"; break;
case PE_IMAGE_FILE_MACHINE_MIPSFPU: machine = "Mips FPU"; break;
case PE_IMAGE_FILE_MACHINE_MIPSFPU16: machine = "Mips FPU 16"; break;
case PE_IMAGE_FILE_MACHINE_POWERPC: machine = "PowerPC"; break;
case PE_IMAGE_FILE_MACHINE_POWERPCFP: machine = "PowerPC FP"; break;
case PE_IMAGE_FILE_MACHINE_R10000: machine = "R10000"; break;
case PE_IMAGE_FILE_MACHINE_R3000: machine = "R3000"; break;
case PE_IMAGE_FILE_MACHINE_R4000: machine = "R4000"; break;
case PE_IMAGE_FILE_MACHINE_SH3: machine = "SH3"; break;
case PE_IMAGE_FILE_MACHINE_SH3DSP: machine = "SH3DSP"; break;
case PE_IMAGE_FILE_MACHINE_SH3E: machine = "SH3E"; break;
case PE_IMAGE_FILE_MACHINE_SH4: machine = "SH4"; break;
case PE_IMAGE_FILE_MACHINE_SH5: machine = "SH5"; break;
case PE_IMAGE_FILE_MACHINE_THUMB: machine = "Thumb"; break;
case PE_IMAGE_FILE_MACHINE_TRICORE: machine = "Tricore"; break;
case PE_IMAGE_FILE_MACHINE_WCEMIPSV2: machine = "WCE Mips V2"; break;
default: machine = "unknown";
}
}
return machine? strdup (machine): NULL;
}
// TODO: make it const! like in elf
char* PE_(r_bin_pe_get_os)(struct PE_(r_bin_pe_obj_t)* bin) {
char* os;
if (!bin || !bin->nt_headers) {
return NULL;
}
switch (bin->nt_headers->optional_header.Subsystem) {
case PE_IMAGE_SUBSYSTEM_NATIVE:
os = strdup ("native");
break;
case PE_IMAGE_SUBSYSTEM_WINDOWS_GUI:
case PE_IMAGE_SUBSYSTEM_WINDOWS_CUI:
case PE_IMAGE_SUBSYSTEM_WINDOWS_CE_GUI:
os = strdup ("windows");
break;
case PE_IMAGE_SUBSYSTEM_POSIX_CUI:
os = strdup ("posix");
break;
case PE_IMAGE_SUBSYSTEM_EFI_APPLICATION:
case PE_IMAGE_SUBSYSTEM_EFI_BOOT_SERVICE_DRIVER:
case PE_IMAGE_SUBSYSTEM_EFI_RUNTIME_DRIVER:
case PE_IMAGE_SUBSYSTEM_EFI_ROM:
os = strdup ("efi");
break;
case PE_IMAGE_SUBSYSTEM_XBOX:
os = strdup ("xbox");
break;
default:
// XXX: this is unknown
os = strdup ("windows");
}
return os;
}
// TODO: make it const
char* PE_(r_bin_pe_get_class)(struct PE_(r_bin_pe_obj_t)* bin) {
if (bin && bin->nt_headers) {
switch (bin->nt_headers->optional_header.Magic) {
case PE_IMAGE_FILE_TYPE_PE32: return strdup ("PE32");
case PE_IMAGE_FILE_TYPE_PE32PLUS: return strdup ("PE32+");
default: return strdup ("Unknown");
}
}
return NULL;
}
int PE_(r_bin_pe_get_bits)(struct PE_(r_bin_pe_obj_t)* bin) {
int bits = 32;
if (bin && bin->nt_headers) {
if (is_arm (bin)) {
if (is_thumb (bin)) {
bits = 16;
}
} else {
switch (bin->nt_headers->optional_header.Magic) {
case PE_IMAGE_FILE_TYPE_PE32: bits = 32; break;
case PE_IMAGE_FILE_TYPE_PE32PLUS: bits = 64; break;
default: bits = -1;
}
}
}
return bits;
}
//This function try to detect anomalies within section
//we check if there is a section mapped at entrypoint, otherwise add it up
void PE_(r_bin_pe_check_sections)(struct PE_(r_bin_pe_obj_t)* bin, struct r_bin_pe_section_t* * sects) {
int i = 0;
struct r_bin_pe_section_t* sections = *sects;
ut64 addr_beg, addr_end, new_section_size, new_perm, base_addr;
struct r_bin_pe_addr_t* entry = PE_(r_bin_pe_get_entrypoint) (bin);
if (!entry) {
return;
}
new_section_size = bin->size;
new_section_size -= entry->paddr > bin->size? 0: entry->paddr;
new_perm = (PE_IMAGE_SCN_MEM_READ | PE_IMAGE_SCN_MEM_WRITE | PE_IMAGE_SCN_MEM_EXECUTE);
base_addr = PE_(r_bin_pe_get_image_base) (bin);
for (i = 0; !sections[i].last; i++) {
//strcmp against .text doesn't work in somes cases
if (strstr ((const char*) sections[i].name, "text")) {
bool fix = false;
int j;
//check paddr boundaries
addr_beg = sections[i].paddr;
addr_end = addr_beg + sections[i].size;
if (entry->paddr < addr_beg || entry->paddr > addr_end) {
fix = true;
}
//check vaddr boundaries
addr_beg = sections[i].vaddr + base_addr;
addr_end = addr_beg + sections[i].vsize;
if (entry->vaddr < addr_beg || entry->vaddr > addr_end) {
fix = true;
}
//look for other segment with x that is already mapped and hold entrypoint
for (j = 0; !sections[j].last; j++) {
if (sections[j].flags & PE_IMAGE_SCN_MEM_EXECUTE) {
addr_beg = sections[j].paddr;
addr_end = addr_beg + sections[j].size;
if (addr_beg <= entry->paddr && entry->paddr < addr_end) {
if (!sections[j].vsize) {
sections[j].vsize = sections[j].size;
}
addr_beg = sections[j].vaddr + base_addr;
addr_end = addr_beg + sections[j].vsize;
if (addr_beg <= entry->vaddr || entry->vaddr < addr_end) {
fix = false;
break;
}
}
}
}
//if either vaddr or paddr fail we should update this section
if (fix) {
strcpy ((char*) sections[i].name, "blob");
sections[i].paddr = entry->paddr;
sections[i].vaddr = entry->vaddr - base_addr;
sections[i].size = sections[i].vsize = new_section_size;
sections[i].flags = new_perm;
}
goto out_function;
}
}
//if we arrive til here means there is no text section find one that is holding the code
for (i = 0; !sections[i].last; i++) {
if (sections[i].size > bin->size) {
continue;
}
addr_beg = sections[i].paddr;
addr_end = addr_beg + sections[i].size;
if (addr_beg <= entry->paddr && entry->paddr < addr_end) {
if (!sections[i].vsize) {
sections[i].vsize = sections[i].size;
}
addr_beg = sections[i].vaddr + base_addr;
addr_end = addr_beg + sections[i].vsize;
if (entry->vaddr < addr_beg || entry->vaddr > addr_end) {
sections[i].vaddr = entry->vaddr - base_addr;
}
goto out_function;
}
}
//we need to create another section in order to load the entrypoint
sections = realloc (sections, (bin->num_sections + 2) * sizeof(struct r_bin_pe_section_t));
i = bin->num_sections;
sections[i].last = 0;
strcpy ((char*) sections[i].name, "blob");
sections[i].paddr = entry->paddr;
sections[i].vaddr = entry->vaddr - base_addr;
sections[i].size = sections[i].vsize = new_section_size;
sections[i].flags = new_perm;
sections[i + 1].last = 1;
*sects = sections;
out_function:
free (entry);
return;
}
struct r_bin_pe_section_t* PE_(r_bin_pe_get_sections)(struct PE_(r_bin_pe_obj_t)* bin) {
struct r_bin_pe_section_t* sections = NULL;
PE_(image_section_header) * shdr;
int i, j, section_count = 0;
if (!bin || !bin->nt_headers) {
return NULL;
}
shdr = bin->section_header;
for (i = 0; i < bin->num_sections; i++) {
//just allocate the needed
if (shdr[i].SizeOfRawData || shdr[i].Misc.VirtualSize) {
section_count++;
}
}
sections = calloc (section_count + 1, sizeof(struct r_bin_pe_section_t));
if (!sections) {
r_sys_perror ("malloc (sections)");
return NULL;
}
for (i = 0, j = 0; i < bin->num_sections; i++) {
//if sz = 0 r_io_section_add will not add it so just skeep
if (!shdr[i].SizeOfRawData && !shdr[i].Misc.VirtualSize) {
continue;
}
if (shdr[i].Name[0] == '\0') {
char* new_name = r_str_newf ("sect_%d", j);
strncpy ((char*) sections[j].name, new_name, R_ARRAY_SIZE (sections[j].name) - 1);
free (new_name);
} else if (shdr[i].Name[0] == '/') {
//long name is something deprecated but still used
int idx = atoi ((const char *)shdr[i].Name + 1);
ut64 sym_tbl_off = bin->nt_headers->file_header.PointerToSymbolTable;
int num_symbols = bin->nt_headers->file_header.NumberOfSymbols;
int off = num_symbols * COFF_SYMBOL_SIZE;
if (sym_tbl_off &&
sym_tbl_off + off + idx < bin->size &&
sym_tbl_off + off + idx > off) {
int sz = PE_IMAGE_SIZEOF_SHORT_NAME * 3;
char* buf[64] = {0};
if (r_buf_read_at (bin->b,
sym_tbl_off + off + idx,
(ut8*)buf, 64)) {
memcpy (sections[j].name, buf, sz);
sections[j].name[sz - 1] = '\0';
}
}
} else {
memcpy (sections[j].name, shdr[i].Name, PE_IMAGE_SIZEOF_SHORT_NAME);
sections[j].name[PE_IMAGE_SIZEOF_SHORT_NAME] = '\0';
}
sections[j].vaddr = shdr[i].VirtualAddress;
sections[j].size = shdr[i].SizeOfRawData;
sections[j].vsize = shdr[i].Misc.VirtualSize;
if (bin->optional_header) {
int sa = R_MAX (bin->optional_header->SectionAlignment, 0x1000);
ut64 diff = sections[j].vsize % sa;
if (diff) {
sections[j].vsize += sa - diff;
}
}
sections[j].paddr = shdr[i].PointerToRawData;
sections[j].flags = shdr[i].Characteristics;
sections[j].last = 0;
j++;
}
sections[j].last = 1;
bin->num_sections = section_count;
return sections;
}
char* PE_(r_bin_pe_get_subsystem)(struct PE_(r_bin_pe_obj_t)* bin) {
char* subsystem = NULL;
if (bin && bin->nt_headers) {
switch (bin->nt_headers->optional_header.Subsystem) {
case PE_IMAGE_SUBSYSTEM_NATIVE:
subsystem = "Native"; break;
case PE_IMAGE_SUBSYSTEM_WINDOWS_GUI:
subsystem = "Windows GUI"; break;
case PE_IMAGE_SUBSYSTEM_WINDOWS_CUI:
subsystem = "Windows CUI"; break;
case PE_IMAGE_SUBSYSTEM_POSIX_CUI:
subsystem = "POSIX CUI"; break;
case PE_IMAGE_SUBSYSTEM_WINDOWS_CE_GUI:
subsystem = "Windows CE GUI"; break;
case PE_IMAGE_SUBSYSTEM_EFI_APPLICATION:
subsystem = "EFI Application"; break;
case PE_IMAGE_SUBSYSTEM_EFI_BOOT_SERVICE_DRIVER:
subsystem = "EFI Boot Service Driver"; break;
case PE_IMAGE_SUBSYSTEM_EFI_RUNTIME_DRIVER:
subsystem = "EFI Runtime Driver"; break;
case PE_IMAGE_SUBSYSTEM_EFI_ROM:
subsystem = "EFI ROM"; break;
case PE_IMAGE_SUBSYSTEM_XBOX:
subsystem = "XBOX"; break;
default:
subsystem = "Unknown"; break;
}
}
return subsystem? strdup (subsystem): NULL;
}
#define HASCHR(x) bin->nt_headers->file_header.Characteristics & x
int PE_(r_bin_pe_is_dll)(struct PE_(r_bin_pe_obj_t)* bin) {
if (!bin || !bin->nt_headers) {
return false;
}
return HASCHR (PE_IMAGE_FILE_DLL);
}
int PE_(r_bin_pe_is_pie)(struct PE_(r_bin_pe_obj_t)* bin) {
if (!bin || !bin->nt_headers) {
return false;
}
return HASCHR (IMAGE_DLL_CHARACTERISTICS_DYNAMIC_BASE);
#if 0
BOOL aslr = inh->OptionalHeader.DllCharacteristics & IMAGE_DLLCHARACTERISTICS_DYNAMIC_BASE;
//TODO: implement dep?
BOOL dep = inh->OptionalHeader.DllCharacteristics & IMAGE_DLLCHARACTERISTICS_NX_COMPAT;
#endif
}
int PE_(r_bin_pe_is_big_endian)(struct PE_(r_bin_pe_obj_t)* bin) {
ut16 arch;
if (!bin || !bin->nt_headers) {
return false;
}
arch = bin->nt_headers->file_header.Machine;
if (arch == PE_IMAGE_FILE_MACHINE_I386 ||
arch == PE_IMAGE_FILE_MACHINE_AMD64) {
return false;
}
return HASCHR (PE_IMAGE_FILE_BYTES_REVERSED_HI);
}
int PE_(r_bin_pe_is_stripped_relocs)(struct PE_(r_bin_pe_obj_t)* bin) {
if (!bin || !bin->nt_headers) {
return false;
}
return HASCHR (PE_IMAGE_FILE_RELOCS_STRIPPED);
}
int PE_(r_bin_pe_is_stripped_line_nums)(struct PE_(r_bin_pe_obj_t)* bin) {
if (!bin || !bin->nt_headers) {
return false;
}
return HASCHR (PE_IMAGE_FILE_LINE_NUMS_STRIPPED);
}
int PE_(r_bin_pe_is_stripped_local_syms)(struct PE_(r_bin_pe_obj_t)* bin) {
if (!bin || !bin->nt_headers) {
return false;
}
return HASCHR (PE_IMAGE_FILE_LOCAL_SYMS_STRIPPED);
}
int PE_(r_bin_pe_is_stripped_debug)(struct PE_(r_bin_pe_obj_t)* bin) {
if (!bin || !bin->nt_headers) {
return false;
}
return HASCHR (PE_IMAGE_FILE_DEBUG_STRIPPED);
}
void* PE_(r_bin_pe_free)(struct PE_(r_bin_pe_obj_t)* bin) {
if (!bin) {
return NULL;
}
free (bin->dos_header);
free (bin->nt_headers);
free (bin->section_header);
free (bin->export_directory);
free (bin->import_directory);
free (bin->resource_directory);
free (bin->delay_import_directory);
free (bin->tls_directory);
r_list_free (bin->resources);
r_pkcs7_free_cms (bin->cms);
r_buf_free (bin->b);
bin->b = NULL;
free (bin);
return NULL;
}
struct PE_(r_bin_pe_obj_t)* PE_(r_bin_pe_new)(const char* file, bool verbose) {
ut8* buf;
struct PE_(r_bin_pe_obj_t)* bin = R_NEW0 (struct PE_(r_bin_pe_obj_t));
if (!bin) {
return NULL;
}
bin->file = file;
if (!(buf = (ut8*) r_file_slurp (file, &bin->size))) {
return PE_(r_bin_pe_free)(bin);
}
bin->b = r_buf_new ();
if (!r_buf_set_bytes (bin->b, buf, bin->size)) {
free (buf);
return PE_(r_bin_pe_free)(bin);
}
bin->verbose = verbose;
free (buf);
if (!bin_pe_init (bin)) {
return PE_(r_bin_pe_free)(bin);
}
return bin;
}
struct PE_(r_bin_pe_obj_t)* PE_(r_bin_pe_new_buf)(RBuffer * buf, bool verbose) {
struct PE_(r_bin_pe_obj_t)* bin = R_NEW0 (struct PE_(r_bin_pe_obj_t));
if (!bin) {
return NULL;
}
bin->kv = sdb_new0 ();
bin->b = r_buf_new ();
bin->verbose = verbose;
bin->size = buf->length;
if (!r_buf_set_bytes (bin->b, buf->buf, bin->size)) {
return PE_(r_bin_pe_free)(bin);
}
if (!bin_pe_init (bin)) {
return PE_(r_bin_pe_free)(bin);
}
return bin;
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_144_0 |
crossvul-cpp_data_bad_2657_1 | /*
* Copyright (C) 2002 WIDE Project.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the project nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
/* \summary: IPv6 mobility printer */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <netdissect-stdinc.h>
#include "ip6.h"
#include "netdissect.h"
#include "addrtoname.h"
#include "extract.h"
static const char tstr[] = "[|MOBILITY]";
/* Mobility header */
struct ip6_mobility {
uint8_t ip6m_pproto; /* following payload protocol (for PG) */
uint8_t ip6m_len; /* length in units of 8 octets */
uint8_t ip6m_type; /* message type */
uint8_t reserved; /* reserved */
uint16_t ip6m_cksum; /* sum of IPv6 pseudo-header and MH */
union {
uint16_t ip6m_un_data16[1]; /* type-specific field */
uint8_t ip6m_un_data8[2]; /* type-specific field */
} ip6m_dataun;
};
#define ip6m_data16 ip6m_dataun.ip6m_un_data16
#define ip6m_data8 ip6m_dataun.ip6m_un_data8
#define IP6M_MINLEN 8
/* http://www.iana.org/assignments/mobility-parameters/mobility-parameters.xhtml */
/* message type */
#define IP6M_BINDING_REQUEST 0 /* Binding Refresh Request */
#define IP6M_HOME_TEST_INIT 1 /* Home Test Init */
#define IP6M_CAREOF_TEST_INIT 2 /* Care-of Test Init */
#define IP6M_HOME_TEST 3 /* Home Test */
#define IP6M_CAREOF_TEST 4 /* Care-of Test */
#define IP6M_BINDING_UPDATE 5 /* Binding Update */
#define IP6M_BINDING_ACK 6 /* Binding Acknowledgement */
#define IP6M_BINDING_ERROR 7 /* Binding Error */
#define IP6M_MAX 7
static const struct tok ip6m_str[] = {
{ IP6M_BINDING_REQUEST, "BRR" },
{ IP6M_HOME_TEST_INIT, "HoTI" },
{ IP6M_CAREOF_TEST_INIT, "CoTI" },
{ IP6M_HOME_TEST, "HoT" },
{ IP6M_CAREOF_TEST, "CoT" },
{ IP6M_BINDING_UPDATE, "BU" },
{ IP6M_BINDING_ACK, "BA" },
{ IP6M_BINDING_ERROR, "BE" },
{ 0, NULL }
};
static const unsigned ip6m_hdrlen[IP6M_MAX + 1] = {
IP6M_MINLEN, /* IP6M_BINDING_REQUEST */
IP6M_MINLEN + 8, /* IP6M_HOME_TEST_INIT */
IP6M_MINLEN + 8, /* IP6M_CAREOF_TEST_INIT */
IP6M_MINLEN + 16, /* IP6M_HOME_TEST */
IP6M_MINLEN + 16, /* IP6M_CAREOF_TEST */
IP6M_MINLEN + 4, /* IP6M_BINDING_UPDATE */
IP6M_MINLEN + 4, /* IP6M_BINDING_ACK */
IP6M_MINLEN + 16, /* IP6M_BINDING_ERROR */
};
/* Mobility Header Options */
#define IP6MOPT_MINLEN 2
#define IP6MOPT_PAD1 0x0 /* Pad1 */
#define IP6MOPT_PADN 0x1 /* PadN */
#define IP6MOPT_REFRESH 0x2 /* Binding Refresh Advice */
#define IP6MOPT_REFRESH_MINLEN 4
#define IP6MOPT_ALTCOA 0x3 /* Alternate Care-of Address */
#define IP6MOPT_ALTCOA_MINLEN 18
#define IP6MOPT_NONCEID 0x4 /* Nonce Indices */
#define IP6MOPT_NONCEID_MINLEN 6
#define IP6MOPT_AUTH 0x5 /* Binding Authorization Data */
#define IP6MOPT_AUTH_MINLEN 12
static int
mobility_opt_print(netdissect_options *ndo,
const u_char *bp, const unsigned len)
{
unsigned i, optlen;
for (i = 0; i < len; i += optlen) {
ND_TCHECK(bp[i]);
if (bp[i] == IP6MOPT_PAD1)
optlen = 1;
else {
if (i + 1 < len) {
ND_TCHECK(bp[i + 1]);
optlen = bp[i + 1] + 2;
}
else
goto trunc;
}
if (i + optlen > len)
goto trunc;
ND_TCHECK(bp[i + optlen]);
switch (bp[i]) {
case IP6MOPT_PAD1:
ND_PRINT((ndo, "(pad1)"));
break;
case IP6MOPT_PADN:
if (len - i < IP6MOPT_MINLEN) {
ND_PRINT((ndo, "(padn: trunc)"));
goto trunc;
}
ND_PRINT((ndo, "(padn)"));
break;
case IP6MOPT_REFRESH:
if (len - i < IP6MOPT_REFRESH_MINLEN) {
ND_PRINT((ndo, "(refresh: trunc)"));
goto trunc;
}
/* units of 4 secs */
ND_PRINT((ndo, "(refresh: %u)",
EXTRACT_16BITS(&bp[i+2]) << 2));
break;
case IP6MOPT_ALTCOA:
if (len - i < IP6MOPT_ALTCOA_MINLEN) {
ND_PRINT((ndo, "(altcoa: trunc)"));
goto trunc;
}
ND_PRINT((ndo, "(alt-CoA: %s)", ip6addr_string(ndo, &bp[i+2])));
break;
case IP6MOPT_NONCEID:
if (len - i < IP6MOPT_NONCEID_MINLEN) {
ND_PRINT((ndo, "(ni: trunc)"));
goto trunc;
}
ND_PRINT((ndo, "(ni: ho=0x%04x co=0x%04x)",
EXTRACT_16BITS(&bp[i+2]),
EXTRACT_16BITS(&bp[i+4])));
break;
case IP6MOPT_AUTH:
if (len - i < IP6MOPT_AUTH_MINLEN) {
ND_PRINT((ndo, "(auth: trunc)"));
goto trunc;
}
ND_PRINT((ndo, "(auth)"));
break;
default:
if (len - i < IP6MOPT_MINLEN) {
ND_PRINT((ndo, "(sopt_type %u: trunc)", bp[i]));
goto trunc;
}
ND_PRINT((ndo, "(type-0x%02x: len=%u)", bp[i], bp[i + 1]));
break;
}
}
return 0;
trunc:
return 1;
}
/*
* Mobility Header
*/
int
mobility_print(netdissect_options *ndo,
const u_char *bp, const u_char *bp2 _U_)
{
const struct ip6_mobility *mh;
const u_char *ep;
unsigned mhlen, hlen;
uint8_t type;
mh = (const struct ip6_mobility *)bp;
/* 'ep' points to the end of available data. */
ep = ndo->ndo_snapend;
if (!ND_TTEST(mh->ip6m_len)) {
/*
* There's not enough captured data to include the
* mobility header length.
*
* Our caller expects us to return the length, however,
* so return a value that will run to the end of the
* captured data.
*
* XXX - "ip6_print()" doesn't do anything with the
* returned length, however, as it breaks out of the
* header-processing loop.
*/
mhlen = ep - bp;
goto trunc;
}
mhlen = (mh->ip6m_len + 1) << 3;
/* XXX ip6m_cksum */
ND_TCHECK(mh->ip6m_type);
type = mh->ip6m_type;
if (type <= IP6M_MAX && mhlen < ip6m_hdrlen[type]) {
ND_PRINT((ndo, "(header length %u is too small for type %u)", mhlen, type));
goto trunc;
}
ND_PRINT((ndo, "mobility: %s", tok2str(ip6m_str, "type-#%u", type)));
switch (type) {
case IP6M_BINDING_REQUEST:
hlen = IP6M_MINLEN;
break;
case IP6M_HOME_TEST_INIT:
case IP6M_CAREOF_TEST_INIT:
hlen = IP6M_MINLEN;
if (ndo->ndo_vflag) {
ND_TCHECK2(*mh, hlen + 8);
ND_PRINT((ndo, " %s Init Cookie=%08x:%08x",
type == IP6M_HOME_TEST_INIT ? "Home" : "Care-of",
EXTRACT_32BITS(&bp[hlen]),
EXTRACT_32BITS(&bp[hlen + 4])));
}
hlen += 8;
break;
case IP6M_HOME_TEST:
case IP6M_CAREOF_TEST:
ND_TCHECK(mh->ip6m_data16[0]);
ND_PRINT((ndo, " nonce id=0x%x", EXTRACT_16BITS(&mh->ip6m_data16[0])));
hlen = IP6M_MINLEN;
if (ndo->ndo_vflag) {
ND_TCHECK2(*mh, hlen + 8);
ND_PRINT((ndo, " %s Init Cookie=%08x:%08x",
type == IP6M_HOME_TEST ? "Home" : "Care-of",
EXTRACT_32BITS(&bp[hlen]),
EXTRACT_32BITS(&bp[hlen + 4])));
}
hlen += 8;
if (ndo->ndo_vflag) {
ND_TCHECK2(*mh, hlen + 8);
ND_PRINT((ndo, " %s Keygen Token=%08x:%08x",
type == IP6M_HOME_TEST ? "Home" : "Care-of",
EXTRACT_32BITS(&bp[hlen]),
EXTRACT_32BITS(&bp[hlen + 4])));
}
hlen += 8;
break;
case IP6M_BINDING_UPDATE:
ND_TCHECK(mh->ip6m_data16[0]);
ND_PRINT((ndo, " seq#=%u", EXTRACT_16BITS(&mh->ip6m_data16[0])));
hlen = IP6M_MINLEN;
ND_TCHECK2(*mh, hlen + 1);
if (bp[hlen] & 0xf0)
ND_PRINT((ndo, " "));
if (bp[hlen] & 0x80)
ND_PRINT((ndo, "A"));
if (bp[hlen] & 0x40)
ND_PRINT((ndo, "H"));
if (bp[hlen] & 0x20)
ND_PRINT((ndo, "L"));
if (bp[hlen] & 0x10)
ND_PRINT((ndo, "K"));
/* Reserved (4bits) */
hlen += 1;
/* Reserved (8bits) */
hlen += 1;
ND_TCHECK2(*mh, hlen + 2);
/* units of 4 secs */
ND_PRINT((ndo, " lifetime=%u", EXTRACT_16BITS(&bp[hlen]) << 2));
hlen += 2;
break;
case IP6M_BINDING_ACK:
ND_TCHECK(mh->ip6m_data8[0]);
ND_PRINT((ndo, " status=%u", mh->ip6m_data8[0]));
if (mh->ip6m_data8[1] & 0x80)
ND_PRINT((ndo, " K"));
/* Reserved (7bits) */
hlen = IP6M_MINLEN;
ND_TCHECK2(*mh, hlen + 2);
ND_PRINT((ndo, " seq#=%u", EXTRACT_16BITS(&bp[hlen])));
hlen += 2;
ND_TCHECK2(*mh, hlen + 2);
/* units of 4 secs */
ND_PRINT((ndo, " lifetime=%u", EXTRACT_16BITS(&bp[hlen]) << 2));
hlen += 2;
break;
case IP6M_BINDING_ERROR:
ND_TCHECK(mh->ip6m_data8[0]);
ND_PRINT((ndo, " status=%u", mh->ip6m_data8[0]));
/* Reserved */
hlen = IP6M_MINLEN;
ND_TCHECK2(*mh, hlen + 16);
ND_PRINT((ndo, " homeaddr %s", ip6addr_string(ndo, &bp[hlen])));
hlen += 16;
break;
default:
ND_PRINT((ndo, " len=%u", mh->ip6m_len));
return(mhlen);
break;
}
if (ndo->ndo_vflag)
if (mobility_opt_print(ndo, &bp[hlen], mhlen - hlen))
goto trunc;
return(mhlen);
trunc:
ND_PRINT((ndo, "%s", tstr));
return(mhlen);
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_2657_1 |
crossvul-cpp_data_bad_215_0 | /*
* MOV, 3GP, MP4 muxer
* Copyright (c) 2003 Thomas Raivio
* Copyright (c) 2004 Gildas Bazin <gbazin at videolan dot org>
* Copyright (c) 2009 Baptiste Coudurier <baptiste dot coudurier at gmail dot com>
*
* This file is part of FFmpeg.
*
* FFmpeg is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* FFmpeg is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with FFmpeg; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <stdint.h>
#include <inttypes.h>
#include "movenc.h"
#include "avformat.h"
#include "avio_internal.h"
#include "riff.h"
#include "avio.h"
#include "isom.h"
#include "avc.h"
#include "libavcodec/ac3_parser_internal.h"
#include "libavcodec/dnxhddata.h"
#include "libavcodec/flac.h"
#include "libavcodec/get_bits.h"
#include "libavcodec/internal.h"
#include "libavcodec/put_bits.h"
#include "libavcodec/vc1_common.h"
#include "libavcodec/raw.h"
#include "internal.h"
#include "libavutil/avstring.h"
#include "libavutil/intfloat.h"
#include "libavutil/mathematics.h"
#include "libavutil/libm.h"
#include "libavutil/opt.h"
#include "libavutil/dict.h"
#include "libavutil/pixdesc.h"
#include "libavutil/stereo3d.h"
#include "libavutil/timecode.h"
#include "libavutil/color_utils.h"
#include "hevc.h"
#include "rtpenc.h"
#include "mov_chan.h"
#include "vpcc.h"
static const AVOption options[] = {
{ "movflags", "MOV muxer flags", offsetof(MOVMuxContext, flags), AV_OPT_TYPE_FLAGS, {.i64 = 0}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
{ "rtphint", "Add RTP hint tracks", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_RTP_HINT}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
{ "moov_size", "maximum moov size so it can be placed at the begin", offsetof(MOVMuxContext, reserved_moov_size), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, 0 },
{ "empty_moov", "Make the initial moov atom empty", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_EMPTY_MOOV}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
{ "frag_keyframe", "Fragment at video keyframes", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_FRAG_KEYFRAME}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
{ "frag_every_frame", "Fragment at every frame", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_FRAG_EVERY_FRAME}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
{ "separate_moof", "Write separate moof/mdat atoms for each track", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_SEPARATE_MOOF}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
{ "frag_custom", "Flush fragments on caller requests", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_FRAG_CUSTOM}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
{ "isml", "Create a live smooth streaming feed (for pushing to a publishing point)", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_ISML}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
{ "faststart", "Run a second pass to put the index (moov atom) at the beginning of the file", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_FASTSTART}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
{ "omit_tfhd_offset", "Omit the base data offset in tfhd atoms", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_OMIT_TFHD_OFFSET}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
{ "disable_chpl", "Disable Nero chapter atom", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_DISABLE_CHPL}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
{ "default_base_moof", "Set the default-base-is-moof flag in tfhd atoms", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_DEFAULT_BASE_MOOF}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
{ "dash", "Write DASH compatible fragmented MP4", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_DASH}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
{ "frag_discont", "Signal that the next fragment is discontinuous from earlier ones", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_FRAG_DISCONT}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
{ "delay_moov", "Delay writing the initial moov until the first fragment is cut, or until the first fragment flush", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_DELAY_MOOV}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
{ "global_sidx", "Write a global sidx index at the start of the file", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_GLOBAL_SIDX}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
{ "write_colr", "Write colr atom (Experimental, may be renamed or changed, do not use from scripts)", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_WRITE_COLR}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
{ "write_gama", "Write deprecated gama atom", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_WRITE_GAMA}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
{ "use_metadata_tags", "Use mdta atom for metadata.", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_USE_MDTA}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
{ "skip_trailer", "Skip writing the mfra/tfra/mfro trailer for fragmented files", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_SKIP_TRAILER}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
{ "negative_cts_offsets", "Use negative CTS offsets (reducing the need for edit lists)", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_NEGATIVE_CTS_OFFSETS}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
FF_RTP_FLAG_OPTS(MOVMuxContext, rtp_flags),
{ "skip_iods", "Skip writing iods atom.", offsetof(MOVMuxContext, iods_skip), AV_OPT_TYPE_BOOL, {.i64 = 1}, 0, 1, AV_OPT_FLAG_ENCODING_PARAM},
{ "iods_audio_profile", "iods audio profile atom.", offsetof(MOVMuxContext, iods_audio_profile), AV_OPT_TYPE_INT, {.i64 = -1}, -1, 255, AV_OPT_FLAG_ENCODING_PARAM},
{ "iods_video_profile", "iods video profile atom.", offsetof(MOVMuxContext, iods_video_profile), AV_OPT_TYPE_INT, {.i64 = -1}, -1, 255, AV_OPT_FLAG_ENCODING_PARAM},
{ "frag_duration", "Maximum fragment duration", offsetof(MOVMuxContext, max_fragment_duration), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM},
{ "min_frag_duration", "Minimum fragment duration", offsetof(MOVMuxContext, min_fragment_duration), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM},
{ "frag_size", "Maximum fragment size", offsetof(MOVMuxContext, max_fragment_size), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM},
{ "ism_lookahead", "Number of lookahead entries for ISM files", offsetof(MOVMuxContext, ism_lookahead), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM},
{ "video_track_timescale", "set timescale of all video tracks", offsetof(MOVMuxContext, video_track_timescale), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM},
{ "brand", "Override major brand", offsetof(MOVMuxContext, major_brand), AV_OPT_TYPE_STRING, {.str = NULL}, .flags = AV_OPT_FLAG_ENCODING_PARAM },
{ "use_editlist", "use edit list", offsetof(MOVMuxContext, use_editlist), AV_OPT_TYPE_BOOL, {.i64 = -1}, -1, 1, AV_OPT_FLAG_ENCODING_PARAM},
{ "fragment_index", "Fragment number of the next fragment", offsetof(MOVMuxContext, fragments), AV_OPT_TYPE_INT, {.i64 = 1}, 1, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM},
{ "mov_gamma", "gamma value for gama atom", offsetof(MOVMuxContext, gamma), AV_OPT_TYPE_FLOAT, {.dbl = 0.0 }, 0.0, 10, AV_OPT_FLAG_ENCODING_PARAM},
{ "frag_interleave", "Interleave samples within fragments (max number of consecutive samples, lower is tighter interleaving, but with more overhead)", offsetof(MOVMuxContext, frag_interleave), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM },
{ "encryption_scheme", "Configures the encryption scheme, allowed values are none, cenc-aes-ctr", offsetof(MOVMuxContext, encryption_scheme_str), AV_OPT_TYPE_STRING, {.str = NULL}, .flags = AV_OPT_FLAG_ENCODING_PARAM },
{ "encryption_key", "The media encryption key (hex)", offsetof(MOVMuxContext, encryption_key), AV_OPT_TYPE_BINARY, .flags = AV_OPT_FLAG_ENCODING_PARAM },
{ "encryption_kid", "The media encryption key identifier (hex)", offsetof(MOVMuxContext, encryption_kid), AV_OPT_TYPE_BINARY, .flags = AV_OPT_FLAG_ENCODING_PARAM },
{ "use_stream_ids_as_track_ids", "use stream ids as track ids", offsetof(MOVMuxContext, use_stream_ids_as_track_ids), AV_OPT_TYPE_BOOL, {.i64 = 0}, 0, 1, AV_OPT_FLAG_ENCODING_PARAM},
{ "write_tmcd", "force or disable writing tmcd", offsetof(MOVMuxContext, write_tmcd), AV_OPT_TYPE_BOOL, {.i64 = -1}, -1, 1, AV_OPT_FLAG_ENCODING_PARAM},
{ "write_prft", "Write producer reference time box with specified time source", offsetof(MOVMuxContext, write_prft), AV_OPT_TYPE_INT, {.i64 = MOV_PRFT_NONE}, 0, MOV_PRFT_NB-1, AV_OPT_FLAG_ENCODING_PARAM, "prft"},
{ "wallclock", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = MOV_PRFT_SRC_WALLCLOCK}, 0, 0, AV_OPT_FLAG_ENCODING_PARAM, "prft"},
{ "pts", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = MOV_PRFT_SRC_PTS}, 0, 0, AV_OPT_FLAG_ENCODING_PARAM, "prft"},
{ "empty_hdlr_name", "write zero-length name string in hdlr atoms within mdia and minf atoms", offsetof(MOVMuxContext, empty_hdlr_name), AV_OPT_TYPE_BOOL, {.i64 = 0}, 0, 1, AV_OPT_FLAG_ENCODING_PARAM},
{ NULL },
};
#define MOV_CLASS(flavor)\
static const AVClass flavor ## _muxer_class = {\
.class_name = #flavor " muxer",\
.item_name = av_default_item_name,\
.option = options,\
.version = LIBAVUTIL_VERSION_INT,\
};
static int get_moov_size(AVFormatContext *s);
static int utf8len(const uint8_t *b)
{
int len = 0;
int val;
while (*b) {
GET_UTF8(val, *b++, return -1;)
len++;
}
return len;
}
//FIXME support 64 bit variant with wide placeholders
static int64_t update_size(AVIOContext *pb, int64_t pos)
{
int64_t curpos = avio_tell(pb);
avio_seek(pb, pos, SEEK_SET);
avio_wb32(pb, curpos - pos); /* rewrite size */
avio_seek(pb, curpos, SEEK_SET);
return curpos - pos;
}
static int co64_required(const MOVTrack *track)
{
if (track->entry > 0 && track->cluster[track->entry - 1].pos + track->data_offset > UINT32_MAX)
return 1;
return 0;
}
static int is_cover_image(const AVStream *st)
{
/* Eg. AV_DISPOSITION_ATTACHED_PIC | AV_DISPOSITION_TIMED_THUMBNAILS
* is encoded as sparse video track */
return st && st->disposition == AV_DISPOSITION_ATTACHED_PIC;
}
static int rtp_hinting_needed(const AVStream *st)
{
/* Add hint tracks for each real audio and video stream */
if (is_cover_image(st))
return 0;
return st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO ||
st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO;
}
/* Chunk offset atom */
static int mov_write_stco_tag(AVIOContext *pb, MOVTrack *track)
{
int i;
int mode64 = co64_required(track); // use 32 bit size variant if possible
int64_t pos = avio_tell(pb);
avio_wb32(pb, 0); /* size */
if (mode64)
ffio_wfourcc(pb, "co64");
else
ffio_wfourcc(pb, "stco");
avio_wb32(pb, 0); /* version & flags */
avio_wb32(pb, track->chunkCount); /* entry count */
for (i = 0; i < track->entry; i++) {
if (!track->cluster[i].chunkNum)
continue;
if (mode64 == 1)
avio_wb64(pb, track->cluster[i].pos + track->data_offset);
else
avio_wb32(pb, track->cluster[i].pos + track->data_offset);
}
return update_size(pb, pos);
}
/* Sample size atom */
static int mov_write_stsz_tag(AVIOContext *pb, MOVTrack *track)
{
int equalChunks = 1;
int i, j, entries = 0, tst = -1, oldtst = -1;
int64_t pos = avio_tell(pb);
avio_wb32(pb, 0); /* size */
ffio_wfourcc(pb, "stsz");
avio_wb32(pb, 0); /* version & flags */
for (i = 0; i < track->entry; i++) {
tst = track->cluster[i].size / track->cluster[i].entries;
if (oldtst != -1 && tst != oldtst)
equalChunks = 0;
oldtst = tst;
entries += track->cluster[i].entries;
}
if (equalChunks && track->entry) {
int sSize = track->entry ? track->cluster[0].size / track->cluster[0].entries : 0;
sSize = FFMAX(1, sSize); // adpcm mono case could make sSize == 0
avio_wb32(pb, sSize); // sample size
avio_wb32(pb, entries); // sample count
} else {
avio_wb32(pb, 0); // sample size
avio_wb32(pb, entries); // sample count
for (i = 0; i < track->entry; i++) {
for (j = 0; j < track->cluster[i].entries; j++) {
avio_wb32(pb, track->cluster[i].size /
track->cluster[i].entries);
}
}
}
return update_size(pb, pos);
}
/* Sample to chunk atom */
static int mov_write_stsc_tag(AVIOContext *pb, MOVTrack *track)
{
int index = 0, oldval = -1, i;
int64_t entryPos, curpos;
int64_t pos = avio_tell(pb);
avio_wb32(pb, 0); /* size */
ffio_wfourcc(pb, "stsc");
avio_wb32(pb, 0); // version & flags
entryPos = avio_tell(pb);
avio_wb32(pb, track->chunkCount); // entry count
for (i = 0; i < track->entry; i++) {
if (oldval != track->cluster[i].samples_in_chunk && track->cluster[i].chunkNum) {
avio_wb32(pb, track->cluster[i].chunkNum); // first chunk
avio_wb32(pb, track->cluster[i].samples_in_chunk); // samples per chunk
avio_wb32(pb, 0x1); // sample description index
oldval = track->cluster[i].samples_in_chunk;
index++;
}
}
curpos = avio_tell(pb);
avio_seek(pb, entryPos, SEEK_SET);
avio_wb32(pb, index); // rewrite size
avio_seek(pb, curpos, SEEK_SET);
return update_size(pb, pos);
}
/* Sync sample atom */
static int mov_write_stss_tag(AVIOContext *pb, MOVTrack *track, uint32_t flag)
{
int64_t curpos, entryPos;
int i, index = 0;
int64_t pos = avio_tell(pb);
avio_wb32(pb, 0); // size
ffio_wfourcc(pb, flag == MOV_SYNC_SAMPLE ? "stss" : "stps");
avio_wb32(pb, 0); // version & flags
entryPos = avio_tell(pb);
avio_wb32(pb, track->entry); // entry count
for (i = 0; i < track->entry; i++) {
if (track->cluster[i].flags & flag) {
avio_wb32(pb, i + 1);
index++;
}
}
curpos = avio_tell(pb);
avio_seek(pb, entryPos, SEEK_SET);
avio_wb32(pb, index); // rewrite size
avio_seek(pb, curpos, SEEK_SET);
return update_size(pb, pos);
}
/* Sample dependency atom */
static int mov_write_sdtp_tag(AVIOContext *pb, MOVTrack *track)
{
int i;
uint8_t leading, dependent, reference, redundancy;
int64_t pos = avio_tell(pb);
avio_wb32(pb, 0); // size
ffio_wfourcc(pb, "sdtp");
avio_wb32(pb, 0); // version & flags
for (i = 0; i < track->entry; i++) {
dependent = MOV_SAMPLE_DEPENDENCY_YES;
leading = reference = redundancy = MOV_SAMPLE_DEPENDENCY_UNKNOWN;
if (track->cluster[i].flags & MOV_DISPOSABLE_SAMPLE) {
reference = MOV_SAMPLE_DEPENDENCY_NO;
}
if (track->cluster[i].flags & MOV_SYNC_SAMPLE) {
dependent = MOV_SAMPLE_DEPENDENCY_NO;
}
avio_w8(pb, (leading << 6) | (dependent << 4) |
(reference << 2) | redundancy);
}
return update_size(pb, pos);
}
static int mov_write_amr_tag(AVIOContext *pb, MOVTrack *track)
{
avio_wb32(pb, 0x11); /* size */
if (track->mode == MODE_MOV) ffio_wfourcc(pb, "samr");
else ffio_wfourcc(pb, "damr");
ffio_wfourcc(pb, "FFMP");
avio_w8(pb, 0); /* decoder version */
avio_wb16(pb, 0x81FF); /* Mode set (all modes for AMR_NB) */
avio_w8(pb, 0x00); /* Mode change period (no restriction) */
avio_w8(pb, 0x01); /* Frames per sample */
return 0x11;
}
static int mov_write_ac3_tag(AVIOContext *pb, MOVTrack *track)
{
GetBitContext gbc;
PutBitContext pbc;
uint8_t buf[3];
int fscod, bsid, bsmod, acmod, lfeon, frmsizecod;
if (track->vos_len < 7)
return -1;
avio_wb32(pb, 11);
ffio_wfourcc(pb, "dac3");
init_get_bits(&gbc, track->vos_data + 4, (track->vos_len - 4) * 8);
fscod = get_bits(&gbc, 2);
frmsizecod = get_bits(&gbc, 6);
bsid = get_bits(&gbc, 5);
bsmod = get_bits(&gbc, 3);
acmod = get_bits(&gbc, 3);
if (acmod == 2) {
skip_bits(&gbc, 2); // dsurmod
} else {
if ((acmod & 1) && acmod != 1)
skip_bits(&gbc, 2); // cmixlev
if (acmod & 4)
skip_bits(&gbc, 2); // surmixlev
}
lfeon = get_bits1(&gbc);
init_put_bits(&pbc, buf, sizeof(buf));
put_bits(&pbc, 2, fscod);
put_bits(&pbc, 5, bsid);
put_bits(&pbc, 3, bsmod);
put_bits(&pbc, 3, acmod);
put_bits(&pbc, 1, lfeon);
put_bits(&pbc, 5, frmsizecod >> 1); // bit_rate_code
put_bits(&pbc, 5, 0); // reserved
flush_put_bits(&pbc);
avio_write(pb, buf, sizeof(buf));
return 11;
}
struct eac3_info {
AVPacket pkt;
uint8_t ec3_done;
uint8_t num_blocks;
/* Layout of the EC3SpecificBox */
/* maximum bitrate */
uint16_t data_rate;
/* number of independent substreams */
uint8_t num_ind_sub;
struct {
/* sample rate code (see ff_ac3_sample_rate_tab) 2 bits */
uint8_t fscod;
/* bit stream identification 5 bits */
uint8_t bsid;
/* one bit reserved */
/* audio service mixing (not supported yet) 1 bit */
/* bit stream mode 3 bits */
uint8_t bsmod;
/* audio coding mode 3 bits */
uint8_t acmod;
/* sub woofer on 1 bit */
uint8_t lfeon;
/* 3 bits reserved */
/* number of dependent substreams associated with this substream 4 bits */
uint8_t num_dep_sub;
/* channel locations of the dependent substream(s), if any, 9 bits */
uint16_t chan_loc;
/* if there is no dependent substream, then one bit reserved instead */
} substream[1]; /* TODO: support 8 independent substreams */
};
#if CONFIG_AC3_PARSER
static int handle_eac3(MOVMuxContext *mov, AVPacket *pkt, MOVTrack *track)
{
AC3HeaderInfo *hdr = NULL;
struct eac3_info *info;
int num_blocks, ret;
if (!track->eac3_priv && !(track->eac3_priv = av_mallocz(sizeof(*info))))
return AVERROR(ENOMEM);
info = track->eac3_priv;
if (avpriv_ac3_parse_header(&hdr, pkt->data, pkt->size) < 0) {
/* drop the packets until we see a good one */
if (!track->entry) {
av_log(mov, AV_LOG_WARNING, "Dropping invalid packet from start of the stream\n");
ret = 0;
} else
ret = AVERROR_INVALIDDATA;
goto end;
}
info->data_rate = FFMAX(info->data_rate, hdr->bit_rate / 1000);
num_blocks = hdr->num_blocks;
if (!info->ec3_done) {
/* AC-3 substream must be the first one */
if (hdr->bitstream_id <= 10 && hdr->substreamid != 0) {
ret = AVERROR(EINVAL);
goto end;
}
/* this should always be the case, given that our AC-3 parser
* concatenates dependent frames to their independent parent */
if (hdr->frame_type == EAC3_FRAME_TYPE_INDEPENDENT) {
/* substream ids must be incremental */
if (hdr->substreamid > info->num_ind_sub + 1) {
ret = AVERROR(EINVAL);
goto end;
}
if (hdr->substreamid == info->num_ind_sub + 1) {
//info->num_ind_sub++;
avpriv_request_sample(track->par, "Multiple independent substreams");
ret = AVERROR_PATCHWELCOME;
goto end;
} else if (hdr->substreamid < info->num_ind_sub ||
hdr->substreamid == 0 && info->substream[0].bsid) {
info->ec3_done = 1;
goto concatenate;
}
} else {
if (hdr->substreamid != 0) {
avpriv_request_sample(mov->fc, "Multiple non EAC3 independent substreams");
ret = AVERROR_PATCHWELCOME;
goto end;
}
}
/* fill the info needed for the "dec3" atom */
info->substream[hdr->substreamid].fscod = hdr->sr_code;
info->substream[hdr->substreamid].bsid = hdr->bitstream_id;
info->substream[hdr->substreamid].bsmod = hdr->bitstream_mode;
info->substream[hdr->substreamid].acmod = hdr->channel_mode;
info->substream[hdr->substreamid].lfeon = hdr->lfe_on;
/* Parse dependent substream(s), if any */
if (pkt->size != hdr->frame_size) {
int cumul_size = hdr->frame_size;
int parent = hdr->substreamid;
while (cumul_size != pkt->size) {
GetBitContext gbc;
int i;
ret = avpriv_ac3_parse_header(&hdr, pkt->data + cumul_size, pkt->size - cumul_size);
if (ret < 0)
goto end;
if (hdr->frame_type != EAC3_FRAME_TYPE_DEPENDENT) {
ret = AVERROR(EINVAL);
goto end;
}
info->substream[parent].num_dep_sub++;
ret /= 8;
/* header is parsed up to lfeon, but custom channel map may be needed */
init_get_bits8(&gbc, pkt->data + cumul_size + ret, pkt->size - cumul_size - ret);
/* skip bsid */
skip_bits(&gbc, 5);
/* skip volume control params */
for (i = 0; i < (hdr->channel_mode ? 1 : 2); i++) {
skip_bits(&gbc, 5); // skip dialog normalization
if (get_bits1(&gbc)) {
skip_bits(&gbc, 8); // skip compression gain word
}
}
/* get the dependent stream channel map, if exists */
if (get_bits1(&gbc))
info->substream[parent].chan_loc |= (get_bits(&gbc, 16) >> 5) & 0x1f;
else
info->substream[parent].chan_loc |= hdr->channel_mode;
cumul_size += hdr->frame_size;
}
}
}
concatenate:
if (!info->num_blocks && num_blocks == 6) {
ret = pkt->size;
goto end;
}
else if (info->num_blocks + num_blocks > 6) {
ret = AVERROR_INVALIDDATA;
goto end;
}
if (!info->num_blocks) {
ret = av_packet_ref(&info->pkt, pkt);
if (!ret)
info->num_blocks = num_blocks;
goto end;
} else {
if ((ret = av_grow_packet(&info->pkt, pkt->size)) < 0)
goto end;
memcpy(info->pkt.data + info->pkt.size - pkt->size, pkt->data, pkt->size);
info->num_blocks += num_blocks;
info->pkt.duration += pkt->duration;
if ((ret = av_copy_packet_side_data(&info->pkt, pkt)) < 0)
goto end;
if (info->num_blocks != 6)
goto end;
av_packet_unref(pkt);
av_packet_move_ref(pkt, &info->pkt);
info->num_blocks = 0;
}
ret = pkt->size;
end:
av_free(hdr);
return ret;
}
#endif
static int mov_write_eac3_tag(AVIOContext *pb, MOVTrack *track)
{
PutBitContext pbc;
uint8_t *buf;
struct eac3_info *info;
int size, i;
if (!track->eac3_priv)
return AVERROR(EINVAL);
info = track->eac3_priv;
size = 2 + 4 * (info->num_ind_sub + 1);
buf = av_malloc(size);
if (!buf) {
size = AVERROR(ENOMEM);
goto end;
}
init_put_bits(&pbc, buf, size);
put_bits(&pbc, 13, info->data_rate);
put_bits(&pbc, 3, info->num_ind_sub);
for (i = 0; i <= info->num_ind_sub; i++) {
put_bits(&pbc, 2, info->substream[i].fscod);
put_bits(&pbc, 5, info->substream[i].bsid);
put_bits(&pbc, 1, 0); /* reserved */
put_bits(&pbc, 1, 0); /* asvc */
put_bits(&pbc, 3, info->substream[i].bsmod);
put_bits(&pbc, 3, info->substream[i].acmod);
put_bits(&pbc, 1, info->substream[i].lfeon);
put_bits(&pbc, 5, 0); /* reserved */
put_bits(&pbc, 4, info->substream[i].num_dep_sub);
if (!info->substream[i].num_dep_sub) {
put_bits(&pbc, 1, 0); /* reserved */
size--;
} else {
put_bits(&pbc, 9, info->substream[i].chan_loc);
}
}
flush_put_bits(&pbc);
avio_wb32(pb, size + 8);
ffio_wfourcc(pb, "dec3");
avio_write(pb, buf, size);
av_free(buf);
end:
av_packet_unref(&info->pkt);
av_freep(&track->eac3_priv);
return size;
}
/**
* This function writes extradata "as is".
* Extradata must be formatted like a valid atom (with size and tag).
*/
static int mov_write_extradata_tag(AVIOContext *pb, MOVTrack *track)
{
avio_write(pb, track->par->extradata, track->par->extradata_size);
return track->par->extradata_size;
}
static int mov_write_enda_tag(AVIOContext *pb)
{
avio_wb32(pb, 10);
ffio_wfourcc(pb, "enda");
avio_wb16(pb, 1); /* little endian */
return 10;
}
static int mov_write_enda_tag_be(AVIOContext *pb)
{
avio_wb32(pb, 10);
ffio_wfourcc(pb, "enda");
avio_wb16(pb, 0); /* big endian */
return 10;
}
static void put_descr(AVIOContext *pb, int tag, unsigned int size)
{
int i = 3;
avio_w8(pb, tag);
for (; i > 0; i--)
avio_w8(pb, (size >> (7 * i)) | 0x80);
avio_w8(pb, size & 0x7F);
}
static unsigned compute_avg_bitrate(MOVTrack *track)
{
uint64_t size = 0;
int i;
if (!track->track_duration)
return 0;
for (i = 0; i < track->entry; i++)
size += track->cluster[i].size;
return size * 8 * track->timescale / track->track_duration;
}
static int mov_write_esds_tag(AVIOContext *pb, MOVTrack *track) // Basic
{
AVCPBProperties *props;
int64_t pos = avio_tell(pb);
int decoder_specific_info_len = track->vos_len ? 5 + track->vos_len : 0;
unsigned avg_bitrate;
avio_wb32(pb, 0); // size
ffio_wfourcc(pb, "esds");
avio_wb32(pb, 0); // Version
// ES descriptor
put_descr(pb, 0x03, 3 + 5+13 + decoder_specific_info_len + 5+1);
avio_wb16(pb, track->track_id);
avio_w8(pb, 0x00); // flags (= no flags)
// DecoderConfig descriptor
put_descr(pb, 0x04, 13 + decoder_specific_info_len);
// Object type indication
if ((track->par->codec_id == AV_CODEC_ID_MP2 ||
track->par->codec_id == AV_CODEC_ID_MP3) &&
track->par->sample_rate > 24000)
avio_w8(pb, 0x6B); // 11172-3
else
avio_w8(pb, ff_codec_get_tag(ff_mp4_obj_type, track->par->codec_id));
// the following fields is made of 6 bits to identify the streamtype (4 for video, 5 for audio)
// plus 1 bit to indicate upstream and 1 bit set to 1 (reserved)
if (track->par->codec_id == AV_CODEC_ID_DVD_SUBTITLE)
avio_w8(pb, (0x38 << 2) | 1); // flags (= NeroSubpicStream)
else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO)
avio_w8(pb, 0x15); // flags (= Audiostream)
else
avio_w8(pb, 0x11); // flags (= Visualstream)
props = (AVCPBProperties*)av_stream_get_side_data(track->st, AV_PKT_DATA_CPB_PROPERTIES,
NULL);
avio_wb24(pb, props ? props->buffer_size / 8 : 0); // Buffersize DB
avg_bitrate = compute_avg_bitrate(track);
avio_wb32(pb, props ? FFMAX3(props->max_bitrate, props->avg_bitrate, avg_bitrate) : FFMAX(track->par->bit_rate, avg_bitrate)); // maxbitrate (FIXME should be max rate in any 1 sec window)
avio_wb32(pb, avg_bitrate);
if (track->vos_len) {
// DecoderSpecific info descriptor
put_descr(pb, 0x05, track->vos_len);
avio_write(pb, track->vos_data, track->vos_len);
}
// SL descriptor
put_descr(pb, 0x06, 1);
avio_w8(pb, 0x02);
return update_size(pb, pos);
}
static int mov_pcm_le_gt16(enum AVCodecID codec_id)
{
return codec_id == AV_CODEC_ID_PCM_S24LE ||
codec_id == AV_CODEC_ID_PCM_S32LE ||
codec_id == AV_CODEC_ID_PCM_F32LE ||
codec_id == AV_CODEC_ID_PCM_F64LE;
}
static int mov_pcm_be_gt16(enum AVCodecID codec_id)
{
return codec_id == AV_CODEC_ID_PCM_S24BE ||
codec_id == AV_CODEC_ID_PCM_S32BE ||
codec_id == AV_CODEC_ID_PCM_F32BE ||
codec_id == AV_CODEC_ID_PCM_F64BE;
}
static int mov_write_ms_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
{
int ret;
int64_t pos = avio_tell(pb);
avio_wb32(pb, 0);
avio_wl32(pb, track->tag); // store it byteswapped
track->par->codec_tag = av_bswap16(track->tag >> 16);
if ((ret = ff_put_wav_header(s, pb, track->par, 0)) < 0)
return ret;
return update_size(pb, pos);
}
static int mov_write_wfex_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
{
int ret;
int64_t pos = avio_tell(pb);
avio_wb32(pb, 0);
ffio_wfourcc(pb, "wfex");
if ((ret = ff_put_wav_header(s, pb, track->st->codecpar, FF_PUT_WAV_HEADER_FORCE_WAVEFORMATEX)) < 0)
return ret;
return update_size(pb, pos);
}
static int mov_write_dfla_tag(AVIOContext *pb, MOVTrack *track)
{
int64_t pos = avio_tell(pb);
avio_wb32(pb, 0);
ffio_wfourcc(pb, "dfLa");
avio_w8(pb, 0); /* version */
avio_wb24(pb, 0); /* flags */
/* Expect the encoder to pass a METADATA_BLOCK_TYPE_STREAMINFO. */
if (track->par->extradata_size != FLAC_STREAMINFO_SIZE)
return AVERROR_INVALIDDATA;
/* TODO: Write other METADATA_BLOCK_TYPEs if the encoder makes them available. */
avio_w8(pb, 1 << 7 | FLAC_METADATA_TYPE_STREAMINFO); /* LastMetadataBlockFlag << 7 | BlockType */
avio_wb24(pb, track->par->extradata_size); /* Length */
avio_write(pb, track->par->extradata, track->par->extradata_size); /* BlockData[Length] */
return update_size(pb, pos);
}
static int mov_write_dops_tag(AVIOContext *pb, MOVTrack *track)
{
int64_t pos = avio_tell(pb);
avio_wb32(pb, 0);
ffio_wfourcc(pb, "dOps");
avio_w8(pb, 0); /* Version */
if (track->par->extradata_size < 19) {
av_log(pb, AV_LOG_ERROR, "invalid extradata size\n");
return AVERROR_INVALIDDATA;
}
/* extradata contains an Ogg OpusHead, other than byte-ordering and
OpusHead's preceeding magic/version, OpusSpecificBox is currently
identical. */
avio_w8(pb, AV_RB8(track->par->extradata + 9)); /* OuputChannelCount */
avio_wb16(pb, AV_RL16(track->par->extradata + 10)); /* PreSkip */
avio_wb32(pb, AV_RL32(track->par->extradata + 12)); /* InputSampleRate */
avio_wb16(pb, AV_RL16(track->par->extradata + 16)); /* OutputGain */
/* Write the rest of the header out without byte-swapping. */
avio_write(pb, track->par->extradata + 18, track->par->extradata_size - 18);
return update_size(pb, pos);
}
static int mov_write_chan_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
{
uint32_t layout_tag, bitmap;
int64_t pos = avio_tell(pb);
layout_tag = ff_mov_get_channel_layout_tag(track->par->codec_id,
track->par->channel_layout,
&bitmap);
if (!layout_tag) {
av_log(s, AV_LOG_WARNING, "not writing 'chan' tag due to "
"lack of channel information\n");
return 0;
}
if (track->multichannel_as_mono)
return 0;
avio_wb32(pb, 0); // Size
ffio_wfourcc(pb, "chan"); // Type
avio_w8(pb, 0); // Version
avio_wb24(pb, 0); // Flags
avio_wb32(pb, layout_tag); // mChannelLayoutTag
avio_wb32(pb, bitmap); // mChannelBitmap
avio_wb32(pb, 0); // mNumberChannelDescriptions
return update_size(pb, pos);
}
static int mov_write_wave_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
{
int64_t pos = avio_tell(pb);
avio_wb32(pb, 0); /* size */
ffio_wfourcc(pb, "wave");
if (track->par->codec_id != AV_CODEC_ID_QDM2) {
avio_wb32(pb, 12); /* size */
ffio_wfourcc(pb, "frma");
avio_wl32(pb, track->tag);
}
if (track->par->codec_id == AV_CODEC_ID_AAC) {
/* useless atom needed by mplayer, ipod, not needed by quicktime */
avio_wb32(pb, 12); /* size */
ffio_wfourcc(pb, "mp4a");
avio_wb32(pb, 0);
mov_write_esds_tag(pb, track);
} else if (mov_pcm_le_gt16(track->par->codec_id)) {
mov_write_enda_tag(pb);
} else if (mov_pcm_be_gt16(track->par->codec_id)) {
mov_write_enda_tag_be(pb);
} else if (track->par->codec_id == AV_CODEC_ID_AMR_NB) {
mov_write_amr_tag(pb, track);
} else if (track->par->codec_id == AV_CODEC_ID_AC3) {
mov_write_ac3_tag(pb, track);
} else if (track->par->codec_id == AV_CODEC_ID_EAC3) {
mov_write_eac3_tag(pb, track);
} else if (track->par->codec_id == AV_CODEC_ID_ALAC ||
track->par->codec_id == AV_CODEC_ID_QDM2) {
mov_write_extradata_tag(pb, track);
} else if (track->par->codec_id == AV_CODEC_ID_ADPCM_MS ||
track->par->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV) {
mov_write_ms_tag(s, pb, track);
}
avio_wb32(pb, 8); /* size */
avio_wb32(pb, 0); /* null tag */
return update_size(pb, pos);
}
static int mov_write_dvc1_structs(MOVTrack *track, uint8_t *buf)
{
uint8_t *unescaped;
const uint8_t *start, *next, *end = track->vos_data + track->vos_len;
int unescaped_size, seq_found = 0;
int level = 0, interlace = 0;
int packet_seq = track->vc1_info.packet_seq;
int packet_entry = track->vc1_info.packet_entry;
int slices = track->vc1_info.slices;
PutBitContext pbc;
if (track->start_dts == AV_NOPTS_VALUE) {
/* No packets written yet, vc1_info isn't authoritative yet. */
/* Assume inline sequence and entry headers. */
packet_seq = packet_entry = 1;
av_log(NULL, AV_LOG_WARNING,
"moov atom written before any packets, unable to write correct "
"dvc1 atom. Set the delay_moov flag to fix this.\n");
}
unescaped = av_mallocz(track->vos_len + AV_INPUT_BUFFER_PADDING_SIZE);
if (!unescaped)
return AVERROR(ENOMEM);
start = find_next_marker(track->vos_data, end);
for (next = start; next < end; start = next) {
GetBitContext gb;
int size;
next = find_next_marker(start + 4, end);
size = next - start - 4;
if (size <= 0)
continue;
unescaped_size = vc1_unescape_buffer(start + 4, size, unescaped);
init_get_bits(&gb, unescaped, 8 * unescaped_size);
if (AV_RB32(start) == VC1_CODE_SEQHDR) {
int profile = get_bits(&gb, 2);
if (profile != PROFILE_ADVANCED) {
av_free(unescaped);
return AVERROR(ENOSYS);
}
seq_found = 1;
level = get_bits(&gb, 3);
/* chromaformat, frmrtq_postproc, bitrtq_postproc, postprocflag,
* width, height */
skip_bits_long(&gb, 2 + 3 + 5 + 1 + 2*12);
skip_bits(&gb, 1); /* broadcast */
interlace = get_bits1(&gb);
skip_bits(&gb, 4); /* tfcntrflag, finterpflag, reserved, psf */
}
}
if (!seq_found) {
av_free(unescaped);
return AVERROR(ENOSYS);
}
init_put_bits(&pbc, buf, 7);
/* VC1DecSpecStruc */
put_bits(&pbc, 4, 12); /* profile - advanced */
put_bits(&pbc, 3, level);
put_bits(&pbc, 1, 0); /* reserved */
/* VC1AdvDecSpecStruc */
put_bits(&pbc, 3, level);
put_bits(&pbc, 1, 0); /* cbr */
put_bits(&pbc, 6, 0); /* reserved */
put_bits(&pbc, 1, !interlace); /* no interlace */
put_bits(&pbc, 1, !packet_seq); /* no multiple seq */
put_bits(&pbc, 1, !packet_entry); /* no multiple entry */
put_bits(&pbc, 1, !slices); /* no slice code */
put_bits(&pbc, 1, 0); /* no bframe */
put_bits(&pbc, 1, 0); /* reserved */
/* framerate */
if (track->st->avg_frame_rate.num > 0 && track->st->avg_frame_rate.den > 0)
put_bits32(&pbc, track->st->avg_frame_rate.num / track->st->avg_frame_rate.den);
else
put_bits32(&pbc, 0xffffffff);
flush_put_bits(&pbc);
av_free(unescaped);
return 0;
}
static int mov_write_dvc1_tag(AVIOContext *pb, MOVTrack *track)
{
uint8_t buf[7] = { 0 };
int ret;
if ((ret = mov_write_dvc1_structs(track, buf)) < 0)
return ret;
avio_wb32(pb, track->vos_len + 8 + sizeof(buf));
ffio_wfourcc(pb, "dvc1");
avio_write(pb, buf, sizeof(buf));
avio_write(pb, track->vos_data, track->vos_len);
return 0;
}
static int mov_write_glbl_tag(AVIOContext *pb, MOVTrack *track)
{
avio_wb32(pb, track->vos_len + 8);
ffio_wfourcc(pb, "glbl");
avio_write(pb, track->vos_data, track->vos_len);
return 8 + track->vos_len;
}
/**
* Compute flags for 'lpcm' tag.
* See CoreAudioTypes and AudioStreamBasicDescription at Apple.
*/
static int mov_get_lpcm_flags(enum AVCodecID codec_id)
{
switch (codec_id) {
case AV_CODEC_ID_PCM_F32BE:
case AV_CODEC_ID_PCM_F64BE:
return 11;
case AV_CODEC_ID_PCM_F32LE:
case AV_CODEC_ID_PCM_F64LE:
return 9;
case AV_CODEC_ID_PCM_U8:
return 10;
case AV_CODEC_ID_PCM_S16BE:
case AV_CODEC_ID_PCM_S24BE:
case AV_CODEC_ID_PCM_S32BE:
return 14;
case AV_CODEC_ID_PCM_S8:
case AV_CODEC_ID_PCM_S16LE:
case AV_CODEC_ID_PCM_S24LE:
case AV_CODEC_ID_PCM_S32LE:
return 12;
default:
return 0;
}
}
static int get_cluster_duration(MOVTrack *track, int cluster_idx)
{
int64_t next_dts;
if (cluster_idx >= track->entry)
return 0;
if (cluster_idx + 1 == track->entry)
next_dts = track->track_duration + track->start_dts;
else
next_dts = track->cluster[cluster_idx + 1].dts;
next_dts -= track->cluster[cluster_idx].dts;
av_assert0(next_dts >= 0);
av_assert0(next_dts <= INT_MAX);
return next_dts;
}
static int get_samples_per_packet(MOVTrack *track)
{
int i, first_duration;
// return track->par->frame_size;
/* use 1 for raw PCM */
if (!track->audio_vbr)
return 1;
/* check to see if duration is constant for all clusters */
if (!track->entry)
return 0;
first_duration = get_cluster_duration(track, 0);
for (i = 1; i < track->entry; i++) {
if (get_cluster_duration(track, i) != first_duration)
return 0;
}
return first_duration;
}
static int mov_write_audio_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track)
{
int64_t pos = avio_tell(pb);
int version = 0;
uint32_t tag = track->tag;
if (track->mode == MODE_MOV) {
if (track->timescale > UINT16_MAX) {
if (mov_get_lpcm_flags(track->par->codec_id))
tag = AV_RL32("lpcm");
version = 2;
} else if (track->audio_vbr || mov_pcm_le_gt16(track->par->codec_id) ||
mov_pcm_be_gt16(track->par->codec_id) ||
track->par->codec_id == AV_CODEC_ID_ADPCM_MS ||
track->par->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV ||
track->par->codec_id == AV_CODEC_ID_QDM2) {
version = 1;
}
}
avio_wb32(pb, 0); /* size */
if (mov->encryption_scheme != MOV_ENC_NONE) {
ffio_wfourcc(pb, "enca");
} else {
avio_wl32(pb, tag); // store it byteswapped
}
avio_wb32(pb, 0); /* Reserved */
avio_wb16(pb, 0); /* Reserved */
avio_wb16(pb, 1); /* Data-reference index, XXX == 1 */
/* SoundDescription */
avio_wb16(pb, version); /* Version */
avio_wb16(pb, 0); /* Revision level */
avio_wb32(pb, 0); /* Reserved */
if (version == 2) {
avio_wb16(pb, 3);
avio_wb16(pb, 16);
avio_wb16(pb, 0xfffe);
avio_wb16(pb, 0);
avio_wb32(pb, 0x00010000);
avio_wb32(pb, 72);
avio_wb64(pb, av_double2int(track->par->sample_rate));
avio_wb32(pb, track->par->channels);
avio_wb32(pb, 0x7F000000);
avio_wb32(pb, av_get_bits_per_sample(track->par->codec_id));
avio_wb32(pb, mov_get_lpcm_flags(track->par->codec_id));
avio_wb32(pb, track->sample_size);
avio_wb32(pb, get_samples_per_packet(track));
} else {
if (track->mode == MODE_MOV) {
avio_wb16(pb, track->par->channels);
if (track->par->codec_id == AV_CODEC_ID_PCM_U8 ||
track->par->codec_id == AV_CODEC_ID_PCM_S8)
avio_wb16(pb, 8); /* bits per sample */
else if (track->par->codec_id == AV_CODEC_ID_ADPCM_G726)
avio_wb16(pb, track->par->bits_per_coded_sample);
else
avio_wb16(pb, 16);
avio_wb16(pb, track->audio_vbr ? -2 : 0); /* compression ID */
} else { /* reserved for mp4/3gp */
if (track->par->codec_id == AV_CODEC_ID_FLAC ||
track->par->codec_id == AV_CODEC_ID_OPUS) {
avio_wb16(pb, track->par->channels);
} else {
avio_wb16(pb, 2);
}
if (track->par->codec_id == AV_CODEC_ID_FLAC) {
avio_wb16(pb, track->par->bits_per_raw_sample);
} else {
avio_wb16(pb, 16);
}
avio_wb16(pb, 0);
}
avio_wb16(pb, 0); /* packet size (= 0) */
if (track->par->codec_id == AV_CODEC_ID_OPUS)
avio_wb16(pb, 48000);
else
avio_wb16(pb, track->par->sample_rate <= UINT16_MAX ?
track->par->sample_rate : 0);
avio_wb16(pb, 0); /* Reserved */
}
if (version == 1) { /* SoundDescription V1 extended info */
if (mov_pcm_le_gt16(track->par->codec_id) ||
mov_pcm_be_gt16(track->par->codec_id))
avio_wb32(pb, 1); /* must be 1 for uncompressed formats */
else
avio_wb32(pb, track->par->frame_size); /* Samples per packet */
avio_wb32(pb, track->sample_size / track->par->channels); /* Bytes per packet */
avio_wb32(pb, track->sample_size); /* Bytes per frame */
avio_wb32(pb, 2); /* Bytes per sample */
}
if (track->mode == MODE_MOV &&
(track->par->codec_id == AV_CODEC_ID_AAC ||
track->par->codec_id == AV_CODEC_ID_AC3 ||
track->par->codec_id == AV_CODEC_ID_EAC3 ||
track->par->codec_id == AV_CODEC_ID_AMR_NB ||
track->par->codec_id == AV_CODEC_ID_ALAC ||
track->par->codec_id == AV_CODEC_ID_ADPCM_MS ||
track->par->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV ||
track->par->codec_id == AV_CODEC_ID_QDM2 ||
(mov_pcm_le_gt16(track->par->codec_id) && version==1) ||
(mov_pcm_be_gt16(track->par->codec_id) && version==1)))
mov_write_wave_tag(s, pb, track);
else if (track->tag == MKTAG('m','p','4','a'))
mov_write_esds_tag(pb, track);
else if (track->par->codec_id == AV_CODEC_ID_AMR_NB)
mov_write_amr_tag(pb, track);
else if (track->par->codec_id == AV_CODEC_ID_AC3)
mov_write_ac3_tag(pb, track);
else if (track->par->codec_id == AV_CODEC_ID_EAC3)
mov_write_eac3_tag(pb, track);
else if (track->par->codec_id == AV_CODEC_ID_ALAC)
mov_write_extradata_tag(pb, track);
else if (track->par->codec_id == AV_CODEC_ID_WMAPRO)
mov_write_wfex_tag(s, pb, track);
else if (track->par->codec_id == AV_CODEC_ID_FLAC)
mov_write_dfla_tag(pb, track);
else if (track->par->codec_id == AV_CODEC_ID_OPUS)
mov_write_dops_tag(pb, track);
else if (track->vos_len > 0)
mov_write_glbl_tag(pb, track);
if (track->mode == MODE_MOV && track->par->codec_type == AVMEDIA_TYPE_AUDIO)
mov_write_chan_tag(s, pb, track);
if (mov->encryption_scheme != MOV_ENC_NONE) {
ff_mov_cenc_write_sinf_tag(track, pb, mov->encryption_kid);
}
return update_size(pb, pos);
}
static int mov_write_d263_tag(AVIOContext *pb)
{
avio_wb32(pb, 0xf); /* size */
ffio_wfourcc(pb, "d263");
ffio_wfourcc(pb, "FFMP");
avio_w8(pb, 0); /* decoder version */
/* FIXME use AVCodecContext level/profile, when encoder will set values */
avio_w8(pb, 0xa); /* level */
avio_w8(pb, 0); /* profile */
return 0xf;
}
static int mov_write_avcc_tag(AVIOContext *pb, MOVTrack *track)
{
int64_t pos = avio_tell(pb);
avio_wb32(pb, 0);
ffio_wfourcc(pb, "avcC");
ff_isom_write_avcc(pb, track->vos_data, track->vos_len);
return update_size(pb, pos);
}
static int mov_write_vpcc_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
{
int64_t pos = avio_tell(pb);
avio_wb32(pb, 0);
ffio_wfourcc(pb, "vpcC");
avio_w8(pb, 1); /* version */
avio_wb24(pb, 0); /* flags */
ff_isom_write_vpcc(s, pb, track->par);
return update_size(pb, pos);
}
static int mov_write_hvcc_tag(AVIOContext *pb, MOVTrack *track)
{
int64_t pos = avio_tell(pb);
avio_wb32(pb, 0);
ffio_wfourcc(pb, "hvcC");
if (track->tag == MKTAG('h','v','c','1'))
ff_isom_write_hvcc(pb, track->vos_data, track->vos_len, 1);
else
ff_isom_write_hvcc(pb, track->vos_data, track->vos_len, 0);
return update_size(pb, pos);
}
/* also used by all avid codecs (dv, imx, meridien) and their variants */
static int mov_write_avid_tag(AVIOContext *pb, MOVTrack *track)
{
int i;
int interlaced;
int cid;
int display_width = track->par->width;
if (track->vos_data && track->vos_len > 0x29) {
if (ff_dnxhd_parse_header_prefix(track->vos_data) != 0) {
/* looks like a DNxHD bit stream */
interlaced = (track->vos_data[5] & 2);
cid = AV_RB32(track->vos_data + 0x28);
} else {
av_log(NULL, AV_LOG_WARNING, "Could not locate DNxHD bit stream in vos_data\n");
return 0;
}
} else {
av_log(NULL, AV_LOG_WARNING, "Could not locate DNxHD bit stream, vos_data too small\n");
return 0;
}
avio_wb32(pb, 24); /* size */
ffio_wfourcc(pb, "ACLR");
ffio_wfourcc(pb, "ACLR");
ffio_wfourcc(pb, "0001");
if (track->par->color_range == AVCOL_RANGE_MPEG || /* Legal range (16-235) */
track->par->color_range == AVCOL_RANGE_UNSPECIFIED) {
avio_wb32(pb, 1); /* Corresponds to 709 in official encoder */
} else { /* Full range (0-255) */
avio_wb32(pb, 2); /* Corresponds to RGB in official encoder */
}
avio_wb32(pb, 0); /* unknown */
if (track->tag == MKTAG('A','V','d','h')) {
avio_wb32(pb, 32);
ffio_wfourcc(pb, "ADHR");
ffio_wfourcc(pb, "0001");
avio_wb32(pb, cid);
avio_wb32(pb, 0); /* unknown */
avio_wb32(pb, 1); /* unknown */
avio_wb32(pb, 0); /* unknown */
avio_wb32(pb, 0); /* unknown */
return 0;
}
avio_wb32(pb, 24); /* size */
ffio_wfourcc(pb, "APRG");
ffio_wfourcc(pb, "APRG");
ffio_wfourcc(pb, "0001");
avio_wb32(pb, 1); /* unknown */
avio_wb32(pb, 0); /* unknown */
avio_wb32(pb, 120); /* size */
ffio_wfourcc(pb, "ARES");
ffio_wfourcc(pb, "ARES");
ffio_wfourcc(pb, "0001");
avio_wb32(pb, cid); /* dnxhd cid, some id ? */
if ( track->par->sample_aspect_ratio.num > 0
&& track->par->sample_aspect_ratio.den > 0)
display_width = display_width * track->par->sample_aspect_ratio.num / track->par->sample_aspect_ratio.den;
avio_wb32(pb, display_width);
/* values below are based on samples created with quicktime and avid codecs */
if (interlaced) {
avio_wb32(pb, track->par->height / 2);
avio_wb32(pb, 2); /* unknown */
avio_wb32(pb, 0); /* unknown */
avio_wb32(pb, 4); /* unknown */
} else {
avio_wb32(pb, track->par->height);
avio_wb32(pb, 1); /* unknown */
avio_wb32(pb, 0); /* unknown */
if (track->par->height == 1080)
avio_wb32(pb, 5); /* unknown */
else
avio_wb32(pb, 6); /* unknown */
}
/* padding */
for (i = 0; i < 10; i++)
avio_wb64(pb, 0);
return 0;
}
static int mov_write_dpxe_tag(AVIOContext *pb, MOVTrack *track)
{
avio_wb32(pb, 12);
ffio_wfourcc(pb, "DpxE");
if (track->par->extradata_size >= 12 &&
!memcmp(&track->par->extradata[4], "DpxE", 4)) {
avio_wb32(pb, track->par->extradata[11]);
} else {
avio_wb32(pb, 1);
}
return 0;
}
static int mov_get_dv_codec_tag(AVFormatContext *s, MOVTrack *track)
{
int tag;
if (track->par->width == 720) { /* SD */
if (track->par->height == 480) { /* NTSC */
if (track->par->format == AV_PIX_FMT_YUV422P) tag = MKTAG('d','v','5','n');
else tag = MKTAG('d','v','c',' ');
}else if (track->par->format == AV_PIX_FMT_YUV422P) tag = MKTAG('d','v','5','p');
else if (track->par->format == AV_PIX_FMT_YUV420P) tag = MKTAG('d','v','c','p');
else tag = MKTAG('d','v','p','p');
} else if (track->par->height == 720) { /* HD 720 line */
if (track->st->time_base.den == 50) tag = MKTAG('d','v','h','q');
else tag = MKTAG('d','v','h','p');
} else if (track->par->height == 1080) { /* HD 1080 line */
if (track->st->time_base.den == 25) tag = MKTAG('d','v','h','5');
else tag = MKTAG('d','v','h','6');
} else {
av_log(s, AV_LOG_ERROR, "unsupported height for dv codec\n");
return 0;
}
return tag;
}
static AVRational find_fps(AVFormatContext *s, AVStream *st)
{
AVRational rate = st->avg_frame_rate;
#if FF_API_LAVF_AVCTX
FF_DISABLE_DEPRECATION_WARNINGS
rate = av_inv_q(st->codec->time_base);
if (av_timecode_check_frame_rate(rate) < 0) {
av_log(s, AV_LOG_DEBUG, "timecode: tbc=%d/%d invalid, fallback on %d/%d\n",
rate.num, rate.den, st->avg_frame_rate.num, st->avg_frame_rate.den);
rate = st->avg_frame_rate;
}
FF_ENABLE_DEPRECATION_WARNINGS
#endif
return rate;
}
static int defined_frame_rate(AVFormatContext *s, AVStream *st)
{
AVRational rational_framerate = find_fps(s, st);
int rate = 0;
if (rational_framerate.den != 0)
rate = av_q2d(rational_framerate);
return rate;
}
static int mov_get_mpeg2_xdcam_codec_tag(AVFormatContext *s, MOVTrack *track)
{
int tag = track->par->codec_tag;
int interlaced = track->par->field_order > AV_FIELD_PROGRESSIVE;
AVStream *st = track->st;
int rate = defined_frame_rate(s, st);
if (!tag)
tag = MKTAG('m', '2', 'v', '1'); //fallback tag
if (track->par->format == AV_PIX_FMT_YUV420P) {
if (track->par->width == 1280 && track->par->height == 720) {
if (!interlaced) {
if (rate == 24) tag = MKTAG('x','d','v','4');
else if (rate == 25) tag = MKTAG('x','d','v','5');
else if (rate == 30) tag = MKTAG('x','d','v','1');
else if (rate == 50) tag = MKTAG('x','d','v','a');
else if (rate == 60) tag = MKTAG('x','d','v','9');
}
} else if (track->par->width == 1440 && track->par->height == 1080) {
if (!interlaced) {
if (rate == 24) tag = MKTAG('x','d','v','6');
else if (rate == 25) tag = MKTAG('x','d','v','7');
else if (rate == 30) tag = MKTAG('x','d','v','8');
} else {
if (rate == 25) tag = MKTAG('x','d','v','3');
else if (rate == 30) tag = MKTAG('x','d','v','2');
}
} else if (track->par->width == 1920 && track->par->height == 1080) {
if (!interlaced) {
if (rate == 24) tag = MKTAG('x','d','v','d');
else if (rate == 25) tag = MKTAG('x','d','v','e');
else if (rate == 30) tag = MKTAG('x','d','v','f');
} else {
if (rate == 25) tag = MKTAG('x','d','v','c');
else if (rate == 30) tag = MKTAG('x','d','v','b');
}
}
} else if (track->par->format == AV_PIX_FMT_YUV422P) {
if (track->par->width == 1280 && track->par->height == 720) {
if (!interlaced) {
if (rate == 24) tag = MKTAG('x','d','5','4');
else if (rate == 25) tag = MKTAG('x','d','5','5');
else if (rate == 30) tag = MKTAG('x','d','5','1');
else if (rate == 50) tag = MKTAG('x','d','5','a');
else if (rate == 60) tag = MKTAG('x','d','5','9');
}
} else if (track->par->width == 1920 && track->par->height == 1080) {
if (!interlaced) {
if (rate == 24) tag = MKTAG('x','d','5','d');
else if (rate == 25) tag = MKTAG('x','d','5','e');
else if (rate == 30) tag = MKTAG('x','d','5','f');
} else {
if (rate == 25) tag = MKTAG('x','d','5','c');
else if (rate == 30) tag = MKTAG('x','d','5','b');
}
}
}
return tag;
}
static int mov_get_h264_codec_tag(AVFormatContext *s, MOVTrack *track)
{
int tag = track->par->codec_tag;
int interlaced = track->par->field_order > AV_FIELD_PROGRESSIVE;
AVStream *st = track->st;
int rate = defined_frame_rate(s, st);
if (!tag)
tag = MKTAG('a', 'v', 'c', 'i'); //fallback tag
if (track->par->format == AV_PIX_FMT_YUV420P10) {
if (track->par->width == 960 && track->par->height == 720) {
if (!interlaced) {
if (rate == 24) tag = MKTAG('a','i','5','p');
else if (rate == 25) tag = MKTAG('a','i','5','q');
else if (rate == 30) tag = MKTAG('a','i','5','p');
else if (rate == 50) tag = MKTAG('a','i','5','q');
else if (rate == 60) tag = MKTAG('a','i','5','p');
}
} else if (track->par->width == 1440 && track->par->height == 1080) {
if (!interlaced) {
if (rate == 24) tag = MKTAG('a','i','5','3');
else if (rate == 25) tag = MKTAG('a','i','5','2');
else if (rate == 30) tag = MKTAG('a','i','5','3');
} else {
if (rate == 50) tag = MKTAG('a','i','5','5');
else if (rate == 60) tag = MKTAG('a','i','5','6');
}
}
} else if (track->par->format == AV_PIX_FMT_YUV422P10) {
if (track->par->width == 1280 && track->par->height == 720) {
if (!interlaced) {
if (rate == 24) tag = MKTAG('a','i','1','p');
else if (rate == 25) tag = MKTAG('a','i','1','q');
else if (rate == 30) tag = MKTAG('a','i','1','p');
else if (rate == 50) tag = MKTAG('a','i','1','q');
else if (rate == 60) tag = MKTAG('a','i','1','p');
}
} else if (track->par->width == 1920 && track->par->height == 1080) {
if (!interlaced) {
if (rate == 24) tag = MKTAG('a','i','1','3');
else if (rate == 25) tag = MKTAG('a','i','1','2');
else if (rate == 30) tag = MKTAG('a','i','1','3');
} else {
if (rate == 25) tag = MKTAG('a','i','1','5');
else if (rate == 50) tag = MKTAG('a','i','1','5');
else if (rate == 60) tag = MKTAG('a','i','1','6');
}
} else if ( track->par->width == 4096 && track->par->height == 2160
|| track->par->width == 3840 && track->par->height == 2160
|| track->par->width == 2048 && track->par->height == 1080) {
tag = MKTAG('a','i','v','x');
}
}
return tag;
}
static const struct {
enum AVPixelFormat pix_fmt;
uint32_t tag;
unsigned bps;
} mov_pix_fmt_tags[] = {
{ AV_PIX_FMT_YUYV422, MKTAG('y','u','v','2'), 0 },
{ AV_PIX_FMT_YUYV422, MKTAG('y','u','v','s'), 0 },
{ AV_PIX_FMT_UYVY422, MKTAG('2','v','u','y'), 0 },
{ AV_PIX_FMT_RGB555BE,MKTAG('r','a','w',' '), 16 },
{ AV_PIX_FMT_RGB555LE,MKTAG('L','5','5','5'), 16 },
{ AV_PIX_FMT_RGB565LE,MKTAG('L','5','6','5'), 16 },
{ AV_PIX_FMT_RGB565BE,MKTAG('B','5','6','5'), 16 },
{ AV_PIX_FMT_GRAY16BE,MKTAG('b','1','6','g'), 16 },
{ AV_PIX_FMT_RGB24, MKTAG('r','a','w',' '), 24 },
{ AV_PIX_FMT_BGR24, MKTAG('2','4','B','G'), 24 },
{ AV_PIX_FMT_ARGB, MKTAG('r','a','w',' '), 32 },
{ AV_PIX_FMT_BGRA, MKTAG('B','G','R','A'), 32 },
{ AV_PIX_FMT_RGBA, MKTAG('R','G','B','A'), 32 },
{ AV_PIX_FMT_ABGR, MKTAG('A','B','G','R'), 32 },
{ AV_PIX_FMT_RGB48BE, MKTAG('b','4','8','r'), 48 },
};
static int mov_get_dnxhd_codec_tag(AVFormatContext *s, MOVTrack *track)
{
int tag = MKTAG('A','V','d','n');
if (track->par->profile != FF_PROFILE_UNKNOWN &&
track->par->profile != FF_PROFILE_DNXHD)
tag = MKTAG('A','V','d','h');
return tag;
}
static int mov_get_rawvideo_codec_tag(AVFormatContext *s, MOVTrack *track)
{
int tag = track->par->codec_tag;
int i;
enum AVPixelFormat pix_fmt;
for (i = 0; i < FF_ARRAY_ELEMS(mov_pix_fmt_tags); i++) {
if (track->par->format == mov_pix_fmt_tags[i].pix_fmt) {
tag = mov_pix_fmt_tags[i].tag;
track->par->bits_per_coded_sample = mov_pix_fmt_tags[i].bps;
if (track->par->codec_tag == mov_pix_fmt_tags[i].tag)
break;
}
}
pix_fmt = avpriv_find_pix_fmt(avpriv_pix_fmt_bps_mov,
track->par->bits_per_coded_sample);
if (tag == MKTAG('r','a','w',' ') &&
track->par->format != pix_fmt &&
track->par->format != AV_PIX_FMT_GRAY8 &&
track->par->format != AV_PIX_FMT_NONE)
av_log(s, AV_LOG_ERROR, "%s rawvideo cannot be written to mov, output file will be unreadable\n",
av_get_pix_fmt_name(track->par->format));
return tag;
}
static int mov_get_codec_tag(AVFormatContext *s, MOVTrack *track)
{
int tag = track->par->codec_tag;
if (!tag || (s->strict_std_compliance >= FF_COMPLIANCE_NORMAL &&
(track->par->codec_id == AV_CODEC_ID_DVVIDEO ||
track->par->codec_id == AV_CODEC_ID_RAWVIDEO ||
track->par->codec_id == AV_CODEC_ID_H263 ||
track->par->codec_id == AV_CODEC_ID_H264 ||
track->par->codec_id == AV_CODEC_ID_DNXHD ||
track->par->codec_id == AV_CODEC_ID_MPEG2VIDEO ||
av_get_bits_per_sample(track->par->codec_id)))) { // pcm audio
if (track->par->codec_id == AV_CODEC_ID_DVVIDEO)
tag = mov_get_dv_codec_tag(s, track);
else if (track->par->codec_id == AV_CODEC_ID_RAWVIDEO)
tag = mov_get_rawvideo_codec_tag(s, track);
else if (track->par->codec_id == AV_CODEC_ID_MPEG2VIDEO)
tag = mov_get_mpeg2_xdcam_codec_tag(s, track);
else if (track->par->codec_id == AV_CODEC_ID_H264)
tag = mov_get_h264_codec_tag(s, track);
else if (track->par->codec_id == AV_CODEC_ID_DNXHD)
tag = mov_get_dnxhd_codec_tag(s, track);
else if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) {
tag = ff_codec_get_tag(ff_codec_movvideo_tags, track->par->codec_id);
if (!tag) { // if no mac fcc found, try with Microsoft tags
tag = ff_codec_get_tag(ff_codec_bmp_tags, track->par->codec_id);
if (tag)
av_log(s, AV_LOG_WARNING, "Using MS style video codec tag, "
"the file may be unplayable!\n");
}
} else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO) {
tag = ff_codec_get_tag(ff_codec_movaudio_tags, track->par->codec_id);
if (!tag) { // if no mac fcc found, try with Microsoft tags
int ms_tag = ff_codec_get_tag(ff_codec_wav_tags, track->par->codec_id);
if (ms_tag) {
tag = MKTAG('m', 's', ((ms_tag >> 8) & 0xff), (ms_tag & 0xff));
av_log(s, AV_LOG_WARNING, "Using MS style audio codec tag, "
"the file may be unplayable!\n");
}
}
} else if (track->par->codec_type == AVMEDIA_TYPE_SUBTITLE)
tag = ff_codec_get_tag(ff_codec_movsubtitle_tags, track->par->codec_id);
}
return tag;
}
static const AVCodecTag codec_cover_image_tags[] = {
{ AV_CODEC_ID_MJPEG, 0xD },
{ AV_CODEC_ID_PNG, 0xE },
{ AV_CODEC_ID_BMP, 0x1B },
{ AV_CODEC_ID_NONE, 0 },
};
static int mov_find_codec_tag(AVFormatContext *s, MOVTrack *track)
{
int tag;
if (is_cover_image(track->st))
return ff_codec_get_tag(codec_cover_image_tags, track->par->codec_id);
if (track->mode == MODE_MP4 || track->mode == MODE_PSP)
tag = track->par->codec_tag;
else if (track->mode == MODE_ISM)
tag = track->par->codec_tag;
else if (track->mode == MODE_IPOD) {
if (!av_match_ext(s->url, "m4a") &&
!av_match_ext(s->url, "m4v") &&
!av_match_ext(s->url, "m4b"))
av_log(s, AV_LOG_WARNING, "Warning, extension is not .m4a nor .m4v "
"Quicktime/Ipod might not play the file\n");
tag = track->par->codec_tag;
} else if (track->mode & MODE_3GP)
tag = track->par->codec_tag;
else if (track->mode == MODE_F4V)
tag = track->par->codec_tag;
else
tag = mov_get_codec_tag(s, track);
return tag;
}
/** Write uuid atom.
* Needed to make file play in iPods running newest firmware
* goes after avcC atom in moov.trak.mdia.minf.stbl.stsd.avc1
*/
static int mov_write_uuid_tag_ipod(AVIOContext *pb)
{
avio_wb32(pb, 28);
ffio_wfourcc(pb, "uuid");
avio_wb32(pb, 0x6b6840f2);
avio_wb32(pb, 0x5f244fc5);
avio_wb32(pb, 0xba39a51b);
avio_wb32(pb, 0xcf0323f3);
avio_wb32(pb, 0x0);
return 28;
}
static const uint16_t fiel_data[] = {
0x0000, 0x0100, 0x0201, 0x0206, 0x0209, 0x020e
};
static int mov_write_fiel_tag(AVIOContext *pb, MOVTrack *track, int field_order)
{
unsigned mov_field_order = 0;
if (field_order < FF_ARRAY_ELEMS(fiel_data))
mov_field_order = fiel_data[field_order];
else
return 0;
avio_wb32(pb, 10);
ffio_wfourcc(pb, "fiel");
avio_wb16(pb, mov_field_order);
return 10;
}
static int mov_write_subtitle_tag(AVIOContext *pb, MOVTrack *track)
{
int64_t pos = avio_tell(pb);
avio_wb32(pb, 0); /* size */
avio_wl32(pb, track->tag); // store it byteswapped
avio_wb32(pb, 0); /* Reserved */
avio_wb16(pb, 0); /* Reserved */
avio_wb16(pb, 1); /* Data-reference index */
if (track->par->codec_id == AV_CODEC_ID_DVD_SUBTITLE)
mov_write_esds_tag(pb, track);
else if (track->par->extradata_size)
avio_write(pb, track->par->extradata, track->par->extradata_size);
return update_size(pb, pos);
}
static int mov_write_st3d_tag(AVIOContext *pb, AVStereo3D *stereo_3d)
{
int8_t stereo_mode;
if (stereo_3d->flags != 0) {
av_log(pb, AV_LOG_WARNING, "Unsupported stereo_3d flags %x. st3d not written.\n", stereo_3d->flags);
return 0;
}
switch (stereo_3d->type) {
case AV_STEREO3D_2D:
stereo_mode = 0;
break;
case AV_STEREO3D_TOPBOTTOM:
stereo_mode = 1;
break;
case AV_STEREO3D_SIDEBYSIDE:
stereo_mode = 2;
break;
default:
av_log(pb, AV_LOG_WARNING, "Unsupported stereo_3d type %s. st3d not written.\n", av_stereo3d_type_name(stereo_3d->type));
return 0;
}
avio_wb32(pb, 13); /* size */
ffio_wfourcc(pb, "st3d");
avio_wb32(pb, 0); /* version = 0 & flags = 0 */
avio_w8(pb, stereo_mode);
return 13;
}
static int mov_write_sv3d_tag(AVFormatContext *s, AVIOContext *pb, AVSphericalMapping *spherical_mapping)
{
int64_t sv3d_pos, svhd_pos, proj_pos;
const char* metadata_source = s->flags & AVFMT_FLAG_BITEXACT ? "Lavf" : LIBAVFORMAT_IDENT;
if (spherical_mapping->projection != AV_SPHERICAL_EQUIRECTANGULAR &&
spherical_mapping->projection != AV_SPHERICAL_EQUIRECTANGULAR_TILE &&
spherical_mapping->projection != AV_SPHERICAL_CUBEMAP) {
av_log(pb, AV_LOG_WARNING, "Unsupported projection %d. sv3d not written.\n", spherical_mapping->projection);
return 0;
}
sv3d_pos = avio_tell(pb);
avio_wb32(pb, 0); /* size */
ffio_wfourcc(pb, "sv3d");
svhd_pos = avio_tell(pb);
avio_wb32(pb, 0); /* size */
ffio_wfourcc(pb, "svhd");
avio_wb32(pb, 0); /* version = 0 & flags = 0 */
avio_put_str(pb, metadata_source);
update_size(pb, svhd_pos);
proj_pos = avio_tell(pb);
avio_wb32(pb, 0); /* size */
ffio_wfourcc(pb, "proj");
avio_wb32(pb, 24); /* size */
ffio_wfourcc(pb, "prhd");
avio_wb32(pb, 0); /* version = 0 & flags = 0 */
avio_wb32(pb, spherical_mapping->yaw);
avio_wb32(pb, spherical_mapping->pitch);
avio_wb32(pb, spherical_mapping->roll);
switch (spherical_mapping->projection) {
case AV_SPHERICAL_EQUIRECTANGULAR:
case AV_SPHERICAL_EQUIRECTANGULAR_TILE:
avio_wb32(pb, 28); /* size */
ffio_wfourcc(pb, "equi");
avio_wb32(pb, 0); /* version = 0 & flags = 0 */
avio_wb32(pb, spherical_mapping->bound_top);
avio_wb32(pb, spherical_mapping->bound_bottom);
avio_wb32(pb, spherical_mapping->bound_left);
avio_wb32(pb, spherical_mapping->bound_right);
break;
case AV_SPHERICAL_CUBEMAP:
avio_wb32(pb, 20); /* size */
ffio_wfourcc(pb, "cbmp");
avio_wb32(pb, 0); /* version = 0 & flags = 0 */
avio_wb32(pb, 0); /* layout */
avio_wb32(pb, spherical_mapping->padding); /* padding */
break;
}
update_size(pb, proj_pos);
return update_size(pb, sv3d_pos);
}
static int mov_write_clap_tag(AVIOContext *pb, MOVTrack *track)
{
avio_wb32(pb, 40);
ffio_wfourcc(pb, "clap");
avio_wb32(pb, track->par->width); /* apertureWidth_N */
avio_wb32(pb, 1); /* apertureWidth_D (= 1) */
avio_wb32(pb, track->height); /* apertureHeight_N */
avio_wb32(pb, 1); /* apertureHeight_D (= 1) */
avio_wb32(pb, 0); /* horizOff_N (= 0) */
avio_wb32(pb, 1); /* horizOff_D (= 1) */
avio_wb32(pb, 0); /* vertOff_N (= 0) */
avio_wb32(pb, 1); /* vertOff_D (= 1) */
return 40;
}
static int mov_write_pasp_tag(AVIOContext *pb, MOVTrack *track)
{
AVRational sar;
av_reduce(&sar.num, &sar.den, track->par->sample_aspect_ratio.num,
track->par->sample_aspect_ratio.den, INT_MAX);
avio_wb32(pb, 16);
ffio_wfourcc(pb, "pasp");
avio_wb32(pb, sar.num);
avio_wb32(pb, sar.den);
return 16;
}
static int mov_write_gama_tag(AVIOContext *pb, MOVTrack *track, double gamma)
{
uint32_t gama = 0;
if (gamma <= 0.0)
{
gamma = avpriv_get_gamma_from_trc(track->par->color_trc);
}
av_log(pb, AV_LOG_DEBUG, "gamma value %g\n", gamma);
if (gamma > 1e-6) {
gama = (uint32_t)lrint((double)(1<<16) * gamma);
av_log(pb, AV_LOG_DEBUG, "writing gama value %"PRId32"\n", gama);
av_assert0(track->mode == MODE_MOV);
avio_wb32(pb, 12);
ffio_wfourcc(pb, "gama");
avio_wb32(pb, gama);
return 12;
}
else {
av_log(pb, AV_LOG_WARNING, "gamma value unknown, unable to write gama atom\n");
}
return 0;
}
static int mov_write_colr_tag(AVIOContext *pb, MOVTrack *track)
{
// Ref (MOV): https://developer.apple.com/library/mac/technotes/tn2162/_index.html#//apple_ref/doc/uid/DTS40013070-CH1-TNTAG9
// Ref (MP4): ISO/IEC 14496-12:2012
if (track->par->color_primaries == AVCOL_PRI_UNSPECIFIED &&
track->par->color_trc == AVCOL_TRC_UNSPECIFIED &&
track->par->color_space == AVCOL_SPC_UNSPECIFIED) {
if ((track->par->width >= 1920 && track->par->height >= 1080)
|| (track->par->width == 1280 && track->par->height == 720)) {
av_log(NULL, AV_LOG_WARNING, "color primaries unspecified, assuming bt709\n");
track->par->color_primaries = AVCOL_PRI_BT709;
} else if (track->par->width == 720 && track->height == 576) {
av_log(NULL, AV_LOG_WARNING, "color primaries unspecified, assuming bt470bg\n");
track->par->color_primaries = AVCOL_PRI_BT470BG;
} else if (track->par->width == 720 &&
(track->height == 486 || track->height == 480)) {
av_log(NULL, AV_LOG_WARNING, "color primaries unspecified, assuming smpte170\n");
track->par->color_primaries = AVCOL_PRI_SMPTE170M;
} else {
av_log(NULL, AV_LOG_WARNING, "color primaries unspecified, unable to assume anything\n");
}
switch (track->par->color_primaries) {
case AVCOL_PRI_BT709:
track->par->color_trc = AVCOL_TRC_BT709;
track->par->color_space = AVCOL_SPC_BT709;
break;
case AVCOL_PRI_SMPTE170M:
case AVCOL_PRI_BT470BG:
track->par->color_trc = AVCOL_TRC_BT709;
track->par->color_space = AVCOL_SPC_SMPTE170M;
break;
}
}
/* We should only ever be called by MOV or MP4. */
av_assert0(track->mode == MODE_MOV || track->mode == MODE_MP4);
avio_wb32(pb, 18 + (track->mode == MODE_MP4));
ffio_wfourcc(pb, "colr");
if (track->mode == MODE_MP4)
ffio_wfourcc(pb, "nclx");
else
ffio_wfourcc(pb, "nclc");
switch (track->par->color_primaries) {
case AVCOL_PRI_BT709: avio_wb16(pb, 1); break;
case AVCOL_PRI_BT470BG: avio_wb16(pb, 5); break;
case AVCOL_PRI_SMPTE170M:
case AVCOL_PRI_SMPTE240M: avio_wb16(pb, 6); break;
case AVCOL_PRI_BT2020: avio_wb16(pb, 9); break;
case AVCOL_PRI_SMPTE431: avio_wb16(pb, 11); break;
case AVCOL_PRI_SMPTE432: avio_wb16(pb, 12); break;
default: avio_wb16(pb, 2);
}
switch (track->par->color_trc) {
case AVCOL_TRC_BT709: avio_wb16(pb, 1); break;
case AVCOL_TRC_SMPTE170M: avio_wb16(pb, 1); break; // remapped
case AVCOL_TRC_SMPTE240M: avio_wb16(pb, 7); break;
case AVCOL_TRC_SMPTEST2084: avio_wb16(pb, 16); break;
case AVCOL_TRC_SMPTE428: avio_wb16(pb, 17); break;
case AVCOL_TRC_ARIB_STD_B67: avio_wb16(pb, 18); break;
default: avio_wb16(pb, 2);
}
switch (track->par->color_space) {
case AVCOL_SPC_BT709: avio_wb16(pb, 1); break;
case AVCOL_SPC_BT470BG:
case AVCOL_SPC_SMPTE170M: avio_wb16(pb, 6); break;
case AVCOL_SPC_SMPTE240M: avio_wb16(pb, 7); break;
case AVCOL_SPC_BT2020_NCL: avio_wb16(pb, 9); break;
default: avio_wb16(pb, 2);
}
if (track->mode == MODE_MP4) {
int full_range = track->par->color_range == AVCOL_RANGE_JPEG;
avio_w8(pb, full_range << 7);
return 19;
} else {
return 18;
}
}
static void find_compressor(char * compressor_name, int len, MOVTrack *track)
{
AVDictionaryEntry *encoder;
int xdcam_res = (track->par->width == 1280 && track->par->height == 720)
|| (track->par->width == 1440 && track->par->height == 1080)
|| (track->par->width == 1920 && track->par->height == 1080);
if (track->mode == MODE_MOV &&
(encoder = av_dict_get(track->st->metadata, "encoder", NULL, 0))) {
av_strlcpy(compressor_name, encoder->value, 32);
} else if (track->par->codec_id == AV_CODEC_ID_MPEG2VIDEO && xdcam_res) {
int interlaced = track->par->field_order > AV_FIELD_PROGRESSIVE;
AVStream *st = track->st;
int rate = defined_frame_rate(NULL, st);
av_strlcatf(compressor_name, len, "XDCAM");
if (track->par->format == AV_PIX_FMT_YUV422P) {
av_strlcatf(compressor_name, len, " HD422");
} else if(track->par->width == 1440) {
av_strlcatf(compressor_name, len, " HD");
} else
av_strlcatf(compressor_name, len, " EX");
av_strlcatf(compressor_name, len, " %d%c", track->par->height, interlaced ? 'i' : 'p');
av_strlcatf(compressor_name, len, "%d", rate * (interlaced + 1));
}
}
static int mov_write_video_tag(AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track)
{
int64_t pos = avio_tell(pb);
char compressor_name[32] = { 0 };
int avid = 0;
int uncompressed_ycbcr = ((track->par->codec_id == AV_CODEC_ID_RAWVIDEO && track->par->format == AV_PIX_FMT_UYVY422)
|| (track->par->codec_id == AV_CODEC_ID_RAWVIDEO && track->par->format == AV_PIX_FMT_YUYV422)
|| track->par->codec_id == AV_CODEC_ID_V308
|| track->par->codec_id == AV_CODEC_ID_V408
|| track->par->codec_id == AV_CODEC_ID_V410
|| track->par->codec_id == AV_CODEC_ID_V210);
avio_wb32(pb, 0); /* size */
if (mov->encryption_scheme != MOV_ENC_NONE) {
ffio_wfourcc(pb, "encv");
} else {
avio_wl32(pb, track->tag); // store it byteswapped
}
avio_wb32(pb, 0); /* Reserved */
avio_wb16(pb, 0); /* Reserved */
avio_wb16(pb, 1); /* Data-reference index */
if (uncompressed_ycbcr) {
avio_wb16(pb, 2); /* Codec stream version */
} else {
avio_wb16(pb, 0); /* Codec stream version */
}
avio_wb16(pb, 0); /* Codec stream revision (=0) */
if (track->mode == MODE_MOV) {
ffio_wfourcc(pb, "FFMP"); /* Vendor */
if (track->par->codec_id == AV_CODEC_ID_RAWVIDEO || uncompressed_ycbcr) {
avio_wb32(pb, 0); /* Temporal Quality */
avio_wb32(pb, 0x400); /* Spatial Quality = lossless*/
} else {
avio_wb32(pb, 0x200); /* Temporal Quality = normal */
avio_wb32(pb, 0x200); /* Spatial Quality = normal */
}
} else {
avio_wb32(pb, 0); /* Reserved */
avio_wb32(pb, 0); /* Reserved */
avio_wb32(pb, 0); /* Reserved */
}
avio_wb16(pb, track->par->width); /* Video width */
avio_wb16(pb, track->height); /* Video height */
avio_wb32(pb, 0x00480000); /* Horizontal resolution 72dpi */
avio_wb32(pb, 0x00480000); /* Vertical resolution 72dpi */
avio_wb32(pb, 0); /* Data size (= 0) */
avio_wb16(pb, 1); /* Frame count (= 1) */
/* FIXME not sure, ISO 14496-1 draft where it shall be set to 0 */
find_compressor(compressor_name, 32, track);
avio_w8(pb, strlen(compressor_name));
avio_write(pb, compressor_name, 31);
if (track->mode == MODE_MOV &&
(track->par->codec_id == AV_CODEC_ID_V410 || track->par->codec_id == AV_CODEC_ID_V210))
avio_wb16(pb, 0x18);
else if (track->mode == MODE_MOV && track->par->bits_per_coded_sample)
avio_wb16(pb, track->par->bits_per_coded_sample |
(track->par->format == AV_PIX_FMT_GRAY8 ? 0x20 : 0));
else
avio_wb16(pb, 0x18); /* Reserved */
if (track->mode == MODE_MOV && track->par->format == AV_PIX_FMT_PAL8) {
int pal_size = 1 << track->par->bits_per_coded_sample;
int i;
avio_wb16(pb, 0); /* Color table ID */
avio_wb32(pb, 0); /* Color table seed */
avio_wb16(pb, 0x8000); /* Color table flags */
avio_wb16(pb, pal_size - 1); /* Color table size (zero-relative) */
for (i = 0; i < pal_size; i++) {
uint32_t rgb = track->palette[i];
uint16_t r = (rgb >> 16) & 0xff;
uint16_t g = (rgb >> 8) & 0xff;
uint16_t b = rgb & 0xff;
avio_wb16(pb, 0);
avio_wb16(pb, (r << 8) | r);
avio_wb16(pb, (g << 8) | g);
avio_wb16(pb, (b << 8) | b);
}
} else
avio_wb16(pb, 0xffff); /* Reserved */
if (track->tag == MKTAG('m','p','4','v'))
mov_write_esds_tag(pb, track);
else if (track->par->codec_id == AV_CODEC_ID_H263)
mov_write_d263_tag(pb);
else if (track->par->codec_id == AV_CODEC_ID_AVUI ||
track->par->codec_id == AV_CODEC_ID_SVQ3) {
mov_write_extradata_tag(pb, track);
avio_wb32(pb, 0);
} else if (track->par->codec_id == AV_CODEC_ID_DNXHD) {
mov_write_avid_tag(pb, track);
avid = 1;
} else if (track->par->codec_id == AV_CODEC_ID_HEVC)
mov_write_hvcc_tag(pb, track);
else if (track->par->codec_id == AV_CODEC_ID_H264 && !TAG_IS_AVCI(track->tag)) {
mov_write_avcc_tag(pb, track);
if (track->mode == MODE_IPOD)
mov_write_uuid_tag_ipod(pb);
} else if (track->par->codec_id == AV_CODEC_ID_VP9) {
mov_write_vpcc_tag(mov->fc, pb, track);
} else if (track->par->codec_id == AV_CODEC_ID_VC1 && track->vos_len > 0)
mov_write_dvc1_tag(pb, track);
else if (track->par->codec_id == AV_CODEC_ID_VP6F ||
track->par->codec_id == AV_CODEC_ID_VP6A) {
/* Don't write any potential extradata here - the cropping
* is signalled via the normal width/height fields. */
} else if (track->par->codec_id == AV_CODEC_ID_R10K) {
if (track->par->codec_tag == MKTAG('R','1','0','k'))
mov_write_dpxe_tag(pb, track);
} else if (track->vos_len > 0)
mov_write_glbl_tag(pb, track);
if (track->par->codec_id != AV_CODEC_ID_H264 &&
track->par->codec_id != AV_CODEC_ID_MPEG4 &&
track->par->codec_id != AV_CODEC_ID_DNXHD) {
int field_order = track->par->field_order;
#if FF_API_LAVF_AVCTX
FF_DISABLE_DEPRECATION_WARNINGS
if (field_order != track->st->codec->field_order && track->st->codec->field_order != AV_FIELD_UNKNOWN)
field_order = track->st->codec->field_order;
FF_ENABLE_DEPRECATION_WARNINGS
#endif
if (field_order != AV_FIELD_UNKNOWN)
mov_write_fiel_tag(pb, track, field_order);
}
if (mov->flags & FF_MOV_FLAG_WRITE_GAMA) {
if (track->mode == MODE_MOV)
mov_write_gama_tag(pb, track, mov->gamma);
else
av_log(mov->fc, AV_LOG_WARNING, "Not writing 'gama' atom. Format is not MOV.\n");
}
if (mov->flags & FF_MOV_FLAG_WRITE_COLR) {
if (track->mode == MODE_MOV || track->mode == MODE_MP4)
mov_write_colr_tag(pb, track);
else
av_log(mov->fc, AV_LOG_WARNING, "Not writing 'colr' atom. Format is not MOV or MP4.\n");
}
if (track->mode == MODE_MP4 && mov->fc->strict_std_compliance <= FF_COMPLIANCE_UNOFFICIAL) {
AVStereo3D* stereo_3d = (AVStereo3D*) av_stream_get_side_data(track->st, AV_PKT_DATA_STEREO3D, NULL);
AVSphericalMapping* spherical_mapping = (AVSphericalMapping*)av_stream_get_side_data(track->st, AV_PKT_DATA_SPHERICAL, NULL);
if (stereo_3d)
mov_write_st3d_tag(pb, stereo_3d);
if (spherical_mapping)
mov_write_sv3d_tag(mov->fc, pb, spherical_mapping);
}
if (track->par->sample_aspect_ratio.den && track->par->sample_aspect_ratio.num) {
mov_write_pasp_tag(pb, track);
}
if (uncompressed_ycbcr){
mov_write_clap_tag(pb, track);
}
if (mov->encryption_scheme != MOV_ENC_NONE) {
ff_mov_cenc_write_sinf_tag(track, pb, mov->encryption_kid);
}
/* extra padding for avid stsd */
/* https://developer.apple.com/library/mac/documentation/QuickTime/QTFF/QTFFChap2/qtff2.html#//apple_ref/doc/uid/TP40000939-CH204-61112 */
if (avid)
avio_wb32(pb, 0);
return update_size(pb, pos);
}
static int mov_write_rtp_tag(AVIOContext *pb, MOVTrack *track)
{
int64_t pos = avio_tell(pb);
avio_wb32(pb, 0); /* size */
ffio_wfourcc(pb, "rtp ");
avio_wb32(pb, 0); /* Reserved */
avio_wb16(pb, 0); /* Reserved */
avio_wb16(pb, 1); /* Data-reference index */
avio_wb16(pb, 1); /* Hint track version */
avio_wb16(pb, 1); /* Highest compatible version */
avio_wb32(pb, track->max_packet_size); /* Max packet size */
avio_wb32(pb, 12); /* size */
ffio_wfourcc(pb, "tims");
avio_wb32(pb, track->timescale);
return update_size(pb, pos);
}
static int mov_write_source_reference_tag(AVIOContext *pb, MOVTrack *track, const char *reel_name)
{
uint64_t str_size =strlen(reel_name);
int64_t pos = avio_tell(pb);
if (str_size >= UINT16_MAX){
av_log(NULL, AV_LOG_ERROR, "reel_name length %"PRIu64" is too large\n", str_size);
avio_wb16(pb, 0);
return AVERROR(EINVAL);
}
avio_wb32(pb, 0); /* size */
ffio_wfourcc(pb, "name"); /* Data format */
avio_wb16(pb, str_size); /* string size */
avio_wb16(pb, track->language); /* langcode */
avio_write(pb, reel_name, str_size); /* reel name */
return update_size(pb,pos);
}
static int mov_write_tmcd_tag(AVIOContext *pb, MOVTrack *track)
{
int64_t pos = avio_tell(pb);
#if 1
int frame_duration;
int nb_frames;
AVDictionaryEntry *t = NULL;
if (!track->st->avg_frame_rate.num || !track->st->avg_frame_rate.den) {
#if FF_API_LAVF_AVCTX
FF_DISABLE_DEPRECATION_WARNINGS
frame_duration = av_rescale(track->timescale, track->st->codec->time_base.num, track->st->codec->time_base.den);
nb_frames = ROUNDED_DIV(track->st->codec->time_base.den, track->st->codec->time_base.num);
FF_ENABLE_DEPRECATION_WARNINGS
#else
av_log(NULL, AV_LOG_ERROR, "avg_frame_rate not set for tmcd track.\n");
return AVERROR(EINVAL);
#endif
} else {
frame_duration = av_rescale(track->timescale, track->st->avg_frame_rate.num, track->st->avg_frame_rate.den);
nb_frames = ROUNDED_DIV(track->st->avg_frame_rate.den, track->st->avg_frame_rate.num);
}
if (nb_frames > 255) {
av_log(NULL, AV_LOG_ERROR, "fps %d is too large\n", nb_frames);
return AVERROR(EINVAL);
}
avio_wb32(pb, 0); /* size */
ffio_wfourcc(pb, "tmcd"); /* Data format */
avio_wb32(pb, 0); /* Reserved */
avio_wb32(pb, 1); /* Data reference index */
avio_wb32(pb, 0); /* Flags */
avio_wb32(pb, track->timecode_flags); /* Flags (timecode) */
avio_wb32(pb, track->timescale); /* Timescale */
avio_wb32(pb, frame_duration); /* Frame duration */
avio_w8(pb, nb_frames); /* Number of frames */
avio_w8(pb, 0); /* Reserved */
t = av_dict_get(track->st->metadata, "reel_name", NULL, 0);
if (t && utf8len(t->value) && track->mode != MODE_MP4)
mov_write_source_reference_tag(pb, track, t->value);
else
avio_wb16(pb, 0); /* zero size */
#else
avio_wb32(pb, 0); /* size */
ffio_wfourcc(pb, "tmcd"); /* Data format */
avio_wb32(pb, 0); /* Reserved */
avio_wb32(pb, 1); /* Data reference index */
if (track->par->extradata_size)
avio_write(pb, track->par->extradata, track->par->extradata_size);
#endif
return update_size(pb, pos);
}
static int mov_write_gpmd_tag(AVIOContext *pb, const MOVTrack *track)
{
int64_t pos = avio_tell(pb);
avio_wb32(pb, 0); /* size */
ffio_wfourcc(pb, "gpmd");
avio_wb32(pb, 0); /* Reserved */
avio_wb16(pb, 0); /* Reserved */
avio_wb16(pb, 1); /* Data-reference index */
avio_wb32(pb, 0); /* Reserved */
return update_size(pb, pos);
}
static int mov_write_stsd_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track)
{
int64_t pos = avio_tell(pb);
avio_wb32(pb, 0); /* size */
ffio_wfourcc(pb, "stsd");
avio_wb32(pb, 0); /* version & flags */
avio_wb32(pb, 1); /* entry count */
if (track->par->codec_type == AVMEDIA_TYPE_VIDEO)
mov_write_video_tag(pb, mov, track);
else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO)
mov_write_audio_tag(s, pb, mov, track);
else if (track->par->codec_type == AVMEDIA_TYPE_SUBTITLE)
mov_write_subtitle_tag(pb, track);
else if (track->par->codec_tag == MKTAG('r','t','p',' '))
mov_write_rtp_tag(pb, track);
else if (track->par->codec_tag == MKTAG('t','m','c','d'))
mov_write_tmcd_tag(pb, track);
else if (track->par->codec_tag == MKTAG('g','p','m','d'))
mov_write_gpmd_tag(pb, track);
return update_size(pb, pos);
}
static int mov_write_ctts_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
{
MOVMuxContext *mov = s->priv_data;
MOVStts *ctts_entries;
uint32_t entries = 0;
uint32_t atom_size;
int i;
ctts_entries = av_malloc_array((track->entry + 1), sizeof(*ctts_entries)); /* worst case */
if (!ctts_entries)
return AVERROR(ENOMEM);
ctts_entries[0].count = 1;
ctts_entries[0].duration = track->cluster[0].cts;
for (i = 1; i < track->entry; i++) {
if (track->cluster[i].cts == ctts_entries[entries].duration) {
ctts_entries[entries].count++; /* compress */
} else {
entries++;
ctts_entries[entries].duration = track->cluster[i].cts;
ctts_entries[entries].count = 1;
}
}
entries++; /* last one */
atom_size = 16 + (entries * 8);
avio_wb32(pb, atom_size); /* size */
ffio_wfourcc(pb, "ctts");
if (mov->flags & FF_MOV_FLAG_NEGATIVE_CTS_OFFSETS)
avio_w8(pb, 1); /* version */
else
avio_w8(pb, 0); /* version */
avio_wb24(pb, 0); /* flags */
avio_wb32(pb, entries); /* entry count */
for (i = 0; i < entries; i++) {
avio_wb32(pb, ctts_entries[i].count);
avio_wb32(pb, ctts_entries[i].duration);
}
av_free(ctts_entries);
return atom_size;
}
/* Time to sample atom */
static int mov_write_stts_tag(AVIOContext *pb, MOVTrack *track)
{
MOVStts *stts_entries = NULL;
uint32_t entries = -1;
uint32_t atom_size;
int i;
if (track->par->codec_type == AVMEDIA_TYPE_AUDIO && !track->audio_vbr) {
stts_entries = av_malloc(sizeof(*stts_entries)); /* one entry */
if (!stts_entries)
return AVERROR(ENOMEM);
stts_entries[0].count = track->sample_count;
stts_entries[0].duration = 1;
entries = 1;
} else {
if (track->entry) {
stts_entries = av_malloc_array(track->entry, sizeof(*stts_entries)); /* worst case */
if (!stts_entries)
return AVERROR(ENOMEM);
}
for (i = 0; i < track->entry; i++) {
int duration = get_cluster_duration(track, i);
if (i && duration == stts_entries[entries].duration) {
stts_entries[entries].count++; /* compress */
} else {
entries++;
stts_entries[entries].duration = duration;
stts_entries[entries].count = 1;
}
}
entries++; /* last one */
}
atom_size = 16 + (entries * 8);
avio_wb32(pb, atom_size); /* size */
ffio_wfourcc(pb, "stts");
avio_wb32(pb, 0); /* version & flags */
avio_wb32(pb, entries); /* entry count */
for (i = 0; i < entries; i++) {
avio_wb32(pb, stts_entries[i].count);
avio_wb32(pb, stts_entries[i].duration);
}
av_free(stts_entries);
return atom_size;
}
static int mov_write_dref_tag(AVIOContext *pb)
{
avio_wb32(pb, 28); /* size */
ffio_wfourcc(pb, "dref");
avio_wb32(pb, 0); /* version & flags */
avio_wb32(pb, 1); /* entry count */
avio_wb32(pb, 0xc); /* size */
//FIXME add the alis and rsrc atom
ffio_wfourcc(pb, "url ");
avio_wb32(pb, 1); /* version & flags */
return 28;
}
static int mov_preroll_write_stbl_atoms(AVIOContext *pb, MOVTrack *track)
{
struct sgpd_entry {
int count;
int16_t roll_distance;
int group_description_index;
};
struct sgpd_entry *sgpd_entries = NULL;
int entries = -1;
int group = 0;
int i, j;
const int OPUS_SEEK_PREROLL_MS = 80;
int roll_samples = av_rescale_q(OPUS_SEEK_PREROLL_MS,
(AVRational){1, 1000},
(AVRational){1, 48000});
if (!track->entry)
return 0;
sgpd_entries = av_malloc_array(track->entry, sizeof(*sgpd_entries));
if (!sgpd_entries)
return AVERROR(ENOMEM);
av_assert0(track->par->codec_id == AV_CODEC_ID_OPUS || track->par->codec_id == AV_CODEC_ID_AAC);
if (track->par->codec_id == AV_CODEC_ID_OPUS) {
for (i = 0; i < track->entry; i++) {
int roll_samples_remaining = roll_samples;
int distance = 0;
for (j = i - 1; j >= 0; j--) {
roll_samples_remaining -= get_cluster_duration(track, j);
distance++;
if (roll_samples_remaining <= 0)
break;
}
/* We don't have enough preceeding samples to compute a valid
roll_distance here, so this sample can't be independently
decoded. */
if (roll_samples_remaining > 0)
distance = 0;
/* Verify distance is a minimum of 2 (60ms) packets and a maximum of
32 (2.5ms) packets. */
av_assert0(distance == 0 || (distance >= 2 && distance <= 32));
if (i && distance == sgpd_entries[entries].roll_distance) {
sgpd_entries[entries].count++;
} else {
entries++;
sgpd_entries[entries].count = 1;
sgpd_entries[entries].roll_distance = distance;
sgpd_entries[entries].group_description_index = distance ? ++group : 0;
}
}
} else {
entries++;
sgpd_entries[entries].count = track->sample_count;
sgpd_entries[entries].roll_distance = 1;
sgpd_entries[entries].group_description_index = ++group;
}
entries++;
if (!group) {
av_free(sgpd_entries);
return 0;
}
/* Write sgpd tag */
avio_wb32(pb, 24 + (group * 2)); /* size */
ffio_wfourcc(pb, "sgpd");
avio_wb32(pb, 1 << 24); /* fullbox */
ffio_wfourcc(pb, "roll");
avio_wb32(pb, 2); /* default_length */
avio_wb32(pb, group); /* entry_count */
for (i = 0; i < entries; i++) {
if (sgpd_entries[i].group_description_index) {
avio_wb16(pb, -sgpd_entries[i].roll_distance); /* roll_distance */
}
}
/* Write sbgp tag */
avio_wb32(pb, 20 + (entries * 8)); /* size */
ffio_wfourcc(pb, "sbgp");
avio_wb32(pb, 0); /* fullbox */
ffio_wfourcc(pb, "roll");
avio_wb32(pb, entries); /* entry_count */
for (i = 0; i < entries; i++) {
avio_wb32(pb, sgpd_entries[i].count); /* sample_count */
avio_wb32(pb, sgpd_entries[i].group_description_index); /* group_description_index */
}
av_free(sgpd_entries);
return 0;
}
static int mov_write_stbl_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track)
{
int64_t pos = avio_tell(pb);
int ret;
avio_wb32(pb, 0); /* size */
ffio_wfourcc(pb, "stbl");
mov_write_stsd_tag(s, pb, mov, track);
mov_write_stts_tag(pb, track);
if ((track->par->codec_type == AVMEDIA_TYPE_VIDEO ||
track->par->codec_tag == MKTAG('r','t','p',' ')) &&
track->has_keyframes && track->has_keyframes < track->entry)
mov_write_stss_tag(pb, track, MOV_SYNC_SAMPLE);
if (track->par->codec_type == AVMEDIA_TYPE_VIDEO && track->has_disposable)
mov_write_sdtp_tag(pb, track);
if (track->mode == MODE_MOV && track->flags & MOV_TRACK_STPS)
mov_write_stss_tag(pb, track, MOV_PARTIAL_SYNC_SAMPLE);
if (track->par->codec_type == AVMEDIA_TYPE_VIDEO &&
track->flags & MOV_TRACK_CTTS && track->entry) {
if ((ret = mov_write_ctts_tag(s, pb, track)) < 0)
return ret;
}
mov_write_stsc_tag(pb, track);
mov_write_stsz_tag(pb, track);
mov_write_stco_tag(pb, track);
if (track->cenc.aes_ctr) {
ff_mov_cenc_write_stbl_atoms(&track->cenc, pb);
}
if (track->par->codec_id == AV_CODEC_ID_OPUS || track->par->codec_id == AV_CODEC_ID_AAC) {
mov_preroll_write_stbl_atoms(pb, track);
}
return update_size(pb, pos);
}
static int mov_write_dinf_tag(AVIOContext *pb)
{
int64_t pos = avio_tell(pb);
avio_wb32(pb, 0); /* size */
ffio_wfourcc(pb, "dinf");
mov_write_dref_tag(pb);
return update_size(pb, pos);
}
static int mov_write_nmhd_tag(AVIOContext *pb)
{
avio_wb32(pb, 12);
ffio_wfourcc(pb, "nmhd");
avio_wb32(pb, 0);
return 12;
}
static int mov_write_tcmi_tag(AVIOContext *pb, MOVTrack *track)
{
int64_t pos = avio_tell(pb);
const char *font = "Lucida Grande";
avio_wb32(pb, 0); /* size */
ffio_wfourcc(pb, "tcmi"); /* timecode media information atom */
avio_wb32(pb, 0); /* version & flags */
avio_wb16(pb, 0); /* text font */
avio_wb16(pb, 0); /* text face */
avio_wb16(pb, 12); /* text size */
avio_wb16(pb, 0); /* (unknown, not in the QT specs...) */
avio_wb16(pb, 0x0000); /* text color (red) */
avio_wb16(pb, 0x0000); /* text color (green) */
avio_wb16(pb, 0x0000); /* text color (blue) */
avio_wb16(pb, 0xffff); /* background color (red) */
avio_wb16(pb, 0xffff); /* background color (green) */
avio_wb16(pb, 0xffff); /* background color (blue) */
avio_w8(pb, strlen(font)); /* font len (part of the pascal string) */
avio_write(pb, font, strlen(font)); /* font name */
return update_size(pb, pos);
}
static int mov_write_gmhd_tag(AVIOContext *pb, MOVTrack *track)
{
int64_t pos = avio_tell(pb);
avio_wb32(pb, 0); /* size */
ffio_wfourcc(pb, "gmhd");
avio_wb32(pb, 0x18); /* gmin size */
ffio_wfourcc(pb, "gmin");/* generic media info */
avio_wb32(pb, 0); /* version & flags */
avio_wb16(pb, 0x40); /* graphics mode = */
avio_wb16(pb, 0x8000); /* opColor (r?) */
avio_wb16(pb, 0x8000); /* opColor (g?) */
avio_wb16(pb, 0x8000); /* opColor (b?) */
avio_wb16(pb, 0); /* balance */
avio_wb16(pb, 0); /* reserved */
/*
* This special text atom is required for
* Apple Quicktime chapters. The contents
* don't appear to be documented, so the
* bytes are copied verbatim.
*/
if (track->tag != MKTAG('c','6','0','8')) {
avio_wb32(pb, 0x2C); /* size */
ffio_wfourcc(pb, "text");
avio_wb16(pb, 0x01);
avio_wb32(pb, 0x00);
avio_wb32(pb, 0x00);
avio_wb32(pb, 0x00);
avio_wb32(pb, 0x01);
avio_wb32(pb, 0x00);
avio_wb32(pb, 0x00);
avio_wb32(pb, 0x00);
avio_wb32(pb, 0x00004000);
avio_wb16(pb, 0x0000);
}
if (track->par->codec_tag == MKTAG('t','m','c','d')) {
int64_t tmcd_pos = avio_tell(pb);
avio_wb32(pb, 0); /* size */
ffio_wfourcc(pb, "tmcd");
mov_write_tcmi_tag(pb, track);
update_size(pb, tmcd_pos);
} else if (track->par->codec_tag == MKTAG('g','p','m','d')) {
int64_t gpmd_pos = avio_tell(pb);
avio_wb32(pb, 0); /* size */
ffio_wfourcc(pb, "gpmd");
avio_wb32(pb, 0); /* version */
update_size(pb, gpmd_pos);
}
return update_size(pb, pos);
}
static int mov_write_smhd_tag(AVIOContext *pb)
{
avio_wb32(pb, 16); /* size */
ffio_wfourcc(pb, "smhd");
avio_wb32(pb, 0); /* version & flags */
avio_wb16(pb, 0); /* reserved (balance, normally = 0) */
avio_wb16(pb, 0); /* reserved */
return 16;
}
static int mov_write_vmhd_tag(AVIOContext *pb)
{
avio_wb32(pb, 0x14); /* size (always 0x14) */
ffio_wfourcc(pb, "vmhd");
avio_wb32(pb, 0x01); /* version & flags */
avio_wb64(pb, 0); /* reserved (graphics mode = copy) */
return 0x14;
}
static int is_clcp_track(MOVTrack *track)
{
return track->tag == MKTAG('c','7','0','8') ||
track->tag == MKTAG('c','6','0','8');
}
static int mov_write_hdlr_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
{
MOVMuxContext *mov = s->priv_data;
const char *hdlr, *descr = NULL, *hdlr_type = NULL;
int64_t pos = avio_tell(pb);
hdlr = "dhlr";
hdlr_type = "url ";
descr = "DataHandler";
if (track) {
hdlr = (track->mode == MODE_MOV) ? "mhlr" : "\0\0\0\0";
if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) {
hdlr_type = "vide";
descr = "VideoHandler";
} else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO) {
hdlr_type = "soun";
descr = "SoundHandler";
} else if (track->par->codec_type == AVMEDIA_TYPE_SUBTITLE) {
if (is_clcp_track(track)) {
hdlr_type = "clcp";
descr = "ClosedCaptionHandler";
} else {
if (track->tag == MKTAG('t','x','3','g')) {
hdlr_type = "sbtl";
} else if (track->tag == MKTAG('m','p','4','s')) {
hdlr_type = "subp";
} else {
hdlr_type = "text";
}
descr = "SubtitleHandler";
}
} else if (track->par->codec_tag == MKTAG('r','t','p',' ')) {
hdlr_type = "hint";
descr = "HintHandler";
} else if (track->par->codec_tag == MKTAG('t','m','c','d')) {
hdlr_type = "tmcd";
descr = "TimeCodeHandler";
} else if (track->par->codec_tag == MKTAG('g','p','m','d')) {
hdlr_type = "meta";
descr = "GoPro MET"; // GoPro Metadata
} else {
av_log(s, AV_LOG_WARNING,
"Unknown hldr_type for %s, writing dummy values\n",
av_fourcc2str(track->par->codec_tag));
}
if (track->st) {
// hdlr.name is used by some players to identify the content title
// of the track. So if an alternate handler description is
// specified, use it.
AVDictionaryEntry *t;
t = av_dict_get(track->st->metadata, "handler_name", NULL, 0);
if (t && utf8len(t->value))
descr = t->value;
}
}
if (mov->empty_hdlr_name) /* expressly allowed by QTFF and not prohibited in ISO 14496-12 8.4.3.3 */
descr = "";
avio_wb32(pb, 0); /* size */
ffio_wfourcc(pb, "hdlr");
avio_wb32(pb, 0); /* Version & flags */
avio_write(pb, hdlr, 4); /* handler */
ffio_wfourcc(pb, hdlr_type); /* handler type */
avio_wb32(pb, 0); /* reserved */
avio_wb32(pb, 0); /* reserved */
avio_wb32(pb, 0); /* reserved */
if (!track || track->mode == MODE_MOV)
avio_w8(pb, strlen(descr)); /* pascal string */
avio_write(pb, descr, strlen(descr)); /* handler description */
if (track && track->mode != MODE_MOV)
avio_w8(pb, 0); /* c string */
return update_size(pb, pos);
}
static int mov_write_hmhd_tag(AVIOContext *pb)
{
/* This atom must be present, but leaving the values at zero
* seems harmless. */
avio_wb32(pb, 28); /* size */
ffio_wfourcc(pb, "hmhd");
avio_wb32(pb, 0); /* version, flags */
avio_wb16(pb, 0); /* maxPDUsize */
avio_wb16(pb, 0); /* avgPDUsize */
avio_wb32(pb, 0); /* maxbitrate */
avio_wb32(pb, 0); /* avgbitrate */
avio_wb32(pb, 0); /* reserved */
return 28;
}
static int mov_write_minf_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track)
{
int64_t pos = avio_tell(pb);
int ret;
avio_wb32(pb, 0); /* size */
ffio_wfourcc(pb, "minf");
if (track->par->codec_type == AVMEDIA_TYPE_VIDEO)
mov_write_vmhd_tag(pb);
else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO)
mov_write_smhd_tag(pb);
else if (track->par->codec_type == AVMEDIA_TYPE_SUBTITLE) {
if (track->tag == MKTAG('t','e','x','t') || is_clcp_track(track)) {
mov_write_gmhd_tag(pb, track);
} else {
mov_write_nmhd_tag(pb);
}
} else if (track->tag == MKTAG('r','t','p',' ')) {
mov_write_hmhd_tag(pb);
} else if (track->tag == MKTAG('t','m','c','d')) {
if (track->mode != MODE_MOV)
mov_write_nmhd_tag(pb);
else
mov_write_gmhd_tag(pb, track);
} else if (track->tag == MKTAG('g','p','m','d')) {
mov_write_gmhd_tag(pb, track);
}
if (track->mode == MODE_MOV) /* FIXME: Why do it for MODE_MOV only ? */
mov_write_hdlr_tag(s, pb, NULL);
mov_write_dinf_tag(pb);
if ((ret = mov_write_stbl_tag(s, pb, mov, track)) < 0)
return ret;
return update_size(pb, pos);
}
static int mov_write_mdhd_tag(AVIOContext *pb, MOVMuxContext *mov,
MOVTrack *track)
{
int version = track->track_duration < INT32_MAX ? 0 : 1;
if (track->mode == MODE_ISM)
version = 1;
(version == 1) ? avio_wb32(pb, 44) : avio_wb32(pb, 32); /* size */
ffio_wfourcc(pb, "mdhd");
avio_w8(pb, version);
avio_wb24(pb, 0); /* flags */
if (version == 1) {
avio_wb64(pb, track->time);
avio_wb64(pb, track->time);
} else {
avio_wb32(pb, track->time); /* creation time */
avio_wb32(pb, track->time); /* modification time */
}
avio_wb32(pb, track->timescale); /* time scale (sample rate for audio) */
if (!track->entry && mov->mode == MODE_ISM)
(version == 1) ? avio_wb64(pb, UINT64_C(0xffffffffffffffff)) : avio_wb32(pb, 0xffffffff);
else if (!track->entry)
(version == 1) ? avio_wb64(pb, 0) : avio_wb32(pb, 0);
else
(version == 1) ? avio_wb64(pb, track->track_duration) : avio_wb32(pb, track->track_duration); /* duration */
avio_wb16(pb, track->language); /* language */
avio_wb16(pb, 0); /* reserved (quality) */
if (version != 0 && track->mode == MODE_MOV) {
av_log(NULL, AV_LOG_ERROR,
"FATAL error, file duration too long for timebase, this file will not be\n"
"playable with quicktime. Choose a different timebase or a different\n"
"container format\n");
}
return 32;
}
static int mov_write_mdia_tag(AVFormatContext *s, AVIOContext *pb,
MOVMuxContext *mov, MOVTrack *track)
{
int64_t pos = avio_tell(pb);
int ret;
avio_wb32(pb, 0); /* size */
ffio_wfourcc(pb, "mdia");
mov_write_mdhd_tag(pb, mov, track);
mov_write_hdlr_tag(s, pb, track);
if ((ret = mov_write_minf_tag(s, pb, mov, track)) < 0)
return ret;
return update_size(pb, pos);
}
/* transformation matrix
|a b u|
|c d v|
|tx ty w| */
static void write_matrix(AVIOContext *pb, int16_t a, int16_t b, int16_t c,
int16_t d, int16_t tx, int16_t ty)
{
avio_wb32(pb, a << 16); /* 16.16 format */
avio_wb32(pb, b << 16); /* 16.16 format */
avio_wb32(pb, 0); /* u in 2.30 format */
avio_wb32(pb, c << 16); /* 16.16 format */
avio_wb32(pb, d << 16); /* 16.16 format */
avio_wb32(pb, 0); /* v in 2.30 format */
avio_wb32(pb, tx << 16); /* 16.16 format */
avio_wb32(pb, ty << 16); /* 16.16 format */
avio_wb32(pb, 1 << 30); /* w in 2.30 format */
}
static int mov_write_tkhd_tag(AVIOContext *pb, MOVMuxContext *mov,
MOVTrack *track, AVStream *st)
{
int64_t duration = av_rescale_rnd(track->track_duration, MOV_TIMESCALE,
track->timescale, AV_ROUND_UP);
int version = duration < INT32_MAX ? 0 : 1;
int flags = MOV_TKHD_FLAG_IN_MOVIE;
int rotation = 0;
int group = 0;
uint32_t *display_matrix = NULL;
int display_matrix_size, i;
if (st) {
if (mov->per_stream_grouping)
group = st->index;
else
group = st->codecpar->codec_type;
display_matrix = (uint32_t*)av_stream_get_side_data(st, AV_PKT_DATA_DISPLAYMATRIX,
&display_matrix_size);
if (display_matrix && display_matrix_size < 9 * sizeof(*display_matrix))
display_matrix = NULL;
}
if (track->flags & MOV_TRACK_ENABLED)
flags |= MOV_TKHD_FLAG_ENABLED;
if (track->mode == MODE_ISM)
version = 1;
(version == 1) ? avio_wb32(pb, 104) : avio_wb32(pb, 92); /* size */
ffio_wfourcc(pb, "tkhd");
avio_w8(pb, version);
avio_wb24(pb, flags);
if (version == 1) {
avio_wb64(pb, track->time);
avio_wb64(pb, track->time);
} else {
avio_wb32(pb, track->time); /* creation time */
avio_wb32(pb, track->time); /* modification time */
}
avio_wb32(pb, track->track_id); /* track-id */
avio_wb32(pb, 0); /* reserved */
if (!track->entry && mov->mode == MODE_ISM)
(version == 1) ? avio_wb64(pb, UINT64_C(0xffffffffffffffff)) : avio_wb32(pb, 0xffffffff);
else if (!track->entry)
(version == 1) ? avio_wb64(pb, 0) : avio_wb32(pb, 0);
else
(version == 1) ? avio_wb64(pb, duration) : avio_wb32(pb, duration);
avio_wb32(pb, 0); /* reserved */
avio_wb32(pb, 0); /* reserved */
avio_wb16(pb, 0); /* layer */
avio_wb16(pb, group); /* alternate group) */
/* Volume, only for audio */
if (track->par->codec_type == AVMEDIA_TYPE_AUDIO)
avio_wb16(pb, 0x0100);
else
avio_wb16(pb, 0);
avio_wb16(pb, 0); /* reserved */
/* Matrix structure */
#if FF_API_OLD_ROTATE_API
if (st && st->metadata) {
AVDictionaryEntry *rot = av_dict_get(st->metadata, "rotate", NULL, 0);
rotation = (rot && rot->value) ? atoi(rot->value) : 0;
}
#endif
if (display_matrix) {
for (i = 0; i < 9; i++)
avio_wb32(pb, display_matrix[i]);
#if FF_API_OLD_ROTATE_API
} else if (rotation == 90) {
write_matrix(pb, 0, 1, -1, 0, track->par->height, 0);
} else if (rotation == 180) {
write_matrix(pb, -1, 0, 0, -1, track->par->width, track->par->height);
} else if (rotation == 270) {
write_matrix(pb, 0, -1, 1, 0, 0, track->par->width);
#endif
} else {
write_matrix(pb, 1, 0, 0, 1, 0, 0);
}
/* Track width and height, for visual only */
if (st && (track->par->codec_type == AVMEDIA_TYPE_VIDEO ||
track->par->codec_type == AVMEDIA_TYPE_SUBTITLE)) {
int64_t track_width_1616;
if (track->mode == MODE_MOV) {
track_width_1616 = track->par->width * 0x10000ULL;
} else {
track_width_1616 = av_rescale(st->sample_aspect_ratio.num,
track->par->width * 0x10000LL,
st->sample_aspect_ratio.den);
if (!track_width_1616 ||
track->height != track->par->height ||
track_width_1616 > UINT32_MAX)
track_width_1616 = track->par->width * 0x10000ULL;
}
if (track_width_1616 > UINT32_MAX) {
av_log(mov->fc, AV_LOG_WARNING, "track width is too large\n");
track_width_1616 = 0;
}
avio_wb32(pb, track_width_1616);
if (track->height > 0xFFFF) {
av_log(mov->fc, AV_LOG_WARNING, "track height is too large\n");
avio_wb32(pb, 0);
} else
avio_wb32(pb, track->height * 0x10000U);
} else {
avio_wb32(pb, 0);
avio_wb32(pb, 0);
}
return 0x5c;
}
static int mov_write_tapt_tag(AVIOContext *pb, MOVTrack *track)
{
int32_t width = av_rescale(track->par->sample_aspect_ratio.num, track->par->width,
track->par->sample_aspect_ratio.den);
int64_t pos = avio_tell(pb);
avio_wb32(pb, 0); /* size */
ffio_wfourcc(pb, "tapt");
avio_wb32(pb, 20);
ffio_wfourcc(pb, "clef");
avio_wb32(pb, 0);
avio_wb32(pb, width << 16);
avio_wb32(pb, track->par->height << 16);
avio_wb32(pb, 20);
ffio_wfourcc(pb, "prof");
avio_wb32(pb, 0);
avio_wb32(pb, width << 16);
avio_wb32(pb, track->par->height << 16);
avio_wb32(pb, 20);
ffio_wfourcc(pb, "enof");
avio_wb32(pb, 0);
avio_wb32(pb, track->par->width << 16);
avio_wb32(pb, track->par->height << 16);
return update_size(pb, pos);
}
// This box seems important for the psp playback ... without it the movie seems to hang
static int mov_write_edts_tag(AVIOContext *pb, MOVMuxContext *mov,
MOVTrack *track)
{
int64_t duration = av_rescale_rnd(track->track_duration, MOV_TIMESCALE,
track->timescale, AV_ROUND_UP);
int version = duration < INT32_MAX ? 0 : 1;
int entry_size, entry_count, size;
int64_t delay, start_ct = track->start_cts;
int64_t start_dts = track->start_dts;
if (track->entry) {
if (start_dts != track->cluster[0].dts || start_ct != track->cluster[0].cts) {
av_log(mov->fc, AV_LOG_DEBUG,
"EDTS using dts:%"PRId64" cts:%d instead of dts:%"PRId64" cts:%"PRId64" tid:%d\n",
track->cluster[0].dts, track->cluster[0].cts,
start_dts, start_ct, track->track_id);
start_dts = track->cluster[0].dts;
start_ct = track->cluster[0].cts;
}
}
delay = av_rescale_rnd(start_dts + start_ct, MOV_TIMESCALE,
track->timescale, AV_ROUND_DOWN);
version |= delay < INT32_MAX ? 0 : 1;
entry_size = (version == 1) ? 20 : 12;
entry_count = 1 + (delay > 0);
size = 24 + entry_count * entry_size;
/* write the atom data */
avio_wb32(pb, size);
ffio_wfourcc(pb, "edts");
avio_wb32(pb, size - 8);
ffio_wfourcc(pb, "elst");
avio_w8(pb, version);
avio_wb24(pb, 0); /* flags */
avio_wb32(pb, entry_count);
if (delay > 0) { /* add an empty edit to delay presentation */
/* In the positive delay case, the delay includes the cts
* offset, and the second edit list entry below trims out
* the same amount from the actual content. This makes sure
* that the offset last sample is included in the edit
* list duration as well. */
if (version == 1) {
avio_wb64(pb, delay);
avio_wb64(pb, -1);
} else {
avio_wb32(pb, delay);
avio_wb32(pb, -1);
}
avio_wb32(pb, 0x00010000);
} else {
/* Avoid accidentally ending up with start_ct = -1 which has got a
* special meaning. Normally start_ct should end up positive or zero
* here, but use FFMIN in case dts is a small positive integer
* rounded to 0 when represented in MOV_TIMESCALE units. */
av_assert0(av_rescale_rnd(start_dts, MOV_TIMESCALE, track->timescale, AV_ROUND_DOWN) <= 0);
start_ct = -FFMIN(start_dts, 0);
/* Note, this delay is calculated from the pts of the first sample,
* ensuring that we don't reduce the duration for cases with
* dts<0 pts=0. */
duration += delay;
}
/* For fragmented files, we don't know the full length yet. Setting
* duration to 0 allows us to only specify the offset, including
* the rest of the content (from all future fragments) without specifying
* an explicit duration. */
if (mov->flags & FF_MOV_FLAG_FRAGMENT)
duration = 0;
/* duration */
if (version == 1) {
avio_wb64(pb, duration);
avio_wb64(pb, start_ct);
} else {
avio_wb32(pb, duration);
avio_wb32(pb, start_ct);
}
avio_wb32(pb, 0x00010000);
return size;
}
static int mov_write_tref_tag(AVIOContext *pb, MOVTrack *track)
{
avio_wb32(pb, 20); // size
ffio_wfourcc(pb, "tref");
avio_wb32(pb, 12); // size (subatom)
avio_wl32(pb, track->tref_tag);
avio_wb32(pb, track->tref_id);
return 20;
}
// goes at the end of each track! ... Critical for PSP playback ("Incompatible data" without it)
static int mov_write_uuid_tag_psp(AVIOContext *pb, MOVTrack *mov)
{
avio_wb32(pb, 0x34); /* size ... reports as 28 in mp4box! */
ffio_wfourcc(pb, "uuid");
ffio_wfourcc(pb, "USMT");
avio_wb32(pb, 0x21d24fce);
avio_wb32(pb, 0xbb88695c);
avio_wb32(pb, 0xfac9c740);
avio_wb32(pb, 0x1c); // another size here!
ffio_wfourcc(pb, "MTDT");
avio_wb32(pb, 0x00010012);
avio_wb32(pb, 0x0a);
avio_wb32(pb, 0x55c40000);
avio_wb32(pb, 0x1);
avio_wb32(pb, 0x0);
return 0x34;
}
static int mov_write_udta_sdp(AVIOContext *pb, MOVTrack *track)
{
AVFormatContext *ctx = track->rtp_ctx;
char buf[1000] = "";
int len;
ff_sdp_write_media(buf, sizeof(buf), ctx->streams[0], track->src_track,
NULL, NULL, 0, 0, ctx);
av_strlcatf(buf, sizeof(buf), "a=control:streamid=%d\r\n", track->track_id);
len = strlen(buf);
avio_wb32(pb, len + 24);
ffio_wfourcc(pb, "udta");
avio_wb32(pb, len + 16);
ffio_wfourcc(pb, "hnti");
avio_wb32(pb, len + 8);
ffio_wfourcc(pb, "sdp ");
avio_write(pb, buf, len);
return len + 24;
}
static int mov_write_track_metadata(AVIOContext *pb, AVStream *st,
const char *tag, const char *str)
{
int64_t pos = avio_tell(pb);
AVDictionaryEntry *t = av_dict_get(st->metadata, str, NULL, 0);
if (!t || !utf8len(t->value))
return 0;
avio_wb32(pb, 0); /* size */
ffio_wfourcc(pb, tag); /* type */
avio_write(pb, t->value, strlen(t->value)); /* UTF8 string value */
return update_size(pb, pos);
}
static int mov_write_track_udta_tag(AVIOContext *pb, MOVMuxContext *mov,
AVStream *st)
{
AVIOContext *pb_buf;
int ret, size;
uint8_t *buf;
if (!st)
return 0;
ret = avio_open_dyn_buf(&pb_buf);
if (ret < 0)
return ret;
if (mov->mode & (MODE_MP4|MODE_MOV))
mov_write_track_metadata(pb_buf, st, "name", "title");
if ((size = avio_close_dyn_buf(pb_buf, &buf)) > 0) {
avio_wb32(pb, size + 8);
ffio_wfourcc(pb, "udta");
avio_write(pb, buf, size);
}
av_free(buf);
return 0;
}
static int mov_write_trak_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContext *mov,
MOVTrack *track, AVStream *st)
{
int64_t pos = avio_tell(pb);
int entry_backup = track->entry;
int chunk_backup = track->chunkCount;
int ret;
/* If we want to have an empty moov, but some samples already have been
* buffered (delay_moov), pretend that no samples have been written yet. */
if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV)
track->chunkCount = track->entry = 0;
avio_wb32(pb, 0); /* size */
ffio_wfourcc(pb, "trak");
mov_write_tkhd_tag(pb, mov, track, st);
av_assert2(mov->use_editlist >= 0);
if (track->start_dts != AV_NOPTS_VALUE) {
if (mov->use_editlist)
mov_write_edts_tag(pb, mov, track); // PSP Movies and several other cases require edts box
else if ((track->entry && track->cluster[0].dts) || track->mode == MODE_PSP || is_clcp_track(track))
av_log(mov->fc, AV_LOG_WARNING,
"Not writing any edit list even though one would have been required\n");
}
if (track->tref_tag)
mov_write_tref_tag(pb, track);
if ((ret = mov_write_mdia_tag(s, pb, mov, track)) < 0)
return ret;
if (track->mode == MODE_PSP)
mov_write_uuid_tag_psp(pb, track); // PSP Movies require this uuid box
if (track->tag == MKTAG('r','t','p',' '))
mov_write_udta_sdp(pb, track);
if (track->mode == MODE_MOV) {
if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) {
double sample_aspect_ratio = av_q2d(st->sample_aspect_ratio);
if (st->sample_aspect_ratio.num && 1.0 != sample_aspect_ratio) {
mov_write_tapt_tag(pb, track);
}
}
if (is_clcp_track(track) && st->sample_aspect_ratio.num) {
mov_write_tapt_tag(pb, track);
}
}
mov_write_track_udta_tag(pb, mov, st);
track->entry = entry_backup;
track->chunkCount = chunk_backup;
return update_size(pb, pos);
}
static int mov_write_iods_tag(AVIOContext *pb, MOVMuxContext *mov)
{
int i, has_audio = 0, has_video = 0;
int64_t pos = avio_tell(pb);
int audio_profile = mov->iods_audio_profile;
int video_profile = mov->iods_video_profile;
for (i = 0; i < mov->nb_streams; i++) {
if (mov->tracks[i].entry > 0 || mov->flags & FF_MOV_FLAG_EMPTY_MOOV) {
has_audio |= mov->tracks[i].par->codec_type == AVMEDIA_TYPE_AUDIO;
has_video |= mov->tracks[i].par->codec_type == AVMEDIA_TYPE_VIDEO;
}
}
if (audio_profile < 0)
audio_profile = 0xFF - has_audio;
if (video_profile < 0)
video_profile = 0xFF - has_video;
avio_wb32(pb, 0x0); /* size */
ffio_wfourcc(pb, "iods");
avio_wb32(pb, 0); /* version & flags */
put_descr(pb, 0x10, 7);
avio_wb16(pb, 0x004f);
avio_w8(pb, 0xff);
avio_w8(pb, 0xff);
avio_w8(pb, audio_profile);
avio_w8(pb, video_profile);
avio_w8(pb, 0xff);
return update_size(pb, pos);
}
static int mov_write_trex_tag(AVIOContext *pb, MOVTrack *track)
{
avio_wb32(pb, 0x20); /* size */
ffio_wfourcc(pb, "trex");
avio_wb32(pb, 0); /* version & flags */
avio_wb32(pb, track->track_id); /* track ID */
avio_wb32(pb, 1); /* default sample description index */
avio_wb32(pb, 0); /* default sample duration */
avio_wb32(pb, 0); /* default sample size */
avio_wb32(pb, 0); /* default sample flags */
return 0;
}
static int mov_write_mvex_tag(AVIOContext *pb, MOVMuxContext *mov)
{
int64_t pos = avio_tell(pb);
int i;
avio_wb32(pb, 0x0); /* size */
ffio_wfourcc(pb, "mvex");
for (i = 0; i < mov->nb_streams; i++)
mov_write_trex_tag(pb, &mov->tracks[i]);
return update_size(pb, pos);
}
static int mov_write_mvhd_tag(AVIOContext *pb, MOVMuxContext *mov)
{
int max_track_id = 1, i;
int64_t max_track_len = 0;
int version;
for (i = 0; i < mov->nb_streams; i++) {
if (mov->tracks[i].entry > 0 && mov->tracks[i].timescale) {
int64_t max_track_len_temp = av_rescale_rnd(mov->tracks[i].track_duration,
MOV_TIMESCALE,
mov->tracks[i].timescale,
AV_ROUND_UP);
if (max_track_len < max_track_len_temp)
max_track_len = max_track_len_temp;
if (max_track_id < mov->tracks[i].track_id)
max_track_id = mov->tracks[i].track_id;
}
}
/* If using delay_moov, make sure the output is the same as if no
* samples had been written yet. */
if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV) {
max_track_len = 0;
max_track_id = 1;
}
version = max_track_len < UINT32_MAX ? 0 : 1;
avio_wb32(pb, version == 1 ? 120 : 108); /* size */
ffio_wfourcc(pb, "mvhd");
avio_w8(pb, version);
avio_wb24(pb, 0); /* flags */
if (version == 1) {
avio_wb64(pb, mov->time);
avio_wb64(pb, mov->time);
} else {
avio_wb32(pb, mov->time); /* creation time */
avio_wb32(pb, mov->time); /* modification time */
}
avio_wb32(pb, MOV_TIMESCALE);
(version == 1) ? avio_wb64(pb, max_track_len) : avio_wb32(pb, max_track_len); /* duration of longest track */
avio_wb32(pb, 0x00010000); /* reserved (preferred rate) 1.0 = normal */
avio_wb16(pb, 0x0100); /* reserved (preferred volume) 1.0 = normal */
avio_wb16(pb, 0); /* reserved */
avio_wb32(pb, 0); /* reserved */
avio_wb32(pb, 0); /* reserved */
/* Matrix structure */
write_matrix(pb, 1, 0, 0, 1, 0, 0);
avio_wb32(pb, 0); /* reserved (preview time) */
avio_wb32(pb, 0); /* reserved (preview duration) */
avio_wb32(pb, 0); /* reserved (poster time) */
avio_wb32(pb, 0); /* reserved (selection time) */
avio_wb32(pb, 0); /* reserved (selection duration) */
avio_wb32(pb, 0); /* reserved (current time) */
avio_wb32(pb, max_track_id + 1); /* Next track id */
return 0x6c;
}
static int mov_write_itunes_hdlr_tag(AVIOContext *pb, MOVMuxContext *mov,
AVFormatContext *s)
{
avio_wb32(pb, 33); /* size */
ffio_wfourcc(pb, "hdlr");
avio_wb32(pb, 0);
avio_wb32(pb, 0);
ffio_wfourcc(pb, "mdir");
ffio_wfourcc(pb, "appl");
avio_wb32(pb, 0);
avio_wb32(pb, 0);
avio_w8(pb, 0);
return 33;
}
/* helper function to write a data tag with the specified string as data */
static int mov_write_string_data_tag(AVIOContext *pb, const char *data, int lang, int long_style)
{
if (long_style) {
int size = 16 + strlen(data);
avio_wb32(pb, size); /* size */
ffio_wfourcc(pb, "data");
avio_wb32(pb, 1);
avio_wb32(pb, 0);
avio_write(pb, data, strlen(data));
return size;
} else {
if (!lang)
lang = ff_mov_iso639_to_lang("und", 1);
avio_wb16(pb, strlen(data)); /* string length */
avio_wb16(pb, lang);
avio_write(pb, data, strlen(data));
return strlen(data) + 4;
}
}
static int mov_write_string_tag(AVIOContext *pb, const char *name,
const char *value, int lang, int long_style)
{
int size = 0;
if (value && value[0]) {
int64_t pos = avio_tell(pb);
avio_wb32(pb, 0); /* size */
ffio_wfourcc(pb, name);
mov_write_string_data_tag(pb, value, lang, long_style);
size = update_size(pb, pos);
}
return size;
}
static AVDictionaryEntry *get_metadata_lang(AVFormatContext *s,
const char *tag, int *lang)
{
int l, len, len2;
AVDictionaryEntry *t, *t2 = NULL;
char tag2[16];
*lang = 0;
if (!(t = av_dict_get(s->metadata, tag, NULL, 0)))
return NULL;
len = strlen(t->key);
snprintf(tag2, sizeof(tag2), "%s-", tag);
while ((t2 = av_dict_get(s->metadata, tag2, t2, AV_DICT_IGNORE_SUFFIX))) {
len2 = strlen(t2->key);
if (len2 == len + 4 && !strcmp(t->value, t2->value)
&& (l = ff_mov_iso639_to_lang(&t2->key[len2 - 3], 1)) >= 0) {
*lang = l;
return t;
}
}
return t;
}
static int mov_write_string_metadata(AVFormatContext *s, AVIOContext *pb,
const char *name, const char *tag,
int long_style)
{
int lang;
AVDictionaryEntry *t = get_metadata_lang(s, tag, &lang);
if (!t)
return 0;
return mov_write_string_tag(pb, name, t->value, lang, long_style);
}
/* iTunes bpm number */
static int mov_write_tmpo_tag(AVIOContext *pb, AVFormatContext *s)
{
AVDictionaryEntry *t = av_dict_get(s->metadata, "tmpo", NULL, 0);
int size = 0, tmpo = t ? atoi(t->value) : 0;
if (tmpo) {
size = 26;
avio_wb32(pb, size);
ffio_wfourcc(pb, "tmpo");
avio_wb32(pb, size-8); /* size */
ffio_wfourcc(pb, "data");
avio_wb32(pb, 0x15); //type specifier
avio_wb32(pb, 0);
avio_wb16(pb, tmpo); // data
}
return size;
}
/* 3GPP TS 26.244 */
static int mov_write_loci_tag(AVFormatContext *s, AVIOContext *pb)
{
int lang;
int64_t pos = avio_tell(pb);
double latitude, longitude, altitude;
int32_t latitude_fix, longitude_fix, altitude_fix;
AVDictionaryEntry *t = get_metadata_lang(s, "location", &lang);
const char *ptr, *place = "";
char *end;
static const char *astronomical_body = "earth";
if (!t)
return 0;
ptr = t->value;
longitude = strtod(ptr, &end);
if (end == ptr) {
av_log(s, AV_LOG_WARNING, "malformed location metadata\n");
return 0;
}
ptr = end;
latitude = strtod(ptr, &end);
if (end == ptr) {
av_log(s, AV_LOG_WARNING, "malformed location metadata\n");
return 0;
}
ptr = end;
altitude = strtod(ptr, &end);
/* If no altitude was present, the default 0 should be fine */
if (*end == '/')
place = end + 1;
latitude_fix = (int32_t) ((1 << 16) * latitude);
longitude_fix = (int32_t) ((1 << 16) * longitude);
altitude_fix = (int32_t) ((1 << 16) * altitude);
avio_wb32(pb, 0); /* size */
ffio_wfourcc(pb, "loci"); /* type */
avio_wb32(pb, 0); /* version + flags */
avio_wb16(pb, lang);
avio_write(pb, place, strlen(place) + 1);
avio_w8(pb, 0); /* role of place (0 == shooting location, 1 == real location, 2 == fictional location) */
avio_wb32(pb, latitude_fix);
avio_wb32(pb, longitude_fix);
avio_wb32(pb, altitude_fix);
avio_write(pb, astronomical_body, strlen(astronomical_body) + 1);
avio_w8(pb, 0); /* additional notes, null terminated string */
return update_size(pb, pos);
}
/* iTunes track or disc number */
static int mov_write_trkn_tag(AVIOContext *pb, MOVMuxContext *mov,
AVFormatContext *s, int disc)
{
AVDictionaryEntry *t = av_dict_get(s->metadata,
disc ? "disc" : "track",
NULL, 0);
int size = 0, track = t ? atoi(t->value) : 0;
if (track) {
int tracks = 0;
char *slash = strchr(t->value, '/');
if (slash)
tracks = atoi(slash + 1);
avio_wb32(pb, 32); /* size */
ffio_wfourcc(pb, disc ? "disk" : "trkn");
avio_wb32(pb, 24); /* size */
ffio_wfourcc(pb, "data");
avio_wb32(pb, 0); // 8 bytes empty
avio_wb32(pb, 0);
avio_wb16(pb, 0); // empty
avio_wb16(pb, track); // track / disc number
avio_wb16(pb, tracks); // total track / disc number
avio_wb16(pb, 0); // empty
size = 32;
}
return size;
}
static int mov_write_int8_metadata(AVFormatContext *s, AVIOContext *pb,
const char *name, const char *tag,
int len)
{
AVDictionaryEntry *t = NULL;
uint8_t num;
int size = 24 + len;
if (len != 1 && len != 4)
return -1;
if (!(t = av_dict_get(s->metadata, tag, NULL, 0)))
return 0;
num = atoi(t->value);
avio_wb32(pb, size);
ffio_wfourcc(pb, name);
avio_wb32(pb, size - 8);
ffio_wfourcc(pb, "data");
avio_wb32(pb, 0x15);
avio_wb32(pb, 0);
if (len==4) avio_wb32(pb, num);
else avio_w8 (pb, num);
return size;
}
static int mov_write_covr(AVIOContext *pb, AVFormatContext *s)
{
MOVMuxContext *mov = s->priv_data;
int64_t pos = 0;
int i;
for (i = 0; i < s->nb_streams; i++) {
MOVTrack *trk = &mov->tracks[i];
if (!is_cover_image(trk->st) || trk->cover_image.size <= 0)
continue;
if (!pos) {
pos = avio_tell(pb);
avio_wb32(pb, 0);
ffio_wfourcc(pb, "covr");
}
avio_wb32(pb, 16 + trk->cover_image.size);
ffio_wfourcc(pb, "data");
avio_wb32(pb, trk->tag);
avio_wb32(pb , 0);
avio_write(pb, trk->cover_image.data, trk->cover_image.size);
}
return pos ? update_size(pb, pos) : 0;
}
/* iTunes meta data list */
static int mov_write_ilst_tag(AVIOContext *pb, MOVMuxContext *mov,
AVFormatContext *s)
{
int64_t pos = avio_tell(pb);
avio_wb32(pb, 0); /* size */
ffio_wfourcc(pb, "ilst");
mov_write_string_metadata(s, pb, "\251nam", "title" , 1);
mov_write_string_metadata(s, pb, "\251ART", "artist" , 1);
mov_write_string_metadata(s, pb, "aART", "album_artist", 1);
mov_write_string_metadata(s, pb, "\251wrt", "composer" , 1);
mov_write_string_metadata(s, pb, "\251alb", "album" , 1);
mov_write_string_metadata(s, pb, "\251day", "date" , 1);
if (!mov_write_string_metadata(s, pb, "\251too", "encoding_tool", 1)) {
if (!(s->flags & AVFMT_FLAG_BITEXACT))
mov_write_string_tag(pb, "\251too", LIBAVFORMAT_IDENT, 0, 1);
}
mov_write_string_metadata(s, pb, "\251cmt", "comment" , 1);
mov_write_string_metadata(s, pb, "\251gen", "genre" , 1);
mov_write_string_metadata(s, pb, "cprt", "copyright", 1);
mov_write_string_metadata(s, pb, "\251grp", "grouping" , 1);
mov_write_string_metadata(s, pb, "\251lyr", "lyrics" , 1);
mov_write_string_metadata(s, pb, "desc", "description",1);
mov_write_string_metadata(s, pb, "ldes", "synopsis" , 1);
mov_write_string_metadata(s, pb, "tvsh", "show" , 1);
mov_write_string_metadata(s, pb, "tven", "episode_id",1);
mov_write_string_metadata(s, pb, "tvnn", "network" , 1);
mov_write_string_metadata(s, pb, "keyw", "keywords" , 1);
mov_write_int8_metadata (s, pb, "tves", "episode_sort",4);
mov_write_int8_metadata (s, pb, "tvsn", "season_number",4);
mov_write_int8_metadata (s, pb, "stik", "media_type",1);
mov_write_int8_metadata (s, pb, "hdvd", "hd_video", 1);
mov_write_int8_metadata (s, pb, "pgap", "gapless_playback",1);
mov_write_int8_metadata (s, pb, "cpil", "compilation", 1);
mov_write_covr(pb, s);
mov_write_trkn_tag(pb, mov, s, 0); // track number
mov_write_trkn_tag(pb, mov, s, 1); // disc number
mov_write_tmpo_tag(pb, s);
return update_size(pb, pos);
}
static int mov_write_mdta_hdlr_tag(AVIOContext *pb, MOVMuxContext *mov,
AVFormatContext *s)
{
avio_wb32(pb, 33); /* size */
ffio_wfourcc(pb, "hdlr");
avio_wb32(pb, 0);
avio_wb32(pb, 0);
ffio_wfourcc(pb, "mdta");
avio_wb32(pb, 0);
avio_wb32(pb, 0);
avio_wb32(pb, 0);
avio_w8(pb, 0);
return 33;
}
static int mov_write_mdta_keys_tag(AVIOContext *pb, MOVMuxContext *mov,
AVFormatContext *s)
{
AVDictionaryEntry *t = NULL;
int64_t pos = avio_tell(pb);
int64_t curpos, entry_pos;
int count = 0;
avio_wb32(pb, 0); /* size */
ffio_wfourcc(pb, "keys");
avio_wb32(pb, 0);
entry_pos = avio_tell(pb);
avio_wb32(pb, 0); /* entry count */
while (t = av_dict_get(s->metadata, "", t, AV_DICT_IGNORE_SUFFIX)) {
avio_wb32(pb, strlen(t->key) + 8);
ffio_wfourcc(pb, "mdta");
avio_write(pb, t->key, strlen(t->key));
count += 1;
}
curpos = avio_tell(pb);
avio_seek(pb, entry_pos, SEEK_SET);
avio_wb32(pb, count); // rewrite entry count
avio_seek(pb, curpos, SEEK_SET);
return update_size(pb, pos);
}
static int mov_write_mdta_ilst_tag(AVIOContext *pb, MOVMuxContext *mov,
AVFormatContext *s)
{
AVDictionaryEntry *t = NULL;
int64_t pos = avio_tell(pb);
int count = 1; /* keys are 1-index based */
avio_wb32(pb, 0); /* size */
ffio_wfourcc(pb, "ilst");
while (t = av_dict_get(s->metadata, "", t, AV_DICT_IGNORE_SUFFIX)) {
int64_t entry_pos = avio_tell(pb);
avio_wb32(pb, 0); /* size */
avio_wb32(pb, count); /* key */
mov_write_string_data_tag(pb, t->value, 0, 1);
update_size(pb, entry_pos);
count += 1;
}
return update_size(pb, pos);
}
/* meta data tags */
static int mov_write_meta_tag(AVIOContext *pb, MOVMuxContext *mov,
AVFormatContext *s)
{
int size = 0;
int64_t pos = avio_tell(pb);
avio_wb32(pb, 0); /* size */
ffio_wfourcc(pb, "meta");
avio_wb32(pb, 0);
if (mov->flags & FF_MOV_FLAG_USE_MDTA) {
mov_write_mdta_hdlr_tag(pb, mov, s);
mov_write_mdta_keys_tag(pb, mov, s);
mov_write_mdta_ilst_tag(pb, mov, s);
}
else {
/* iTunes metadata tag */
mov_write_itunes_hdlr_tag(pb, mov, s);
mov_write_ilst_tag(pb, mov, s);
}
size = update_size(pb, pos);
return size;
}
static int mov_write_raw_metadata_tag(AVFormatContext *s, AVIOContext *pb,
const char *name, const char *key)
{
int len;
AVDictionaryEntry *t;
if (!(t = av_dict_get(s->metadata, key, NULL, 0)))
return 0;
len = strlen(t->value);
if (len > 0) {
int size = len + 8;
avio_wb32(pb, size);
ffio_wfourcc(pb, name);
avio_write(pb, t->value, len);
return size;
}
return 0;
}
static int ascii_to_wc(AVIOContext *pb, const uint8_t *b)
{
int val;
while (*b) {
GET_UTF8(val, *b++, return -1;)
avio_wb16(pb, val);
}
avio_wb16(pb, 0x00);
return 0;
}
static uint16_t language_code(const char *str)
{
return (((str[0] - 0x60) & 0x1F) << 10) +
(((str[1] - 0x60) & 0x1F) << 5) +
(( str[2] - 0x60) & 0x1F);
}
static int mov_write_3gp_udta_tag(AVIOContext *pb, AVFormatContext *s,
const char *tag, const char *str)
{
int64_t pos = avio_tell(pb);
AVDictionaryEntry *t = av_dict_get(s->metadata, str, NULL, 0);
if (!t || !utf8len(t->value))
return 0;
avio_wb32(pb, 0); /* size */
ffio_wfourcc(pb, tag); /* type */
avio_wb32(pb, 0); /* version + flags */
if (!strcmp(tag, "yrrc"))
avio_wb16(pb, atoi(t->value));
else {
avio_wb16(pb, language_code("eng")); /* language */
avio_write(pb, t->value, strlen(t->value) + 1); /* UTF8 string value */
if (!strcmp(tag, "albm") &&
(t = av_dict_get(s->metadata, "track", NULL, 0)))
avio_w8(pb, atoi(t->value));
}
return update_size(pb, pos);
}
static int mov_write_chpl_tag(AVIOContext *pb, AVFormatContext *s)
{
int64_t pos = avio_tell(pb);
int i, nb_chapters = FFMIN(s->nb_chapters, 255);
avio_wb32(pb, 0); // size
ffio_wfourcc(pb, "chpl");
avio_wb32(pb, 0x01000000); // version + flags
avio_wb32(pb, 0); // unknown
avio_w8(pb, nb_chapters);
for (i = 0; i < nb_chapters; i++) {
AVChapter *c = s->chapters[i];
AVDictionaryEntry *t;
avio_wb64(pb, av_rescale_q(c->start, c->time_base, (AVRational){1,10000000}));
if ((t = av_dict_get(c->metadata, "title", NULL, 0))) {
int len = FFMIN(strlen(t->value), 255);
avio_w8(pb, len);
avio_write(pb, t->value, len);
} else
avio_w8(pb, 0);
}
return update_size(pb, pos);
}
static int mov_write_udta_tag(AVIOContext *pb, MOVMuxContext *mov,
AVFormatContext *s)
{
AVIOContext *pb_buf;
int ret, size;
uint8_t *buf;
ret = avio_open_dyn_buf(&pb_buf);
if (ret < 0)
return ret;
if (mov->mode & MODE_3GP) {
mov_write_3gp_udta_tag(pb_buf, s, "perf", "artist");
mov_write_3gp_udta_tag(pb_buf, s, "titl", "title");
mov_write_3gp_udta_tag(pb_buf, s, "auth", "author");
mov_write_3gp_udta_tag(pb_buf, s, "gnre", "genre");
mov_write_3gp_udta_tag(pb_buf, s, "dscp", "comment");
mov_write_3gp_udta_tag(pb_buf, s, "albm", "album");
mov_write_3gp_udta_tag(pb_buf, s, "cprt", "copyright");
mov_write_3gp_udta_tag(pb_buf, s, "yrrc", "date");
mov_write_loci_tag(s, pb_buf);
} else if (mov->mode == MODE_MOV && !(mov->flags & FF_MOV_FLAG_USE_MDTA)) { // the title field breaks gtkpod with mp4 and my suspicion is that stuff is not valid in mp4
mov_write_string_metadata(s, pb_buf, "\251ART", "artist", 0);
mov_write_string_metadata(s, pb_buf, "\251nam", "title", 0);
mov_write_string_metadata(s, pb_buf, "\251aut", "author", 0);
mov_write_string_metadata(s, pb_buf, "\251alb", "album", 0);
mov_write_string_metadata(s, pb_buf, "\251day", "date", 0);
mov_write_string_metadata(s, pb_buf, "\251swr", "encoder", 0);
// currently ignored by mov.c
mov_write_string_metadata(s, pb_buf, "\251des", "comment", 0);
// add support for libquicktime, this atom is also actually read by mov.c
mov_write_string_metadata(s, pb_buf, "\251cmt", "comment", 0);
mov_write_string_metadata(s, pb_buf, "\251gen", "genre", 0);
mov_write_string_metadata(s, pb_buf, "\251cpy", "copyright", 0);
mov_write_string_metadata(s, pb_buf, "\251mak", "make", 0);
mov_write_string_metadata(s, pb_buf, "\251mod", "model", 0);
mov_write_string_metadata(s, pb_buf, "\251xyz", "location", 0);
mov_write_string_metadata(s, pb_buf, "\251key", "keywords", 0);
mov_write_raw_metadata_tag(s, pb_buf, "XMP_", "xmp");
} else {
/* iTunes meta data */
mov_write_meta_tag(pb_buf, mov, s);
mov_write_loci_tag(s, pb_buf);
}
if (s->nb_chapters && !(mov->flags & FF_MOV_FLAG_DISABLE_CHPL))
mov_write_chpl_tag(pb_buf, s);
if ((size = avio_close_dyn_buf(pb_buf, &buf)) > 0) {
avio_wb32(pb, size + 8);
ffio_wfourcc(pb, "udta");
avio_write(pb, buf, size);
}
av_free(buf);
return 0;
}
static void mov_write_psp_udta_tag(AVIOContext *pb,
const char *str, const char *lang, int type)
{
int len = utf8len(str) + 1;
if (len <= 0)
return;
avio_wb16(pb, len * 2 + 10); /* size */
avio_wb32(pb, type); /* type */
avio_wb16(pb, language_code(lang)); /* language */
avio_wb16(pb, 0x01); /* ? */
ascii_to_wc(pb, str);
}
static int mov_write_uuidusmt_tag(AVIOContext *pb, AVFormatContext *s)
{
AVDictionaryEntry *title = av_dict_get(s->metadata, "title", NULL, 0);
int64_t pos, pos2;
if (title) {
pos = avio_tell(pb);
avio_wb32(pb, 0); /* size placeholder*/
ffio_wfourcc(pb, "uuid");
ffio_wfourcc(pb, "USMT");
avio_wb32(pb, 0x21d24fce); /* 96 bit UUID */
avio_wb32(pb, 0xbb88695c);
avio_wb32(pb, 0xfac9c740);
pos2 = avio_tell(pb);
avio_wb32(pb, 0); /* size placeholder*/
ffio_wfourcc(pb, "MTDT");
avio_wb16(pb, 4);
// ?
avio_wb16(pb, 0x0C); /* size */
avio_wb32(pb, 0x0B); /* type */
avio_wb16(pb, language_code("und")); /* language */
avio_wb16(pb, 0x0); /* ? */
avio_wb16(pb, 0x021C); /* data */
if (!(s->flags & AVFMT_FLAG_BITEXACT))
mov_write_psp_udta_tag(pb, LIBAVCODEC_IDENT, "eng", 0x04);
mov_write_psp_udta_tag(pb, title->value, "eng", 0x01);
mov_write_psp_udta_tag(pb, "2006/04/01 11:11:11", "und", 0x03);
update_size(pb, pos2);
return update_size(pb, pos);
}
return 0;
}
static void build_chunks(MOVTrack *trk)
{
int i;
MOVIentry *chunk = &trk->cluster[0];
uint64_t chunkSize = chunk->size;
chunk->chunkNum = 1;
if (trk->chunkCount)
return;
trk->chunkCount = 1;
for (i = 1; i<trk->entry; i++){
if (chunk->pos + chunkSize == trk->cluster[i].pos &&
chunkSize + trk->cluster[i].size < (1<<20)){
chunkSize += trk->cluster[i].size;
chunk->samples_in_chunk += trk->cluster[i].entries;
} else {
trk->cluster[i].chunkNum = chunk->chunkNum+1;
chunk=&trk->cluster[i];
chunkSize = chunk->size;
trk->chunkCount++;
}
}
}
/**
* Assign track ids. If option "use_stream_ids_as_track_ids" is set,
* the stream ids are used as track ids.
*
* This assumes mov->tracks and s->streams are in the same order and
* there are no gaps in either of them (so mov->tracks[n] refers to
* s->streams[n]).
*
* As an exception, there can be more entries in
* s->streams than in mov->tracks, in which case new track ids are
* generated (starting after the largest found stream id).
*/
static int mov_setup_track_ids(MOVMuxContext *mov, AVFormatContext *s)
{
int i;
if (mov->track_ids_ok)
return 0;
if (mov->use_stream_ids_as_track_ids) {
int next_generated_track_id = 0;
for (i = 0; i < s->nb_streams; i++) {
if (s->streams[i]->id > next_generated_track_id)
next_generated_track_id = s->streams[i]->id;
}
for (i = 0; i < mov->nb_streams; i++) {
if (mov->tracks[i].entry <= 0 && !(mov->flags & FF_MOV_FLAG_FRAGMENT))
continue;
mov->tracks[i].track_id = i >= s->nb_streams ? ++next_generated_track_id : s->streams[i]->id;
}
} else {
for (i = 0; i < mov->nb_streams; i++) {
if (mov->tracks[i].entry <= 0 && !(mov->flags & FF_MOV_FLAG_FRAGMENT))
continue;
mov->tracks[i].track_id = i + 1;
}
}
mov->track_ids_ok = 1;
return 0;
}
static int mov_write_moov_tag(AVIOContext *pb, MOVMuxContext *mov,
AVFormatContext *s)
{
int i;
int64_t pos = avio_tell(pb);
avio_wb32(pb, 0); /* size placeholder*/
ffio_wfourcc(pb, "moov");
mov_setup_track_ids(mov, s);
for (i = 0; i < mov->nb_streams; i++) {
if (mov->tracks[i].entry <= 0 && !(mov->flags & FF_MOV_FLAG_FRAGMENT))
continue;
mov->tracks[i].time = mov->time;
if (mov->tracks[i].entry)
build_chunks(&mov->tracks[i]);
}
if (mov->chapter_track)
for (i = 0; i < s->nb_streams; i++) {
mov->tracks[i].tref_tag = MKTAG('c','h','a','p');
mov->tracks[i].tref_id = mov->tracks[mov->chapter_track].track_id;
}
for (i = 0; i < mov->nb_streams; i++) {
MOVTrack *track = &mov->tracks[i];
if (track->tag == MKTAG('r','t','p',' ')) {
track->tref_tag = MKTAG('h','i','n','t');
track->tref_id = mov->tracks[track->src_track].track_id;
} else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO) {
int * fallback, size;
fallback = (int*)av_stream_get_side_data(track->st,
AV_PKT_DATA_FALLBACK_TRACK,
&size);
if (fallback != NULL && size == sizeof(int)) {
if (*fallback >= 0 && *fallback < mov->nb_streams) {
track->tref_tag = MKTAG('f','a','l','l');
track->tref_id = mov->tracks[*fallback].track_id;
}
}
}
}
for (i = 0; i < mov->nb_streams; i++) {
if (mov->tracks[i].tag == MKTAG('t','m','c','d')) {
int src_trk = mov->tracks[i].src_track;
mov->tracks[src_trk].tref_tag = mov->tracks[i].tag;
mov->tracks[src_trk].tref_id = mov->tracks[i].track_id;
//src_trk may have a different timescale than the tmcd track
mov->tracks[i].track_duration = av_rescale(mov->tracks[src_trk].track_duration,
mov->tracks[i].timescale,
mov->tracks[src_trk].timescale);
}
}
mov_write_mvhd_tag(pb, mov);
if (mov->mode != MODE_MOV && !mov->iods_skip)
mov_write_iods_tag(pb, mov);
for (i = 0; i < mov->nb_streams; i++) {
if (mov->tracks[i].entry > 0 || mov->flags & FF_MOV_FLAG_FRAGMENT) {
int ret = mov_write_trak_tag(s, pb, mov, &(mov->tracks[i]), i < s->nb_streams ? s->streams[i] : NULL);
if (ret < 0)
return ret;
}
}
if (mov->flags & FF_MOV_FLAG_FRAGMENT)
mov_write_mvex_tag(pb, mov); /* QuickTime requires trak to precede this */
if (mov->mode == MODE_PSP)
mov_write_uuidusmt_tag(pb, s);
else
mov_write_udta_tag(pb, mov, s);
return update_size(pb, pos);
}
static void param_write_int(AVIOContext *pb, const char *name, int value)
{
avio_printf(pb, "<param name=\"%s\" value=\"%d\" valuetype=\"data\"/>\n", name, value);
}
static void param_write_string(AVIOContext *pb, const char *name, const char *value)
{
avio_printf(pb, "<param name=\"%s\" value=\"%s\" valuetype=\"data\"/>\n", name, value);
}
static void param_write_hex(AVIOContext *pb, const char *name, const uint8_t *value, int len)
{
char buf[150];
len = FFMIN(sizeof(buf) / 2 - 1, len);
ff_data_to_hex(buf, value, len, 0);
buf[2 * len] = '\0';
avio_printf(pb, "<param name=\"%s\" value=\"%s\" valuetype=\"data\"/>\n", name, buf);
}
static int mov_write_isml_manifest(AVIOContext *pb, MOVMuxContext *mov, AVFormatContext *s)
{
int64_t pos = avio_tell(pb);
int i;
int64_t manifest_bit_rate = 0;
AVCPBProperties *props = NULL;
static const uint8_t uuid[] = {
0xa5, 0xd4, 0x0b, 0x30, 0xe8, 0x14, 0x11, 0xdd,
0xba, 0x2f, 0x08, 0x00, 0x20, 0x0c, 0x9a, 0x66
};
avio_wb32(pb, 0);
ffio_wfourcc(pb, "uuid");
avio_write(pb, uuid, sizeof(uuid));
avio_wb32(pb, 0);
avio_printf(pb, "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
avio_printf(pb, "<smil xmlns=\"http://www.w3.org/2001/SMIL20/Language\">\n");
avio_printf(pb, "<head>\n");
if (!(mov->fc->flags & AVFMT_FLAG_BITEXACT))
avio_printf(pb, "<meta name=\"creator\" content=\"%s\" />\n",
LIBAVFORMAT_IDENT);
avio_printf(pb, "</head>\n");
avio_printf(pb, "<body>\n");
avio_printf(pb, "<switch>\n");
mov_setup_track_ids(mov, s);
for (i = 0; i < mov->nb_streams; i++) {
MOVTrack *track = &mov->tracks[i];
const char *type;
int track_id = track->track_id;
char track_name_buf[32] = { 0 };
AVStream *st = track->st;
AVDictionaryEntry *lang = av_dict_get(st->metadata, "language", NULL,0);
if (track->par->codec_type == AVMEDIA_TYPE_VIDEO && !is_cover_image(st)) {
type = "video";
} else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO) {
type = "audio";
} else {
continue;
}
props = (AVCPBProperties*)av_stream_get_side_data(track->st, AV_PKT_DATA_CPB_PROPERTIES, NULL);
if (track->par->bit_rate) {
manifest_bit_rate = track->par->bit_rate;
} else if (props) {
manifest_bit_rate = props->max_bitrate;
}
avio_printf(pb, "<%s systemBitrate=\"%"PRId64"\">\n", type,
manifest_bit_rate);
param_write_int(pb, "systemBitrate", manifest_bit_rate);
param_write_int(pb, "trackID", track_id);
param_write_string(pb, "systemLanguage", lang ? lang->value : "und");
/* Build track name piece by piece: */
/* 1. track type */
av_strlcat(track_name_buf, type, sizeof(track_name_buf));
/* 2. track language, if available */
if (lang)
av_strlcatf(track_name_buf, sizeof(track_name_buf),
"_%s", lang->value);
/* 3. special type suffix */
/* "_cc" = closed captions, "_ad" = audio_description */
if (st->disposition & AV_DISPOSITION_HEARING_IMPAIRED)
av_strlcat(track_name_buf, "_cc", sizeof(track_name_buf));
else if (st->disposition & AV_DISPOSITION_VISUAL_IMPAIRED)
av_strlcat(track_name_buf, "_ad", sizeof(track_name_buf));
param_write_string(pb, "trackName", track_name_buf);
if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) {
if (track->par->codec_id == AV_CODEC_ID_H264) {
uint8_t *ptr;
int size = track->par->extradata_size;
if (!ff_avc_write_annexb_extradata(track->par->extradata, &ptr,
&size)) {
param_write_hex(pb, "CodecPrivateData",
ptr ? ptr : track->par->extradata,
size);
av_free(ptr);
}
param_write_string(pb, "FourCC", "H264");
} else if (track->par->codec_id == AV_CODEC_ID_VC1) {
param_write_string(pb, "FourCC", "WVC1");
param_write_hex(pb, "CodecPrivateData", track->par->extradata,
track->par->extradata_size);
}
param_write_int(pb, "MaxWidth", track->par->width);
param_write_int(pb, "MaxHeight", track->par->height);
param_write_int(pb, "DisplayWidth", track->par->width);
param_write_int(pb, "DisplayHeight", track->par->height);
} else {
if (track->par->codec_id == AV_CODEC_ID_AAC) {
switch (track->par->profile)
{
case FF_PROFILE_AAC_HE_V2:
param_write_string(pb, "FourCC", "AACP");
break;
case FF_PROFILE_AAC_HE:
param_write_string(pb, "FourCC", "AACH");
break;
default:
param_write_string(pb, "FourCC", "AACL");
}
} else if (track->par->codec_id == AV_CODEC_ID_WMAPRO) {
param_write_string(pb, "FourCC", "WMAP");
}
param_write_hex(pb, "CodecPrivateData", track->par->extradata,
track->par->extradata_size);
param_write_int(pb, "AudioTag", ff_codec_get_tag(ff_codec_wav_tags,
track->par->codec_id));
param_write_int(pb, "Channels", track->par->channels);
param_write_int(pb, "SamplingRate", track->par->sample_rate);
param_write_int(pb, "BitsPerSample", 16);
param_write_int(pb, "PacketSize", track->par->block_align ?
track->par->block_align : 4);
}
avio_printf(pb, "</%s>\n", type);
}
avio_printf(pb, "</switch>\n");
avio_printf(pb, "</body>\n");
avio_printf(pb, "</smil>\n");
return update_size(pb, pos);
}
static int mov_write_mfhd_tag(AVIOContext *pb, MOVMuxContext *mov)
{
avio_wb32(pb, 16);
ffio_wfourcc(pb, "mfhd");
avio_wb32(pb, 0);
avio_wb32(pb, mov->fragments);
return 0;
}
static uint32_t get_sample_flags(MOVTrack *track, MOVIentry *entry)
{
return entry->flags & MOV_SYNC_SAMPLE ? MOV_FRAG_SAMPLE_FLAG_DEPENDS_NO :
(MOV_FRAG_SAMPLE_FLAG_DEPENDS_YES | MOV_FRAG_SAMPLE_FLAG_IS_NON_SYNC);
}
static int mov_write_tfhd_tag(AVIOContext *pb, MOVMuxContext *mov,
MOVTrack *track, int64_t moof_offset)
{
int64_t pos = avio_tell(pb);
uint32_t flags = MOV_TFHD_DEFAULT_SIZE | MOV_TFHD_DEFAULT_DURATION |
MOV_TFHD_BASE_DATA_OFFSET;
if (!track->entry) {
flags |= MOV_TFHD_DURATION_IS_EMPTY;
} else {
flags |= MOV_TFHD_DEFAULT_FLAGS;
}
if (mov->flags & FF_MOV_FLAG_OMIT_TFHD_OFFSET)
flags &= ~MOV_TFHD_BASE_DATA_OFFSET;
if (mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF) {
flags &= ~MOV_TFHD_BASE_DATA_OFFSET;
flags |= MOV_TFHD_DEFAULT_BASE_IS_MOOF;
}
/* Don't set a default sample size, the silverlight player refuses
* to play files with that set. Don't set a default sample duration,
* WMP freaks out if it is set. Don't set a base data offset, PIFF
* file format says it MUST NOT be set. */
if (track->mode == MODE_ISM)
flags &= ~(MOV_TFHD_DEFAULT_SIZE | MOV_TFHD_DEFAULT_DURATION |
MOV_TFHD_BASE_DATA_OFFSET);
avio_wb32(pb, 0); /* size placeholder */
ffio_wfourcc(pb, "tfhd");
avio_w8(pb, 0); /* version */
avio_wb24(pb, flags);
avio_wb32(pb, track->track_id); /* track-id */
if (flags & MOV_TFHD_BASE_DATA_OFFSET)
avio_wb64(pb, moof_offset);
if (flags & MOV_TFHD_DEFAULT_DURATION) {
track->default_duration = get_cluster_duration(track, 0);
avio_wb32(pb, track->default_duration);
}
if (flags & MOV_TFHD_DEFAULT_SIZE) {
track->default_size = track->entry ? track->cluster[0].size : 1;
avio_wb32(pb, track->default_size);
} else
track->default_size = -1;
if (flags & MOV_TFHD_DEFAULT_FLAGS) {
/* Set the default flags based on the second sample, if available.
* If the first sample is different, that can be signaled via a separate field. */
if (track->entry > 1)
track->default_sample_flags = get_sample_flags(track, &track->cluster[1]);
else
track->default_sample_flags =
track->par->codec_type == AVMEDIA_TYPE_VIDEO ?
(MOV_FRAG_SAMPLE_FLAG_DEPENDS_YES | MOV_FRAG_SAMPLE_FLAG_IS_NON_SYNC) :
MOV_FRAG_SAMPLE_FLAG_DEPENDS_NO;
avio_wb32(pb, track->default_sample_flags);
}
return update_size(pb, pos);
}
static int mov_write_trun_tag(AVIOContext *pb, MOVMuxContext *mov,
MOVTrack *track, int moof_size,
int first, int end)
{
int64_t pos = avio_tell(pb);
uint32_t flags = MOV_TRUN_DATA_OFFSET;
int i;
for (i = first; i < end; i++) {
if (get_cluster_duration(track, i) != track->default_duration)
flags |= MOV_TRUN_SAMPLE_DURATION;
if (track->cluster[i].size != track->default_size)
flags |= MOV_TRUN_SAMPLE_SIZE;
if (i > first && get_sample_flags(track, &track->cluster[i]) != track->default_sample_flags)
flags |= MOV_TRUN_SAMPLE_FLAGS;
}
if (!(flags & MOV_TRUN_SAMPLE_FLAGS) && track->entry > 0 &&
get_sample_flags(track, &track->cluster[0]) != track->default_sample_flags)
flags |= MOV_TRUN_FIRST_SAMPLE_FLAGS;
if (track->flags & MOV_TRACK_CTTS)
flags |= MOV_TRUN_SAMPLE_CTS;
avio_wb32(pb, 0); /* size placeholder */
ffio_wfourcc(pb, "trun");
if (mov->flags & FF_MOV_FLAG_NEGATIVE_CTS_OFFSETS)
avio_w8(pb, 1); /* version */
else
avio_w8(pb, 0); /* version */
avio_wb24(pb, flags);
avio_wb32(pb, end - first); /* sample count */
if (mov->flags & FF_MOV_FLAG_OMIT_TFHD_OFFSET &&
!(mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF) &&
!mov->first_trun)
avio_wb32(pb, 0); /* Later tracks follow immediately after the previous one */
else
avio_wb32(pb, moof_size + 8 + track->data_offset +
track->cluster[first].pos); /* data offset */
if (flags & MOV_TRUN_FIRST_SAMPLE_FLAGS)
avio_wb32(pb, get_sample_flags(track, &track->cluster[first]));
for (i = first; i < end; i++) {
if (flags & MOV_TRUN_SAMPLE_DURATION)
avio_wb32(pb, get_cluster_duration(track, i));
if (flags & MOV_TRUN_SAMPLE_SIZE)
avio_wb32(pb, track->cluster[i].size);
if (flags & MOV_TRUN_SAMPLE_FLAGS)
avio_wb32(pb, get_sample_flags(track, &track->cluster[i]));
if (flags & MOV_TRUN_SAMPLE_CTS)
avio_wb32(pb, track->cluster[i].cts);
}
mov->first_trun = 0;
return update_size(pb, pos);
}
static int mov_write_tfxd_tag(AVIOContext *pb, MOVTrack *track)
{
int64_t pos = avio_tell(pb);
static const uint8_t uuid[] = {
0x6d, 0x1d, 0x9b, 0x05, 0x42, 0xd5, 0x44, 0xe6,
0x80, 0xe2, 0x14, 0x1d, 0xaf, 0xf7, 0x57, 0xb2
};
avio_wb32(pb, 0); /* size placeholder */
ffio_wfourcc(pb, "uuid");
avio_write(pb, uuid, sizeof(uuid));
avio_w8(pb, 1);
avio_wb24(pb, 0);
avio_wb64(pb, track->start_dts + track->frag_start +
track->cluster[0].cts);
avio_wb64(pb, track->end_pts -
(track->cluster[0].dts + track->cluster[0].cts));
return update_size(pb, pos);
}
static int mov_write_tfrf_tag(AVIOContext *pb, MOVMuxContext *mov,
MOVTrack *track, int entry)
{
int n = track->nb_frag_info - 1 - entry, i;
int size = 8 + 16 + 4 + 1 + 16*n;
static const uint8_t uuid[] = {
0xd4, 0x80, 0x7e, 0xf2, 0xca, 0x39, 0x46, 0x95,
0x8e, 0x54, 0x26, 0xcb, 0x9e, 0x46, 0xa7, 0x9f
};
if (entry < 0)
return 0;
avio_seek(pb, track->frag_info[entry].tfrf_offset, SEEK_SET);
avio_wb32(pb, size);
ffio_wfourcc(pb, "uuid");
avio_write(pb, uuid, sizeof(uuid));
avio_w8(pb, 1);
avio_wb24(pb, 0);
avio_w8(pb, n);
for (i = 0; i < n; i++) {
int index = entry + 1 + i;
avio_wb64(pb, track->frag_info[index].time);
avio_wb64(pb, track->frag_info[index].duration);
}
if (n < mov->ism_lookahead) {
int free_size = 16 * (mov->ism_lookahead - n);
avio_wb32(pb, free_size);
ffio_wfourcc(pb, "free");
ffio_fill(pb, 0, free_size - 8);
}
return 0;
}
static int mov_write_tfrf_tags(AVIOContext *pb, MOVMuxContext *mov,
MOVTrack *track)
{
int64_t pos = avio_tell(pb);
int i;
for (i = 0; i < mov->ism_lookahead; i++) {
/* Update the tfrf tag for the last ism_lookahead fragments,
* nb_frag_info - 1 is the next fragment to be written. */
mov_write_tfrf_tag(pb, mov, track, track->nb_frag_info - 2 - i);
}
avio_seek(pb, pos, SEEK_SET);
return 0;
}
static int mov_add_tfra_entries(AVIOContext *pb, MOVMuxContext *mov, int tracks,
int size)
{
int i;
for (i = 0; i < mov->nb_streams; i++) {
MOVTrack *track = &mov->tracks[i];
MOVFragmentInfo *info;
if ((tracks >= 0 && i != tracks) || !track->entry)
continue;
track->nb_frag_info++;
if (track->nb_frag_info >= track->frag_info_capacity) {
unsigned new_capacity = track->nb_frag_info + MOV_FRAG_INFO_ALLOC_INCREMENT;
if (av_reallocp_array(&track->frag_info,
new_capacity,
sizeof(*track->frag_info)))
return AVERROR(ENOMEM);
track->frag_info_capacity = new_capacity;
}
info = &track->frag_info[track->nb_frag_info - 1];
info->offset = avio_tell(pb);
info->size = size;
// Try to recreate the original pts for the first packet
// from the fields we have stored
info->time = track->start_dts + track->frag_start +
track->cluster[0].cts;
info->duration = track->end_pts -
(track->cluster[0].dts + track->cluster[0].cts);
// If the pts is less than zero, we will have trimmed
// away parts of the media track using an edit list,
// and the corresponding start presentation time is zero.
if (info->time < 0) {
info->duration += info->time;
info->time = 0;
}
info->tfrf_offset = 0;
mov_write_tfrf_tags(pb, mov, track);
}
return 0;
}
static void mov_prune_frag_info(MOVMuxContext *mov, int tracks, int max)
{
int i;
for (i = 0; i < mov->nb_streams; i++) {
MOVTrack *track = &mov->tracks[i];
if ((tracks >= 0 && i != tracks) || !track->entry)
continue;
if (track->nb_frag_info > max) {
memmove(track->frag_info, track->frag_info + (track->nb_frag_info - max), max * sizeof(*track->frag_info));
track->nb_frag_info = max;
}
}
}
static int mov_write_tfdt_tag(AVIOContext *pb, MOVTrack *track)
{
int64_t pos = avio_tell(pb);
avio_wb32(pb, 0); /* size */
ffio_wfourcc(pb, "tfdt");
avio_w8(pb, 1); /* version */
avio_wb24(pb, 0);
avio_wb64(pb, track->frag_start);
return update_size(pb, pos);
}
static int mov_write_traf_tag(AVIOContext *pb, MOVMuxContext *mov,
MOVTrack *track, int64_t moof_offset,
int moof_size)
{
int64_t pos = avio_tell(pb);
int i, start = 0;
avio_wb32(pb, 0); /* size placeholder */
ffio_wfourcc(pb, "traf");
mov_write_tfhd_tag(pb, mov, track, moof_offset);
if (mov->mode != MODE_ISM)
mov_write_tfdt_tag(pb, track);
for (i = 1; i < track->entry; i++) {
if (track->cluster[i].pos != track->cluster[i - 1].pos + track->cluster[i - 1].size) {
mov_write_trun_tag(pb, mov, track, moof_size, start, i);
start = i;
}
}
mov_write_trun_tag(pb, mov, track, moof_size, start, track->entry);
if (mov->mode == MODE_ISM) {
mov_write_tfxd_tag(pb, track);
if (mov->ism_lookahead) {
int i, size = 16 + 4 + 1 + 16 * mov->ism_lookahead;
if (track->nb_frag_info > 0) {
MOVFragmentInfo *info = &track->frag_info[track->nb_frag_info - 1];
if (!info->tfrf_offset)
info->tfrf_offset = avio_tell(pb);
}
avio_wb32(pb, 8 + size);
ffio_wfourcc(pb, "free");
for (i = 0; i < size; i++)
avio_w8(pb, 0);
}
}
return update_size(pb, pos);
}
static int mov_write_moof_tag_internal(AVIOContext *pb, MOVMuxContext *mov,
int tracks, int moof_size)
{
int64_t pos = avio_tell(pb);
int i;
avio_wb32(pb, 0); /* size placeholder */
ffio_wfourcc(pb, "moof");
mov->first_trun = 1;
mov_write_mfhd_tag(pb, mov);
for (i = 0; i < mov->nb_streams; i++) {
MOVTrack *track = &mov->tracks[i];
if (tracks >= 0 && i != tracks)
continue;
if (!track->entry)
continue;
mov_write_traf_tag(pb, mov, track, pos, moof_size);
}
return update_size(pb, pos);
}
static int mov_write_sidx_tag(AVIOContext *pb,
MOVTrack *track, int ref_size, int total_sidx_size)
{
int64_t pos = avio_tell(pb), offset_pos, end_pos;
int64_t presentation_time, duration, offset;
int starts_with_SAP, i, entries;
if (track->entry) {
entries = 1;
presentation_time = track->start_dts + track->frag_start +
track->cluster[0].cts;
duration = track->end_pts -
(track->cluster[0].dts + track->cluster[0].cts);
starts_with_SAP = track->cluster[0].flags & MOV_SYNC_SAMPLE;
// pts<0 should be cut away using edts
if (presentation_time < 0) {
duration += presentation_time;
presentation_time = 0;
}
} else {
entries = track->nb_frag_info;
if (entries <= 0)
return 0;
presentation_time = track->frag_info[0].time;
}
avio_wb32(pb, 0); /* size */
ffio_wfourcc(pb, "sidx");
avio_w8(pb, 1); /* version */
avio_wb24(pb, 0);
avio_wb32(pb, track->track_id); /* reference_ID */
avio_wb32(pb, track->timescale); /* timescale */
avio_wb64(pb, presentation_time); /* earliest_presentation_time */
offset_pos = avio_tell(pb);
avio_wb64(pb, 0); /* first_offset (offset to referenced moof) */
avio_wb16(pb, 0); /* reserved */
avio_wb16(pb, entries); /* reference_count */
for (i = 0; i < entries; i++) {
if (!track->entry) {
if (i > 1 && track->frag_info[i].offset != track->frag_info[i - 1].offset + track->frag_info[i - 1].size) {
av_log(NULL, AV_LOG_ERROR, "Non-consecutive fragments, writing incorrect sidx\n");
}
duration = track->frag_info[i].duration;
ref_size = track->frag_info[i].size;
starts_with_SAP = 1;
}
avio_wb32(pb, (0 << 31) | (ref_size & 0x7fffffff)); /* reference_type (0 = media) | referenced_size */
avio_wb32(pb, duration); /* subsegment_duration */
avio_wb32(pb, (starts_with_SAP << 31) | (0 << 28) | 0); /* starts_with_SAP | SAP_type | SAP_delta_time */
}
end_pos = avio_tell(pb);
offset = pos + total_sidx_size - end_pos;
avio_seek(pb, offset_pos, SEEK_SET);
avio_wb64(pb, offset);
avio_seek(pb, end_pos, SEEK_SET);
return update_size(pb, pos);
}
static int mov_write_sidx_tags(AVIOContext *pb, MOVMuxContext *mov,
int tracks, int ref_size)
{
int i, round, ret;
AVIOContext *avio_buf;
int total_size = 0;
for (round = 0; round < 2; round++) {
// First run one round to calculate the total size of all
// sidx atoms.
// This would be much simpler if we'd only write one sidx
// atom, for the first track in the moof.
if (round == 0) {
if ((ret = ffio_open_null_buf(&avio_buf)) < 0)
return ret;
} else {
avio_buf = pb;
}
for (i = 0; i < mov->nb_streams; i++) {
MOVTrack *track = &mov->tracks[i];
if (tracks >= 0 && i != tracks)
continue;
// When writing a sidx for the full file, entry is 0, but
// we want to include all tracks. ref_size is 0 in this case,
// since we read it from frag_info instead.
if (!track->entry && ref_size > 0)
continue;
total_size -= mov_write_sidx_tag(avio_buf, track, ref_size,
total_size);
}
if (round == 0)
total_size = ffio_close_null_buf(avio_buf);
}
return 0;
}
static int mov_write_prft_tag(AVIOContext *pb, MOVMuxContext *mov, int tracks)
{
int64_t pos = avio_tell(pb), pts_us, ntp_ts;
MOVTrack *first_track;
/* PRFT should be associated with at most one track. So, choosing only the
* first track. */
if (tracks > 0)
return 0;
first_track = &(mov->tracks[0]);
if (!first_track->entry) {
av_log(mov->fc, AV_LOG_WARNING, "Unable to write PRFT, no entries in the track\n");
return 0;
}
if (first_track->cluster[0].pts == AV_NOPTS_VALUE) {
av_log(mov->fc, AV_LOG_WARNING, "Unable to write PRFT, first PTS is invalid\n");
return 0;
}
if (mov->write_prft == MOV_PRFT_SRC_WALLCLOCK) {
ntp_ts = ff_get_formatted_ntp_time(ff_ntp_time());
} else if (mov->write_prft == MOV_PRFT_SRC_PTS) {
pts_us = av_rescale_q(first_track->cluster[0].pts,
first_track->st->time_base, AV_TIME_BASE_Q);
ntp_ts = ff_get_formatted_ntp_time(pts_us + NTP_OFFSET_US);
} else {
av_log(mov->fc, AV_LOG_WARNING, "Unsupported PRFT box configuration: %d\n",
mov->write_prft);
return 0;
}
avio_wb32(pb, 0); // Size place holder
ffio_wfourcc(pb, "prft"); // Type
avio_w8(pb, 1); // Version
avio_wb24(pb, 0); // Flags
avio_wb32(pb, first_track->track_id); // reference track ID
avio_wb64(pb, ntp_ts); // NTP time stamp
avio_wb64(pb, first_track->cluster[0].pts); //media time
return update_size(pb, pos);
}
static int mov_write_moof_tag(AVIOContext *pb, MOVMuxContext *mov, int tracks,
int64_t mdat_size)
{
AVIOContext *avio_buf;
int ret, moof_size;
if ((ret = ffio_open_null_buf(&avio_buf)) < 0)
return ret;
mov_write_moof_tag_internal(avio_buf, mov, tracks, 0);
moof_size = ffio_close_null_buf(avio_buf);
if (mov->flags & FF_MOV_FLAG_DASH && !(mov->flags & FF_MOV_FLAG_GLOBAL_SIDX))
mov_write_sidx_tags(pb, mov, tracks, moof_size + 8 + mdat_size);
if (mov->write_prft > MOV_PRFT_NONE && mov->write_prft < MOV_PRFT_NB)
mov_write_prft_tag(pb, mov, tracks);
if (mov->flags & FF_MOV_FLAG_GLOBAL_SIDX ||
!(mov->flags & FF_MOV_FLAG_SKIP_TRAILER) ||
mov->ism_lookahead) {
if ((ret = mov_add_tfra_entries(pb, mov, tracks, moof_size + 8 + mdat_size)) < 0)
return ret;
if (!(mov->flags & FF_MOV_FLAG_GLOBAL_SIDX) &&
mov->flags & FF_MOV_FLAG_SKIP_TRAILER) {
mov_prune_frag_info(mov, tracks, mov->ism_lookahead + 1);
}
}
return mov_write_moof_tag_internal(pb, mov, tracks, moof_size);
}
static int mov_write_tfra_tag(AVIOContext *pb, MOVTrack *track)
{
int64_t pos = avio_tell(pb);
int i;
avio_wb32(pb, 0); /* size placeholder */
ffio_wfourcc(pb, "tfra");
avio_w8(pb, 1); /* version */
avio_wb24(pb, 0);
avio_wb32(pb, track->track_id);
avio_wb32(pb, 0); /* length of traf/trun/sample num */
avio_wb32(pb, track->nb_frag_info);
for (i = 0; i < track->nb_frag_info; i++) {
avio_wb64(pb, track->frag_info[i].time);
avio_wb64(pb, track->frag_info[i].offset + track->data_offset);
avio_w8(pb, 1); /* traf number */
avio_w8(pb, 1); /* trun number */
avio_w8(pb, 1); /* sample number */
}
return update_size(pb, pos);
}
static int mov_write_mfra_tag(AVIOContext *pb, MOVMuxContext *mov)
{
int64_t pos = avio_tell(pb);
int i;
avio_wb32(pb, 0); /* size placeholder */
ffio_wfourcc(pb, "mfra");
/* An empty mfra atom is enough to indicate to the publishing point that
* the stream has ended. */
if (mov->flags & FF_MOV_FLAG_ISML)
return update_size(pb, pos);
for (i = 0; i < mov->nb_streams; i++) {
MOVTrack *track = &mov->tracks[i];
if (track->nb_frag_info)
mov_write_tfra_tag(pb, track);
}
avio_wb32(pb, 16);
ffio_wfourcc(pb, "mfro");
avio_wb32(pb, 0); /* version + flags */
avio_wb32(pb, avio_tell(pb) + 4 - pos);
return update_size(pb, pos);
}
static int mov_write_mdat_tag(AVIOContext *pb, MOVMuxContext *mov)
{
avio_wb32(pb, 8); // placeholder for extended size field (64 bit)
ffio_wfourcc(pb, mov->mode == MODE_MOV ? "wide" : "free");
mov->mdat_pos = avio_tell(pb);
avio_wb32(pb, 0); /* size placeholder*/
ffio_wfourcc(pb, "mdat");
return 0;
}
/* TODO: This needs to be more general */
static int mov_write_ftyp_tag(AVIOContext *pb, AVFormatContext *s)
{
MOVMuxContext *mov = s->priv_data;
int64_t pos = avio_tell(pb);
int has_h264 = 0, has_video = 0;
int minor = 0x200;
int i;
for (i = 0; i < s->nb_streams; i++) {
AVStream *st = s->streams[i];
if (is_cover_image(st))
continue;
if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO)
has_video = 1;
if (st->codecpar->codec_id == AV_CODEC_ID_H264)
has_h264 = 1;
}
avio_wb32(pb, 0); /* size */
ffio_wfourcc(pb, "ftyp");
if (mov->major_brand && strlen(mov->major_brand) >= 4)
ffio_wfourcc(pb, mov->major_brand);
else if (mov->mode == MODE_3GP) {
ffio_wfourcc(pb, has_h264 ? "3gp6" : "3gp4");
minor = has_h264 ? 0x100 : 0x200;
} else if (mov->mode & MODE_3G2) {
ffio_wfourcc(pb, has_h264 ? "3g2b" : "3g2a");
minor = has_h264 ? 0x20000 : 0x10000;
} else if (mov->mode == MODE_PSP)
ffio_wfourcc(pb, "MSNV");
else if (mov->mode == MODE_MP4 && mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF)
ffio_wfourcc(pb, "iso5"); // Required when using default-base-is-moof
else if (mov->mode == MODE_MP4 && mov->flags & FF_MOV_FLAG_NEGATIVE_CTS_OFFSETS)
ffio_wfourcc(pb, "iso4");
else if (mov->mode == MODE_MP4)
ffio_wfourcc(pb, "isom");
else if (mov->mode == MODE_IPOD)
ffio_wfourcc(pb, has_video ? "M4V ":"M4A ");
else if (mov->mode == MODE_ISM)
ffio_wfourcc(pb, "isml");
else if (mov->mode == MODE_F4V)
ffio_wfourcc(pb, "f4v ");
else
ffio_wfourcc(pb, "qt ");
avio_wb32(pb, minor);
if (mov->mode == MODE_MOV)
ffio_wfourcc(pb, "qt ");
else if (mov->mode == MODE_ISM) {
ffio_wfourcc(pb, "piff");
} else if (!(mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF)) {
ffio_wfourcc(pb, "isom");
ffio_wfourcc(pb, "iso2");
if (has_h264)
ffio_wfourcc(pb, "avc1");
}
// We add tfdt atoms when fragmenting, signal this with the iso6 compatible
// brand. This is compatible with users that don't understand tfdt.
if (mov->flags & FF_MOV_FLAG_FRAGMENT && mov->mode != MODE_ISM)
ffio_wfourcc(pb, "iso6");
if (mov->mode == MODE_3GP)
ffio_wfourcc(pb, has_h264 ? "3gp6":"3gp4");
else if (mov->mode & MODE_3G2)
ffio_wfourcc(pb, has_h264 ? "3g2b":"3g2a");
else if (mov->mode == MODE_PSP)
ffio_wfourcc(pb, "MSNV");
else if (mov->mode == MODE_MP4)
ffio_wfourcc(pb, "mp41");
if (mov->flags & FF_MOV_FLAG_DASH && mov->flags & FF_MOV_FLAG_GLOBAL_SIDX)
ffio_wfourcc(pb, "dash");
return update_size(pb, pos);
}
static int mov_write_uuidprof_tag(AVIOContext *pb, AVFormatContext *s)
{
AVStream *video_st = s->streams[0];
AVCodecParameters *video_par = s->streams[0]->codecpar;
AVCodecParameters *audio_par = s->streams[1]->codecpar;
int audio_rate = audio_par->sample_rate;
int64_t frame_rate = video_st->avg_frame_rate.den ?
(video_st->avg_frame_rate.num * 0x10000LL) / video_st->avg_frame_rate.den :
0;
int audio_kbitrate = audio_par->bit_rate / 1000;
int video_kbitrate = FFMIN(video_par->bit_rate / 1000, 800 - audio_kbitrate);
if (frame_rate < 0 || frame_rate > INT32_MAX) {
av_log(s, AV_LOG_ERROR, "Frame rate %f outside supported range\n", frame_rate / (double)0x10000);
return AVERROR(EINVAL);
}
avio_wb32(pb, 0x94); /* size */
ffio_wfourcc(pb, "uuid");
ffio_wfourcc(pb, "PROF");
avio_wb32(pb, 0x21d24fce); /* 96 bit UUID */
avio_wb32(pb, 0xbb88695c);
avio_wb32(pb, 0xfac9c740);
avio_wb32(pb, 0x0); /* ? */
avio_wb32(pb, 0x3); /* 3 sections ? */
avio_wb32(pb, 0x14); /* size */
ffio_wfourcc(pb, "FPRF");
avio_wb32(pb, 0x0); /* ? */
avio_wb32(pb, 0x0); /* ? */
avio_wb32(pb, 0x0); /* ? */
avio_wb32(pb, 0x2c); /* size */
ffio_wfourcc(pb, "APRF"); /* audio */
avio_wb32(pb, 0x0);
avio_wb32(pb, 0x2); /* TrackID */
ffio_wfourcc(pb, "mp4a");
avio_wb32(pb, 0x20f);
avio_wb32(pb, 0x0);
avio_wb32(pb, audio_kbitrate);
avio_wb32(pb, audio_kbitrate);
avio_wb32(pb, audio_rate);
avio_wb32(pb, audio_par->channels);
avio_wb32(pb, 0x34); /* size */
ffio_wfourcc(pb, "VPRF"); /* video */
avio_wb32(pb, 0x0);
avio_wb32(pb, 0x1); /* TrackID */
if (video_par->codec_id == AV_CODEC_ID_H264) {
ffio_wfourcc(pb, "avc1");
avio_wb16(pb, 0x014D);
avio_wb16(pb, 0x0015);
} else {
ffio_wfourcc(pb, "mp4v");
avio_wb16(pb, 0x0000);
avio_wb16(pb, 0x0103);
}
avio_wb32(pb, 0x0);
avio_wb32(pb, video_kbitrate);
avio_wb32(pb, video_kbitrate);
avio_wb32(pb, frame_rate);
avio_wb32(pb, frame_rate);
avio_wb16(pb, video_par->width);
avio_wb16(pb, video_par->height);
avio_wb32(pb, 0x010001); /* ? */
return 0;
}
static int mov_write_identification(AVIOContext *pb, AVFormatContext *s)
{
MOVMuxContext *mov = s->priv_data;
int i;
mov_write_ftyp_tag(pb,s);
if (mov->mode == MODE_PSP) {
int video_streams_nb = 0, audio_streams_nb = 0, other_streams_nb = 0;
for (i = 0; i < s->nb_streams; i++) {
AVStream *st = s->streams[i];
if (is_cover_image(st))
continue;
if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO)
video_streams_nb++;
else if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO)
audio_streams_nb++;
else
other_streams_nb++;
}
if (video_streams_nb != 1 || audio_streams_nb != 1 || other_streams_nb) {
av_log(s, AV_LOG_ERROR, "PSP mode need one video and one audio stream\n");
return AVERROR(EINVAL);
}
return mov_write_uuidprof_tag(pb, s);
}
return 0;
}
static int mov_parse_mpeg2_frame(AVPacket *pkt, uint32_t *flags)
{
uint32_t c = -1;
int i, closed_gop = 0;
for (i = 0; i < pkt->size - 4; i++) {
c = (c << 8) + pkt->data[i];
if (c == 0x1b8) { // gop
closed_gop = pkt->data[i + 4] >> 6 & 0x01;
} else if (c == 0x100) { // pic
int temp_ref = (pkt->data[i + 1] << 2) | (pkt->data[i + 2] >> 6);
if (!temp_ref || closed_gop) // I picture is not reordered
*flags = MOV_SYNC_SAMPLE;
else
*flags = MOV_PARTIAL_SYNC_SAMPLE;
break;
}
}
return 0;
}
static void mov_parse_vc1_frame(AVPacket *pkt, MOVTrack *trk)
{
const uint8_t *start, *next, *end = pkt->data + pkt->size;
int seq = 0, entry = 0;
int key = pkt->flags & AV_PKT_FLAG_KEY;
start = find_next_marker(pkt->data, end);
for (next = start; next < end; start = next) {
next = find_next_marker(start + 4, end);
switch (AV_RB32(start)) {
case VC1_CODE_SEQHDR:
seq = 1;
break;
case VC1_CODE_ENTRYPOINT:
entry = 1;
break;
case VC1_CODE_SLICE:
trk->vc1_info.slices = 1;
break;
}
}
if (!trk->entry && trk->vc1_info.first_packet_seen)
trk->vc1_info.first_frag_written = 1;
if (!trk->entry && !trk->vc1_info.first_frag_written) {
/* First packet in first fragment */
trk->vc1_info.first_packet_seq = seq;
trk->vc1_info.first_packet_entry = entry;
trk->vc1_info.first_packet_seen = 1;
} else if ((seq && !trk->vc1_info.packet_seq) ||
(entry && !trk->vc1_info.packet_entry)) {
int i;
for (i = 0; i < trk->entry; i++)
trk->cluster[i].flags &= ~MOV_SYNC_SAMPLE;
trk->has_keyframes = 0;
if (seq)
trk->vc1_info.packet_seq = 1;
if (entry)
trk->vc1_info.packet_entry = 1;
if (!trk->vc1_info.first_frag_written) {
/* First fragment */
if ((!seq || trk->vc1_info.first_packet_seq) &&
(!entry || trk->vc1_info.first_packet_entry)) {
/* First packet had the same headers as this one, readd the
* sync sample flag. */
trk->cluster[0].flags |= MOV_SYNC_SAMPLE;
trk->has_keyframes = 1;
}
}
}
if (trk->vc1_info.packet_seq && trk->vc1_info.packet_entry)
key = seq && entry;
else if (trk->vc1_info.packet_seq)
key = seq;
else if (trk->vc1_info.packet_entry)
key = entry;
if (key) {
trk->cluster[trk->entry].flags |= MOV_SYNC_SAMPLE;
trk->has_keyframes++;
}
}
static int mov_flush_fragment_interleaving(AVFormatContext *s, MOVTrack *track)
{
MOVMuxContext *mov = s->priv_data;
int ret, buf_size;
uint8_t *buf;
int i, offset;
if (!track->mdat_buf)
return 0;
if (!mov->mdat_buf) {
if ((ret = avio_open_dyn_buf(&mov->mdat_buf)) < 0)
return ret;
}
buf_size = avio_close_dyn_buf(track->mdat_buf, &buf);
track->mdat_buf = NULL;
offset = avio_tell(mov->mdat_buf);
avio_write(mov->mdat_buf, buf, buf_size);
av_free(buf);
for (i = track->entries_flushed; i < track->entry; i++)
track->cluster[i].pos += offset;
track->entries_flushed = track->entry;
return 0;
}
static int mov_flush_fragment(AVFormatContext *s, int force)
{
MOVMuxContext *mov = s->priv_data;
int i, first_track = -1;
int64_t mdat_size = 0;
int ret;
int has_video = 0, starts_with_key = 0, first_video_track = 1;
if (!(mov->flags & FF_MOV_FLAG_FRAGMENT))
return 0;
// Try to fill in the duration of the last packet in each stream
// from queued packets in the interleave queues. If the flushing
// of fragments was triggered automatically by an AVPacket, we
// already have reliable info for the end of that track, but other
// tracks may need to be filled in.
for (i = 0; i < s->nb_streams; i++) {
MOVTrack *track = &mov->tracks[i];
if (!track->end_reliable) {
AVPacket pkt;
if (!ff_interleaved_peek(s, i, &pkt, 1)) {
if (track->dts_shift != AV_NOPTS_VALUE)
pkt.dts += track->dts_shift;
track->track_duration = pkt.dts - track->start_dts;
if (pkt.pts != AV_NOPTS_VALUE)
track->end_pts = pkt.pts;
else
track->end_pts = pkt.dts;
}
}
}
for (i = 0; i < mov->nb_streams; i++) {
MOVTrack *track = &mov->tracks[i];
if (track->entry <= 1)
continue;
// Sample durations are calculated as the diff of dts values,
// but for the last sample in a fragment, we don't know the dts
// of the first sample in the next fragment, so we have to rely
// on what was set as duration in the AVPacket. Not all callers
// set this though, so we might want to replace it with an
// estimate if it currently is zero.
if (get_cluster_duration(track, track->entry - 1) != 0)
continue;
// Use the duration (i.e. dts diff) of the second last sample for
// the last one. This is a wild guess (and fatal if it turns out
// to be too long), but probably the best we can do - having a zero
// duration is bad as well.
track->track_duration += get_cluster_duration(track, track->entry - 2);
track->end_pts += get_cluster_duration(track, track->entry - 2);
if (!mov->missing_duration_warned) {
av_log(s, AV_LOG_WARNING,
"Estimating the duration of the last packet in a "
"fragment, consider setting the duration field in "
"AVPacket instead.\n");
mov->missing_duration_warned = 1;
}
}
if (!mov->moov_written) {
int64_t pos = avio_tell(s->pb);
uint8_t *buf;
int buf_size, moov_size;
for (i = 0; i < mov->nb_streams; i++)
if (!mov->tracks[i].entry && !is_cover_image(mov->tracks[i].st))
break;
/* Don't write the initial moov unless all tracks have data */
if (i < mov->nb_streams && !force)
return 0;
moov_size = get_moov_size(s);
for (i = 0; i < mov->nb_streams; i++)
mov->tracks[i].data_offset = pos + moov_size + 8;
avio_write_marker(s->pb, AV_NOPTS_VALUE, AVIO_DATA_MARKER_HEADER);
if (mov->flags & FF_MOV_FLAG_DELAY_MOOV)
mov_write_identification(s->pb, s);
if ((ret = mov_write_moov_tag(s->pb, mov, s)) < 0)
return ret;
if (mov->flags & FF_MOV_FLAG_DELAY_MOOV) {
if (mov->flags & FF_MOV_FLAG_GLOBAL_SIDX)
mov->reserved_header_pos = avio_tell(s->pb);
avio_flush(s->pb);
mov->moov_written = 1;
return 0;
}
buf_size = avio_close_dyn_buf(mov->mdat_buf, &buf);
mov->mdat_buf = NULL;
avio_wb32(s->pb, buf_size + 8);
ffio_wfourcc(s->pb, "mdat");
avio_write(s->pb, buf, buf_size);
av_free(buf);
if (mov->flags & FF_MOV_FLAG_GLOBAL_SIDX)
mov->reserved_header_pos = avio_tell(s->pb);
mov->moov_written = 1;
mov->mdat_size = 0;
for (i = 0; i < mov->nb_streams; i++) {
if (mov->tracks[i].entry)
mov->tracks[i].frag_start += mov->tracks[i].start_dts +
mov->tracks[i].track_duration -
mov->tracks[i].cluster[0].dts;
mov->tracks[i].entry = 0;
mov->tracks[i].end_reliable = 0;
}
avio_flush(s->pb);
return 0;
}
if (mov->frag_interleave) {
for (i = 0; i < mov->nb_streams; i++) {
MOVTrack *track = &mov->tracks[i];
int ret;
if ((ret = mov_flush_fragment_interleaving(s, track)) < 0)
return ret;
}
if (!mov->mdat_buf)
return 0;
mdat_size = avio_tell(mov->mdat_buf);
}
for (i = 0; i < mov->nb_streams; i++) {
MOVTrack *track = &mov->tracks[i];
if (mov->flags & FF_MOV_FLAG_SEPARATE_MOOF || mov->frag_interleave)
track->data_offset = 0;
else
track->data_offset = mdat_size;
if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) {
has_video = 1;
if (first_video_track) {
if (track->entry)
starts_with_key = track->cluster[0].flags & MOV_SYNC_SAMPLE;
first_video_track = 0;
}
}
if (!track->entry)
continue;
if (track->mdat_buf)
mdat_size += avio_tell(track->mdat_buf);
if (first_track < 0)
first_track = i;
}
if (!mdat_size)
return 0;
avio_write_marker(s->pb,
av_rescale(mov->tracks[first_track].cluster[0].dts, AV_TIME_BASE, mov->tracks[first_track].timescale),
(has_video ? starts_with_key : mov->tracks[first_track].cluster[0].flags & MOV_SYNC_SAMPLE) ? AVIO_DATA_MARKER_SYNC_POINT : AVIO_DATA_MARKER_BOUNDARY_POINT);
for (i = 0; i < mov->nb_streams; i++) {
MOVTrack *track = &mov->tracks[i];
int buf_size, write_moof = 1, moof_tracks = -1;
uint8_t *buf;
int64_t duration = 0;
if (track->entry)
duration = track->start_dts + track->track_duration -
track->cluster[0].dts;
if (mov->flags & FF_MOV_FLAG_SEPARATE_MOOF) {
if (!track->mdat_buf)
continue;
mdat_size = avio_tell(track->mdat_buf);
moof_tracks = i;
} else {
write_moof = i == first_track;
}
if (write_moof) {
avio_flush(s->pb);
mov_write_moof_tag(s->pb, mov, moof_tracks, mdat_size);
mov->fragments++;
avio_wb32(s->pb, mdat_size + 8);
ffio_wfourcc(s->pb, "mdat");
}
if (track->entry)
track->frag_start += duration;
track->entry = 0;
track->entries_flushed = 0;
track->end_reliable = 0;
if (!mov->frag_interleave) {
if (!track->mdat_buf)
continue;
buf_size = avio_close_dyn_buf(track->mdat_buf, &buf);
track->mdat_buf = NULL;
} else {
if (!mov->mdat_buf)
continue;
buf_size = avio_close_dyn_buf(mov->mdat_buf, &buf);
mov->mdat_buf = NULL;
}
avio_write(s->pb, buf, buf_size);
av_free(buf);
}
mov->mdat_size = 0;
avio_flush(s->pb);
return 0;
}
static int mov_auto_flush_fragment(AVFormatContext *s, int force)
{
MOVMuxContext *mov = s->priv_data;
int had_moov = mov->moov_written;
int ret = mov_flush_fragment(s, force);
if (ret < 0)
return ret;
// If using delay_moov, the first flush only wrote the moov,
// not the actual moof+mdat pair, thus flush once again.
if (!had_moov && mov->flags & FF_MOV_FLAG_DELAY_MOOV)
ret = mov_flush_fragment(s, force);
return ret;
}
static int check_pkt(AVFormatContext *s, AVPacket *pkt)
{
MOVMuxContext *mov = s->priv_data;
MOVTrack *trk = &mov->tracks[pkt->stream_index];
int64_t ref;
uint64_t duration;
if (trk->entry) {
ref = trk->cluster[trk->entry - 1].dts;
} else if ( trk->start_dts != AV_NOPTS_VALUE
&& !trk->frag_discont) {
ref = trk->start_dts + trk->track_duration;
} else
ref = pkt->dts; // Skip tests for the first packet
if (trk->dts_shift != AV_NOPTS_VALUE) {
/* With negative CTS offsets we have set an offset to the DTS,
* reverse this for the check. */
ref -= trk->dts_shift;
}
duration = pkt->dts - ref;
if (pkt->dts < ref || duration >= INT_MAX) {
av_log(s, AV_LOG_ERROR, "Application provided duration: %"PRId64" / timestamp: %"PRId64" is out of range for mov/mp4 format\n",
duration, pkt->dts
);
pkt->dts = ref + 1;
pkt->pts = AV_NOPTS_VALUE;
}
if (pkt->duration < 0 || pkt->duration > INT_MAX) {
av_log(s, AV_LOG_ERROR, "Application provided duration: %"PRId64" is invalid\n", pkt->duration);
return AVERROR(EINVAL);
}
return 0;
}
int ff_mov_write_packet(AVFormatContext *s, AVPacket *pkt)
{
MOVMuxContext *mov = s->priv_data;
AVIOContext *pb = s->pb;
MOVTrack *trk = &mov->tracks[pkt->stream_index];
AVCodecParameters *par = trk->par;
unsigned int samples_in_chunk = 0;
int size = pkt->size, ret = 0;
uint8_t *reformatted_data = NULL;
ret = check_pkt(s, pkt);
if (ret < 0)
return ret;
if (mov->flags & FF_MOV_FLAG_FRAGMENT) {
int ret;
if (mov->moov_written || mov->flags & FF_MOV_FLAG_EMPTY_MOOV) {
if (mov->frag_interleave && mov->fragments > 0) {
if (trk->entry - trk->entries_flushed >= mov->frag_interleave) {
if ((ret = mov_flush_fragment_interleaving(s, trk)) < 0)
return ret;
}
}
if (!trk->mdat_buf) {
if ((ret = avio_open_dyn_buf(&trk->mdat_buf)) < 0)
return ret;
}
pb = trk->mdat_buf;
} else {
if (!mov->mdat_buf) {
if ((ret = avio_open_dyn_buf(&mov->mdat_buf)) < 0)
return ret;
}
pb = mov->mdat_buf;
}
}
if (par->codec_id == AV_CODEC_ID_AMR_NB) {
/* We must find out how many AMR blocks there are in one packet */
static const uint16_t packed_size[16] =
{13, 14, 16, 18, 20, 21, 27, 32, 6, 0, 0, 0, 0, 0, 0, 1};
int len = 0;
while (len < size && samples_in_chunk < 100) {
len += packed_size[(pkt->data[len] >> 3) & 0x0F];
samples_in_chunk++;
}
if (samples_in_chunk > 1) {
av_log(s, AV_LOG_ERROR, "fatal error, input is not a single packet, implement a AVParser for it\n");
return -1;
}
} else if (par->codec_id == AV_CODEC_ID_ADPCM_MS ||
par->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV) {
samples_in_chunk = trk->par->frame_size;
} else if (trk->sample_size)
samples_in_chunk = size / trk->sample_size;
else
samples_in_chunk = 1;
/* copy extradata if it exists */
if (trk->vos_len == 0 && par->extradata_size > 0 &&
!TAG_IS_AVCI(trk->tag) &&
(par->codec_id != AV_CODEC_ID_DNXHD)) {
trk->vos_len = par->extradata_size;
trk->vos_data = av_malloc(trk->vos_len);
if (!trk->vos_data) {
ret = AVERROR(ENOMEM);
goto err;
}
memcpy(trk->vos_data, par->extradata, trk->vos_len);
}
if (par->codec_id == AV_CODEC_ID_AAC && pkt->size > 2 &&
(AV_RB16(pkt->data) & 0xfff0) == 0xfff0) {
if (!s->streams[pkt->stream_index]->nb_frames) {
av_log(s, AV_LOG_ERROR, "Malformed AAC bitstream detected: "
"use the audio bitstream filter 'aac_adtstoasc' to fix it "
"('-bsf:a aac_adtstoasc' option with ffmpeg)\n");
return -1;
}
av_log(s, AV_LOG_WARNING, "aac bitstream error\n");
}
if (par->codec_id == AV_CODEC_ID_H264 && trk->vos_len > 0 && *(uint8_t *)trk->vos_data != 1 && !TAG_IS_AVCI(trk->tag)) {
/* from x264 or from bytestream H.264 */
/* NAL reformatting needed */
if (trk->hint_track >= 0 && trk->hint_track < mov->nb_streams) {
ff_avc_parse_nal_units_buf(pkt->data, &reformatted_data,
&size);
avio_write(pb, reformatted_data, size);
} else {
if (trk->cenc.aes_ctr) {
size = ff_mov_cenc_avc_parse_nal_units(&trk->cenc, pb, pkt->data, size);
if (size < 0) {
ret = size;
goto err;
}
} else {
size = ff_avc_parse_nal_units(pb, pkt->data, pkt->size);
}
}
} else if (par->codec_id == AV_CODEC_ID_HEVC && trk->vos_len > 6 &&
(AV_RB24(trk->vos_data) == 1 || AV_RB32(trk->vos_data) == 1)) {
/* extradata is Annex B, assume the bitstream is too and convert it */
if (trk->hint_track >= 0 && trk->hint_track < mov->nb_streams) {
ff_hevc_annexb2mp4_buf(pkt->data, &reformatted_data, &size, 0, NULL);
avio_write(pb, reformatted_data, size);
} else {
size = ff_hevc_annexb2mp4(pb, pkt->data, pkt->size, 0, NULL);
}
#if CONFIG_AC3_PARSER
} else if (par->codec_id == AV_CODEC_ID_EAC3) {
size = handle_eac3(mov, pkt, trk);
if (size < 0)
return size;
else if (!size)
goto end;
avio_write(pb, pkt->data, size);
#endif
} else {
if (trk->cenc.aes_ctr) {
if (par->codec_id == AV_CODEC_ID_H264 && par->extradata_size > 4) {
int nal_size_length = (par->extradata[4] & 0x3) + 1;
ret = ff_mov_cenc_avc_write_nal_units(s, &trk->cenc, nal_size_length, pb, pkt->data, size);
} else {
ret = ff_mov_cenc_write_packet(&trk->cenc, pb, pkt->data, size);
}
if (ret) {
goto err;
}
} else {
avio_write(pb, pkt->data, size);
}
}
if ((par->codec_id == AV_CODEC_ID_DNXHD ||
par->codec_id == AV_CODEC_ID_AC3) && !trk->vos_len) {
/* copy frame to create needed atoms */
trk->vos_len = size;
trk->vos_data = av_malloc(size);
if (!trk->vos_data) {
ret = AVERROR(ENOMEM);
goto err;
}
memcpy(trk->vos_data, pkt->data, size);
}
if (trk->entry >= trk->cluster_capacity) {
unsigned new_capacity = 2 * (trk->entry + MOV_INDEX_CLUSTER_SIZE);
if (av_reallocp_array(&trk->cluster, new_capacity,
sizeof(*trk->cluster))) {
ret = AVERROR(ENOMEM);
goto err;
}
trk->cluster_capacity = new_capacity;
}
trk->cluster[trk->entry].pos = avio_tell(pb) - size;
trk->cluster[trk->entry].samples_in_chunk = samples_in_chunk;
trk->cluster[trk->entry].chunkNum = 0;
trk->cluster[trk->entry].size = size;
trk->cluster[trk->entry].entries = samples_in_chunk;
trk->cluster[trk->entry].dts = pkt->dts;
trk->cluster[trk->entry].pts = pkt->pts;
if (!trk->entry && trk->start_dts != AV_NOPTS_VALUE) {
if (!trk->frag_discont) {
/* First packet of a new fragment. We already wrote the duration
* of the last packet of the previous fragment based on track_duration,
* which might not exactly match our dts. Therefore adjust the dts
* of this packet to be what the previous packets duration implies. */
trk->cluster[trk->entry].dts = trk->start_dts + trk->track_duration;
/* We also may have written the pts and the corresponding duration
* in sidx/tfrf/tfxd tags; make sure the sidx pts and duration match up with
* the next fragment. This means the cts of the first sample must
* be the same in all fragments, unless end_pts was updated by
* the packet causing the fragment to be written. */
if ((mov->flags & FF_MOV_FLAG_DASH && !(mov->flags & FF_MOV_FLAG_GLOBAL_SIDX)) ||
mov->mode == MODE_ISM)
pkt->pts = pkt->dts + trk->end_pts - trk->cluster[trk->entry].dts;
} else {
/* New fragment, but discontinuous from previous fragments.
* Pretend the duration sum of the earlier fragments is
* pkt->dts - trk->start_dts. */
trk->frag_start = pkt->dts - trk->start_dts;
trk->end_pts = AV_NOPTS_VALUE;
trk->frag_discont = 0;
}
}
if (!trk->entry && trk->start_dts == AV_NOPTS_VALUE && !mov->use_editlist &&
s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_MAKE_ZERO) {
/* Not using edit lists and shifting the first track to start from zero.
* If the other streams start from a later timestamp, we won't be able
* to signal the difference in starting time without an edit list.
* Thus move the timestamp for this first sample to 0, increasing
* its duration instead. */
trk->cluster[trk->entry].dts = trk->start_dts = 0;
}
if (trk->start_dts == AV_NOPTS_VALUE) {
trk->start_dts = pkt->dts;
if (trk->frag_discont) {
if (mov->use_editlist) {
/* Pretend the whole stream started at pts=0, with earlier fragments
* already written. If the stream started at pts=0, the duration sum
* of earlier fragments would have been pkt->pts. */
trk->frag_start = pkt->pts;
trk->start_dts = pkt->dts - pkt->pts;
} else {
/* Pretend the whole stream started at dts=0, with earlier fragments
* already written, with a duration summing up to pkt->dts. */
trk->frag_start = pkt->dts;
trk->start_dts = 0;
}
trk->frag_discont = 0;
} else if (pkt->dts && mov->moov_written)
av_log(s, AV_LOG_WARNING,
"Track %d starts with a nonzero dts %"PRId64", while the moov "
"already has been written. Set the delay_moov flag to handle "
"this case.\n",
pkt->stream_index, pkt->dts);
}
trk->track_duration = pkt->dts - trk->start_dts + pkt->duration;
trk->last_sample_is_subtitle_end = 0;
if (pkt->pts == AV_NOPTS_VALUE) {
av_log(s, AV_LOG_WARNING, "pts has no value\n");
pkt->pts = pkt->dts;
}
if (pkt->dts != pkt->pts)
trk->flags |= MOV_TRACK_CTTS;
trk->cluster[trk->entry].cts = pkt->pts - pkt->dts;
trk->cluster[trk->entry].flags = 0;
if (trk->start_cts == AV_NOPTS_VALUE)
trk->start_cts = pkt->pts - pkt->dts;
if (trk->end_pts == AV_NOPTS_VALUE)
trk->end_pts = trk->cluster[trk->entry].dts +
trk->cluster[trk->entry].cts + pkt->duration;
else
trk->end_pts = FFMAX(trk->end_pts, trk->cluster[trk->entry].dts +
trk->cluster[trk->entry].cts +
pkt->duration);
if (par->codec_id == AV_CODEC_ID_VC1) {
mov_parse_vc1_frame(pkt, trk);
} else if (pkt->flags & AV_PKT_FLAG_KEY) {
if (mov->mode == MODE_MOV && par->codec_id == AV_CODEC_ID_MPEG2VIDEO &&
trk->entry > 0) { // force sync sample for the first key frame
mov_parse_mpeg2_frame(pkt, &trk->cluster[trk->entry].flags);
if (trk->cluster[trk->entry].flags & MOV_PARTIAL_SYNC_SAMPLE)
trk->flags |= MOV_TRACK_STPS;
} else {
trk->cluster[trk->entry].flags = MOV_SYNC_SAMPLE;
}
if (trk->cluster[trk->entry].flags & MOV_SYNC_SAMPLE)
trk->has_keyframes++;
}
if (pkt->flags & AV_PKT_FLAG_DISPOSABLE) {
trk->cluster[trk->entry].flags |= MOV_DISPOSABLE_SAMPLE;
trk->has_disposable++;
}
trk->entry++;
trk->sample_count += samples_in_chunk;
mov->mdat_size += size;
if (trk->hint_track >= 0 && trk->hint_track < mov->nb_streams)
ff_mov_add_hinted_packet(s, pkt, trk->hint_track, trk->entry,
reformatted_data, size);
end:
err:
av_free(reformatted_data);
return ret;
}
static int mov_write_single_packet(AVFormatContext *s, AVPacket *pkt)
{
MOVMuxContext *mov = s->priv_data;
MOVTrack *trk = &mov->tracks[pkt->stream_index];
AVCodecParameters *par = trk->par;
int64_t frag_duration = 0;
int size = pkt->size;
int ret = check_pkt(s, pkt);
if (ret < 0)
return ret;
if (mov->flags & FF_MOV_FLAG_FRAG_DISCONT) {
int i;
for (i = 0; i < s->nb_streams; i++)
mov->tracks[i].frag_discont = 1;
mov->flags &= ~FF_MOV_FLAG_FRAG_DISCONT;
}
if (mov->flags & FF_MOV_FLAG_NEGATIVE_CTS_OFFSETS) {
if (trk->dts_shift == AV_NOPTS_VALUE)
trk->dts_shift = pkt->pts - pkt->dts;
pkt->dts += trk->dts_shift;
}
if (trk->par->codec_id == AV_CODEC_ID_MP4ALS ||
trk->par->codec_id == AV_CODEC_ID_AAC ||
trk->par->codec_id == AV_CODEC_ID_FLAC) {
int side_size = 0;
uint8_t *side = av_packet_get_side_data(pkt, AV_PKT_DATA_NEW_EXTRADATA, &side_size);
if (side && side_size > 0 && (side_size != par->extradata_size || memcmp(side, par->extradata, side_size))) {
void *newextra = av_mallocz(side_size + AV_INPUT_BUFFER_PADDING_SIZE);
if (!newextra)
return AVERROR(ENOMEM);
av_free(par->extradata);
par->extradata = newextra;
memcpy(par->extradata, side, side_size);
par->extradata_size = side_size;
if (!pkt->size) // Flush packet
mov->need_rewrite_extradata = 1;
}
}
if (!pkt->size) {
if (trk->start_dts == AV_NOPTS_VALUE && trk->frag_discont) {
trk->start_dts = pkt->dts;
if (pkt->pts != AV_NOPTS_VALUE)
trk->start_cts = pkt->pts - pkt->dts;
else
trk->start_cts = 0;
}
return 0; /* Discard 0 sized packets */
}
if (trk->entry && pkt->stream_index < s->nb_streams)
frag_duration = av_rescale_q(pkt->dts - trk->cluster[0].dts,
s->streams[pkt->stream_index]->time_base,
AV_TIME_BASE_Q);
if ((mov->max_fragment_duration &&
frag_duration >= mov->max_fragment_duration) ||
(mov->max_fragment_size && mov->mdat_size + size >= mov->max_fragment_size) ||
(mov->flags & FF_MOV_FLAG_FRAG_KEYFRAME &&
par->codec_type == AVMEDIA_TYPE_VIDEO &&
trk->entry && pkt->flags & AV_PKT_FLAG_KEY) ||
(mov->flags & FF_MOV_FLAG_FRAG_EVERY_FRAME)) {
if (frag_duration >= mov->min_fragment_duration) {
// Set the duration of this track to line up with the next
// sample in this track. This avoids relying on AVPacket
// duration, but only helps for this particular track, not
// for the other ones that are flushed at the same time.
trk->track_duration = pkt->dts - trk->start_dts;
if (pkt->pts != AV_NOPTS_VALUE)
trk->end_pts = pkt->pts;
else
trk->end_pts = pkt->dts;
trk->end_reliable = 1;
mov_auto_flush_fragment(s, 0);
}
}
return ff_mov_write_packet(s, pkt);
}
static int mov_write_subtitle_end_packet(AVFormatContext *s,
int stream_index,
int64_t dts) {
AVPacket end;
uint8_t data[2] = {0};
int ret;
av_init_packet(&end);
end.size = sizeof(data);
end.data = data;
end.pts = dts;
end.dts = dts;
end.duration = 0;
end.stream_index = stream_index;
ret = mov_write_single_packet(s, &end);
av_packet_unref(&end);
return ret;
}
static int mov_write_packet(AVFormatContext *s, AVPacket *pkt)
{
MOVMuxContext *mov = s->priv_data;
MOVTrack *trk;
if (!pkt) {
mov_flush_fragment(s, 1);
return 1;
}
trk = &mov->tracks[pkt->stream_index];
if (is_cover_image(trk->st)) {
int ret;
if (trk->st->nb_frames >= 1) {
if (trk->st->nb_frames == 1)
av_log(s, AV_LOG_WARNING, "Got more than one picture in stream %d,"
" ignoring.\n", pkt->stream_index);
return 0;
}
if ((ret = av_packet_ref(&trk->cover_image, pkt)) < 0)
return ret;
return 0;
} else {
int i;
if (!pkt->size)
return mov_write_single_packet(s, pkt); /* Passthrough. */
/*
* Subtitles require special handling.
*
* 1) For full complaince, every track must have a sample at
* dts == 0, which is rarely true for subtitles. So, as soon
* as we see any packet with dts > 0, write an empty subtitle
* at dts == 0 for any subtitle track with no samples in it.
*
* 2) For each subtitle track, check if the current packet's
* dts is past the duration of the last subtitle sample. If
* so, we now need to write an end sample for that subtitle.
*
* This must be done conditionally to allow for subtitles that
* immediately replace each other, in which case an end sample
* is not needed, and is, in fact, actively harmful.
*
* 3) See mov_write_trailer for how the final end sample is
* handled.
*/
for (i = 0; i < mov->nb_streams; i++) {
MOVTrack *trk = &mov->tracks[i];
int ret;
if (trk->par->codec_id == AV_CODEC_ID_MOV_TEXT &&
trk->track_duration < pkt->dts &&
(trk->entry == 0 || !trk->last_sample_is_subtitle_end)) {
ret = mov_write_subtitle_end_packet(s, i, trk->track_duration);
if (ret < 0) return ret;
trk->last_sample_is_subtitle_end = 1;
}
}
if (trk->mode == MODE_MOV && trk->par->codec_type == AVMEDIA_TYPE_VIDEO) {
AVPacket *opkt = pkt;
int reshuffle_ret, ret;
if (trk->is_unaligned_qt_rgb) {
int64_t bpc = trk->par->bits_per_coded_sample != 15 ? trk->par->bits_per_coded_sample : 16;
int expected_stride = ((trk->par->width * bpc + 15) >> 4)*2;
reshuffle_ret = ff_reshuffle_raw_rgb(s, &pkt, trk->par, expected_stride);
if (reshuffle_ret < 0)
return reshuffle_ret;
} else
reshuffle_ret = 0;
if (trk->par->format == AV_PIX_FMT_PAL8 && !trk->pal_done) {
ret = ff_get_packet_palette(s, opkt, reshuffle_ret, trk->palette);
if (ret < 0)
goto fail;
if (ret)
trk->pal_done++;
} else if (trk->par->codec_id == AV_CODEC_ID_RAWVIDEO &&
(trk->par->format == AV_PIX_FMT_GRAY8 ||
trk->par->format == AV_PIX_FMT_MONOBLACK)) {
for (i = 0; i < pkt->size; i++)
pkt->data[i] = ~pkt->data[i];
}
if (reshuffle_ret) {
ret = mov_write_single_packet(s, pkt);
fail:
if (reshuffle_ret)
av_packet_free(&pkt);
return ret;
}
}
return mov_write_single_packet(s, pkt);
}
}
// QuickTime chapters involve an additional text track with the chapter names
// as samples, and a tref pointing from the other tracks to the chapter one.
static int mov_create_chapter_track(AVFormatContext *s, int tracknum)
{
AVIOContext *pb;
MOVMuxContext *mov = s->priv_data;
MOVTrack *track = &mov->tracks[tracknum];
AVPacket pkt = { .stream_index = tracknum, .flags = AV_PKT_FLAG_KEY };
int i, len;
track->mode = mov->mode;
track->tag = MKTAG('t','e','x','t');
track->timescale = MOV_TIMESCALE;
track->par = avcodec_parameters_alloc();
if (!track->par)
return AVERROR(ENOMEM);
track->par->codec_type = AVMEDIA_TYPE_SUBTITLE;
#if 0
// These properties are required to make QT recognize the chapter track
uint8_t chapter_properties[43] = { 0, 0, 0, 0, 0, 0, 0, 1, };
if (ff_alloc_extradata(track->par, sizeof(chapter_properties)))
return AVERROR(ENOMEM);
memcpy(track->par->extradata, chapter_properties, sizeof(chapter_properties));
#else
if (avio_open_dyn_buf(&pb) >= 0) {
int size;
uint8_t *buf;
/* Stub header (usually for Quicktime chapter track) */
// TextSampleEntry
avio_wb32(pb, 0x01); // displayFlags
avio_w8(pb, 0x00); // horizontal justification
avio_w8(pb, 0x00); // vertical justification
avio_w8(pb, 0x00); // bgColourRed
avio_w8(pb, 0x00); // bgColourGreen
avio_w8(pb, 0x00); // bgColourBlue
avio_w8(pb, 0x00); // bgColourAlpha
// BoxRecord
avio_wb16(pb, 0x00); // defTextBoxTop
avio_wb16(pb, 0x00); // defTextBoxLeft
avio_wb16(pb, 0x00); // defTextBoxBottom
avio_wb16(pb, 0x00); // defTextBoxRight
// StyleRecord
avio_wb16(pb, 0x00); // startChar
avio_wb16(pb, 0x00); // endChar
avio_wb16(pb, 0x01); // fontID
avio_w8(pb, 0x00); // fontStyleFlags
avio_w8(pb, 0x00); // fontSize
avio_w8(pb, 0x00); // fgColourRed
avio_w8(pb, 0x00); // fgColourGreen
avio_w8(pb, 0x00); // fgColourBlue
avio_w8(pb, 0x00); // fgColourAlpha
// FontTableBox
avio_wb32(pb, 0x0D); // box size
ffio_wfourcc(pb, "ftab"); // box atom name
avio_wb16(pb, 0x01); // entry count
// FontRecord
avio_wb16(pb, 0x01); // font ID
avio_w8(pb, 0x00); // font name length
if ((size = avio_close_dyn_buf(pb, &buf)) > 0) {
track->par->extradata = buf;
track->par->extradata_size = size;
} else {
av_freep(&buf);
}
}
#endif
for (i = 0; i < s->nb_chapters; i++) {
AVChapter *c = s->chapters[i];
AVDictionaryEntry *t;
int64_t end = av_rescale_q(c->end, c->time_base, (AVRational){1,MOV_TIMESCALE});
pkt.pts = pkt.dts = av_rescale_q(c->start, c->time_base, (AVRational){1,MOV_TIMESCALE});
pkt.duration = end - pkt.dts;
if ((t = av_dict_get(c->metadata, "title", NULL, 0))) {
static const char encd[12] = {
0x00, 0x00, 0x00, 0x0C,
'e', 'n', 'c', 'd',
0x00, 0x00, 0x01, 0x00 };
len = strlen(t->value);
pkt.size = len + 2 + 12;
pkt.data = av_malloc(pkt.size);
if (!pkt.data)
return AVERROR(ENOMEM);
AV_WB16(pkt.data, len);
memcpy(pkt.data + 2, t->value, len);
memcpy(pkt.data + len + 2, encd, sizeof(encd));
ff_mov_write_packet(s, &pkt);
av_freep(&pkt.data);
}
}
return 0;
}
static int mov_check_timecode_track(AVFormatContext *s, AVTimecode *tc, int src_index, const char *tcstr)
{
int ret;
/* compute the frame number */
ret = av_timecode_init_from_string(tc, find_fps(s, s->streams[src_index]), tcstr, s);
return ret;
}
static int mov_create_timecode_track(AVFormatContext *s, int index, int src_index, AVTimecode tc)
{
int ret;
MOVMuxContext *mov = s->priv_data;
MOVTrack *track = &mov->tracks[index];
AVStream *src_st = s->streams[src_index];
AVPacket pkt = {.stream_index = index, .flags = AV_PKT_FLAG_KEY, .size = 4};
AVRational rate = find_fps(s, src_st);
/* tmcd track based on video stream */
track->mode = mov->mode;
track->tag = MKTAG('t','m','c','d');
track->src_track = src_index;
track->timescale = mov->tracks[src_index].timescale;
if (tc.flags & AV_TIMECODE_FLAG_DROPFRAME)
track->timecode_flags |= MOV_TIMECODE_FLAG_DROPFRAME;
/* set st to src_st for metadata access*/
track->st = src_st;
/* encode context: tmcd data stream */
track->par = avcodec_parameters_alloc();
if (!track->par)
return AVERROR(ENOMEM);
track->par->codec_type = AVMEDIA_TYPE_DATA;
track->par->codec_tag = track->tag;
track->st->avg_frame_rate = av_inv_q(rate);
/* the tmcd track just contains one packet with the frame number */
pkt.data = av_malloc(pkt.size);
if (!pkt.data)
return AVERROR(ENOMEM);
AV_WB32(pkt.data, tc.start);
ret = ff_mov_write_packet(s, &pkt);
av_free(pkt.data);
return ret;
}
/*
* st->disposition controls the "enabled" flag in the tkhd tag.
* QuickTime will not play a track if it is not enabled. So make sure
* that one track of each type (audio, video, subtitle) is enabled.
*
* Subtitles are special. For audio and video, setting "enabled" also
* makes the track "default" (i.e. it is rendered when played). For
* subtitles, an "enabled" subtitle is not rendered by default, but
* if no subtitle is enabled, the subtitle menu in QuickTime will be
* empty!
*/
static void enable_tracks(AVFormatContext *s)
{
MOVMuxContext *mov = s->priv_data;
int i;
int enabled[AVMEDIA_TYPE_NB];
int first[AVMEDIA_TYPE_NB];
for (i = 0; i < AVMEDIA_TYPE_NB; i++) {
enabled[i] = 0;
first[i] = -1;
}
for (i = 0; i < s->nb_streams; i++) {
AVStream *st = s->streams[i];
if (st->codecpar->codec_type <= AVMEDIA_TYPE_UNKNOWN ||
st->codecpar->codec_type >= AVMEDIA_TYPE_NB ||
is_cover_image(st))
continue;
if (first[st->codecpar->codec_type] < 0)
first[st->codecpar->codec_type] = i;
if (st->disposition & AV_DISPOSITION_DEFAULT) {
mov->tracks[i].flags |= MOV_TRACK_ENABLED;
enabled[st->codecpar->codec_type]++;
}
}
for (i = 0; i < AVMEDIA_TYPE_NB; i++) {
switch (i) {
case AVMEDIA_TYPE_VIDEO:
case AVMEDIA_TYPE_AUDIO:
case AVMEDIA_TYPE_SUBTITLE:
if (enabled[i] > 1)
mov->per_stream_grouping = 1;
if (!enabled[i] && first[i] >= 0)
mov->tracks[first[i]].flags |= MOV_TRACK_ENABLED;
break;
}
}
}
static void mov_free(AVFormatContext *s)
{
MOVMuxContext *mov = s->priv_data;
int i;
if (mov->chapter_track) {
if (mov->tracks[mov->chapter_track].par)
av_freep(&mov->tracks[mov->chapter_track].par->extradata);
av_freep(&mov->tracks[mov->chapter_track].par);
}
for (i = 0; i < mov->nb_streams; i++) {
if (mov->tracks[i].tag == MKTAG('r','t','p',' '))
ff_mov_close_hinting(&mov->tracks[i]);
else if (mov->tracks[i].tag == MKTAG('t','m','c','d') && mov->nb_meta_tmcd)
av_freep(&mov->tracks[i].par);
av_freep(&mov->tracks[i].cluster);
av_freep(&mov->tracks[i].frag_info);
av_packet_unref(&mov->tracks[i].cover_image);
if (mov->tracks[i].vos_len)
av_freep(&mov->tracks[i].vos_data);
ff_mov_cenc_free(&mov->tracks[i].cenc);
}
av_freep(&mov->tracks);
}
static uint32_t rgb_to_yuv(uint32_t rgb)
{
uint8_t r, g, b;
int y, cb, cr;
r = (rgb >> 16) & 0xFF;
g = (rgb >> 8) & 0xFF;
b = (rgb ) & 0xFF;
y = av_clip_uint8(( 16000 + 257 * r + 504 * g + 98 * b)/1000);
cb = av_clip_uint8((128000 - 148 * r - 291 * g + 439 * b)/1000);
cr = av_clip_uint8((128000 + 439 * r - 368 * g - 71 * b)/1000);
return (y << 16) | (cr << 8) | cb;
}
static int mov_create_dvd_sub_decoder_specific_info(MOVTrack *track,
AVStream *st)
{
int i, width = 720, height = 480;
int have_palette = 0, have_size = 0;
uint32_t palette[16];
char *cur = st->codecpar->extradata;
while (cur && *cur) {
if (strncmp("palette:", cur, 8) == 0) {
int i, count;
count = sscanf(cur + 8,
"%06"PRIx32", %06"PRIx32", %06"PRIx32", %06"PRIx32", "
"%06"PRIx32", %06"PRIx32", %06"PRIx32", %06"PRIx32", "
"%06"PRIx32", %06"PRIx32", %06"PRIx32", %06"PRIx32", "
"%06"PRIx32", %06"PRIx32", %06"PRIx32", %06"PRIx32"",
&palette[ 0], &palette[ 1], &palette[ 2], &palette[ 3],
&palette[ 4], &palette[ 5], &palette[ 6], &palette[ 7],
&palette[ 8], &palette[ 9], &palette[10], &palette[11],
&palette[12], &palette[13], &palette[14], &palette[15]);
for (i = 0; i < count; i++) {
palette[i] = rgb_to_yuv(palette[i]);
}
have_palette = 1;
} else if (!strncmp("size:", cur, 5)) {
sscanf(cur + 5, "%dx%d", &width, &height);
have_size = 1;
}
if (have_palette && have_size)
break;
cur += strcspn(cur, "\n\r");
cur += strspn(cur, "\n\r");
}
if (have_palette) {
track->vos_data = av_malloc(16*4);
if (!track->vos_data)
return AVERROR(ENOMEM);
for (i = 0; i < 16; i++) {
AV_WB32(track->vos_data + i * 4, palette[i]);
}
track->vos_len = 16 * 4;
}
st->codecpar->width = width;
st->codecpar->height = track->height = height;
return 0;
}
static int mov_init(AVFormatContext *s)
{
MOVMuxContext *mov = s->priv_data;
AVDictionaryEntry *global_tcr = av_dict_get(s->metadata, "timecode", NULL, 0);
int i, ret;
mov->fc = s;
/* Default mode == MP4 */
mov->mode = MODE_MP4;
if (s->oformat) {
if (!strcmp("3gp", s->oformat->name)) mov->mode = MODE_3GP;
else if (!strcmp("3g2", s->oformat->name)) mov->mode = MODE_3GP|MODE_3G2;
else if (!strcmp("mov", s->oformat->name)) mov->mode = MODE_MOV;
else if (!strcmp("psp", s->oformat->name)) mov->mode = MODE_PSP;
else if (!strcmp("ipod",s->oformat->name)) mov->mode = MODE_IPOD;
else if (!strcmp("ismv",s->oformat->name)) mov->mode = MODE_ISM;
else if (!strcmp("f4v", s->oformat->name)) mov->mode = MODE_F4V;
}
if (mov->flags & FF_MOV_FLAG_DELAY_MOOV)
mov->flags |= FF_MOV_FLAG_EMPTY_MOOV;
/* Set the FRAGMENT flag if any of the fragmentation methods are
* enabled. */
if (mov->max_fragment_duration || mov->max_fragment_size ||
mov->flags & (FF_MOV_FLAG_EMPTY_MOOV |
FF_MOV_FLAG_FRAG_KEYFRAME |
FF_MOV_FLAG_FRAG_CUSTOM |
FF_MOV_FLAG_FRAG_EVERY_FRAME))
mov->flags |= FF_MOV_FLAG_FRAGMENT;
/* Set other implicit flags immediately */
if (mov->mode == MODE_ISM)
mov->flags |= FF_MOV_FLAG_EMPTY_MOOV | FF_MOV_FLAG_SEPARATE_MOOF |
FF_MOV_FLAG_FRAGMENT;
if (mov->flags & FF_MOV_FLAG_DASH)
mov->flags |= FF_MOV_FLAG_FRAGMENT | FF_MOV_FLAG_EMPTY_MOOV |
FF_MOV_FLAG_DEFAULT_BASE_MOOF;
if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV && s->flags & AVFMT_FLAG_AUTO_BSF) {
av_log(s, AV_LOG_VERBOSE, "Empty MOOV enabled; disabling automatic bitstream filtering\n");
s->flags &= ~AVFMT_FLAG_AUTO_BSF;
}
if (mov->flags & FF_MOV_FLAG_FASTSTART) {
mov->reserved_moov_size = -1;
}
if (mov->use_editlist < 0) {
mov->use_editlist = 1;
if (mov->flags & FF_MOV_FLAG_FRAGMENT &&
!(mov->flags & FF_MOV_FLAG_DELAY_MOOV)) {
// If we can avoid needing an edit list by shifting the
// tracks, prefer that over (trying to) write edit lists
// in fragmented output.
if (s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_AUTO ||
s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_MAKE_ZERO)
mov->use_editlist = 0;
}
}
if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV &&
!(mov->flags & FF_MOV_FLAG_DELAY_MOOV) && mov->use_editlist)
av_log(s, AV_LOG_WARNING, "No meaningful edit list will be written when using empty_moov without delay_moov\n");
if (!mov->use_editlist && s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_AUTO)
s->avoid_negative_ts = AVFMT_AVOID_NEG_TS_MAKE_ZERO;
/* Clear the omit_tfhd_offset flag if default_base_moof is set;
* if the latter is set that's enough and omit_tfhd_offset doesn't
* add anything extra on top of that. */
if (mov->flags & FF_MOV_FLAG_OMIT_TFHD_OFFSET &&
mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF)
mov->flags &= ~FF_MOV_FLAG_OMIT_TFHD_OFFSET;
if (mov->frag_interleave &&
mov->flags & (FF_MOV_FLAG_OMIT_TFHD_OFFSET | FF_MOV_FLAG_SEPARATE_MOOF)) {
av_log(s, AV_LOG_ERROR,
"Sample interleaving in fragments is mutually exclusive with "
"omit_tfhd_offset and separate_moof\n");
return AVERROR(EINVAL);
}
/* Non-seekable output is ok if using fragmentation. If ism_lookahead
* is enabled, we don't support non-seekable output at all. */
if (!(s->pb->seekable & AVIO_SEEKABLE_NORMAL) &&
(!(mov->flags & FF_MOV_FLAG_FRAGMENT) || mov->ism_lookahead)) {
av_log(s, AV_LOG_ERROR, "muxer does not support non seekable output\n");
return AVERROR(EINVAL);
}
mov->nb_streams = s->nb_streams;
if (mov->mode & (MODE_MP4|MODE_MOV|MODE_IPOD) && s->nb_chapters)
mov->chapter_track = mov->nb_streams++;
if (mov->flags & FF_MOV_FLAG_RTP_HINT) {
for (i = 0; i < s->nb_streams; i++)
if (rtp_hinting_needed(s->streams[i]))
mov->nb_streams++;
}
if ( mov->write_tmcd == -1 && (mov->mode == MODE_MOV || mov->mode == MODE_MP4)
|| mov->write_tmcd == 1) {
/* +1 tmcd track for each video stream with a timecode */
for (i = 0; i < s->nb_streams; i++) {
AVStream *st = s->streams[i];
AVDictionaryEntry *t = global_tcr;
if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO &&
(t || (t=av_dict_get(st->metadata, "timecode", NULL, 0)))) {
AVTimecode tc;
ret = mov_check_timecode_track(s, &tc, i, t->value);
if (ret >= 0)
mov->nb_meta_tmcd++;
}
}
/* check if there is already a tmcd track to remux */
if (mov->nb_meta_tmcd) {
for (i = 0; i < s->nb_streams; i++) {
AVStream *st = s->streams[i];
if (st->codecpar->codec_tag == MKTAG('t','m','c','d')) {
av_log(s, AV_LOG_WARNING, "You requested a copy of the original timecode track "
"so timecode metadata are now ignored\n");
mov->nb_meta_tmcd = 0;
}
}
}
mov->nb_streams += mov->nb_meta_tmcd;
}
// Reserve an extra stream for chapters for the case where chapters
// are written in the trailer
mov->tracks = av_mallocz_array((mov->nb_streams + 1), sizeof(*mov->tracks));
if (!mov->tracks)
return AVERROR(ENOMEM);
if (mov->encryption_scheme_str != NULL && strcmp(mov->encryption_scheme_str, "none") != 0) {
if (strcmp(mov->encryption_scheme_str, "cenc-aes-ctr") == 0) {
mov->encryption_scheme = MOV_ENC_CENC_AES_CTR;
if (mov->encryption_key_len != AES_CTR_KEY_SIZE) {
av_log(s, AV_LOG_ERROR, "Invalid encryption key len %d expected %d\n",
mov->encryption_key_len, AES_CTR_KEY_SIZE);
return AVERROR(EINVAL);
}
if (mov->encryption_kid_len != CENC_KID_SIZE) {
av_log(s, AV_LOG_ERROR, "Invalid encryption kid len %d expected %d\n",
mov->encryption_kid_len, CENC_KID_SIZE);
return AVERROR(EINVAL);
}
} else {
av_log(s, AV_LOG_ERROR, "unsupported encryption scheme %s\n",
mov->encryption_scheme_str);
return AVERROR(EINVAL);
}
}
for (i = 0; i < s->nb_streams; i++) {
AVStream *st= s->streams[i];
MOVTrack *track= &mov->tracks[i];
AVDictionaryEntry *lang = av_dict_get(st->metadata, "language", NULL,0);
track->st = st;
track->par = st->codecpar;
track->language = ff_mov_iso639_to_lang(lang?lang->value:"und", mov->mode!=MODE_MOV);
if (track->language < 0)
track->language = 0;
track->mode = mov->mode;
track->tag = mov_find_codec_tag(s, track);
if (!track->tag) {
av_log(s, AV_LOG_ERROR, "Could not find tag for codec %s in stream #%d, "
"codec not currently supported in container\n",
avcodec_get_name(st->codecpar->codec_id), i);
return AVERROR(EINVAL);
}
/* If hinting of this track is enabled by a later hint track,
* this is updated. */
track->hint_track = -1;
track->start_dts = AV_NOPTS_VALUE;
track->start_cts = AV_NOPTS_VALUE;
track->end_pts = AV_NOPTS_VALUE;
track->dts_shift = AV_NOPTS_VALUE;
if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
if (track->tag == MKTAG('m','x','3','p') || track->tag == MKTAG('m','x','3','n') ||
track->tag == MKTAG('m','x','4','p') || track->tag == MKTAG('m','x','4','n') ||
track->tag == MKTAG('m','x','5','p') || track->tag == MKTAG('m','x','5','n')) {
if (st->codecpar->width != 720 || (st->codecpar->height != 608 && st->codecpar->height != 512)) {
av_log(s, AV_LOG_ERROR, "D-10/IMX must use 720x608 or 720x512 video resolution\n");
return AVERROR(EINVAL);
}
track->height = track->tag >> 24 == 'n' ? 486 : 576;
}
if (mov->video_track_timescale) {
track->timescale = mov->video_track_timescale;
} else {
track->timescale = st->time_base.den;
while(track->timescale < 10000)
track->timescale *= 2;
}
if (st->codecpar->width > 65535 || st->codecpar->height > 65535) {
av_log(s, AV_LOG_ERROR, "Resolution %dx%d too large for mov/mp4\n", st->codecpar->width, st->codecpar->height);
return AVERROR(EINVAL);
}
if (track->mode == MODE_MOV && track->timescale > 100000)
av_log(s, AV_LOG_WARNING,
"WARNING codec timebase is very high. If duration is too long,\n"
"file may not be playable by quicktime. Specify a shorter timebase\n"
"or choose different container.\n");
if (track->mode == MODE_MOV &&
track->par->codec_id == AV_CODEC_ID_RAWVIDEO &&
track->tag == MKTAG('r','a','w',' ')) {
enum AVPixelFormat pix_fmt = track->par->format;
if (pix_fmt == AV_PIX_FMT_NONE && track->par->bits_per_coded_sample == 1)
pix_fmt = AV_PIX_FMT_MONOWHITE;
track->is_unaligned_qt_rgb =
pix_fmt == AV_PIX_FMT_RGB24 ||
pix_fmt == AV_PIX_FMT_BGR24 ||
pix_fmt == AV_PIX_FMT_PAL8 ||
pix_fmt == AV_PIX_FMT_GRAY8 ||
pix_fmt == AV_PIX_FMT_MONOWHITE ||
pix_fmt == AV_PIX_FMT_MONOBLACK;
}
if (track->par->codec_id == AV_CODEC_ID_VP9) {
if (track->mode != MODE_MP4) {
av_log(s, AV_LOG_ERROR, "VP9 only supported in MP4.\n");
return AVERROR(EINVAL);
}
} else if (track->par->codec_id == AV_CODEC_ID_AV1) {
/* spec is not finished, so forbid for now */
av_log(s, AV_LOG_ERROR, "AV1 muxing is currently not supported.\n");
return AVERROR_PATCHWELCOME;
} else if (track->par->codec_id == AV_CODEC_ID_VP8) {
/* altref frames handling is not defined in the spec as of version v1.0,
* so just forbid muxing VP8 streams altogether until a new version does */
av_log(s, AV_LOG_ERROR, "VP8 muxing is currently not supported.\n");
return AVERROR_PATCHWELCOME;
}
} else if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
track->timescale = st->codecpar->sample_rate;
if (!st->codecpar->frame_size && !av_get_bits_per_sample(st->codecpar->codec_id)) {
av_log(s, AV_LOG_WARNING, "track %d: codec frame size is not set\n", i);
track->audio_vbr = 1;
}else if (st->codecpar->codec_id == AV_CODEC_ID_ADPCM_MS ||
st->codecpar->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV ||
st->codecpar->codec_id == AV_CODEC_ID_ILBC){
if (!st->codecpar->block_align) {
av_log(s, AV_LOG_ERROR, "track %d: codec block align is not set for adpcm\n", i);
return AVERROR(EINVAL);
}
track->sample_size = st->codecpar->block_align;
}else if (st->codecpar->frame_size > 1){ /* assume compressed audio */
track->audio_vbr = 1;
}else{
track->sample_size = (av_get_bits_per_sample(st->codecpar->codec_id) >> 3) * st->codecpar->channels;
}
if (st->codecpar->codec_id == AV_CODEC_ID_ILBC ||
st->codecpar->codec_id == AV_CODEC_ID_ADPCM_IMA_QT) {
track->audio_vbr = 1;
}
if (track->mode != MODE_MOV &&
track->par->codec_id == AV_CODEC_ID_MP3 && track->timescale < 16000) {
if (s->strict_std_compliance >= FF_COMPLIANCE_NORMAL) {
av_log(s, AV_LOG_ERROR, "track %d: muxing mp3 at %dhz is not standard, to mux anyway set strict to -1\n",
i, track->par->sample_rate);
return AVERROR(EINVAL);
} else {
av_log(s, AV_LOG_WARNING, "track %d: muxing mp3 at %dhz is not standard in MP4\n",
i, track->par->sample_rate);
}
}
if (track->par->codec_id == AV_CODEC_ID_FLAC ||
track->par->codec_id == AV_CODEC_ID_OPUS) {
if (track->mode != MODE_MP4) {
av_log(s, AV_LOG_ERROR, "%s only supported in MP4.\n", avcodec_get_name(track->par->codec_id));
return AVERROR(EINVAL);
}
if (s->strict_std_compliance > FF_COMPLIANCE_EXPERIMENTAL) {
av_log(s, AV_LOG_ERROR,
"%s in MP4 support is experimental, add "
"'-strict %d' if you want to use it.\n",
avcodec_get_name(track->par->codec_id), FF_COMPLIANCE_EXPERIMENTAL);
return AVERROR_EXPERIMENTAL;
}
}
} else if (st->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE) {
track->timescale = st->time_base.den;
} else if (st->codecpar->codec_type == AVMEDIA_TYPE_DATA) {
track->timescale = st->time_base.den;
} else {
track->timescale = MOV_TIMESCALE;
}
if (!track->height)
track->height = st->codecpar->height;
/* The ism specific timescale isn't mandatory, but is assumed by
* some tools, such as mp4split. */
if (mov->mode == MODE_ISM)
track->timescale = 10000000;
avpriv_set_pts_info(st, 64, 1, track->timescale);
if (mov->encryption_scheme == MOV_ENC_CENC_AES_CTR) {
ret = ff_mov_cenc_init(&track->cenc, mov->encryption_key,
track->par->codec_id == AV_CODEC_ID_H264, s->flags & AVFMT_FLAG_BITEXACT);
if (ret)
return ret;
}
}
enable_tracks(s);
return 0;
}
static int mov_write_header(AVFormatContext *s)
{
AVIOContext *pb = s->pb;
MOVMuxContext *mov = s->priv_data;
AVDictionaryEntry *t, *global_tcr = av_dict_get(s->metadata, "timecode", NULL, 0);
int i, ret, hint_track = 0, tmcd_track = 0, nb_tracks = s->nb_streams;
if (mov->mode & (MODE_MP4|MODE_MOV|MODE_IPOD) && s->nb_chapters)
nb_tracks++;
if (mov->flags & FF_MOV_FLAG_RTP_HINT) {
hint_track = nb_tracks;
for (i = 0; i < s->nb_streams; i++)
if (rtp_hinting_needed(s->streams[i]))
nb_tracks++;
}
if (mov->mode == MODE_MOV || mov->mode == MODE_MP4)
tmcd_track = nb_tracks;
for (i = 0; i < s->nb_streams; i++) {
int j;
AVStream *st= s->streams[i];
MOVTrack *track= &mov->tracks[i];
/* copy extradata if it exists */
if (st->codecpar->extradata_size) {
if (st->codecpar->codec_id == AV_CODEC_ID_DVD_SUBTITLE)
mov_create_dvd_sub_decoder_specific_info(track, st);
else if (!TAG_IS_AVCI(track->tag) && st->codecpar->codec_id != AV_CODEC_ID_DNXHD) {
track->vos_len = st->codecpar->extradata_size;
track->vos_data = av_malloc(track->vos_len);
if (!track->vos_data) {
return AVERROR(ENOMEM);
}
memcpy(track->vos_data, st->codecpar->extradata, track->vos_len);
}
}
if (st->codecpar->codec_type != AVMEDIA_TYPE_AUDIO ||
track->par->channel_layout != AV_CH_LAYOUT_MONO)
continue;
for (j = 0; j < s->nb_streams; j++) {
AVStream *stj= s->streams[j];
MOVTrack *trackj= &mov->tracks[j];
if (j == i)
continue;
if (stj->codecpar->codec_type != AVMEDIA_TYPE_AUDIO ||
trackj->par->channel_layout != AV_CH_LAYOUT_MONO ||
trackj->language != track->language ||
trackj->tag != track->tag
)
continue;
track->multichannel_as_mono++;
}
}
if (!(mov->flags & FF_MOV_FLAG_DELAY_MOOV)) {
if ((ret = mov_write_identification(pb, s)) < 0)
return ret;
}
if (mov->reserved_moov_size){
mov->reserved_header_pos = avio_tell(pb);
if (mov->reserved_moov_size > 0)
avio_skip(pb, mov->reserved_moov_size);
}
if (mov->flags & FF_MOV_FLAG_FRAGMENT) {
/* If no fragmentation options have been set, set a default. */
if (!(mov->flags & (FF_MOV_FLAG_FRAG_KEYFRAME |
FF_MOV_FLAG_FRAG_CUSTOM |
FF_MOV_FLAG_FRAG_EVERY_FRAME)) &&
!mov->max_fragment_duration && !mov->max_fragment_size)
mov->flags |= FF_MOV_FLAG_FRAG_KEYFRAME;
} else {
if (mov->flags & FF_MOV_FLAG_FASTSTART)
mov->reserved_header_pos = avio_tell(pb);
mov_write_mdat_tag(pb, mov);
}
ff_parse_creation_time_metadata(s, &mov->time, 1);
if (mov->time)
mov->time += 0x7C25B080; // 1970 based -> 1904 based
if (mov->chapter_track)
if ((ret = mov_create_chapter_track(s, mov->chapter_track)) < 0)
return ret;
if (mov->flags & FF_MOV_FLAG_RTP_HINT) {
for (i = 0; i < s->nb_streams; i++) {
if (rtp_hinting_needed(s->streams[i])) {
if ((ret = ff_mov_init_hinting(s, hint_track, i)) < 0)
return ret;
hint_track++;
}
}
}
if (mov->nb_meta_tmcd) {
/* Initialize the tmcd tracks */
for (i = 0; i < s->nb_streams; i++) {
AVStream *st = s->streams[i];
t = global_tcr;
if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
AVTimecode tc;
if (!t)
t = av_dict_get(st->metadata, "timecode", NULL, 0);
if (!t)
continue;
if (mov_check_timecode_track(s, &tc, i, t->value) < 0)
continue;
if ((ret = mov_create_timecode_track(s, tmcd_track, i, tc)) < 0)
return ret;
tmcd_track++;
}
}
}
avio_flush(pb);
if (mov->flags & FF_MOV_FLAG_ISML)
mov_write_isml_manifest(pb, mov, s);
if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV &&
!(mov->flags & FF_MOV_FLAG_DELAY_MOOV)) {
if ((ret = mov_write_moov_tag(pb, mov, s)) < 0)
return ret;
avio_flush(pb);
mov->moov_written = 1;
if (mov->flags & FF_MOV_FLAG_GLOBAL_SIDX)
mov->reserved_header_pos = avio_tell(pb);
}
return 0;
}
static int get_moov_size(AVFormatContext *s)
{
int ret;
AVIOContext *moov_buf;
MOVMuxContext *mov = s->priv_data;
if ((ret = ffio_open_null_buf(&moov_buf)) < 0)
return ret;
if ((ret = mov_write_moov_tag(moov_buf, mov, s)) < 0)
return ret;
return ffio_close_null_buf(moov_buf);
}
static int get_sidx_size(AVFormatContext *s)
{
int ret;
AVIOContext *buf;
MOVMuxContext *mov = s->priv_data;
if ((ret = ffio_open_null_buf(&buf)) < 0)
return ret;
mov_write_sidx_tags(buf, mov, -1, 0);
return ffio_close_null_buf(buf);
}
/*
* This function gets the moov size if moved to the top of the file: the chunk
* offset table can switch between stco (32-bit entries) to co64 (64-bit
* entries) when the moov is moved to the beginning, so the size of the moov
* would change. It also updates the chunk offset tables.
*/
static int compute_moov_size(AVFormatContext *s)
{
int i, moov_size, moov_size2;
MOVMuxContext *mov = s->priv_data;
moov_size = get_moov_size(s);
if (moov_size < 0)
return moov_size;
for (i = 0; i < mov->nb_streams; i++)
mov->tracks[i].data_offset += moov_size;
moov_size2 = get_moov_size(s);
if (moov_size2 < 0)
return moov_size2;
/* if the size changed, we just switched from stco to co64 and need to
* update the offsets */
if (moov_size2 != moov_size)
for (i = 0; i < mov->nb_streams; i++)
mov->tracks[i].data_offset += moov_size2 - moov_size;
return moov_size2;
}
static int compute_sidx_size(AVFormatContext *s)
{
int i, sidx_size;
MOVMuxContext *mov = s->priv_data;
sidx_size = get_sidx_size(s);
if (sidx_size < 0)
return sidx_size;
for (i = 0; i < mov->nb_streams; i++)
mov->tracks[i].data_offset += sidx_size;
return sidx_size;
}
static int shift_data(AVFormatContext *s)
{
int ret = 0, moov_size;
MOVMuxContext *mov = s->priv_data;
int64_t pos, pos_end = avio_tell(s->pb);
uint8_t *buf, *read_buf[2];
int read_buf_id = 0;
int read_size[2];
AVIOContext *read_pb;
if (mov->flags & FF_MOV_FLAG_FRAGMENT)
moov_size = compute_sidx_size(s);
else
moov_size = compute_moov_size(s);
if (moov_size < 0)
return moov_size;
buf = av_malloc(moov_size * 2);
if (!buf)
return AVERROR(ENOMEM);
read_buf[0] = buf;
read_buf[1] = buf + moov_size;
/* Shift the data: the AVIO context of the output can only be used for
* writing, so we re-open the same output, but for reading. It also avoids
* a read/seek/write/seek back and forth. */
avio_flush(s->pb);
ret = s->io_open(s, &read_pb, s->url, AVIO_FLAG_READ, NULL);
if (ret < 0) {
av_log(s, AV_LOG_ERROR, "Unable to re-open %s output file for "
"the second pass (faststart)\n", s->url);
goto end;
}
/* mark the end of the shift to up to the last data we wrote, and get ready
* for writing */
pos_end = avio_tell(s->pb);
avio_seek(s->pb, mov->reserved_header_pos + moov_size, SEEK_SET);
/* start reading at where the new moov will be placed */
avio_seek(read_pb, mov->reserved_header_pos, SEEK_SET);
pos = avio_tell(read_pb);
#define READ_BLOCK do { \
read_size[read_buf_id] = avio_read(read_pb, read_buf[read_buf_id], moov_size); \
read_buf_id ^= 1; \
} while (0)
/* shift data by chunk of at most moov_size */
READ_BLOCK;
do {
int n;
READ_BLOCK;
n = read_size[read_buf_id];
if (n <= 0)
break;
avio_write(s->pb, read_buf[read_buf_id], n);
pos += n;
} while (pos < pos_end);
ff_format_io_close(s, &read_pb);
end:
av_free(buf);
return ret;
}
static int mov_write_trailer(AVFormatContext *s)
{
MOVMuxContext *mov = s->priv_data;
AVIOContext *pb = s->pb;
int res = 0;
int i;
int64_t moov_pos;
if (mov->need_rewrite_extradata) {
for (i = 0; i < s->nb_streams; i++) {
MOVTrack *track = &mov->tracks[i];
AVCodecParameters *par = track->par;
track->vos_len = par->extradata_size;
track->vos_data = av_malloc(track->vos_len);
if (!track->vos_data)
return AVERROR(ENOMEM);
memcpy(track->vos_data, par->extradata, track->vos_len);
}
mov->need_rewrite_extradata = 0;
}
/*
* Before actually writing the trailer, make sure that there are no
* dangling subtitles, that need a terminating sample.
*/
for (i = 0; i < mov->nb_streams; i++) {
MOVTrack *trk = &mov->tracks[i];
if (trk->par->codec_id == AV_CODEC_ID_MOV_TEXT &&
!trk->last_sample_is_subtitle_end) {
mov_write_subtitle_end_packet(s, i, trk->track_duration);
trk->last_sample_is_subtitle_end = 1;
}
}
// If there were no chapters when the header was written, but there
// are chapters now, write them in the trailer. This only works
// when we are not doing fragments.
if (!mov->chapter_track && !(mov->flags & FF_MOV_FLAG_FRAGMENT)) {
if (mov->mode & (MODE_MP4|MODE_MOV|MODE_IPOD) && s->nb_chapters) {
mov->chapter_track = mov->nb_streams++;
if ((res = mov_create_chapter_track(s, mov->chapter_track)) < 0)
return res;
}
}
if (!(mov->flags & FF_MOV_FLAG_FRAGMENT)) {
moov_pos = avio_tell(pb);
/* Write size of mdat tag */
if (mov->mdat_size + 8 <= UINT32_MAX) {
avio_seek(pb, mov->mdat_pos, SEEK_SET);
avio_wb32(pb, mov->mdat_size + 8);
} else {
/* overwrite 'wide' placeholder atom */
avio_seek(pb, mov->mdat_pos - 8, SEEK_SET);
/* special value: real atom size will be 64 bit value after
* tag field */
avio_wb32(pb, 1);
ffio_wfourcc(pb, "mdat");
avio_wb64(pb, mov->mdat_size + 16);
}
avio_seek(pb, mov->reserved_moov_size > 0 ? mov->reserved_header_pos : moov_pos, SEEK_SET);
if (mov->flags & FF_MOV_FLAG_FASTSTART) {
av_log(s, AV_LOG_INFO, "Starting second pass: moving the moov atom to the beginning of the file\n");
res = shift_data(s);
if (res < 0)
return res;
avio_seek(pb, mov->reserved_header_pos, SEEK_SET);
if ((res = mov_write_moov_tag(pb, mov, s)) < 0)
return res;
} else if (mov->reserved_moov_size > 0) {
int64_t size;
if ((res = mov_write_moov_tag(pb, mov, s)) < 0)
return res;
size = mov->reserved_moov_size - (avio_tell(pb) - mov->reserved_header_pos);
if (size < 8){
av_log(s, AV_LOG_ERROR, "reserved_moov_size is too small, needed %"PRId64" additional\n", 8-size);
return AVERROR(EINVAL);
}
avio_wb32(pb, size);
ffio_wfourcc(pb, "free");
ffio_fill(pb, 0, size - 8);
avio_seek(pb, moov_pos, SEEK_SET);
} else {
if ((res = mov_write_moov_tag(pb, mov, s)) < 0)
return res;
}
res = 0;
} else {
mov_auto_flush_fragment(s, 1);
for (i = 0; i < mov->nb_streams; i++)
mov->tracks[i].data_offset = 0;
if (mov->flags & FF_MOV_FLAG_GLOBAL_SIDX) {
int64_t end;
av_log(s, AV_LOG_INFO, "Starting second pass: inserting sidx atoms\n");
res = shift_data(s);
if (res < 0)
return res;
end = avio_tell(pb);
avio_seek(pb, mov->reserved_header_pos, SEEK_SET);
mov_write_sidx_tags(pb, mov, -1, 0);
avio_seek(pb, end, SEEK_SET);
avio_write_marker(s->pb, AV_NOPTS_VALUE, AVIO_DATA_MARKER_TRAILER);
mov_write_mfra_tag(pb, mov);
} else if (!(mov->flags & FF_MOV_FLAG_SKIP_TRAILER)) {
avio_write_marker(s->pb, AV_NOPTS_VALUE, AVIO_DATA_MARKER_TRAILER);
mov_write_mfra_tag(pb, mov);
}
}
return res;
}
static int mov_check_bitstream(struct AVFormatContext *s, const AVPacket *pkt)
{
int ret = 1;
AVStream *st = s->streams[pkt->stream_index];
if (st->codecpar->codec_id == AV_CODEC_ID_AAC) {
if (pkt->size > 2 && (AV_RB16(pkt->data) & 0xfff0) == 0xfff0)
ret = ff_stream_add_bitstream_filter(st, "aac_adtstoasc", NULL);
} else if (st->codecpar->codec_id == AV_CODEC_ID_VP9) {
ret = ff_stream_add_bitstream_filter(st, "vp9_superframe", NULL);
}
return ret;
}
static const AVCodecTag codec_3gp_tags[] = {
{ AV_CODEC_ID_H263, MKTAG('s','2','6','3') },
{ AV_CODEC_ID_H264, MKTAG('a','v','c','1') },
{ AV_CODEC_ID_MPEG4, MKTAG('m','p','4','v') },
{ AV_CODEC_ID_AAC, MKTAG('m','p','4','a') },
{ AV_CODEC_ID_AMR_NB, MKTAG('s','a','m','r') },
{ AV_CODEC_ID_AMR_WB, MKTAG('s','a','w','b') },
{ AV_CODEC_ID_MOV_TEXT, MKTAG('t','x','3','g') },
{ AV_CODEC_ID_NONE, 0 },
};
const AVCodecTag codec_mp4_tags[] = {
{ AV_CODEC_ID_MPEG4 , MKTAG('m', 'p', '4', 'v') },
{ AV_CODEC_ID_H264 , MKTAG('a', 'v', 'c', '1') },
{ AV_CODEC_ID_H264 , MKTAG('a', 'v', 'c', '3') },
{ AV_CODEC_ID_HEVC , MKTAG('h', 'e', 'v', '1') },
{ AV_CODEC_ID_HEVC , MKTAG('h', 'v', 'c', '1') },
{ AV_CODEC_ID_MPEG2VIDEO , MKTAG('m', 'p', '4', 'v') },
{ AV_CODEC_ID_MPEG1VIDEO , MKTAG('m', 'p', '4', 'v') },
{ AV_CODEC_ID_MJPEG , MKTAG('m', 'p', '4', 'v') },
{ AV_CODEC_ID_PNG , MKTAG('m', 'p', '4', 'v') },
{ AV_CODEC_ID_JPEG2000 , MKTAG('m', 'p', '4', 'v') },
{ AV_CODEC_ID_VC1 , MKTAG('v', 'c', '-', '1') },
{ AV_CODEC_ID_DIRAC , MKTAG('d', 'r', 'a', 'c') },
{ AV_CODEC_ID_TSCC2 , MKTAG('m', 'p', '4', 'v') },
{ AV_CODEC_ID_VP9 , MKTAG('v', 'p', '0', '9') },
{ AV_CODEC_ID_AAC , MKTAG('m', 'p', '4', 'a') },
{ AV_CODEC_ID_MP4ALS , MKTAG('m', 'p', '4', 'a') },
{ AV_CODEC_ID_MP3 , MKTAG('m', 'p', '4', 'a') },
{ AV_CODEC_ID_MP2 , MKTAG('m', 'p', '4', 'a') },
{ AV_CODEC_ID_AC3 , MKTAG('a', 'c', '-', '3') },
{ AV_CODEC_ID_EAC3 , MKTAG('e', 'c', '-', '3') },
{ AV_CODEC_ID_DTS , MKTAG('m', 'p', '4', 'a') },
{ AV_CODEC_ID_FLAC , MKTAG('f', 'L', 'a', 'C') },
{ AV_CODEC_ID_OPUS , MKTAG('O', 'p', 'u', 's') },
{ AV_CODEC_ID_VORBIS , MKTAG('m', 'p', '4', 'a') },
{ AV_CODEC_ID_QCELP , MKTAG('m', 'p', '4', 'a') },
{ AV_CODEC_ID_EVRC , MKTAG('m', 'p', '4', 'a') },
{ AV_CODEC_ID_DVD_SUBTITLE, MKTAG('m', 'p', '4', 's') },
{ AV_CODEC_ID_MOV_TEXT , MKTAG('t', 'x', '3', 'g') },
{ AV_CODEC_ID_NONE , 0 },
};
const AVCodecTag codec_ism_tags[] = {
{ AV_CODEC_ID_WMAPRO , MKTAG('w', 'm', 'a', ' ') },
{ AV_CODEC_ID_NONE , 0 },
};
static const AVCodecTag codec_ipod_tags[] = {
{ AV_CODEC_ID_H264, MKTAG('a','v','c','1') },
{ AV_CODEC_ID_MPEG4, MKTAG('m','p','4','v') },
{ AV_CODEC_ID_AAC, MKTAG('m','p','4','a') },
{ AV_CODEC_ID_ALAC, MKTAG('a','l','a','c') },
{ AV_CODEC_ID_AC3, MKTAG('a','c','-','3') },
{ AV_CODEC_ID_MOV_TEXT, MKTAG('t','x','3','g') },
{ AV_CODEC_ID_MOV_TEXT, MKTAG('t','e','x','t') },
{ AV_CODEC_ID_NONE, 0 },
};
static const AVCodecTag codec_f4v_tags[] = {
{ AV_CODEC_ID_MP3, MKTAG('.','m','p','3') },
{ AV_CODEC_ID_AAC, MKTAG('m','p','4','a') },
{ AV_CODEC_ID_H264, MKTAG('a','v','c','1') },
{ AV_CODEC_ID_VP6A, MKTAG('V','P','6','A') },
{ AV_CODEC_ID_VP6F, MKTAG('V','P','6','F') },
{ AV_CODEC_ID_NONE, 0 },
};
#if CONFIG_MOV_MUXER
MOV_CLASS(mov)
AVOutputFormat ff_mov_muxer = {
.name = "mov",
.long_name = NULL_IF_CONFIG_SMALL("QuickTime / MOV"),
.extensions = "mov",
.priv_data_size = sizeof(MOVMuxContext),
.audio_codec = AV_CODEC_ID_AAC,
.video_codec = CONFIG_LIBX264_ENCODER ?
AV_CODEC_ID_H264 : AV_CODEC_ID_MPEG4,
.init = mov_init,
.write_header = mov_write_header,
.write_packet = mov_write_packet,
.write_trailer = mov_write_trailer,
.deinit = mov_free,
.flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
.codec_tag = (const AVCodecTag* const []){
ff_codec_movvideo_tags, ff_codec_movaudio_tags, 0
},
.check_bitstream = mov_check_bitstream,
.priv_class = &mov_muxer_class,
};
#endif
#if CONFIG_TGP_MUXER
MOV_CLASS(tgp)
AVOutputFormat ff_tgp_muxer = {
.name = "3gp",
.long_name = NULL_IF_CONFIG_SMALL("3GP (3GPP file format)"),
.extensions = "3gp",
.priv_data_size = sizeof(MOVMuxContext),
.audio_codec = AV_CODEC_ID_AMR_NB,
.video_codec = AV_CODEC_ID_H263,
.init = mov_init,
.write_header = mov_write_header,
.write_packet = mov_write_packet,
.write_trailer = mov_write_trailer,
.deinit = mov_free,
.flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
.codec_tag = (const AVCodecTag* const []){ codec_3gp_tags, 0 },
.check_bitstream = mov_check_bitstream,
.priv_class = &tgp_muxer_class,
};
#endif
#if CONFIG_MP4_MUXER
MOV_CLASS(mp4)
AVOutputFormat ff_mp4_muxer = {
.name = "mp4",
.long_name = NULL_IF_CONFIG_SMALL("MP4 (MPEG-4 Part 14)"),
.mime_type = "video/mp4",
.extensions = "mp4",
.priv_data_size = sizeof(MOVMuxContext),
.audio_codec = AV_CODEC_ID_AAC,
.video_codec = CONFIG_LIBX264_ENCODER ?
AV_CODEC_ID_H264 : AV_CODEC_ID_MPEG4,
.init = mov_init,
.write_header = mov_write_header,
.write_packet = mov_write_packet,
.write_trailer = mov_write_trailer,
.deinit = mov_free,
.flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
.codec_tag = (const AVCodecTag* const []){ codec_mp4_tags, 0 },
.check_bitstream = mov_check_bitstream,
.priv_class = &mp4_muxer_class,
};
#endif
#if CONFIG_PSP_MUXER
MOV_CLASS(psp)
AVOutputFormat ff_psp_muxer = {
.name = "psp",
.long_name = NULL_IF_CONFIG_SMALL("PSP MP4 (MPEG-4 Part 14)"),
.extensions = "mp4,psp",
.priv_data_size = sizeof(MOVMuxContext),
.audio_codec = AV_CODEC_ID_AAC,
.video_codec = CONFIG_LIBX264_ENCODER ?
AV_CODEC_ID_H264 : AV_CODEC_ID_MPEG4,
.init = mov_init,
.write_header = mov_write_header,
.write_packet = mov_write_packet,
.write_trailer = mov_write_trailer,
.deinit = mov_free,
.flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
.codec_tag = (const AVCodecTag* const []){ codec_mp4_tags, 0 },
.check_bitstream = mov_check_bitstream,
.priv_class = &psp_muxer_class,
};
#endif
#if CONFIG_TG2_MUXER
MOV_CLASS(tg2)
AVOutputFormat ff_tg2_muxer = {
.name = "3g2",
.long_name = NULL_IF_CONFIG_SMALL("3GP2 (3GPP2 file format)"),
.extensions = "3g2",
.priv_data_size = sizeof(MOVMuxContext),
.audio_codec = AV_CODEC_ID_AMR_NB,
.video_codec = AV_CODEC_ID_H263,
.init = mov_init,
.write_header = mov_write_header,
.write_packet = mov_write_packet,
.write_trailer = mov_write_trailer,
.deinit = mov_free,
.flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
.codec_tag = (const AVCodecTag* const []){ codec_3gp_tags, 0 },
.check_bitstream = mov_check_bitstream,
.priv_class = &tg2_muxer_class,
};
#endif
#if CONFIG_IPOD_MUXER
MOV_CLASS(ipod)
AVOutputFormat ff_ipod_muxer = {
.name = "ipod",
.long_name = NULL_IF_CONFIG_SMALL("iPod H.264 MP4 (MPEG-4 Part 14)"),
.mime_type = "video/mp4",
.extensions = "m4v,m4a,m4b",
.priv_data_size = sizeof(MOVMuxContext),
.audio_codec = AV_CODEC_ID_AAC,
.video_codec = AV_CODEC_ID_H264,
.init = mov_init,
.write_header = mov_write_header,
.write_packet = mov_write_packet,
.write_trailer = mov_write_trailer,
.deinit = mov_free,
.flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
.codec_tag = (const AVCodecTag* const []){ codec_ipod_tags, 0 },
.check_bitstream = mov_check_bitstream,
.priv_class = &ipod_muxer_class,
};
#endif
#if CONFIG_ISMV_MUXER
MOV_CLASS(ismv)
AVOutputFormat ff_ismv_muxer = {
.name = "ismv",
.long_name = NULL_IF_CONFIG_SMALL("ISMV/ISMA (Smooth Streaming)"),
.mime_type = "video/mp4",
.extensions = "ismv,isma",
.priv_data_size = sizeof(MOVMuxContext),
.audio_codec = AV_CODEC_ID_AAC,
.video_codec = AV_CODEC_ID_H264,
.init = mov_init,
.write_header = mov_write_header,
.write_packet = mov_write_packet,
.write_trailer = mov_write_trailer,
.deinit = mov_free,
.flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
.codec_tag = (const AVCodecTag* const []){
codec_mp4_tags, codec_ism_tags, 0 },
.check_bitstream = mov_check_bitstream,
.priv_class = &ismv_muxer_class,
};
#endif
#if CONFIG_F4V_MUXER
MOV_CLASS(f4v)
AVOutputFormat ff_f4v_muxer = {
.name = "f4v",
.long_name = NULL_IF_CONFIG_SMALL("F4V Adobe Flash Video"),
.mime_type = "application/f4v",
.extensions = "f4v",
.priv_data_size = sizeof(MOVMuxContext),
.audio_codec = AV_CODEC_ID_AAC,
.video_codec = AV_CODEC_ID_H264,
.init = mov_init,
.write_header = mov_write_header,
.write_packet = mov_write_packet,
.write_trailer = mov_write_trailer,
.deinit = mov_free,
.flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH,
.codec_tag = (const AVCodecTag* const []){ codec_f4v_tags, 0 },
.check_bitstream = mov_check_bitstream,
.priv_class = &f4v_muxer_class,
};
#endif
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_215_0 |
crossvul-cpp_data_good_459_0 | /* Copyright (C) 2008-2018 - pancake, unlogic, emvivre */
#include <r_flag.h>
#include <r_core.h>
#include <r_asm.h>
#include <r_lib.h>
#include <r_types.h>
#include <stdio.h>
#include <string.h>
static ut64 getnum(RAsm *a, const char *s);
#define ENCODING_SHIFT 0
#define OPTYPE_SHIFT 6
#define REGMASK_SHIFT 16
#define OPSIZE_SHIFT 24
// How to encode the operand?
#define OT_REGMEM (1 << (ENCODING_SHIFT + 0))
#define OT_SPECIAL (1 << (ENCODING_SHIFT + 1))
#define OT_IMMEDIATE (1 << (ENCODING_SHIFT + 2))
#define OT_JMPADDRESS (1 << (ENCODING_SHIFT + 3))
// Register indices - by default, we allow all registers
#define OT_REGALL (0xff << REGMASK_SHIFT)
// Memory or register operands: how is the operand written in assembly code?
#define OT_MEMORY (1 << (OPTYPE_SHIFT + 0))
#define OT_CONSTANT (1 << (OPTYPE_SHIFT + 1))
#define OT_GPREG ((1 << (OPTYPE_SHIFT + 2)) | OT_REGALL)
#define OT_SEGMENTREG ((1 << (OPTYPE_SHIFT + 3)) | OT_REGALL)
#define OT_FPUREG ((1 << (OPTYPE_SHIFT + 4)) | OT_REGALL)
#define OT_MMXREG ((1 << (OPTYPE_SHIFT + 5)) | OT_REGALL)
#define OT_XMMREG ((1 << (OPTYPE_SHIFT + 6)) | OT_REGALL)
#define OT_CONTROLREG ((1 << (OPTYPE_SHIFT + 7)) | OT_REGALL)
#define OT_DEBUGREG ((1 << (OPTYPE_SHIFT + 8)) | OT_REGALL)
#define OT_SREG ((1 << (OPTYPE_SHIFT + 9)) | OT_REGALL)
// more?
#define OT_REGTYPE ((OT_GPREG | OT_SEGMENTREG | OT_FPUREG | OT_MMXREG | OT_XMMREG | OT_CONTROLREG | OT_DEBUGREG) & ~OT_REGALL)
// Register mask
#define OT_REG(num) ((1 << (REGMASK_SHIFT + (num))) | OT_REGTYPE)
#define OT_UNKNOWN (0 << OPSIZE_SHIFT)
#define OT_BYTE (1 << OPSIZE_SHIFT)
#define OT_WORD (2 << OPSIZE_SHIFT)
#define OT_DWORD (4 << OPSIZE_SHIFT)
#define OT_QWORD (8 << OPSIZE_SHIFT)
#define OT_OWORD (16 << OPSIZE_SHIFT)
#define OT_TBYTE (32 << OPSIZE_SHIFT)
#define ALL_SIZE (OT_BYTE | OT_WORD | OT_DWORD | OT_QWORD | OT_OWORD)
// For register operands, we mostl don't care about the size.
// So let's just set all relevant flags.
#define OT_FPUSIZE (OT_DWORD | OT_QWORD | OT_TBYTE)
#define OT_XMMSIZE (OT_DWORD | OT_QWORD | OT_OWORD)
// Macros for encoding
#define OT_REGMEMOP(type) (OT_##type##REG | OT_MEMORY | OT_REGMEM)
#define OT_REGONLYOP(type) (OT_##type##REG | OT_REGMEM)
#define OT_MEMONLYOP (OT_MEMORY | OT_REGMEM)
#define OT_MEMIMMOP (OT_MEMORY | OT_IMMEDIATE)
#define OT_REGSPECOP(type) (OT_##type##REG | OT_SPECIAL)
#define OT_IMMOP (OT_CONSTANT | OT_IMMEDIATE)
#define OT_MEMADDROP (OT_MEMORY | OT_IMMEDIATE)
// Some operations are encoded via opcode + spec field
#define SPECIAL_SPEC 0x00010000
#define SPECIAL_MASK 0x00000007
#define MAX_OPERANDS 3
#define MAX_REPOP_LENGTH 20
const ut8 SEG_REG_PREFIXES[] = {0x26, 0x2e, 0x36, 0x3e, 0x64, 0x65};
typedef enum tokentype_t {
TT_EOF,
TT_WORD,
TT_NUMBER,
TT_SPECIAL
} x86newTokenType;
typedef enum register_t {
X86R_UNDEFINED = -1,
X86R_EAX = 0, X86R_ECX, X86R_EDX, X86R_EBX, X86R_ESP, X86R_EBP, X86R_ESI, X86R_EDI, X86R_EIP,
X86R_AX = 0, X86R_CX, X86R_DX, X86R_BX, X86R_SP, X86R_BP, X86R_SI, X86R_DI,
X86R_AL = 0, X86R_CL, X86R_DL, X86R_BL, X86R_AH, X86R_CH, X86R_DH, X86R_BH,
X86R_RAX = 0, X86R_RCX, X86R_RDX, X86R_RBX, X86R_RSP, X86R_RBP, X86R_RSI, X86R_RDI, X86R_RIP,
X86R_R8 = 0, X86R_R9, X86R_R10, X86R_R11, X86R_R12, X86R_R13, X86R_R14, X86R_R15,
X86R_CS = 0, X86R_SS, X86R_DS, X86R_ES, X86R_FS, X86R_GS // Is this the right order?
} Register;
typedef struct operand_t {
ut32 type;
st8 sign;
struct {
Register reg;
bool extended;
};
union {
struct {
long offset;
st8 offset_sign;
Register regs[2];
int scale[2];
};
struct {
ut64 immediate;
bool is_good_flag;
};
struct {
char rep_op[MAX_REPOP_LENGTH];
};
};
bool explicit_size;
ut32 dest_size;
ut32 reg_size;
} Operand;
typedef struct Opcode_t {
char *mnemonic;
ut32 op[3];
size_t op_len;
bool is_short;
ut8 opcode[3];
int operands_count;
Operand operands[MAX_OPERANDS];
bool has_bnd;
} Opcode;
static ut8 getsib(const ut8 sib) {
if (!sib) {
return 0;
}
return (sib & 0x8) ? 3 : getsib ((sib << 1) | 1) - 1;
}
static int is_al_reg(const Operand *op) {
if (op->type & OT_MEMORY) {
return 0;
}
if (op->reg == X86R_AL && op->type & OT_BYTE) {
return 1;
}
return 0;
}
static int oprep(RAsm *a, ut8 *data, const Opcode *op);
static int process_16bit_group_1(RAsm *a, ut8 *data, const Opcode *op, int op1) {
int l = 0;
int immediate = op->operands[1].immediate * op->operands[1].sign;
data[l++] = 0x66;
if (op->operands[1].immediate < 128) {
data[l++] = 0x83;
data[l++] = op->operands[0].reg | (0xc0 + op1 + op->operands[0].reg);
} else {
if (op->operands[0].reg == X86R_AX) {
data[l++] = 0x05 + op1;
} else {
data[l++] = 0x81;
data[l++] = (0xc0 + op1) | op->operands[0].reg;
}
}
data[l++] = immediate;
if (op->operands[1].immediate > 127) {
data[l++] = immediate >> 8;
}
return l;
}
static int process_group_1(RAsm *a, ut8 *data, const Opcode *op) {
int l = 0;
int modrm = 0;
int mod_byte = 0;
int offset = 0;
int mem_ref = 0;
st32 immediate = 0;
if (!op->operands[1].is_good_flag) {
return -1;
}
if (a->bits == 64 && op->operands[0].type & OT_QWORD) {
data[l++] = 0x48;
}
if (!strcmp (op->mnemonic, "adc")) {
modrm = 2;
} else if (!strcmp (op->mnemonic, "add")) {
modrm = 0;
} else if (!strcmp (op->mnemonic, "or")) {
modrm = 1;
} else if (!strcmp (op->mnemonic, "and")) {
modrm = 4;
} else if (!strcmp (op->mnemonic, "xor")) {
modrm = 6;
} else if (!strcmp (op->mnemonic, "sbb")) {
modrm = 3;
} else if (!strcmp (op->mnemonic, "sub")) {
modrm = 5;
} else if (!strcmp (op->mnemonic, "cmp")) {
modrm = 7;
}
immediate = op->operands[1].immediate * op->operands[1].sign;
if (op->operands[0].type & OT_DWORD ||
op->operands[0].type & OT_QWORD) {
if (op->operands[1].immediate < 128) {
data[l++] = 0x83;
} else if (op->operands[0].reg != X86R_EAX ||
op->operands[0].type & OT_MEMORY) {
data[l++] = 0x81;
}
} else if (op->operands[0].type & OT_BYTE) {
if (op->operands[1].immediate > 255) {
eprintf ("Error: Immediate exceeds bounds\n");
return -1;
}
data[l++] = 0x80;
}
if (op->operands[0].type & OT_MEMORY) {
offset = op->operands[0].offset * op->operands[0].offset_sign;
if (op->operands[0].offset || op->operands[0].regs[0] == X86R_EBP) {
mod_byte = 1;
}
if (offset < ST8_MIN || offset > ST8_MAX) {
mod_byte = 2;
}
int reg0 = op->operands[0].regs[0];
if (reg0 == -1) {
mem_ref = 1;
reg0 = 5;
mod_byte = 0;
}
data[l++] = mod_byte << 6 | modrm << 3 | reg0;
if (op->operands[0].regs[0] == X86R_ESP) {
data[l++] = 0x24;
}
if (mod_byte || mem_ref) {
data[l++] = offset;
if (mod_byte == 2 || mem_ref) {
data[l++] = offset >> 8;
data[l++] = offset >> 16;
data[l++] = offset >> 24;
}
}
} else {
if (op->operands[1].immediate > 127 && op->operands[0].reg == X86R_EAX) {
data[l++] = 5 | modrm << 3 | op->operands[0].reg;
} else {
mod_byte = 3;
data[l++] = mod_byte << 6 | modrm << 3 | op->operands[0].reg;
}
}
data[l++] = immediate;
if ((immediate > 127 || immediate < -128) &&
((op->operands[0].type & OT_DWORD) || (op->operands[0].type & OT_QWORD))) {
data[l++] = immediate >> 8;
data[l++] = immediate >> 16;
data[l++] = immediate >> 24;
}
return l;
}
static int process_group_2(RAsm *a, ut8 *data, const Opcode *op) {
int l = 0;
int modrm = 0;
int mod_byte = 0;
int reg0 = 0;
if (a->bits == 64 && op->operands[0].type & OT_QWORD) { data[l++] = 0x48; }
if (!strcmp (op->mnemonic, "rol")) {
modrm = 0;
} else if (!strcmp (op->mnemonic, "ror")) {
modrm = 1;
} else if (!strcmp (op->mnemonic, "rcl")) {
modrm = 2;
} else if (!strcmp (op->mnemonic, "rcr")) {
modrm = 3;
} else if (!strcmp (op->mnemonic, "shl")) {
modrm = 4;
} else if (!strcmp (op->mnemonic, "shr")) {
modrm = 5;
} else if (!strcmp (op->mnemonic, "sal")) {
modrm = 6;
} else if (!strcmp (op->mnemonic, "sar")) {
modrm = 7;
}
st32 immediate = op->operands[1].immediate * op->operands[1].sign;
if (immediate > 255 || immediate < -128) {
eprintf ("Error: Immediate exceeds bounds\n");
return -1;
}
if (op->operands[0].type & (OT_DWORD | OT_QWORD)) {
if (op->operands[1].type & (OT_GPREG | OT_BYTE)) {
data[l++] = 0xd3;
} else if (immediate == 1) {
data[l++] = 0xd1;
} else {
data[l++] = 0xc1;
}
} else if (op->operands[0].type & OT_BYTE) {
const Operand *o = &op->operands[0];
if (o->regs[0] != -1 && o->regs[1] != -1) {
data[l++] = 0xc0;
data[l++] = 0x44;
data[l++] = o->regs[0]| (o->regs[1]<<3);
data[l++] = (ut8)((o->offset*o->offset_sign) & 0xff);
data[l++] = immediate;
return l;
} else if (op->operands[1].type & (OT_GPREG | OT_WORD)) {
data[l++] = 0xd2;
} else if (immediate == 1) {
data[l++] = 0xd0;
} else {
data[l++] = 0xc0;
}
}
if (op->operands[0].type & OT_MEMORY) {
reg0 = op->operands[0].regs[0];
mod_byte = 0;
} else {
reg0 = op->operands[0].reg;
mod_byte = 3;
}
data[l++] = mod_byte << 6 | modrm << 3 | reg0;
if (immediate != 1 && !(op->operands[1].type & OT_GPREG)) {
data[l++] = immediate;
}
return l;
}
static int process_1byte_op(RAsm *a, ut8 *data, const Opcode *op, int op1) {
int l = 0;
int mod_byte = 0;
int reg = 0;
int rm = 0;
int rex = 0;
int mem_ref = 0;
st32 offset = 0;
int ebp_reg = 0;
if (!op->operands[1].is_good_flag) {
return -1;
}
if (op->operands[0].reg == X86R_AL && op->operands[1].type & OT_CONSTANT) {
data[l++] = op1 + 4;
data[l++] = op->operands[1].immediate * op->operands[1].sign;
return l;
}
if (a->bits == 64) {
if (!(op->operands[0].type & op->operands[1].type)) {
return -1;
}
}
if (a->bits == 64 && ((op->operands[0].type & OT_QWORD) | (op->operands[1].type & OT_QWORD))) {
if (op->operands[0].extended) {
rex = 1;
}
if (op->operands[1].extended) {
rex += 4;
}
data[l++] = 0x48 | rex;
}
if (op->operands[0].type & OT_MEMORY && op->operands[1].type & OT_REGALL) {
if (a->bits == 64 && (op->operands[0].type & OT_DWORD) &&
(op->operands[1].type & OT_DWORD)) {
data[l++] = 0x67;
}
if (op->operands[0].type & OT_BYTE && op->operands[1].type & OT_BYTE) {
data[l++] = op1;
} else if (op->operands[0].type & (OT_DWORD | OT_QWORD) &&
op->operands[1].type & (OT_DWORD | OT_QWORD)) {
data[l++] = op1 + 0x1;
} else {
eprintf ("Error: mismatched operand sizes\n");
return -1;
}
reg = op->operands[1].reg;
rm = op->operands[0].regs[0];
offset = op->operands[0].offset * op->operands[0].offset_sign;
if (rm == -1) {
rm = 5;
mem_ref = 1;
} else {
if (offset) {
mod_byte = 1;
if (offset < ST8_MIN || offset > ST8_MAX) {
mod_byte = 2;
}
} else if (op->operands[0].regs[1] != X86R_UNDEFINED) {
rm = 4;
offset = op->operands[0].regs[1] << 3;
}
}
} else if (op->operands[0].type & OT_REGALL) {
if (op->operands[1].type & OT_MEMORY) {
if (op->operands[0].type & OT_BYTE && op->operands[1].type & OT_BYTE) {
data[l++] = op1 + 0x2;
} else if (op->operands[0].type & (OT_DWORD | OT_QWORD) &&
op->operands[1].type & (OT_DWORD | OT_QWORD)) {
data[l++] = op1 + 0x3;
} else {
eprintf ("Error: mismatched operand sizes\n");
return -1;
}
reg = op->operands[0].reg;
rm = op->operands[1].regs[0];
if (op->operands[1].scale[0] > 1) {
if (op->operands[1].regs[1] != X86R_UNDEFINED) {
data[l++] = op->operands[0].reg << 3 | 4;
data[l++] = getsib (op->operands[1].scale[0]) << 6 |
op->operands[1].regs[0] << 3 |
op->operands[1].regs[1];
return l;
}
data[l++] = op->operands[0].reg << 3 | 4; // 4 = SIB
data[l++] = getsib (op->operands[1].scale[0]) << 6 | op->operands[1].regs[0] << 3 | 5;
data[l++] = op->operands[1].offset * op->operands[1].offset_sign;
data[l++] = 0;
data[l++] = 0;
data[l++] = 0;
return l;
}
offset = op->operands[1].offset * op->operands[1].offset_sign;
if (offset) {
mod_byte = 1;
if (offset < ST8_MIN || offset > ST8_MAX) {
mod_byte = 2;
}
}
} else if (op->operands[1].type & OT_REGALL) {
if (op->operands[0].type & OT_BYTE && op->operands[1].type & OT_BYTE) {
data[l++] = op1;
} else if (op->operands[0].type & OT_DWORD && op->operands[1].type & OT_DWORD) {
data[l++] = op1 + 0x1;
}
if (a->bits == 64) {
if (op->operands[0].type & OT_QWORD &&
op->operands[1].type & OT_QWORD) {
data[l++] = op1 + 0x1;
}
}
mod_byte = 3;
reg = op->operands[1].reg;
rm = op->operands[0].reg;
}
}
if (op->operands[0].regs[0] == X86R_EBP ||
op->operands[1].regs[0] == X86R_EBP) {
//reg += 8;
ebp_reg = 1;
}
data[l++] = mod_byte << 6 | reg << 3 | rm;
if (op->operands[0].regs[0] == X86R_ESP ||
op->operands[1].regs[0] == X86R_ESP) {
data[l++] = 0x24;
}
if (offset || mem_ref || ebp_reg) {
//if ((mod_byte > 0 && mod_byte < 3) || mem_ref) {
data[l++] = offset;
if (mod_byte == 2 || mem_ref) {
data[l++] = offset >> 8;
data[l++] = offset >> 16;
data[l++] = offset >> 24;
}
}
return l;
}
static int opadc(RAsm *a, ut8 *data, const Opcode *op) {
if (op->operands[1].type & OT_CONSTANT) {
if (op->operands[0].type & OT_GPREG &&
op->operands[0].type & OT_WORD) {
return process_16bit_group_1 (a, data, op, 0x10);
}
if (!is_al_reg (&op->operands[0])) {
return process_group_1 (a, data, op);
}
}
return process_1byte_op (a, data, op, 0x10);
}
static int opadd(RAsm *a, ut8 *data, const Opcode *op) {
if (op->operands[1].type & OT_CONSTANT) {
if (op->operands[0].type & OT_GPREG &&
op->operands[0].type & OT_WORD) {
return process_16bit_group_1 (a, data, op, 0x00);
}
if (!is_al_reg (&op->operands[0])) {
return process_group_1 (a, data, op);
}
}
return process_1byte_op (a, data, op, 0x00);
}
static int opand(RAsm *a, ut8 *data, const Opcode *op) {
if (op->operands[1].type & OT_CONSTANT) {
if (op->operands[0].type & OT_GPREG &&
op->operands[0].type & OT_WORD) {
return process_16bit_group_1 (a, data, op, 0x20);
}
if (!is_al_reg (&op->operands[0])) {
return process_group_1 (a, data, op);
}
}
return process_1byte_op (a, data, op, 0x20);
}
static int opcmp(RAsm *a, ut8 *data, const Opcode *op) {
if (op->operands[1].type & OT_CONSTANT) {
if (op->operands[0].type & OT_GPREG &&
op->operands[0].type & OT_WORD) {
return process_16bit_group_1 (a, data, op, 0x38);
}
if (!is_al_reg (&op->operands[0])) {
return process_group_1 (a, data, op);
}
}
return process_1byte_op (a, data, op, 0x38);
}
static int opsub(RAsm *a, ut8 *data, const Opcode *op) {
if (op->operands[1].type & OT_CONSTANT) {
if (op->operands[0].type & OT_GPREG &&
op->operands[0].type & OT_WORD) {
return process_16bit_group_1 (a, data, op, 0x28);
}
if (!is_al_reg (&op->operands[0])) {
return process_group_1 (a, data, op);
}
}
return process_1byte_op (a, data, op, 0x28);
}
static int opor(RAsm *a, ut8 * data, const Opcode *op) {
if (op->operands[1].type & OT_CONSTANT) {
if (op->operands[0].type & OT_GPREG &&
op->operands[0].type & OT_WORD) {
return process_16bit_group_1 (a, data, op, 0x08);
}
if (!is_al_reg (&op->operands[0])) {
return process_group_1 (a, data, op);
}
}
return process_1byte_op (a, data, op, 0x08);
}
static int opxadd(RAsm *a, ut8 *data, const Opcode *op) {
int i = 0;
if (op->operands_count < 2 ) {
return -1;
}
if (a->bits == 64) {
data[i++] = 0x48;
};
data[i++] = 0x0f;
if (op->operands[0].type & OT_BYTE &&
op->operands[1].type & OT_BYTE) {
data[i++] = 0xc0;
} else {
data[i++] = 0xc1;
}
if (op->operands[0].type & OT_REGALL &&
op->operands[1].type & OT_REGALL) { // TODO memory modes
data[i] |= 0xc0;
data[i] |= (op->operands[1].reg << 3);
data[i++] |= op->operands[0].reg;
}
return i;
}
static int opxor(RAsm *a, ut8 * data, const Opcode *op) {
if (op->operands_count < 2) {
return -1;
}
if (op->operands[0].type == 0x80 && op->operands[0].reg == X86R_UNDEFINED) {
return -1;
}
if (op->operands[1].type == 0x80 && op->operands[0].reg == X86R_UNDEFINED) {
return -1;
}
if (op->operands[1].type & OT_CONSTANT) {
if (op->operands[0].type & OT_GPREG &&
op->operands[0].type & OT_WORD) {
return process_16bit_group_1 (a, data, op, 0x30);
}
if (!is_al_reg (&op->operands[0])) {
return process_group_1 (a, data, op);
}
}
return process_1byte_op (a, data, op, 0x30);
}
static int opnot(RAsm *a, ut8 * data, const Opcode *op) {
int l = 0;
if (op->operands[0].reg == X86R_UNDEFINED) {
return -1;
}
int size = op->operands[0].type & ALL_SIZE;
if (op->operands[0].explicit_size) {
size = op->operands[0].dest_size;
}
//rex prefix
int rex = 1 << 6;
bool use_rex = false;
if (size & OT_QWORD) { //W field
use_rex = true;
rex |= 1 << 3;
}
if (op->operands[0].extended) { //B field
use_rex = true;
rex |= 1;
}
if (use_rex) {
data[l++] = rex;
}
data[l++] = 0xf7;
data[l++] = 0xd0 | op->operands[0].reg;
return l;
}
static int opsbb(RAsm *a, ut8 *data, const Opcode *op) {
if (op->operands[1].type & OT_CONSTANT) {
if (op->operands[0].type & OT_GPREG &&
op->operands[0].type & OT_WORD) {
return process_16bit_group_1 (a, data, op, 0x18);
}
if (!is_al_reg (&op->operands[0])) {
return process_group_1 (a, data, op);
}
}
return process_1byte_op (a, data, op, 0x18);
}
static int opbswap(RAsm *a, ut8 *data, const Opcode *op) {
int l = 0;
if (op->operands[0].type & OT_REGALL) {
if (op->operands[0].reg == X86R_UNDEFINED) {
return -1;
}
if (op->operands[0].type & OT_QWORD) {
data[l++] = 0x48;
data[l++] = 0x0f;
data[l++] = 0xc8 + op->operands[0].reg;
} else if (op->operands[0].type & OT_DWORD) {
data[l++] = 0x0f;
data[l++] = 0xc8 + op->operands[0].reg;
} else {
return -1;
}
}
return l;
}
static int opcall(RAsm *a, ut8 *data, const Opcode *op) {
int l = 0;
int immediate = 0;
int offset = 0;
int mod = 0;
if (op->operands[0].type & OT_GPREG) {
if (op->operands[0].reg == X86R_UNDEFINED) {
return -1;
}
if (a->bits == 64 && op->operands[0].extended) {
data[l++] = 0x41;
}
data[l++] = 0xff;
mod = 3;
data[l++] = mod << 6 | 2 << 3 | op->operands[0].reg;
} else if (op->operands[0].type & OT_MEMORY) {
if (op->operands[0].regs[0] == X86R_UNDEFINED) {
return -1;
}
data[l++] = 0xff;
offset = op->operands[0].offset * op->operands[0].offset_sign;
if (offset) {
mod = 1;
if (offset > 127 || offset < -128) {
mod = 2;
}
}
data[l++] = mod << 6 | 2 << 3 | op->operands[0].regs[0];
if (mod) {
data[l++] = offset;
if (mod == 2) {
data[l++] = offset >> 8;
data[l++] = offset >> 16;
data[l++] = offset >> 24;
}
}
} else {
ut64 instr_offset = a->pc;
data[l++] = 0xe8;
immediate = op->operands[0].immediate * op->operands[0].sign;
immediate -= instr_offset + 5;
data[l++] = immediate;
data[l++] = immediate >> 8;
data[l++] = immediate >> 16;
data[l++] = immediate >> 24;
}
return l;
}
static int opcmov(RAsm *a, ut8 *data, const Opcode *op) {
int l = 0;
int mod_byte = 0;
int offset = 0;
if (op->operands[0].type & OT_MEMORY ||
op->operands[1].type & OT_CONSTANT) {
return -1;
}
data[l++] = 0x0f;
char *cmov = op->mnemonic + 4;
if (!strcmp (cmov, "o")) {
data[l++] = 0x40;
} else if (!strcmp (cmov, "no")) {
data [l++] = 0x41;
} else if (!strcmp (cmov, "b") ||
!strcmp (cmov, "c") ||
!strcmp (cmov, "nae")) {
data [l++] = 0x42;
} else if (!strcmp (cmov, "ae") ||
!strcmp (cmov, "nb") ||
!strcmp (cmov, "nc")) {
data [l++] = 0x43;
} else if (!strcmp (cmov, "e") ||
!strcmp (cmov, "z")) {
data [l++] = 0x44;
} else if (!strcmp (cmov, "ne") ||
!strcmp (cmov, "nz")) {
data [l++] = 0x45;
} else if (!strcmp (cmov, "be") ||
!strcmp (cmov, "na")) {
data [l++] = 0x46;
} else if (!strcmp (cmov, "a") ||
!strcmp (cmov, "nbe")) {
data [l++] = 0x47;
} else if (!strcmp (cmov, "s")) {
data [l++] = 0x48;
} else if (!strcmp (cmov, "ns")) {
data [l++] = 0x49;
} else if (!strcmp (cmov, "p") ||
!strcmp (cmov, "pe")) {
data [l++] = 0x4a;
} else if (!strcmp (cmov, "np") ||
!strcmp (cmov, "po")) {
data [l++] = 0x4b;
} else if (!strcmp (cmov, "l") ||
!strcmp (cmov, "nge")) {
data [l++] = 0x4c;
} else if (!strcmp (cmov, "ge") ||
!strcmp (cmov, "nl")) {
data [l++] = 0x4d;
} else if (!strcmp (cmov, "le") ||
!strcmp (cmov, "ng")) {
data [l++] = 0x4e;
} else if (!strcmp (cmov, "g") ||
!strcmp (cmov, "nle")) {
data [l++] = 0x4f;
}
if (op->operands[0].type & OT_REGALL) {
if (op->operands[1].type & OT_MEMORY) {
if (op->operands[1].scale[0] > 1) {
if (op->operands[1].regs[1] != X86R_UNDEFINED) {
data[l++] = op->operands[0].reg << 3 | 4;
data[l++] = getsib (op->operands[1].scale[0]) << 6 |
op->operands[1].regs[0] << 3 |
op->operands[1].regs[1];
return l;
}
offset = op->operands[1].offset * op->operands[1].offset_sign;
if (op->operands[1].scale[0] == 2 && offset) {
data[l++] = 0x40 | op->operands[0].reg << 3 | 4; // 4 = SIB
} else {
data[l++] = op->operands[0].reg << 3 | 4; // 4 = SIB
}
if (op->operands[1].scale[0] == 2) {
data[l++] = op->operands[1].regs[0] << 3 | op->operands[1].regs[0];
} else {
data[l++] = getsib (op->operands[1].scale[0]) << 6 |
op->operands[1].regs[0] << 3 | 5;
}
if (offset) {
data[l++] = offset;
if (offset < ST8_MIN || offset > ST8_MAX) {
data[l++] = offset >> 8;
data[l++] = offset >> 16;
data[l++] = offset >> 24;
}
}
return l;
}
if (op->operands[1].regs[1] != X86R_UNDEFINED) {
data[l++] = op->operands[0].reg << 3 | 4;
data[l++] = op->operands[1].regs[1] << 3 | op->operands[1].regs[0];
return l;
}
offset = op->operands[1].offset * op->operands[1].offset_sign;
if (op->operands[1].offset || op->operands[1].regs[0] == X86R_EBP) {
mod_byte = 1;
}
if (offset < ST8_MIN || offset > ST8_MAX) {
mod_byte = 2;
}
data[l++] = mod_byte << 6 | op->operands[0].reg << 3 | op->operands[1].regs[0];
if (mod_byte) {
data[l++] = offset;
if (mod_byte == 2) {
data[l++] = offset >> 8;
data[l++] = offset >> 16;
data[l++] = offset >> 24;
}
}
} else {
data[l++] = 0xc0 | op->operands[0].reg << 3 | op->operands[1].reg;
}
}
return l;
}
static int opmovx(RAsm *a, ut8 *data, const Opcode *op) {
int l = 0;
int word = 0;
char *movx = op->mnemonic + 3;
if (!(op->operands[0].type & OT_REGTYPE && op->operands[1].type & OT_MEMORY)) {
return -1;
}
if (op->operands[1].type & OT_WORD) {
word = 1;
}
data[l++] = 0x0f;
if (!strcmp (movx, "zx")) {
data[l++] = 0xb6 + word;
} else if (!strcmp (movx, "sx")) {
data[l++] = 0xbe + word;
}
data[l++] = op->operands[0].reg << 3 | op->operands[1].regs[0];
if (op->operands[1].regs[0] == X86R_ESP) {
data[l++] = 0x24;
}
return l;
}
static int opaam(RAsm *a, ut8 *data, const Opcode *op) {
int l = 0;
int immediate = op->operands[0].immediate * op->operands[0].sign;
data[l++] = 0xd4;
if (immediate == 0) {
data[l++] = 0x0a;
} else if (immediate < 256 && immediate > -129) {
data[l++] = immediate;
}
return l;
}
static int opdec(RAsm *a, ut8 *data, const Opcode *op) {
if (op->operands[1].type) {
eprintf ("Error: Invalid operands\n");
return -1;
}
int l = 0;
int size = op->operands[0].type & ALL_SIZE;
if (op->operands[0].explicit_size) {
size = op->operands[0].dest_size;
}
if (size & OT_WORD) {
data[l++] = 0x66;
}
//rex prefix
int rex = 1 << 6;
bool use_rex = false;
if (size & OT_QWORD) { //W field
use_rex = true;
rex |= 1 << 3;
}
if (op->operands[0].extended) { //B field
use_rex = true;
rex |= 1;
}
//opcode selection
int opcode;
if (size & OT_BYTE) {
opcode = 0xfe;
} else {
opcode = 0xff;
}
if (!(op->operands[0].type & OT_MEMORY)) {
if (use_rex) {
data[l++] = rex;
}
if (a->bits > 32 || size & OT_BYTE) {
data[l++] = opcode;
}
if (a->bits == 32 && size & (OT_DWORD | OT_WORD)) {
data[l++] = 0x48 | op->operands[0].reg;
} else {
data[l++] = 0xc8 | op->operands[0].reg;
}
return l;
}
//modrm and SIB selection
bool rip_rel = op->operands[0].regs[0] == X86R_RIP;
int offset = op->operands[0].offset * op->operands[0].offset_sign;
int modrm = 0;
int mod;
int reg = 0;
int rm;
bool use_sib = false;
int sib;
//mod
if (offset == 0) {
mod = 0;
} else if (offset < 128 && offset > -129) {
mod = 1;
} else {
mod = 2;
}
if (op->operands[0].regs[0] & OT_WORD) {
if (op->operands[0].regs[0] == X86R_BX && op->operands[0].regs[1] == X86R_SI) {
rm = B0000;
} else if (op->operands[0].regs[0] == X86R_BX && op->operands[0].regs[1] == X86R_DI) {
rm = B0001;
} else if (op->operands[0].regs[0] == X86R_BP && op->operands[0].regs[1] == X86R_SI) {
rm = B0010;
} else if (op->operands[0].regs[0] == X86R_BP && op->operands[0].regs[1] == X86R_DI) {
rm = B0011;
} else if (op->operands[0].regs[0] == X86R_SI && op->operands[0].regs[1] == -1) {
rm = B0100;
} else if (op->operands[0].regs[0] == X86R_DI && op->operands[0].regs[1] == -1) {
rm = B0101;
} else if (op->operands[0].regs[0] == X86R_BX && op->operands[0].regs[1] == -1) {
rm = B0111;
} else {
//TODO allow for displacement only when parser is reworked
return -1;
}
modrm = (mod << 6) | (reg << 3) | rm;
} else {
//rm
if (op->operands[0].extended) {
rm = op->operands[0].reg;
} else {
rm = op->operands[0].regs[0];
}
//[epb] alone is illegal, so we need to fake a [ebp+0]
if (rm == 5 && mod == 0) {
mod = 1;
}
//sib
int index = op->operands[0].regs[1];
int scale = getsib(op->operands[0].scale[1]);
if (index != -1) {
use_sib = true;
sib = (scale << 6) | (index << 3) | rm;
} else if (rm == 4) {
use_sib = true;
sib = 0x24;
}
if (use_sib) {
rm = B0100;
}
if (rip_rel) {
modrm = (B0000 << 6) | (reg << 3) | B0101;
sib = (scale << 6) | (B0100 << 3) | B0101;
} else {
modrm = (mod << 6) | (reg << 3) | rm;
}
modrm |= 1<<3;
}
if (use_rex) {
data[l++] = rex;
}
data[l++] = opcode;
data[l++] = modrm;
if (use_sib) {
data[l++] = sib;
}
//offset
if (mod == 1) {
data[l++] = offset;
} else if (op->operands[0].regs[0] & OT_WORD && mod == 2) {
data[l++] = offset;
data[l++] = offset >> 8;
} else if (mod == 2 || rip_rel) {
data[l++] = offset;
data[l++] = offset >> 8;
data[l++] = offset >> 16;
data[l++] = offset >> 24;
}
return l;
}
static int opidiv(RAsm *a, ut8 *data, const Opcode *op) {
int l = 0;
if ( op->operands[0].type & OT_QWORD ) {
data[l++] = 0x48;
}
switch (op->operands_count) {
case 1:
if ( op->operands[0].type & OT_WORD ) {
data[l++] = 0x66;
}
if (op->operands[0].type & OT_BYTE) {
data[l++] = 0xf6;
} else {
data[l++] = 0xf7;
}
if (op->operands[0].type & OT_MEMORY) {
data[l++] = 0x38 | op->operands[0].regs[0];
} else {
data[l++] = 0xf8 | op->operands[0].reg;
}
break;
default:
return -1;
}
return l;
}
static int opdiv(RAsm *a, ut8 *data, const Opcode *op) {
int l = 0;
if ( op->operands[0].type & OT_QWORD ) {
data[l++] = 0x48;
}
switch (op->operands_count) {
case 1:
if ( op->operands[0].type & OT_WORD ) {
data[l++] = 0x66;
}
if (op->operands[0].type & OT_BYTE) {
data[l++] = 0xf6;
} else {
data[l++] = 0xf7;
}
if (op->operands[0].type & OT_MEMORY) {
data[l++] = 0x30 | op->operands[0].regs[0];
} else {
data[l++] = 0xf0 | op->operands[0].reg;
}
break;
default:
return -1;
}
return l;
}
static int opimul(RAsm *a, ut8 *data, const Opcode *op) {
int l = 0;
int offset = 0;
st64 immediate = 0;
if ( op->operands[0].type & OT_QWORD ) {
data[l++] = 0x48;
}
switch (op->operands_count) {
case 1:
if ( op->operands[0].type & OT_WORD ) {
data[l++] = 0x66;
}
if (op->operands[0].type & OT_BYTE) {
data[l++] = 0xf6;
} else {
data[l++] = 0xf7;
}
if (op->operands[0].type & OT_MEMORY) {
data[l++] = 0x28 | op->operands[0].regs[0];
} else {
data[l++] = 0xe8 | op->operands[0].reg;
}
break;
case 2:
if (op->operands[0].type & OT_GPREG) {
if (op->operands[1].type & OT_CONSTANT) {
if (op->operands[1].immediate == -1) {
eprintf ("Error: Immediate exceeds max\n");
return -1;
}
immediate = op->operands[1].immediate * op->operands[1].sign;
if (op->operands[0].type & OT_GPREG) {
if (immediate >= 128) {
data[l++] = 0x69;
} else {
data[l++] = 0x6b;
}
data[l++] = 0xc0 | op->operands[0].reg << 3 | op->operands[0].reg;
data[l++] = immediate;
if (immediate >= 128) {
data[l++] = immediate >> 8;
data[l++] = immediate >> 16;
data[l++] = immediate >> 24;
}
if (a->bits == 64 && immediate > UT32_MAX) {
data[l++] = immediate >> 32;
data[l++] = immediate >> 40;
data[l++] = immediate >> 48;
data[l++] = immediate >> 56;
}
}
} else if (op->operands[1].type & OT_MEMORY) {
data[l++] = 0x0f;
data[l++] = 0xaf;
if (op->operands[1].regs[0] != X86R_UNDEFINED) {
offset = op->operands[1].offset * op->operands[1].offset_sign;
if (offset != 0) {
if (offset >= 128 || offset <= -128) {
data[l] = 0x80;
} else {
data[l] = 0x40;
}
data[l++] |= op->operands[0].reg << 3 | op->operands[1].regs[0];
data[l++] = offset;
if (offset >= 128 || offset <= -128) {
data[l++] = offset >> 8;
data[l++] = offset >> 16;
data[l++] = offset >> 24;
}
} else {
if (op->operands[1].regs[1] != X86R_UNDEFINED) {
data[l++] = 0x04 | op->operands[0].reg << 3;
data[l++] = op->operands[1].regs[1] << 3 | op->operands[1].regs[0];
} else {
data[l++] = op->operands[0].reg << 3 | op->operands[1].regs[0];
}
}
} else {
immediate = op->operands[1].immediate * op->operands[1].sign;
data[l++] = op->operands[0].reg << 3 | 0x5;
data[l++] = immediate;
data[l++] = immediate >> 8;
data[l++] = immediate >> 16;
data[l++] = immediate >> 24;
}
} else if (op->operands[1].type & OT_GPREG) {
data[l++] = 0x0f;
data[l++] = 0xaf;
data[l++] = 0xc0 | op->operands[0].reg << 3 | op->operands[1].reg;
}
}
break;
case 3:
if (op->operands[0].type & OT_GPREG &&
(op->operands[1].type & OT_GPREG || op->operands[1].type & OT_MEMORY) &&
op->operands[2].type & OT_CONSTANT) {
data[l++] = 0x6b;
if (op->operands[1].type & OT_MEMORY) {
if (op->operands[1].regs[1] != X86R_UNDEFINED) {
data[l++] = 0x04 | op->operands[0].reg << 3;
data[l++] = op->operands[1].regs[0] | op->operands[1].regs[1] << 3;
} else {
offset = op->operands[1].offset * op->operands[1].offset_sign;
if (offset != 0) {
if (offset >= 128 || offset <= -128) {
data[l] = 0x80;
} else {
data[l] = 0x40;
}
data[l++] |= op->operands[0].reg << 3;
data[l++] = offset;
if (offset >= 128 || offset <= -128) {
data[l++] = offset >> 8;
data[l++] = offset >> 16;
data[l++] = offset >> 24;
}
} else {
data[l++] = 0x00 | op->operands[0].reg << 3 | op->operands[1].regs[0];
}
}
} else {
data[l++] = 0xc0 | op->operands[0].reg << 3 | op->operands[1].reg;
}
immediate = op->operands[2].immediate * op->operands[2].sign;
data[l++] = immediate;
if (immediate >= 128 || immediate <= -128) {
data[l++] = immediate >> 8;
data[l++] = immediate >> 16;
data[l++] = immediate >> 24;
}
}
break;
default:
return -1;
}
return l;
}
static int opin(RAsm *a, ut8 *data, const Opcode *op) {
int l = 0;
st32 immediate = 0;
if (op->operands[1].reg == X86R_DX) {
if (op->operands[0].reg == X86R_AL &&
op->operands[0].type & OT_BYTE) {
data[l++] = 0xec;
return l;
}
if (op->operands[0].reg == X86R_AX &&
op->operands[0].type & OT_WORD) {
data[l++] = 0x66;
data[l++] = 0xed;
return l;
}
if (op->operands[0].reg == X86R_EAX &&
op->operands[0].type & OT_DWORD) {
data[l++] = 0xed;
return l;
}
} else if (op->operands[1].type & OT_CONSTANT) {
immediate = op->operands[1].immediate * op->operands[1].sign;
if (immediate > 255 || immediate < -128) {
return -1;
}
if (op->operands[0].reg == X86R_AL &&
op->operands[0].type & OT_BYTE) {
data[l++] = 0xe4;
} else if (op->operands[0].reg == X86R_AX &&
op->operands[0].type & OT_BYTE) {
data[l++] = 0x66;
data[l++] = 0xe5;
} else if (op->operands[0].reg == X86R_EAX &&
op->operands[0].type & OT_DWORD) {
data[l++] = 0xe5;
}
data[l++] = immediate;
}
return l;
}
static int opclflush(RAsm *a, ut8 *data, const Opcode *op) {
int l = 0;
int offset = 0;
int mod_byte = 0;
if (op->operands[0].type & OT_MEMORY) {
data[l++] = 0x0f;
data[l++] = 0xae;
offset = op->operands[0].offset * op->operands[0].offset_sign;
if (offset) {
if (offset < ST8_MIN || offset > ST8_MAX) {
mod_byte = 2;
} else {
mod_byte = 1;
}
}
data[l++] = (mod_byte << 6) | (7 << 3) | op->operands[0].regs[0];
if (mod_byte) {
data[l++] = offset;
if (mod_byte == 2) {
data[l++] = offset >> 8;
data[l++] = offset >> 16;
data[l++] = offset >> 24;
}
}
}
return l;
}
static int opinc(RAsm *a, ut8 *data, const Opcode *op) {
if (op->operands[1].type) {
eprintf ("Error: Invalid operands\n");
return -1;
}
int l = 0;
int size = op->operands[0].type & ALL_SIZE;
if (op->operands[0].explicit_size) {
size = op->operands[0].dest_size;
}
if (size & OT_WORD) {
data[l++] = 0x66;
}
//rex prefix
int rex = 1 << 6;
bool use_rex = false;
if (size & OT_QWORD) { //W field
use_rex = true;
rex |= 1 << 3;
}
if (op->operands[0].extended) { //B field
use_rex = true;
rex |= 1;
}
//opcode selection
int opcode;
if (size & OT_BYTE) {
opcode = 0xfe;
} else {
opcode = 0xff;
}
if (!(op->operands[0].type & OT_MEMORY)) {
if (use_rex) {
data[l++] = rex;
}
if (a->bits > 32 || size & OT_BYTE) {
data[l++] = opcode;
}
if (a->bits == 32 && size & (OT_DWORD | OT_WORD)) {
data[l++] = 0x40 | op->operands[0].reg;
} else {
data[l++] = 0xc0 | op->operands[0].reg;
}
return l;
}
//modrm and SIB selection
bool rip_rel = op->operands[0].regs[0] == X86R_RIP;
int offset = op->operands[0].offset * op->operands[0].offset_sign;
int modrm = 0;
int mod;
int reg = 0;
int rm;
bool use_sib = false;
int sib;
//mod
if (offset == 0) {
mod = 0;
} else if (offset < 128 && offset > -129) {
mod = 1;
} else {
mod = 2;
}
if (op->operands[0].regs[0] & OT_WORD) {
if (op->operands[0].regs[0] == X86R_BX && op->operands[0].regs[1] == X86R_SI) {
rm = B0000;
} else if (op->operands[0].regs[0] == X86R_BX && op->operands[0].regs[1] == X86R_DI) {
rm = B0001;
} else if (op->operands[0].regs[0] == X86R_BP && op->operands[0].regs[1] == X86R_SI) {
rm = B0010;
} else if (op->operands[0].regs[0] == X86R_BP && op->operands[0].regs[1] == X86R_DI) {
rm = B0011;
} else if (op->operands[0].regs[0] == X86R_SI && op->operands[0].regs[1] == -1) {
rm = B0100;
} else if (op->operands[0].regs[0] == X86R_DI && op->operands[0].regs[1] == -1) {
rm = B0101;
} else if (op->operands[0].regs[0] == X86R_BX && op->operands[0].regs[1] == -1) {
rm = B0111;
} else {
//TODO allow for displacement only when parser is reworked
return -1;
}
modrm = (mod << 6) | (reg << 3) | rm;
} else {
//rm
if (op->operands[0].extended) {
rm = op->operands[0].reg;
} else {
rm = op->operands[0].regs[0];
}
//[epb] alone is illegal, so we need to fake a [ebp+0]
if (rm == 5 && mod == 0) {
mod = 1;
}
//sib
int index = op->operands[0].regs[1];
int scale = getsib(op->operands[0].scale[1]);
if (index != -1) {
use_sib = true;
sib = (scale << 6) | (index << 3) | rm;
} else if (rm == 4) {
use_sib = true;
sib = 0x24;
}
if (use_sib) {
rm = B0100;
}
if (rip_rel) {
modrm = (B0000 << 6) | (reg << 3) | B0101;
sib = (scale << 6) | (B0100 << 3) | B0101;
} else {
modrm = (mod << 6) | (reg << 3) | rm;
}
}
if (use_rex) {
data[l++] = rex;
}
data[l++] = opcode;
data[l++] = modrm;
if (use_sib) {
data[l++] = sib;
}
//offset
if (mod == 1) {
data[l++] = offset;
} else if (op->operands[0].regs[0] & OT_WORD && mod == 2) {
data[l++] = offset;
data[l++] = offset >> 8;
} else if (mod == 2 || rip_rel) {
data[l++] = offset;
data[l++] = offset >> 8;
data[l++] = offset >> 16;
data[l++] = offset >> 24;
}
return l;
}
static int opint(RAsm *a, ut8 *data, const Opcode *op) {
int l = 0;
if (op->operands[0].type & OT_CONSTANT) {
st32 immediate = op->operands[0].immediate * op->operands[0].sign;
if (immediate <= 255 && immediate >= -128) {
data[l++] = 0xcd;
data[l++] = immediate;
}
}
return l;
}
static int opjc(RAsm *a, ut8 *data, const Opcode *op) {
int l = 0;
bool is_short = op->is_short;
// st64 bigimm = op->operands[0].immediate * op->operands[0].sign;
st64 immediate = op->operands[0].immediate * op->operands[0].sign;
if (is_short && (immediate > ST8_MAX || immediate < ST8_MIN)) {
return l;
}
immediate -= a->pc;
if (immediate > ST32_MAX || immediate < -ST32_MAX) {
return -1;
}
if (!strcmp (op->mnemonic, "jmp")) {
if (op->operands[0].type & OT_GPREG) {
data[l++] = 0xff;
if (op->operands[0].type & OT_MEMORY) {
if (op->operands[0].offset) {
int offset = op->operands[0].offset * op->operands[0].offset_sign;
if (offset >= 128 || offset <= -129) {
data[l] = 0xa0;
} else {
data[l] = 0x60;
}
data[l++] |= op->operands[0].regs[0];
data[l++] = offset;
if (op->operands[0].offset >= 0x80) {
data[l++] = offset >> 8;
data[l++] = offset >> 16;
data[l++] = offset >> 24;
}
} else {
data[l++] = 0x20 | op->operands[0].regs[0];
}
} else {
data[l++] = 0xe0 | op->operands[0].reg;
}
} else {
if (-0x80 <= (immediate - 2) && (immediate - 2) <= 0x7f) {
/* relative byte address */
data[l++] = 0xeb;
data[l++] = immediate - 2;
} else {
/* relative address */
immediate -= 5;
data[l++] = 0xe9;
data[l++] = immediate;
data[l++] = immediate >> 8;
data[l++] = immediate >> 16;
data[l++] = immediate >> 24;
}
}
return l;
}
if (immediate <= 0x81 && immediate > -0x7f) {
is_short = true;
}
if (a->bits == 16 && (immediate > 0x81 || immediate < -0x7e)) {
data[l++] = 0x66;
is_short = false;
immediate --;
}
if (!is_short) {data[l++] = 0x0f;}
if (!strcmp (op->mnemonic, "ja") ||
!strcmp (op->mnemonic, "jnbe")) {
data[l++] = 0x87;
} else if (!strcmp (op->mnemonic, "jae") ||
!strcmp (op->mnemonic, "jnb") ||
!strcmp (op->mnemonic, "jnc")) {
data[l++] = 0x83;
} else if (!strcmp (op->mnemonic, "jz") ||
!strcmp (op->mnemonic, "je")) {
data[l++] = 0x84;
} else if (!strcmp (op->mnemonic, "jb") ||
!strcmp (op->mnemonic, "jnae") ||
!strcmp (op->mnemonic, "jc")) {
data[l++] = 0x82;
} else if (!strcmp (op->mnemonic, "jbe") ||
!strcmp (op->mnemonic, "jna")) {
data[l++] = 0x86;
} else if (!strcmp (op->mnemonic, "jg") ||
!strcmp (op->mnemonic, "jnle")) {
data[l++] = 0x8f;
} else if (!strcmp (op->mnemonic, "jge") ||
!strcmp (op->mnemonic, "jnl")) {
data[l++] = 0x8d;
} else if (!strcmp (op->mnemonic, "jl") ||
!strcmp (op->mnemonic, "jnge")) {
data[l++] = 0x8c;
} else if (!strcmp (op->mnemonic, "jle") ||
!strcmp (op->mnemonic, "jng")) {
data[l++] = 0x8e;
} else if (!strcmp (op->mnemonic, "jne") ||
!strcmp (op->mnemonic, "jnz")) {
data[l++] = 0x85;
} else if (!strcmp (op->mnemonic, "jno")) {
data[l++] = 0x81;
} else if (!strcmp (op->mnemonic, "jnp") ||
!strcmp (op->mnemonic, "jpo")) {
data[l++] = 0x8b;
} else if (!strcmp (op->mnemonic, "jns")) {
data[l++] = 0x89;
} else if (!strcmp (op->mnemonic, "jo")) {
data[l++] = 0x80;
} else if (!strcmp (op->mnemonic, "jp") ||
!strcmp(op->mnemonic, "jpe")) {
data[l++] = 0x8a;
} else if (!strcmp (op->mnemonic, "js") ||
!strcmp (op->mnemonic, "jz")) {
data[l++] = 0x88;
}
if (is_short) {
data[l-1] -= 0x10;
}
immediate -= is_short ? 2 : 6;
data[l++] = immediate;
if (!is_short) {
data[l++] = immediate >> 8;
data[l++] = immediate >> 16;
data[l++] = immediate >> 24;
}
return l;
}
static int oplea(RAsm *a, ut8 *data, const Opcode *op){
int l = 0;
int mod = 0;
st32 offset = 0;
int reg = 0;
int rm = 0;
if (op->operands[0].type & OT_REGALL &&
op->operands[1].type & (OT_MEMORY | OT_CONSTANT)) {
if (a->bits == 64) {
data[l++] = 0x48;
}
data[l++] = 0x8d;
if (op->operands[1].regs[0] == X86R_UNDEFINED) {
int high = 0xff00 & op->operands[1].offset;
data[l++] = op->operands[0].reg << 3 | 5;
data[l++] = op->operands[1].offset;
data[l++] = high >> 8;
data[l++] = op->operands[1].offset >> 16;
data[l++] = op->operands[1].offset >> 24;
return l;
} else {
reg = op->operands[0].reg;
rm = op->operands[1].regs[0];
offset = op->operands[1].offset * op->operands[1].offset_sign;
if (offset != 0 || op->operands[1].regs[0] == X86R_EBP) {
mod = 1;
if (offset >= 128 || offset < -128) {
mod = 2;
}
data[l++] = mod << 6 | reg << 3 | rm;
if (op->operands[1].regs[0] == X86R_ESP) {
data[l++] = 0x24;
}
data[l++] = offset;
if (mod == 2) {
data[l++] = offset >> 8;
data[l++] = offset >> 16;
data[l++] = offset >> 24;
}
} else {
data[l++] = op->operands[0].reg << 3 | op->operands[1].regs[0];
if (op->operands[1].regs[0] == X86R_ESP) {
data[l++] = 0x24;
}
}
}
}
return l;
}
static int oples(RAsm *a, ut8* data, const Opcode *op) {
int l = 0;
int offset = 0;
int mod = 0;
if (op->operands[1].type & OT_MEMORY) {
data[l++] = 0xc4;
if (op->operands[1].type & OT_GPREG) {
offset = op->operands[1].offset * op->operands[1].offset_sign;
if (offset) {
mod = 1;
if (offset > 128 || offset < -128) {
mod = 2;
}
}
data[l++] = mod << 6 | op->operands[0].reg << 3 | op->operands[1].regs[0];
if (mod) {
data[l++] = offset;
if (mod > 1) {
data[l++] = offset >> 8;
data[l++] = offset >> 16;
data[l++] = offset >> 24;
}
}
} else {
offset = op->operands[1].offset * op->operands[1].offset_sign;
data[l++] = 0x05;
data[l++] = offset;
data[l++] = offset >> 8;
data[l++] = offset >> 16;
data[l++] = offset >> 24;
}
}
return l;
}
static int opmov(RAsm *a, ut8 *data, const Opcode *op) {
int l = 0;
st64 offset = 0;
int mod = 0;
int base = 0;
int rex = 0;
ut64 immediate = 0;
if (op->operands[1].type & OT_CONSTANT) {
if (!op->operands[1].is_good_flag) {
return -1;
}
if (op->operands[1].immediate == -1) {
return -1;
}
immediate = op->operands[1].immediate * op->operands[1].sign;
if (op->operands[0].type & OT_GPREG && !(op->operands[0].type & OT_MEMORY)) {
if (a->bits == 64 && ((op->operands[0].type & OT_QWORD) | (op->operands[1].type & OT_QWORD))) {
if (!(op->operands[1].type & OT_CONSTANT) && op->operands[1].extended) {
data[l++] = 0x49;
} else {
data[l++] = 0x48;
}
} else if (op->operands[0].extended) {
data[l++] = 0x41;
}
if (op->operands[0].type & OT_WORD) {
if (a->bits > 16) {
data[l++] = 0x66;
}
}
if (op->operands[0].type & OT_BYTE) {
data[l++] = 0xb0 | op->operands[0].reg;
data[l++] = immediate;
} else {
if (a->bits == 64 &&
((op->operands[0].type & OT_QWORD) |
(op->operands[1].type & OT_QWORD)) &&
immediate < UT32_MAX) {
data[l++] = 0xc7;
data[l++] = 0xc0 | op->operands[0].reg;
} else {
data[l++] = 0xb8 | op->operands[0].reg;
}
data[l++] = immediate;
data[l++] = immediate >> 8;
if (!(op->operands[0].type & OT_WORD)) {
data[l++] = immediate >> 16;
data[l++] = immediate >> 24;
}
if (a->bits == 64 && immediate > UT32_MAX) {
data[l++] = immediate >> 32;
data[l++] = immediate >> 40;
data[l++] = immediate >> 48;
data[l++] = immediate >> 56;
}
}
} else if (op->operands[0].type & OT_MEMORY) {
if (!op->operands[0].explicit_size) {
if (op->operands[0].type & OT_GPREG) {
((Opcode *)op)->operands[0].dest_size = op->operands[0].reg_size;
} else {
return -1;
}
}
int dest_bits = 8 * ((op->operands[0].dest_size & ALL_SIZE) >> OPSIZE_SHIFT);
int reg_bits = 8 * ((op->operands[0].reg_size & ALL_SIZE) >> OPSIZE_SHIFT);
int offset = op->operands[0].offset * op->operands[0].offset_sign;
//addr_size_override prefix
bool use_aso = false;
if (reg_bits < a->bits) {
use_aso = true;
}
//op_size_override prefix
bool use_oso = false;
if (dest_bits == 16) {
use_oso = true;
}
bool rip_rel = op->operands[0].regs[0] == X86R_RIP;
//rex prefix
int rex = 1 << 6;
bool use_rex = false;
if (dest_bits == 64) { //W field
use_rex = true;
rex |= 1 << 3;
}
if (op->operands[0].extended) { //B field
use_rex = true;
rex |= 1;
}
//opcode selection
int opcode;
if (dest_bits == 8) {
opcode = 0xc6;
} else {
opcode = 0xc7;
}
//modrm and SIB selection
int modrm = 0;
int mod;
int reg = 0;
int rm;
bool use_sib = false;
int sib;
//mod
if (offset == 0) {
mod = 0;
} else if (offset < 128 && offset > -129) {
mod = 1;
} else {
mod = 2;
}
if (reg_bits == 16) {
if (op->operands[0].regs[0] == X86R_BX && op->operands[0].regs[1] == X86R_SI) {
rm = B0000;
} else if (op->operands[0].regs[0] == X86R_BX && op->operands[0].regs[1] == X86R_DI) {
rm = B0001;
} else if (op->operands[0].regs[0] == X86R_BP && op->operands[0].regs[1] == X86R_SI) {
rm = B0010;
} else if (op->operands[0].regs[0] == X86R_BP && op->operands[0].regs[1] == X86R_DI) {
rm = B0011;
} else if (op->operands[0].regs[0] == X86R_SI && op->operands[0].regs[1] == -1) {
rm = B0100;
} else if (op->operands[0].regs[0] == X86R_DI && op->operands[0].regs[1] == -1) {
rm = B0101;
} else if (op->operands[0].regs[0] == X86R_BX && op->operands[0].regs[1] == -1) {
rm = B0111;
} else {
//TODO allow for displacement only when parser is reworked
return -1;
}
modrm = (mod << 6) | (reg << 3) | rm;
} else {
//rm
if (op->operands[0].extended) {
rm = op->operands[0].reg;
} else {
rm = op->operands[0].regs[0];
}
//[epb] alone is illegal, so we need to fake a [ebp+0]
if (rm == 5 && mod == 0) {
mod = 1;
}
//sib
int index = op->operands[0].regs[1];
int scale = getsib(op->operands[0].scale[1]);
if (index != -1) {
use_sib = true;
sib = (scale << 6) | (index << 3) | rm;
} else if (rm == 4) {
use_sib = true;
sib = 0x24;
}
if (use_sib) {
rm = B0100;
}
if (rip_rel) {
modrm = (B0000 << 6) | (reg << 3) | B0101;
sib = (scale << 6) | (B0100 << 3) | B0101;
} else {
modrm = (mod << 6) | (reg << 3) | rm;
}
}
//build the final result
if (use_aso) {
data[l++] = 0x67;
}
if (use_oso) {
data[l++] = 0x66;
}
if (use_rex) {
data[l++] = rex;
}
data[l++] = opcode;
data[l++] = modrm;
if (use_sib) {
data[l++] = sib;
}
//offset
if (mod == 1) {
data[l++] = offset;
} else if (reg_bits == 16 && mod == 2) {
data[l++] = offset;
data[l++] = offset >> 8;
} else if (mod == 2 || rip_rel) {
data[l++] = offset;
data[l++] = offset >> 8;
data[l++] = offset >> 16;
data[l++] = offset >> 24;
}
//immediate
int byte;
for (byte = 0; byte < dest_bits && byte < 32; byte += 8) {
data[l++] = (immediate >> byte);
}
}
} else if (op->operands[1].type & OT_REGALL &&
!(op->operands[1].type & OT_MEMORY)) {
if (op->operands[0].type & OT_CONSTANT) {
return -1;
}
if (op->operands[0].type & OT_REGTYPE & OT_SEGMENTREG &&
op->operands[1].type & OT_REGTYPE & OT_SEGMENTREG) {
return -1;
}
// Check reg sizes match
if (op->operands[0].type & OT_REGTYPE && op->operands[1].type & OT_REGTYPE) {
if (!((op->operands[0].type & ALL_SIZE) &
(op->operands[1].type & ALL_SIZE))) {
return -1;
}
}
if (a->bits == 64) {
if (op->operands[0].extended) {
rex = 1;
}
if (op->operands[1].extended) {
rex += 4;
}
if (op->operands[1].type & OT_QWORD) {
if (!(op->operands[0].type & OT_QWORD)) {
data[l++] = 0x67;
data[l++] = 0x48;
}
}
if (op->operands[1].type & OT_QWORD &&
op->operands[0].type & OT_QWORD) {
data[l++] = 0x48 | rex;
}
if (op->operands[1].type & OT_DWORD &&
op->operands[0].type & OT_DWORD) {
data[l++] = 0x40 | rex;
}
} else if (op->operands[0].extended && op->operands[1].extended) {
data[l++] = 0x45;
}
offset = op->operands[0].offset * op->operands[0].offset_sign;
if (op->operands[1].type & OT_REGTYPE & OT_SEGMENTREG) {
data[l++] = 0x8c;
} else {
if (op->operands[0].type & OT_WORD) {
data[l++] = 0x66;
}
data[l++] = (op->operands[0].type & OT_BYTE) ? 0x88 : 0x89;
}
if (op->operands[0].scale[0] > 1) {
data[l++] = op->operands[1].reg << 3 | 4;
data[l++] = getsib (op->operands[0].scale[0]) << 6 |
op->operands[0].regs[0] << 3 | 5;
data[l++] = offset;
data[l++] = offset >> 8;
data[l++] = offset >> 16;
data[l++] = offset >> 24;
return l;
}
if (!(op->operands[0].type & OT_MEMORY)) {
if (op->operands[0].reg == X86R_UNDEFINED ||
op->operands[1].reg == X86R_UNDEFINED) {
return -1;
}
mod = 0x3;
data[l++] = mod << 6 | op->operands[1].reg << 3 | op->operands[0].reg;
} else if (op->operands[0].regs[0] == X86R_UNDEFINED) {
data[l++] = op->operands[1].reg << 3 | 0x5;
data[l++] = offset;
data[l++] = offset >> 8;
data[l++] = offset >> 16;
data[l++] = offset >> 24;
} else {
if (op->operands[0].type & OT_MEMORY) {
if (op->operands[0].regs[1] != X86R_UNDEFINED) {
data[l++] = op->operands[1].reg << 3 | 0x4;
data[l++] = op->operands[0].regs[1] << 3 | op->operands[0].regs[0];
return l;
}
if (offset) {
mod = (offset > 128 || offset < -129) ? 0x2 : 0x1;
}
if (op->operands[0].regs[0] == X86R_EBP) {
mod = 0x2;
}
data[l++] = mod << 6 | op->operands[1].reg << 3 | op->operands[0].regs[0];
if (op->operands[0].regs[0] == X86R_ESP) {
data[l++] = 0x24;
}
if (offset) {
data[l++] = offset;
}
if (mod == 2) {
// warning C4293: '>>': shift count negative or too big, undefined behavior
data[l++] = offset >> 8;
data[l++] = offset >> 16;
data[l++] = offset >> 24;
}
}
}
} else if (op->operands[1].type & OT_MEMORY) {
if (op->operands[0].type & OT_MEMORY) {
return -1;
}
offset = op->operands[1].offset * op->operands[1].offset_sign;
if (op->operands[0].reg == X86R_EAX && op->operands[1].regs[0] == X86R_UNDEFINED) {
if (a->bits == 64) {
data[l++] = 0x48;
}
if (op->operands[0].type & OT_BYTE) {
data[l++] = 0xa0;
} else {
data[l++] = 0xa1;
}
data[l++] = offset;
data[l++] = offset >> 8;
data[l++] = offset >> 16;
data[l++] = offset >> 24;
if (a->bits == 64) {
data[l++] = offset >> 32;
data[l++] = offset >> 40;
data[l++] = offset >> 48;
data[l++] = offset >> 54;
}
return l;
}
if (op->operands[0].type & OT_BYTE && a->bits == 64 && op->operands[1].regs[0]) {
if (op->operands[1].regs[0] >= X86R_R8 &&
op->operands[0].reg < 4) {
data[l++] = 0x41;
data[l++] = 0x8a;
data[l++] = op->operands[0].reg << 3 | (op->operands[1].regs[0] - 8);
return l;
}
return -1;
}
if (op->operands[1].type & OT_REGTYPE & OT_SEGMENTREG) {
if (op->operands[1].scale[0] == 0) {
return -1;
}
data[l++] = SEG_REG_PREFIXES[op->operands[1].regs[0] % 6];
data[l++] = 0x8b;
data[l++] = (((ut32)op->operands[0].reg) << 3) | 0x5;
data[l++] = offset;
data[l++] = offset >> 8;
data[l++] = offset >> 16;
data[l++] = offset >> 24;
return l;
}
if (a->bits == 64) {
if (op->operands[0].type & OT_QWORD) {
if (!(op->operands[1].type & OT_QWORD)) {
if (op->operands[1].regs[0] != -1) {
data[l++] = 0x67;
}
data[l++] = 0x48;
}
} else if (op->operands[1].type & OT_DWORD) {
data[l++] = 0x44;
} else if (!(op->operands[1].type & OT_QWORD)) {
data[l++] = 0x67;
}
if (op->operands[1].type & OT_QWORD &&
op->operands[0].type & OT_QWORD) {
data[l++] = 0x48;
}
}
if (op->operands[0].type & OT_WORD) {
data[l++] = 0x66;
data[l++] = op->operands[1].type & OT_BYTE ? 0x8a : 0x8b;
} else {
data[l++] = (op->operands[1].type & OT_BYTE ||
op->operands[0].type & OT_BYTE) ?
0x8a : 0x8b;
}
if (op->operands[1].regs[0] == X86R_UNDEFINED) {
if (a->bits == 64) {
data[l++] = op->operands[0].reg << 3 | 0x4;
data[l++] = 0x25;
} else {
data[l++] = op->operands[0].reg << 3 | 0x5;
}
data[l++] = offset;
data[l++] = offset >> 8;
data[l++] = offset >> 16;
data[l++] = offset >> 24;
} else {
if (op->operands[1].scale[0] > 1) {
data[l++] = op->operands[0].reg << 3 | 4;
if (op->operands[1].scale[0] >= 2) {
base = 5;
}
if (base) {
data[l++] = getsib (op->operands[1].scale[0]) << 6 | op->operands[1].regs[0] << 3 | base;
} else {
data[l++] = getsib (op->operands[1].scale[0]) << 3 | op->operands[1].regs[0];
}
if (offset || base) {
data[l++] = offset;
data[l++] = offset >> 8;
data[l++] = offset >> 16;
data[l++] = offset >> 24;
}
return l;
}
if (op->operands[1].regs[1] != X86R_UNDEFINED) {
data[l++] = op->operands[0].reg << 3 | 0x4;
data[l++] = op->operands[1].regs[1] << 3 | op->operands[1].regs[0];
return l;
}
if (offset || op->operands[1].regs[0] == X86R_EBP) {
mod = 0x2;
if (op->operands[1].offset > 127) {
mod = 0x4;
}
}
if (a->bits == 64 && offset && op->operands[0].type & OT_QWORD) {
if (op->operands[1].regs[0] == X86R_RIP) {
data[l++] = 0x5;
} else {
if (op->operands[1].offset > 127) {
data[l++] = 0x80 | op->operands[0].reg << 3 | op->operands[1].regs[0];
} else {
data[l++] = 0x40 | op->operands[1].regs[0];
}
}
if (op->operands[1].offset > 127) {
mod = 0x1;
}
} else {
if (op->operands[1].regs[0] == X86R_EIP && (op->operands[0].type & OT_DWORD)) {
data[l++] = 0x0d;
} else if (op->operands[1].regs[0] == X86R_RIP && (op->operands[0].type & OT_QWORD)) {
data[l++] = 0x05;
} else {
data[l++] = mod << 5 | op->operands[0].reg << 3 | op->operands[1].regs[0];
}
}
if (op->operands[1].regs[0] == X86R_ESP) {
data[l++] = 0x24;
}
if (mod >= 0x2) {
data[l++] = offset;
if (op->operands[1].offset > 128 || op->operands[1].regs[0] == X86R_EIP) {
data[l++] = offset >> 8;
data[l++] = offset >> 16;
data[l++] = offset >> 24;
}
} else if (a->bits == 64 && (offset || op->operands[1].regs[0] == X86R_RIP)) {
data[l++] = offset;
if (op->operands[1].offset > 127 || op->operands[1].regs[0] == X86R_RIP) {
data[l++] = offset >> 8;
data[l++] = offset >> 16;
data[l++] = offset >> 24;
}
}
}
}
return l;
}
static int opmul(RAsm *a, ut8 *data, const Opcode *op) {
int l = 0;
if ( op->operands[0].type & OT_QWORD ) {
data[l++] = 0x48;
}
switch (op->operands_count) {
case 1:
if ( op->operands[0].type & OT_WORD ) {
data[l++] = 0x66;
}
if (op->operands[0].type & OT_BYTE) {
data[l++] = 0xf6;
} else {
data[l++] = 0xf7;
}
if (op->operands[0].type & OT_MEMORY) {
data[l++] = 0x20 | op->operands[0].regs[0];
} else {
data[l++] = 0xe0 | op->operands[0].reg;
}
break;
default:
return -1;
}
return l;
}
static int oppop(RAsm *a, ut8 *data, const Opcode *op) {
int l = 0;
int offset = 0;
int mod = 0;
if (op->operands[0].type & OT_GPREG) {
if (op->operands[0].type & OT_MEMORY) {
return -1;
}
if (op->operands[0].type & OT_REGTYPE & OT_SEGMENTREG) {
ut8 base;
if (op->operands[0].reg & X86R_FS) {
data[l++] = 0x0f;
base = 0x81;
} else {
base = 0x7;
}
data[l++] = base + (8 * op->operands[0].reg);
} else {
ut8 base = 0x58;
data[l++] = base + op->operands[0].reg;
}
} else if (op->operands[0].type & OT_MEMORY) {
data[l++] = 0x8f;
offset = op->operands[0].offset * op->operands[0].offset_sign;
if (offset != 0 || op->operands[0].regs[0] == X86R_EBP) {
mod = 1;
if (offset >= 128 || offset < -128) {
mod = 2;
}
data[l++] = mod << 6 | op->operands[0].regs[0];
if (op->operands[0].regs[0] == X86R_ESP) {
data[l++] = 0x24;
}
data[l++] = offset;
if (mod == 2) {
data[l++] = offset >> 8;
data[l++] = offset >> 16;
data[l++] = offset >> 24;
}
} else {
data[l++] = op->operands[0].regs[0];
if (op->operands[0].regs[0] == X86R_ESP) {
data[l++] = 0x24;
}
}
}
return l;
}
static int oppush(RAsm *a, ut8 *data, const Opcode *op) {
int l = 0;
int mod = 0;
st32 immediate = 0;;
st32 offset = 0;
if (op->operands[0].type & OT_GPREG &&
!(op->operands[0].type & OT_MEMORY)) {
if (op->operands[0].type & OT_REGTYPE & OT_SEGMENTREG) {
ut8 base;
if (op->operands[0].reg & X86R_FS) {
data[l++] = 0x0f;
base = 0x80;
} else {
base = 0x6;
}
data[l++] = base + (8 * op->operands[0].reg);
} else {
if (op->operands[0].extended && a->bits == 64) {
data[l++] = 0x41;
}
ut8 base = 0x50;
data[l++] = base + op->operands[0].reg;
}
} else if (op->operands[0].type & OT_MEMORY) {
data[l++] = 0xff;
offset = op->operands[0].offset * op->operands[0].offset_sign;
mod = 0;
if (offset != 0 || op->operands[0].regs[0] == X86R_EBP) {
mod = 1;
if (offset >= 128 || offset < -128) {
mod = 2;
}
data[l++] = mod << 6 | 6 << 3 | op->operands[0].regs[0];
if (op->operands[0].regs[0] == X86R_ESP) {
data[l++] = 0x24;
}
data[l++] = offset;
if (mod == 2) {
data[l++] = offset >> 8;
data[l++] = offset >> 16;
data[l++] = offset >> 24;
}
} else {
mod = 3;
data[l++] = mod << 4 | op->operands[0].regs[0];
if (op->operands[0].regs[0] == X86R_ESP) {
data[l++] = 0x24;
}
}
} else {
immediate = op->operands[0].immediate * op->operands[0].sign;
if (immediate >= 128 || immediate < -128) {
data[l++] = 0x68;
data[l++] = immediate;
data[l++] = immediate >> 8;
data[l++] = immediate >> 16;
data[l++] = immediate >> 24;
} else {
data[l++] = 0x6a;
data[l++] = immediate;
}
}
return l;
}
static int opout(RAsm *a, ut8 *data, const Opcode *op) {
int l = 0;
st32 immediate = 0;
if (op->operands[0].reg == X86R_DX) {
if (op->operands[1].reg == X86R_AL && op->operands[1].type & OT_BYTE) {
data[l++] = 0xee;
return l;
}
if (op->operands[1].reg == X86R_AX && op->operands[1].type & OT_WORD) {
data[l++] = 0x66;
data[l++] = 0xef;
return l;
}
if (op->operands[1].reg == X86R_EAX && op->operands[1].type & OT_DWORD) {
data[l++] = 0xef;
return l;
}
} else if (op->operands[0].type & OT_CONSTANT) {
immediate = op->operands[0].immediate * op->operands[0].sign;
if (immediate > 255 || immediate < -128) {
return -1;
}
if (op->operands[1].reg == X86R_AL && op->operands[1].type & OT_BYTE) {
data[l++] = 0xe6;
} else if (op->operands[1].reg == X86R_AX && op->operands[1].type & OT_WORD) {
data[l++] = 0x66;
data[l++] = 0xe7;
} else if (op->operands[1].reg == X86R_EAX && op->operands[1].type & OT_DWORD) {
data[l++] = 0xe7;
} else {
return -1;
}
data[l++] = immediate;
} else {
return -1;
}
return l;
}
static int oploop(RAsm *a, ut8 *data, const Opcode *op) {
int l = 0;
data[l++] = 0xe2;
st8 delta = op->operands[0].immediate - a->pc - 2;
data[l++] = (ut8)delta;
return l;
}
static int opret(RAsm *a, ut8 *data, const Opcode *op) {
int l = 0;
int immediate = 0;
if (a->bits == 16) {
data[l++] = 0xc3;
return l;
}
if (op->operands[0].type == OT_UNKNOWN) {
data[l++] = 0xc3;
} else if (op->operands[0].type & (OT_CONSTANT | OT_WORD)) {
data[l++] = 0xc2;
immediate = op->operands[0].immediate * op->operands[0].sign;
data[l++] = immediate;
data[l++] = immediate << 8;
}
return l;
}
static int opretf(RAsm *a, ut8 *data, const Opcode *op) {
int l = 0;
st32 immediate = 0;
if (op->operands[0].type & OT_CONSTANT) {
immediate = op->operands[0].immediate * op->operands[0].sign;
data[l++] = 0xca;
data[l++] = immediate;
data[l++] = immediate >> 8;
} else if (op->operands[0].type == OT_UNKNOWN) {
data[l++] = 0xcb;
}
return l;
}
static int opstos(RAsm *a, ut8 *data, const Opcode *op) {
int l = 0;
if (!strcmp(op->mnemonic, "stosw")) {
data[l++] = 0x66;
}
if (!strcmp(op->mnemonic, "stosb")) {
data[l++] = 0xaa;
} else if (!strcmp(op->mnemonic, "stosw")) {
data[l++] = 0xab;
} else if (!strcmp(op->mnemonic, "stosd")) {
data[l++] = 0xab;
}
return l;
}
static int opset(RAsm *a, ut8 *data, const Opcode *op) {
if (!(op->operands[0].type & (OT_GPREG | OT_BYTE))) {return -1;}
int l = 0;
int mod = 0;
int reg = op->operands[0].regs[0];
data[l++] = 0x0f;
if (!strcmp (op->mnemonic, "seto")) {
data[l++] = 0x90;
} else if (!strcmp (op->mnemonic, "setno")) {
data[l++] = 0x91;
} else if (!strcmp (op->mnemonic, "setb") ||
!strcmp (op->mnemonic, "setnae") ||
!strcmp (op->mnemonic, "setc")) {
data[l++] = 0x92;
} else if (!strcmp (op->mnemonic, "setnb") ||
!strcmp (op->mnemonic, "setae") ||
!strcmp (op->mnemonic, "setnc")) {
data[l++] = 0x93;
} else if (!strcmp (op->mnemonic, "setz") ||
!strcmp (op->mnemonic, "sete")) {
data[l++] = 0x94;
} else if (!strcmp (op->mnemonic, "setnz") ||
!strcmp (op->mnemonic, "setne")) {
data[l++] = 0x95;
} else if (!strcmp (op->mnemonic, "setbe") ||
!strcmp (op->mnemonic, "setna")) {
data[l++] = 0x96;
} else if (!strcmp (op->mnemonic, "setnbe") ||
!strcmp (op->mnemonic, "seta")) {
data[l++] = 0x97;
} else if (!strcmp (op->mnemonic, "sets")) {
data[l++] = 0x98;
} else if (!strcmp (op->mnemonic, "setns")) {
data[l++] = 0x99;
} else if (!strcmp (op->mnemonic, "setp") ||
!strcmp (op->mnemonic, "setpe")) {
data[l++] = 0x9a;
} else if (!strcmp (op->mnemonic, "setnp") ||
!strcmp (op->mnemonic, "setpo")) {
data[l++] = 0x9b;
} else if (!strcmp (op->mnemonic, "setl") ||
!strcmp (op->mnemonic, "setnge")) {
data[l++] = 0x9c;
} else if (!strcmp (op->mnemonic, "setnl") ||
!strcmp (op->mnemonic, "setge")) {
data[l++] = 0x9d;
} else if (!strcmp (op->mnemonic, "setle") ||
!strcmp (op->mnemonic, "setng")) {
data[l++] = 0x9e;
} else if (!strcmp (op->mnemonic, "setnle") ||
!strcmp (op->mnemonic, "setg")) {
data[l++] = 0x9f;
} else {
return -1;
}
if (!(op->operands[0].type & OT_MEMORY)) {
mod = 3;
reg = op->operands[0].reg;
}
data[l++] = mod << 6 | reg;
return l;
}
static int optest(RAsm *a, ut8 *data, const Opcode *op) {
int l = 0;
if (!op->operands[0].type || !op->operands[1].type) {
eprintf ("Error: Invalid operands\n");
return -1;
}
if (a->bits == 64) {
if (op->operands[0].type & OT_MEMORY ||
op->operands[1].type & OT_MEMORY) {
data[l++] = 0x67;
}
if (op->operands[0].type & OT_QWORD &&
op->operands[1].type & OT_QWORD) {
if (op->operands[0].extended &&
op->operands[1].extended) {
data[l++] = 0x4d;
} else {
data[l++] = 0x48;
}
}
}
if (op->operands[1].type & OT_CONSTANT) {
if (op->operands[0].type & OT_BYTE) {
data[l++] = 0xf6;
data[l++] = op->operands[0].regs[0];
data[l++] = op->operands[1].immediate;
return l;
}
data[l++] = 0xf7;
if (op->operands[0].type & OT_MEMORY) {
data[l++] = 0x00 | op->operands[0].regs[0];
} else {
data[l++] = 0xc0 | op->operands[0].reg;
}
data[l++] = op->operands[1].immediate >> 0;
data[l++] = op->operands[1].immediate >> 8;
data[l++] = op->operands[1].immediate >> 16;
data[l++] = op->operands[1].immediate >> 24;
return l;
}
if (op->operands[0].type & OT_BYTE ||
op->operands[1].type & OT_BYTE) {
data[l++] = 0x84;
} else {
data[l++] = 0x85;
}
if (op->operands[0].type & OT_MEMORY) {
data[l++] = 0x00 | op->operands[1].reg << 3 | op->operands[0].regs[0];
} else {
if (op->operands[1].type & OT_MEMORY) {
data[l++] = 0x00 | op->operands[0].reg << 3 | op->operands[1].regs[0];
} else {
data[l++] = 0xc0 | op->operands[1].reg << 3 | op->operands[0].reg;
}
}
return l;
}
static int opxchg(RAsm *a, ut8 *data, const Opcode *op) {
int l = 0;
int mod_byte = 0;
int reg = 0;
int rm = 0;
st32 offset = 0;
if (op->operands[0].type & OT_MEMORY || op->operands[1].type & OT_MEMORY) {
data[l++] = 0x87;
if (op->operands[0].type & OT_MEMORY) {
rm = op->operands[0].regs[0];
offset = op->operands[0].offset * op->operands[0].offset_sign;
reg = op->operands[1].reg;
} else if (op->operands[1].type & OT_MEMORY) {
rm = op->operands[1].regs[0];
offset = op->operands[1].offset * op->operands[1].offset_sign;
reg = op->operands[0].reg;
}
if (offset) {
mod_byte = 1;
if (offset < ST8_MIN || offset > ST8_MAX) {
mod_byte = 2;
}
}
} else {
if (op->operands[0].reg == X86R_EAX &&
op->operands[1].type & OT_GPREG) {
data[l++] = 0x90 + op->operands[1].reg;
return l;
} else if (op->operands[1].reg == X86R_EAX &&
op->operands[0].type & OT_GPREG) {
data[l++] = 0x90 + op->operands[0].reg;
return l;
} else if (op->operands[0].type & OT_GPREG &&
op->operands[1].type & OT_GPREG) {
mod_byte = 3;
data[l++] = 0x87;
reg = op->operands[1].reg;
rm = op->operands[0].reg;
}
}
data[l++] = mod_byte << 6 | reg << 3 | rm;
if (mod_byte > 0 && mod_byte < 3) {
data[l++] = offset;
if (mod_byte == 2) {
data[l++] = offset >> 8;
data[l++] = offset >> 16;
data[l++] = offset >> 24;
}
}
return l;
}
static int opcdqe(RAsm *a, ut8 *data, const Opcode *op) {
int l = 0;
if (a->bits == 64) {
data[l++] = 0x48;
}
data[l++] = 0x98;
return l;
}
static int opfcmov(RAsm *a, ut8 *data, const Opcode *op) {
int l = 0;
char* fcmov = op->mnemonic + strlen("fcmov");
switch (op->operands_count) {
case 2:
if ( op->operands[0].type & OT_FPUREG & ~OT_REGALL && op->operands[0].reg == 0 &&
op->operands[1].type & OT_FPUREG & ~OT_REGALL ) {
if ( !strcmp( fcmov, "b" ) ) {
data[l++] = 0xda;
data[l++] = 0xc0 | op->operands[1].reg;
} else if ( !strcmp( fcmov, "e" ) ) {
data[l++] = 0xda;
data[l++] = 0xc8 | op->operands[1].reg;
} else if ( !strcmp( fcmov, "be" ) ) {
data[l++] = 0xda;
data[l++] = 0xd0 | op->operands[1].reg;
} else if ( !strcmp( fcmov, "u" ) ) {
data[l++] = 0xda;
data[l++] = 0xd8 | op->operands[1].reg;
} else if ( !strcmp( fcmov, "nb" ) ) {
data[l++] = 0xdb;
data[l++] = 0xc0 | op->operands[1].reg;
} else if ( !strcmp( fcmov, "ne" ) ) {
data[l++] = 0xdb;
data[l++] = 0xc8 | op->operands[1].reg;
} else if ( !strcmp( fcmov, "nbe" ) ) {
data[l++] = 0xdb;
data[l++] = 0xd0 | op->operands[1].reg;
} else if ( !strcmp( fcmov, "nu" ) ) {
data[l++] = 0xdb;
data[l++] = 0xd8 | op->operands[1].reg;
} else {
return -1;
}
} else {
return -1;
}
break;
default:
return -1;
}
return l;
}
static int opffree(RAsm *a, ut8 *data, const Opcode *op) {
int l = 0;
switch (op->operands_count) {
case 1:
if (op->operands[0].type & OT_FPUREG & ~OT_REGALL) {
data[l++] = 0xdd;
data[l++] = 0xc0 | op->operands[0].reg;
} else {
return -1;
}
break;
default:
return -1;
}
return l;
}
static int opfrstor(RAsm *a, ut8 *data, const Opcode *op) {
int l = 0;
switch (op->operands_count) {
case 1:
if (op->operands[0].type & OT_MEMORY) {
data[l++] = 0xdd;
data[l++] = 0x20 | op->operands[0].regs[0];
} else {
return -1;
}
break;
default:
return -1;
}
return l;
}
static int opfxch(RAsm *a, ut8 *data, const Opcode *op) {
int l = 0;
switch (op->operands_count) {
case 0:
data[l++] = 0xd9;
data[l++] = 0xc9;
break;
case 1:
if (op->operands[0].type & OT_FPUREG & ~OT_REGALL) {
data[l++] = 0xd9;
data[l++] = 0xc8 | op->operands[0].reg;
} else {
return -1;
}
break;
default:
return -1;
}
return l;
}
static int opfucom(RAsm *a, ut8 *data, const Opcode *op) {
int l = 0;
switch (op->operands_count) {
case 1:
if ( op->operands[0].type & OT_FPUREG & ~OT_REGALL ) {
data[l++] = 0xdd;
data[l++] = 0xe0 | op->operands[0].reg;
} else {
return -1;
}
break;
case 0:
data[l++] = 0xdd;
data[l++] = 0xe1;
break;
default:
return -1;
}
return l;
}
static int opfucomp(RAsm *a, ut8 *data, const Opcode *op) {
int l = 0;
switch (op->operands_count) {
case 1:
if ( op->operands[0].type & OT_FPUREG & ~OT_REGALL ) {
data[l++] = 0xdd;
data[l++] = 0xe8 | op->operands[0].reg;
} else {
return -1;
}
break;
case 0:
data[l++] = 0xdd;
data[l++] = 0xe9;
break;
default:
return -1;
}
return l;
}
static int opfaddp(RAsm *a, ut8 *data, const Opcode *op) {
int l = 0;
switch (op->operands_count) {
case 2:
if ( op->operands[0].type & OT_FPUREG & ~OT_REGALL &&
op->operands[1].type & OT_FPUREG & ~OT_REGALL && op->operands[1].reg == 0 ) {
data[l++] = 0xde;
data[l++] = 0xc0 | op->operands[0].reg;
} else {
return -1;
}
break;
case 0:
data[l++] = 0xde;
data[l++] = 0xc1;
break;
default:
return -1;
}
return l;
}
static int opfiadd(RAsm *a, ut8 *data, const Opcode *op) {
int l = 0;
switch (op->operands_count) {
case 1:
if ( op->operands[0].type & OT_MEMORY ) {
if ( op->operands[0].type & OT_WORD ) {
data[l++] = 0xde;
data[l++] = 0x00 | op->operands[0].regs[0];
} else if ( op->operands[0].type & OT_DWORD ) {
data[l++] = 0xda;
data[l++] = 0x00 | op->operands[0].regs[0];
} else {
return -1;
}
} else {
return -1;
}
break;
default:
return -1;
}
return l;
}
static int opfadd(RAsm *a, ut8 *data, const Opcode *op) {
int l = 0;
switch (op->operands_count) {
case 1:
if ( op->operands[0].type & OT_MEMORY ) {
if ( op->operands[0].type & OT_QWORD ) {
data[l++] = 0xdc;
data[l++] = 0x00 | op->operands[0].regs[0];
} else if ( op->operands[0].type & OT_DWORD ) {
data[l++] = 0xd8;
data[l++] = 0x00 | op->operands[0].regs[0];
} else {
return -1;
}
} else {
return -1;
}
break;
case 2:
if ( op->operands[0].type & OT_FPUREG & ~OT_REGALL && op->operands[0].reg == 0 &&
op->operands[1].type & OT_FPUREG & ~OT_REGALL ) {
data[l++] = 0xd8;
data[l++] = 0xc0 | op->operands[1].reg;
} else if ( op->operands[0].type & OT_FPUREG & ~OT_REGALL &&
op->operands[1].type & OT_FPUREG & ~OT_REGALL && op->operands[1].reg == 0 ) {
data[l++] = 0xdc;
data[l++] = 0xc0 | op->operands[0].reg;
} else {
return -1;
}
break;
default:
return -1;
}
return l;
}
static int opficom(RAsm *a, ut8 *data, const Opcode *op) {
int l = 0;
switch (op->operands_count) {
case 1:
if ( op->operands[0].type & OT_MEMORY ) {
if ( op->operands[0].type & OT_WORD ) {
data[l++] = 0xde;
data[l++] = 0x10 | op->operands[0].regs[0];
} else if ( op->operands[0].type & OT_DWORD ) {
data[l++] = 0xda;
data[l++] = 0x10 | op->operands[0].regs[0];
} else {
return -1;
}
} else {
return -1;
}
break;
default:
return -1;
}
return l;
}
static int opficomp(RAsm *a, ut8 *data, const Opcode *op) {
int l = 0;
switch (op->operands_count) {
case 1:
if ( op->operands[0].type & OT_MEMORY ) {
if ( op->operands[0].type & OT_WORD ) {
data[l++] = 0xde;
data[l++] = 0x18 | op->operands[0].regs[0];
} else if ( op->operands[0].type & OT_DWORD ) {
data[l++] = 0xda;
data[l++] = 0x18 | op->operands[0].regs[0];
} else {
return -1;
}
} else {
return -1;
}
break;
default:
return -1;
}
return l;
}
static int opfild(RAsm *a, ut8 *data, const Opcode *op) {
int l = 0;
switch (op->operands_count) {
case 1:
if ( op->operands[0].type & OT_MEMORY ) {
if ( op->operands[0].type & OT_WORD ) {
data[l++] = 0xdf;
data[l++] = 0x00 | op->operands[0].regs[0];
} else if ( op->operands[0].type & OT_DWORD ) {
data[l++] = 0xdb;
data[l++] = 0x00 | op->operands[0].regs[0];
} else if ( op->operands[0].type & OT_QWORD ) {
data[l++] = 0xdf;
data[l++] = 0x28 | op->operands[0].regs[0];
} else {
return -1;
}
} else {
return -1;
}
break;
default:
return -1;
}
return l;
}
static int opfldcw(RAsm *a, ut8 *data, const Opcode *op) {
int l = 0;
switch (op->operands_count) {
case 1:
if ( op->operands[0].type & OT_MEMORY &&
op->operands[0].type & OT_WORD ) {
data[l++] = 0xd9;
data[l++] = 0x28 | op->operands[0].regs[0];
} else {
return -1;
}
break;
default:
return -1;
}
return l;
}
static int opfldenv(RAsm *a, ut8 *data, const Opcode *op) {
int l = 0;
switch (op->operands_count) {
case 1:
if ( op->operands[0].type & OT_MEMORY ) {
data[l++] = 0xd9;
data[l++] = 0x20 | op->operands[0].regs[0];
} else {
return -1;
}
break;
default:
return -1;
}
return l;
}
static int opfbld(RAsm *a, ut8 *data, const Opcode *op) {
int l = 0;
switch (op->operands_count) {
case 1:
if ( op->operands[0].type & OT_MEMORY &&
op->operands[0].type & OT_TBYTE ) {
data[l++] = 0xdf;
data[l++] = 0x20 | op->operands[0].regs[0];
} else {
return -1;
}
break;
default:
return -1;
}
return l;
}
static int opfbstp(RAsm *a, ut8 *data, const Opcode *op) {
int l = 0;
switch (op->operands_count) {
case 1:
if ( op->operands[0].type & OT_MEMORY &&
op->operands[0].type & OT_TBYTE ) {
data[l++] = 0xdf;
data[l++] = 0x30 | op->operands[0].regs[0];
} else {
return -1;
}
break;
default:
return -1;
}
return l;
}
static int opfxrstor(RAsm *a, ut8 *data, const Opcode *op) {
int l = 0;
switch (op->operands_count) {
case 1:
if ( op->operands[0].type & OT_MEMORY ) {
data[l++] = 0x0f;
data[l++] = 0xae;
data[l++] = 0x08 | op->operands[0].regs[0];
} else {
return -1;
}
break;
default:
return -1;
}
return l;
}
static int opfxsave(RAsm *a, ut8 *data, const Opcode *op) {
int l = 0;
switch (op->operands_count) {
case 1:
if ( op->operands[0].type & OT_MEMORY ) {
data[l++] = 0x0f;
data[l++] = 0xae;
data[l++] = 0x00 | op->operands[0].regs[0];
} else {
return -1;
}
break;
default:
return -1;
}
return l;
}
static int opfist(RAsm *a, ut8 *data, const Opcode *op) {
int l = 0;
switch (op->operands_count) {
case 1:
if ( op->operands[0].type & OT_MEMORY ) {
if ( op->operands[0].type & OT_WORD ) {
data[l++] = 0xdf;
data[l++] = 0x10 | op->operands[0].regs[0];
} else if ( op->operands[0].type & OT_DWORD ) {
data[l++] = 0xdb;
data[l++] = 0x10 | op->operands[0].regs[0];
} else {
return -1;
}
} else {
return -1;
}
break;
default:
return -1;
}
return l;
}
static int opfistp(RAsm *a, ut8 *data, const Opcode *op) {
int l = 0;
switch (op->operands_count) {
case 1:
if ( op->operands[0].type & OT_MEMORY ) {
if ( op->operands[0].type & OT_WORD ) {
data[l++] = 0xdf;
data[l++] = 0x18 | op->operands[0].regs[0];
} else if ( op->operands[0].type & OT_DWORD ) {
data[l++] = 0xdb;
data[l++] = 0x18 | op->operands[0].regs[0];
} else if ( op->operands[0].type & OT_QWORD ) {
data[l++] = 0xdf;
data[l++] = 0x38 | op->operands[0].regs[0];
} else {
return -1;
}
} else {
return -1;
}
break;
default:
return -1;
}
return l;
}
static int opfisttp(RAsm *a, ut8 *data, const Opcode *op) {
int l = 0;
switch (op->operands_count) {
case 1:
if ( op->operands[0].type & OT_MEMORY ) {
if ( op->operands[0].type & OT_WORD ) {
data[l++] = 0xdf;
data[l++] = 0x08 | op->operands[0].regs[0];
} else if ( op->operands[0].type & OT_DWORD ) {
data[l++] = 0xdb;
data[l++] = 0x08 | op->operands[0].regs[0];
} else if ( op->operands[0].type & OT_QWORD ) {
data[l++] = 0xdd;
data[l++] = 0x08 | op->operands[0].regs[0];
} else {
return -1;
}
} else {
return -1;
}
break;
default:
return -1;
}
return l;
}
static int opfstenv(RAsm *a, ut8 *data, const Opcode *op) {
int l = 0;
switch (op->operands_count) {
case 1:
if ( op->operands[0].type & OT_MEMORY ) {
data[l++] = 0x9b;
data[l++] = 0xd9;
data[l++] = 0x30 | op->operands[0].regs[0];
} else {
return -1;
}
break;
default:
return -1;
}
return l;
}
static int opfnstenv(RAsm *a, ut8 *data, const Opcode *op) {
int l = 0;
switch (op->operands_count) {
case 1:
if ( op->operands[0].type & OT_MEMORY ) {
data[l++] = 0xd9;
data[l++] = 0x30 | op->operands[0].regs[0];
} else {
return -1;
}
break;
default:
return -1;
}
return l;
}
static int opfdiv(RAsm *a, ut8 *data, const Opcode *op) {
int l = 0;
switch (op->operands_count) {
case 1:
if ( op->operands[0].type & OT_MEMORY ) {
if ( op->operands[0].type & OT_DWORD ) {
data[l++] = 0xd8;
data[l++] = 0x30 | op->operands[0].regs[0];
} else if ( op->operands[0].type & OT_QWORD ) {
data[l++] = 0xdc;
data[l++] = 0x30 | op->operands[0].regs[0];
} else {
return -1;
}
} else {
return -1;
}
break;
case 2:
if ( op->operands[0].type & OT_FPUREG & ~OT_REGALL && op->operands[0].reg == 0 &&
op->operands[1].type & OT_FPUREG & ~OT_REGALL ) {
data[l++] = 0xd8;
data[l++] = 0xf0 | op->operands[1].reg;
} else if ( op->operands[0].type & OT_FPUREG & ~OT_REGALL &&
op->operands[1].type & OT_FPUREG & ~OT_REGALL && op->operands[1].reg == 0 ) {
data[l++] = 0xdc;
data[l++] = 0xf8 | op->operands[0].reg;
} else {
return -1;
}
break;
default:
return -1;
}
return l;
}
static int opfdivp(RAsm *a, ut8 *data, const Opcode *op) {
int l = 0;
switch (op->operands_count) {
case 0:
data[l++] = 0xde;
data[l++] = 0xf9;
break;
case 2:
if ( op->operands[0].type & OT_FPUREG & ~OT_REGALL &&
op->operands[1].type & OT_FPUREG & ~OT_REGALL && op->operands[1].reg == 0 ) {
data[l++] = 0xde;
data[l++] = 0xf8 | op->operands[0].reg;
} else {
return -1;
}
break;
default:
return -1;
}
return l;
}
static int opfidiv(RAsm *a, ut8 *data, const Opcode *op) {
int l = 0;
switch (op->operands_count) {
case 1:
if ( op->operands[0].type & OT_MEMORY ) {
if ( op->operands[0].type & OT_DWORD ) {
data[l++] = 0xda;
data[l++] = 0x30 | op->operands[0].regs[0];
} else if ( op->operands[0].type & OT_WORD ) {
data[l++] = 0xde;
data[l++] = 0x30 | op->operands[0].regs[0];
} else {
return -1;
}
} else {
return -1;
}
break;
default:
return -1;
}
return l;
}
static int opfdivr(RAsm *a, ut8 *data, const Opcode *op) {
int l = 0;
switch (op->operands_count) {
case 1:
if ( op->operands[0].type & OT_MEMORY ) {
if ( op->operands[0].type & OT_DWORD ) {
data[l++] = 0xd8;
data[l++] = 0x38 | op->operands[0].regs[0];
} else if ( op->operands[0].type & OT_QWORD ) {
data[l++] = 0xdc;
data[l++] = 0x38 | op->operands[0].regs[0];
} else {
return -1;
}
} else {
return -1;
}
break;
case 2:
if ( op->operands[0].type & OT_FPUREG & ~OT_REGALL && op->operands[0].reg == 0 &&
op->operands[1].type & OT_FPUREG & ~OT_REGALL ) {
data[l++] = 0xd8;
data[l++] = 0xf8 | op->operands[1].reg;
} else if ( op->operands[0].type & OT_FPUREG & ~OT_REGALL &&
op->operands[1].type & OT_FPUREG & ~OT_REGALL && op->operands[1].reg == 0 ) {
data[l++] = 0xdc;
data[l++] = 0xf0 | op->operands[0].reg;
} else {
return -1;
}
break;
default:
return -1;
}
return l;
}
static int opfdivrp(RAsm *a, ut8 *data, const Opcode *op) {
int l = 0;
switch (op->operands_count) {
case 0:
data[l++] = 0xde;
data[l++] = 0xf1;
break;
case 2:
if ( op->operands[0].type & OT_FPUREG & ~OT_REGALL &&
op->operands[1].type & OT_FPUREG & ~OT_REGALL && op->operands[1].reg == 0 ) {
data[l++] = 0xde;
data[l++] = 0xf0 | op->operands[0].reg;
} else {
return -1;
}
break;
default:
return -1;
}
return l;
}
static int opfidivr(RAsm *a, ut8 *data, const Opcode *op) {
int l = 0;
switch (op->operands_count) {
case 1:
if ( op->operands[0].type & OT_MEMORY ) {
if ( op->operands[0].type & OT_DWORD ) {
data[l++] = 0xda;
data[l++] = 0x38 | op->operands[0].regs[0];
} else if ( op->operands[0].type & OT_WORD ) {
data[l++] = 0xde;
data[l++] = 0x38 | op->operands[0].regs[0];
} else {
return -1;
}
} else {
return -1;
}
break;
default:
return -1;
}
return l;
}
static int opfmul(RAsm *a, ut8 *data, const Opcode *op) {
int l = 0;
switch (op->operands_count) {
case 1:
if ( op->operands[0].type & OT_MEMORY ) {
if ( op->operands[0].type & OT_DWORD ) {
data[l++] = 0xd8;
data[l++] = 0x08 | op->operands[0].regs[0];
} else if ( op->operands[0].type & OT_QWORD ) {
data[l++] = 0xdc;
data[l++] = 0x08 | op->operands[0].regs[0];
} else {
return -1;
}
} else {
return -1;
}
break;
case 2:
if ( op->operands[0].type & OT_FPUREG & ~OT_REGALL && op->operands[0].reg == 0 &&
op->operands[1].type & OT_FPUREG & ~OT_REGALL ) {
data[l++] = 0xd8;
data[l++] = 0xc8 | op->operands[1].reg;
} else if ( op->operands[0].type & OT_FPUREG & ~OT_REGALL &&
op->operands[1].type & OT_FPUREG & ~OT_REGALL && op->operands[1].reg == 0 ) {
data[l++] = 0xdc;
data[l++] = 0xc8 | op->operands[0].reg;
} else {
return -1;
}
break;
default:
return -1;
}
return l;
}
static int opfmulp(RAsm *a, ut8 *data, const Opcode *op) {
int l = 0;
switch (op->operands_count) {
case 0:
data[l++] = 0xde;
data[l++] = 0xc9;
break;
case 2:
if ( op->operands[0].type & OT_FPUREG & ~OT_REGALL &&
op->operands[1].type & OT_FPUREG & ~OT_REGALL && op->operands[1].reg == 0 ) {
data[l++] = 0xde;
data[l++] = 0xc8 | op->operands[0].reg;
} else {
return -1;
}
break;
default:
return -1;
}
return l;
}
static int opfimul(RAsm *a, ut8 *data, const Opcode *op) {
int l = 0;
switch (op->operands_count) {
case 1:
if ( op->operands[0].type & OT_MEMORY ) {
if ( op->operands[0].type & OT_DWORD ) {
data[l++] = 0xda;
data[l++] = 0x08 | op->operands[0].regs[0];
} else if ( op->operands[0].type & OT_WORD ) {
data[l++] = 0xde;
data[l++] = 0x08 | op->operands[0].regs[0];
} else {
return -1;
}
} else {
return -1;
}
break;
default:
return -1;
}
return l;
}
static int opfsub(RAsm *a, ut8 *data, const Opcode *op) {
int l = 0;
switch (op->operands_count) {
case 1:
if ( op->operands[0].type & OT_MEMORY ) {
if ( op->operands[0].type & OT_DWORD ) {
data[l++] = 0xd8;
data[l++] = 0x20 | op->operands[0].regs[0];
} else if ( op->operands[0].type & OT_QWORD ) {
data[l++] = 0xdc;
data[l++] = 0x20 | op->operands[0].regs[0];
} else {
return -1;
}
} else {
return -1;
}
break;
case 2:
if ( op->operands[0].type & OT_FPUREG & ~OT_REGALL && op->operands[0].reg == 0 &&
op->operands[1].type & OT_FPUREG & ~OT_REGALL ) {
data[l++] = 0xd8;
data[l++] = 0xe0 | op->operands[1].reg;
} else if ( op->operands[0].type & OT_FPUREG & ~OT_REGALL &&
op->operands[1].type & OT_FPUREG & ~OT_REGALL && op->operands[1].reg == 0 ) {
data[l++] = 0xdc;
data[l++] = 0xe8 | op->operands[0].reg;
} else {
return -1;
}
break;
default:
return -1;
}
return l;
}
static int opfsubp(RAsm *a, ut8 *data, const Opcode *op) {
int l = 0;
switch (op->operands_count) {
case 0:
data[l++] = 0xde;
data[l++] = 0xe9;
break;
case 2:
if ( op->operands[0].type & OT_FPUREG & ~OT_REGALL &&
op->operands[1].type & OT_FPUREG & ~OT_REGALL && op->operands[1].reg == 0 ) {
data[l++] = 0xde;
data[l++] = 0xe8 | op->operands[0].reg;
} else {
return -1;
}
break;
default:
return -1;
}
return l;
}
static int opfisub(RAsm *a, ut8 *data, const Opcode *op) {
int l = 0;
switch (op->operands_count) {
case 1:
if ( op->operands[0].type & OT_MEMORY ) {
if ( op->operands[0].type & OT_DWORD ) {
data[l++] = 0xda;
data[l++] = 0x20 | op->operands[0].regs[0];
} else if ( op->operands[0].type & OT_WORD ) {
data[l++] = 0xde;
data[l++] = 0x20 | op->operands[0].regs[0];
} else {
return -1;
}
} else {
return -1;
}
break;
default:
return -1;
}
return l;
}
static int opfsubr(RAsm *a, ut8 *data, const Opcode *op) {
int l = 0;
switch (op->operands_count) {
case 1:
if ( op->operands[0].type & OT_MEMORY ) {
if ( op->operands[0].type & OT_DWORD ) {
data[l++] = 0xd8;
data[l++] = 0x28 | op->operands[0].regs[0];
} else if ( op->operands[0].type & OT_QWORD ) {
data[l++] = 0xdc;
data[l++] = 0x28 | op->operands[0].regs[0];
} else {
return -1;
}
} else {
return -1;
}
break;
case 2:
if ( op->operands[0].type & OT_FPUREG & ~OT_REGALL && op->operands[0].reg == 0 &&
op->operands[1].type & OT_FPUREG & ~OT_REGALL ) {
data[l++] = 0xd8;
data[l++] = 0xe8 | op->operands[1].reg;
} else if ( op->operands[0].type & OT_FPUREG & ~OT_REGALL &&
op->operands[1].type & OT_FPUREG & ~OT_REGALL && op->operands[1].reg == 0 ) {
data[l++] = 0xdc;
data[l++] = 0xe0 | op->operands[0].reg;
} else {
return -1;
}
break;
default:
return -1;
}
return l;
}
static int opfsubrp(RAsm *a, ut8 *data, const Opcode *op) {
int l = 0;
switch (op->operands_count) {
case 0:
data[l++] = 0xde;
data[l++] = 0xe1;
break;
case 2:
if ( op->operands[0].type & OT_FPUREG & ~OT_REGALL &&
op->operands[1].type & OT_FPUREG & ~OT_REGALL && op->operands[1].reg == 0 ) {
data[l++] = 0xde;
data[l++] = 0xe0 | op->operands[0].reg;
} else {
return -1;
}
break;
default:
return -1;
}
return l;
}
static int opfisubr(RAsm *a, ut8 *data, const Opcode *op) {
int l = 0;
switch (op->operands_count) {
case 1:
if ( op->operands[0].type & OT_MEMORY ) {
if ( op->operands[0].type & OT_DWORD ) {
data[l++] = 0xda;
data[l++] = 0x28 | op->operands[0].regs[0];
} else if ( op->operands[0].type & OT_WORD ) {
data[l++] = 0xde;
data[l++] = 0x28 | op->operands[0].regs[0];
} else {
return -1;
}
} else {
return -1;
}
break;
default:
return -1;
}
return l;
}
static int opfnstcw(RAsm *a, ut8 *data, const Opcode *op) {
int l = 0;
switch (op->operands_count) {
case 1:
if ( op->operands[0].type & OT_MEMORY &&
op->operands[0].type & OT_WORD ) {
data[l++] = 0xd9;
data[l++] = 0x38 | op->operands[0].regs[0];
} else {
return -1;
}
break;
default:
return -1;
}
return l;
}
static int opfstcw(RAsm *a, ut8 *data, const Opcode *op) {
int l = 0;
switch (op->operands_count) {
case 1:
if ( op->operands[0].type & OT_MEMORY &&
op->operands[0].type & OT_WORD ) {
data[l++] = 0x9b;
data[l++] = 0xd9;
data[l++] = 0x38 | op->operands[0].regs[0];
} else {
return -1;
}
break;
default:
return -1;
}
return l;
}
static int opfnstsw(RAsm *a, ut8 *data, const Opcode *op) {
int l = 0;
switch (op->operands_count) {
case 1:
if ( op->operands[0].type & OT_MEMORY &&
op->operands[0].type & OT_WORD ) {
data[l++] = 0xdd;
data[l++] = 0x38 | op->operands[0].regs[0];
} else if ( op->operands[0].type & OT_GPREG &&
op->operands[0].type & OT_WORD &&
op->operands[0].reg == X86R_AX ) {
data[l++] = 0xdf;
data[l++] = 0xe0;
} else {
return -1;
}
break;
default:
return -1;
}
return l;
}
static int opfstsw(RAsm *a, ut8 *data, const Opcode *op) {
int l = 0;
switch (op->operands_count) {
case 1:
if ( op->operands[0].type & OT_MEMORY &&
op->operands[0].type & OT_WORD ) {
data[l++] = 0x9b;
data[l++] = 0xdd;
data[l++] = 0x38 | op->operands[0].regs[0];
} else if ( op->operands[0].type & OT_GPREG &&
op->operands[0].type & OT_WORD &&
op->operands[0].reg == X86R_AX ) {
data[l++] = 0x9b;
data[l++] = 0xdf;
data[l++] = 0xe0;
} else {
return -1;
}
break;
default:
return -1;
}
return l;
}
static int opfnsave(RAsm *a, ut8 *data, const Opcode *op) {
int l = 0;
switch (op->operands_count) {
case 1:
if ( op->operands[0].type & OT_MEMORY &&
op->operands[0].type & OT_DWORD ) {
data[l++] = 0xdd;
data[l++] = 0x30 | op->operands[0].regs[0];
} else {
return -1;
}
break;
default:
return -1;
}
return l;
}
static int opfsave(RAsm *a, ut8 *data, const Opcode *op) {
int l = 0;
switch (op->operands_count) {
case 1:
if ( op->operands[0].type & OT_MEMORY &&
op->operands[0].type & OT_DWORD ) {
data[l++] = 0x9b;
data[l++] = 0xdd;
data[l++] = 0x30 | op->operands[0].regs[0];
} else {
return -1;
}
break;
default:
return -1;
}
return l;
}
static int oplldt(RAsm *a, ut8 *data, const Opcode *op) {
int l = 0;
switch (op->operands_count) {
case 1:
if ( op->operands[0].type & OT_WORD ) {
data[l++] = 0x0f;
data[l++] = 0x00;
if ( op->operands[0].type & OT_MEMORY ) {
data[l++] = 0x10 | op->operands[0].regs[0];
} else {
data[l++] = 0xd0 | op->operands[0].reg;
}
} else {
return -1;
}
break;
default:
return -1;
}
return l;
}
static int oplmsw(RAsm *a, ut8 *data, const Opcode *op) {
int l = 0;
switch (op->operands_count) {
case 1:
if ( op->operands[0].type & OT_WORD ) {
data[l++] = 0x0f;
data[l++] = 0x01;
if ( op->operands[0].type & OT_MEMORY ) {
data[l++] = 0x30 | op->operands[0].regs[0];
} else {
data[l++] = 0xf0 | op->operands[0].reg;
}
} else {
return -1;
}
break;
default:
return -1;
}
return l;
}
static int oplgdt(RAsm *a, ut8 *data, const Opcode *op) {
int l = 0;
switch (op->operands_count) {
case 1:
if ( op->operands[0].type & OT_MEMORY ) {
data[l++] = 0x0f;
data[l++] = 0x01;
data[l++] = 0x10 | op->operands[0].regs[0];
} else {
return -1;
}
break;
default:
return -1;
}
return l;
}
static int oplidt(RAsm *a, ut8 *data, const Opcode *op) {
int l = 0;
switch (op->operands_count) {
case 1:
if ( op->operands[0].type & OT_MEMORY ) {
data[l++] = 0x0f;
data[l++] = 0x01;
data[l++] = 0x18 | op->operands[0].regs[0];
} else {
return -1;
}
break;
default:
return -1;
}
return l;
}
static int opsgdt(RAsm *a, ut8 *data, const Opcode *op) {
int l = 0;
switch (op->operands_count) {
case 1:
if ( op->operands[0].type & OT_MEMORY ) {
data[l++] = 0x0f;
data[l++] = 0x01;
data[l++] = 0x00 | op->operands[0].regs[0];
} else {
return -1;
}
break;
default:
return -1;
}
return l;
}
static int opstmxcsr(RAsm *a, ut8 *data, const Opcode *op) {
int l = 0;
switch (op->operands_count) {
case 1:
if ( op->operands[0].type & OT_MEMORY &&
op->operands[0].type & OT_DWORD ) {
data[l++] = 0x0f;
data[l++] = 0xae;
data[l++] = 0x18 | op->operands[0].regs[0];
} else {
return -1;
}
break;
default:
return -1;
}
return l;
}
static int opstr(RAsm *a, ut8 *data, const Opcode *op) {
int l = 0;
switch (op->operands_count) {
case 1:
if ( op->operands[0].type & OT_MEMORY &&
op->operands[0].type & OT_WORD ) {
data[l++] = 0x0f;
data[l++] = 0x00;
data[l++] = 0x08 | op->operands[0].regs[0];
} else if ( op->operands[0].type & OT_GPREG &&
op->operands[0].type & OT_DWORD ) {
data[l++] = 0x0f;
data[l++] = 0x00;
data[l++] = 0xc8 | op->operands[0].reg;
} else {
return -1;
}
break;
default:
return -1;
}
return l;
}
static int opsidt(RAsm *a, ut8 *data, const Opcode *op) {
int l = 0;
switch (op->operands_count) {
case 1:
if ( op->operands[0].type & OT_MEMORY ) {
data[l++] = 0x0f;
data[l++] = 0x01;
data[l++] = 0x08 | op->operands[0].regs[0];
} else {
return -1;
}
break;
default:
return -1;
}
return l;
}
static int opsldt(RAsm *a, ut8 *data, const Opcode *op) {
int l = 0;
switch (op->operands_count) {
case 1:
if ( a->bits == 64 ) {
data[l++] = 0x48;
}
data[l++] = 0x0f;
data[l++] = 0x00;
if ( op->operands[0].type & OT_MEMORY ) {
data[l++] = 0x00 | op->operands[0].regs[0];
} else {
data[l++] = 0xc0 | op->operands[0].reg;
}
break;
default:
return -1;
}
return l;
}
static int opsmsw(RAsm *a, ut8 *data, const Opcode *op) {
int l = 0;
switch (op->operands_count) {
case 1:
if ( a->bits == 64 ) {
data[l++] = 0x48;
}
data[l++] = 0x0f;
data[l++] = 0x01;
if ( op->operands[0].type & OT_MEMORY ) {
data[l++] = 0x20 | op->operands[0].regs[0];
} else {
data[l++] = 0xe0 | op->operands[0].reg;
}
break;
default:
return -1;
}
return l;
}
static int opverr(RAsm *a, ut8 *data, const Opcode *op) {
int l = 0;
switch (op->operands_count) {
case 1:
if ( op->operands[0].type & OT_WORD ) {
data[l++] = 0x0f;
data[l++] = 0x00;
if ( op->operands[0].type & OT_MEMORY ) {
data[l++] = 0x20 | op->operands[0].regs[0];
} else {
data[l++] = 0xe0 | op->operands[0].reg;
}
} else {
return -1;
}
break;
default:
return -1;
}
return l;
}
static int opverw(RAsm *a, ut8 *data, const Opcode *op) {
int l = 0;
switch (op->operands_count) {
case 1:
if ( op->operands[0].type & OT_WORD ) {
data[l++] = 0x0f;
data[l++] = 0x00;
if ( op->operands[0].type & OT_MEMORY ) {
data[l++] = 0x28 | op->operands[0].regs[0];
} else {
data[l++] = 0xe8 | op->operands[0].reg;
}
} else {
return -1;
}
break;
default:
return -1;
}
return l;
}
static int opvmclear(RAsm *a, ut8 *data, const Opcode *op) {
int l = 0;
switch (op->operands_count) {
case 1:
if ( op->operands[0].type & OT_MEMORY &&
op->operands[0].type & OT_QWORD
) {
data[l++] = 0x66;
data[l++] = 0x0f;
data[l++] = 0xc7;
data[l++] = 0x30 | op->operands[0].regs[0];
} else {
return -1;
}
break;
default:
return -1;
}
return l;
}
static int opvmon(RAsm *a, ut8 *data, const Opcode *op) {
int l = 0;
switch (op->operands_count) {
case 1:
if ( op->operands[0].type & OT_MEMORY &&
op->operands[0].type & OT_QWORD
) {
data[l++] = 0xf3;
data[l++] = 0x0f;
data[l++] = 0xc7;
data[l++] = 0x30 | op->operands[0].regs[0];
} else {
return -1;
}
break;
default:
return -1;
}
return l;
}
static int opvmptrld(RAsm *a, ut8 *data, const Opcode *op) {
int l = 0;
switch (op->operands_count) {
case 1:
if ( op->operands[0].type & OT_MEMORY &&
op->operands[0].type & OT_QWORD
) {
data[l++] = 0x0f;
data[l++] = 0xc7;
data[l++] = 0x30 | op->operands[0].regs[0];
} else {
return -1;
}
break;
default:
return -1;
}
return l;
}
static int opvmptrst(RAsm *a, ut8 *data, const Opcode *op) {
int l = 0;
switch (op->operands_count) {
case 1:
if ( op->operands[0].type & OT_MEMORY &&
op->operands[0].type & OT_QWORD
) {
data[l++] = 0x0f;
data[l++] = 0xc7;
data[l++] = 0x38 | op->operands[0].regs[0];
} else {
return -1;
}
break;
default:
return -1;
}
return l;
}
typedef struct lookup_t {
char mnemonic[12];
int only_x32;
int (*opdo)(RAsm*, ut8*, const Opcode*);
ut64 opcode;
int size;
} LookupTable;
LookupTable oplookup[] = {
{"aaa", 0, NULL, 0x37, 1},
{"aad", 0, NULL, 0xd50a, 2},
{"aam", 0, opaam, 0},
{"aas", 0, NULL, 0x3f, 1},
{"adc", 0, &opadc, 0},
{"add", 0, &opadd, 0},
{"adx", 0, NULL, 0xd4, 1},
{"amx", 0, NULL, 0xd5, 1},
{"and", 0, &opand, 0},
{"bswap", 0, &opbswap, 0},
{"call", 0, &opcall, 0},
{"cbw", 0, NULL, 0x6698, 2},
{"cdq", 0, NULL, 0x99, 1},
{"cdqe", 0, &opcdqe, 0},
{"cwde", 0, &opcdqe, 0},
{"clc", 0, NULL, 0xf8, 1},
{"cld", 0, NULL, 0xfc, 1},
{"clflush", 0, &opclflush, 0},
{"clgi", 0, NULL, 0x0f01dd, 3},
{"cli", 0, NULL, 0xfa, 1},
{"clts", 0, NULL, 0x0f06, 2},
{"cmc", 0, NULL, 0xf5, 1},
{"cmovo", 0, &opcmov, 0},
{"cmovno", 0, &opcmov, 0},
{"cmovb", 0, &opcmov, 0},
{"cmovc", 0, &opcmov, 0},
{"cmovnae", 0, &opcmov, 0},
{"cmovae", 0, &opcmov, 0},
{"cmovnb", 0, &opcmov, 0},
{"cmovnc", 0, &opcmov, 0},
{"cmove", 0, &opcmov, 0},
{"cmovz", 0, &opcmov, 0},
{"cmovne", 0, &opcmov, 0},
{"cmovnz", 0, &opcmov, 0},
{"cmovbe", 0, &opcmov, 0},
{"cmovna", 0, &opcmov, 0},
{"cmova", 0, &opcmov, 0},
{"cmovnbe", 0, &opcmov, 0},
{"cmovne", 0, &opcmov, 0},
{"cmovnz", 0, &opcmov, 0},
{"cmovs", 0, &opcmov, 0},
{"cmovns", 0, &opcmov, 0},
{"cmovp", 0, &opcmov, 0},
{"cmovpe", 0, &opcmov, 0},
{"cmovnp", 0, &opcmov, 0},
{"cmovpo", 0, &opcmov, 0},
{"cmovl", 0, &opcmov, 0},
{"cmovnge", 0, &opcmov, 0},
{"cmovge", 0, &opcmov, 0},
{"cmovnl", 0, &opcmov, 0},
{"cmovle", 0, &opcmov, 0},
{"cmovng", 0, &opcmov, 0},
{"cmovg", 0, &opcmov, 0},
{"cmovnle", 0, &opcmov, 0},
{"cmp", 0, &opcmp, 0},
{"cmpsb", 0, NULL, 0xa6, 1},
{"cmpsd", 0, NULL, 0xa7, 1},
{"cmpsw", 0, NULL, 0x66a7, 2},
{"cpuid", 0, NULL, 0x0fa2, 2},
{"cwd", 0, NULL, 0x6699, 2},
{"cwde", 0, NULL, 0x98, 1},
{"daa", 0, NULL, 0x27, 1},
{"das", 0, NULL, 0x2f, 1},
{"dec", 0, &opdec, 0},
{"div", 0, &opdiv, 0},
{"emms", 0, NULL, 0x0f77, 2},
{"f2xm1", 0, NULL, 0xd9f0, 2},
{"fabs", 0, NULL, 0xd9e1, 2},
{"fadd", 0, &opfadd, 0},
{"faddp", 0, &opfaddp, 0},
{"fbld", 0, &opfbld, 0},
{"fbstp", 0, &opfbstp, 0},
{"fchs", 0, NULL, 0xd9e0, 2},
{"fclex", 0, NULL, 0x9bdbe2, 3},
{"fcmovb", 0, &opfcmov, 0},
{"fcmove", 0, &opfcmov, 0},
{"fcmovbe", 0, &opfcmov, 0},
{"fcmovu", 0, &opfcmov, 0},
{"fcmovnb", 0, &opfcmov, 0},
{"fcmovne", 0, &opfcmov, 0},
{"fcmovnbe", 0, &opfcmov, 0},
{"fcmovnu", 0, &opfcmov, 0},
{"fcos", 0, NULL, 0xd9ff, 2},
{"fdecstp", 0, NULL, 0xd9f6, 2},
{"fdiv", 0, &opfdiv, 0},
{"fdivp", 0, &opfdivp, 0},
{"fdivr", 0, &opfdivr, 0},
{"fdivrp", 0, &opfdivrp, 0},
{"femms", 0, NULL, 0x0f0e, 2},
{"ffree", 0, &opffree, 0},
{"fiadd", 0, &opfiadd, 0},
{"ficom", 0, &opficom, 0},
{"ficomp", 0, &opficomp, 0},
{"fidiv", 0, &opfidiv, 0},
{"fidivr", 0, &opfidivr, 0},
{"fild", 0, &opfild, 0},
{"fimul", 0, &opfimul, 0},
{"fincstp", 0, NULL, 0xd9f7, 2},
{"finit", 0, NULL, 0x9bdbe3, 3},
{"fist", 0, &opfist, 0},
{"fistp", 0, &opfistp, 0},
{"fisttp", 0, &opfisttp, 0},
{"fisub", 0, &opfisub, 0},
{"fisubr", 0, &opfisubr, 0},
{"fld1", 0, NULL, 0xd9e8, 2},
{"fldcw", 0, &opfldcw, 0},
{"fldenv", 0, &opfldenv, 0},
{"fldl2t", 0, NULL, 0xd9e9, 2},
{"fldl2e", 0, NULL, 0xd9ea, 2},
{"fldlg2", 0, NULL, 0xd9ec, 2},
{"fldln2", 0, NULL, 0xd9ed, 2},
{"fldpi", 0, NULL, 0xd9eb, 2},
{"fldz", 0, NULL, 0xd9ee, 2},
{"fmul", 0, &opfmul, 0},
{"fmulp", 0, &opfmulp, 0},
{"fnclex", 0, NULL, 0xdbe2, 2},
{"fninit", 0, NULL, 0xdbe3, 2},
{"fnop", 0, NULL, 0xd9d0, 2},
{"fnsave", 0, &opfnsave, 0},
{"fnstcw", 0, &opfnstcw, 0},
{"fnstenv", 0, &opfnstenv, 0},
{"fnstsw", 0, &opfnstsw, 0},
{"fpatan", 0, NULL, 0xd9f3, 2},
{"fprem", 0, NULL, 0xd9f8, 2},
{"fprem1", 0, NULL, 0xd9f5, 2},
{"fptan", 0, NULL, 0xd9f2, 2},
{"frndint", 0, NULL, 0xd9fc, 2},
{"frstor", 0, &opfrstor, 0},
{"fsave", 0, &opfsave, 0},
{"fscale", 0, NULL, 0xd9fd, 2},
{"fsin", 0, NULL, 0xd9fe, 2},
{"fsincos", 0, NULL, 0xd9fb, 2},
{"fsqrt", 0, NULL, 0xd9fa, 2},
{"fstcw", 0, &opfstcw, 0},
{"fstenv", 0, &opfstenv, 0},
{"fstsw", 0, &opfstsw, 0},
{"fsub", 0, &opfsub, 0},
{"fsubp", 0, &opfsubp, 0},
{"fsubr", 0, &opfsubr, 0},
{"fsubrp", 0, &opfsubrp, 0},
{"ftst", 0, NULL, 0xd9e4, 2},
{"fucom", 0, &opfucom, 0},
{"fucomp", 0, &opfucomp, 0},
{"fucompp", 0, NULL, 0xdae9, 2},
{"fwait", 0, NULL, 0x9b, 1},
{"fxam", 0, NULL, 0xd9e5, 2},
{"fxch", 0, &opfxch, 0},
{"fxrstor", 0, &opfxrstor, 0},
{"fxsave", 0, &opfxsave, 0},
{"fxtract", 0, NULL, 0xd9f4, 2},
{"fyl2x", 0, NULL, 0xd9f1, 2},
{"fyl2xp1", 0, NULL, 0xd9f9, 2},
{"getsec", 0, NULL, 0x0f37, 2},
{"hlt", 0, NULL, 0xf4, 1},
{"idiv", 0, &opidiv, 0},
{"imul", 0, &opimul, 0},
{"in", 0, &opin, 0},
{"inc", 0, &opinc, 0},
{"ins", 0, NULL, 0x6d, 1},
{"insb", 0, NULL, 0x6c, 1},
{"insd", 0, NULL, 0x6d, 1},
{"insw", 0, NULL, 0x666d, 2},
{"int", 0, &opint, 0},
{"int1", 0, NULL, 0xf1, 1},
{"int3", 0, NULL, 0xcc, 1},
{"into", 0, NULL, 0xce, 1},
{"invd", 0, NULL, 0x0f08, 2},
{"iret", 0, NULL, 0x66cf, 2},
{"iretd", 0, NULL, 0xcf, 1},
{"ja", 0, &opjc, 0},
{"jae", 0, &opjc, 0},
{"jb", 0, &opjc, 0},
{"jbe", 0, &opjc, 0},
{"jc", 0, &opjc, 0},
{"je", 0, &opjc, 0},
{"jg", 0, &opjc, 0},
{"jge", 0, &opjc, 0},
{"jl", 0, &opjc, 0},
{"jle", 0, &opjc, 0},
{"jmp", 0, &opjc, 0},
{"jna", 0, &opjc, 0},
{"jnae", 0, &opjc, 0},
{"jnb", 0, &opjc, 0},
{"jnbe", 0, &opjc, 0},
{"jnc", 0, &opjc, 0},
{"jne", 0, &opjc, 0},
{"jng", 0, &opjc, 0},
{"jnge", 0, &opjc, 0},
{"jnl", 0, &opjc, 0},
{"jnle", 0, &opjc, 0},
{"jno", 0, &opjc, 0},
{"jnp", 0, &opjc, 0},
{"jns", 0, &opjc, 0},
{"jnz", 0, &opjc, 0},
{"jo", 0, &opjc, 0},
{"jp", 0, &opjc, 0},
{"jpe", 0, &opjc, 0},
{"jpo", 0, &opjc, 0},
{"js", 0, &opjc, 0},
{"jz", 0, &opjc, 0},
{"lahf", 0, NULL, 0x9f},
{"lea", 0, &oplea, 0},
{"leave", 0, NULL, 0xc9, 1},
{"les", 0, &oples, 0},
{"lfence", 0, NULL, 0x0faee8, 3},
{"lgdt", 0, &oplgdt, 0},
{"lidt", 0, &oplidt, 0},
{"lldt", 0, &oplldt, 0},
{"lmsw", 0, &oplmsw, 0},
{"lodsb", 0, NULL, 0xac, 1},
{"lodsd", 0, NULL, 0xad, 1},
{"lodsw", 0, NULL, 0x66ad, 2},
{"loop", 0, &oploop, 0},
{"mfence", 0, NULL, 0x0faef0, 3},
{"monitor", 0, NULL, 0x0f01c8, 3},
{"mov", 0, &opmov, 0},
{"movsb", 0, NULL, 0xa4, 1},
{"movsd", 0, NULL, 0xa5, 1},
{"movsw", 0, NULL, 0x66a5, 2},
{"movzx", 0, &opmovx, 0},
{"movsx", 0, &opmovx, 0},
{"mul", 0, &opmul, 0},
{"mwait", 0, NULL, 0x0f01c9, 3},
{"nop", 0, NULL, 0x90, 1},
{"not", 0, &opnot, 0},
{"or", 0, &opor, 0},
{"out", 0, &opout, 0},
{"outsb", 0, NULL, 0x6e, 1},
{"outs", 0, NULL, 0x6f, 1},
{"outsd", 0, NULL, 0x6f, 1},
{"outsw", 0, NULL, 0x666f, 2},
{"pop", 0, &oppop, 0},
{"popa", 1, NULL, 0x61, 1},
{"popad", 1, NULL, 0x61, 1},
{"popal", 1, NULL, 0x61, 1},
{"popaw", 1, NULL, 0x6661, 2},
{"popfd", 1, NULL, 0x9d, 1},
{"prefetch", 0, NULL, 0x0f0d, 2},
{"push", 0, &oppush, 0},
{"pusha", 1, NULL, 0x60, 1},
{"pushad", 1, NULL, 0x60, 1},
{"pushal", 1, NULL, 0x60, 1},
{"pushfd", 0, NULL, 0x9c, 1},
{"rcl", 0, &process_group_2, 0},
{"rcr", 0, &process_group_2, 0},
{"rep", 0, &oprep, 0},
{"repe", 0, &oprep, 0},
{"repne", 0, &oprep, 0},
{"repz", 0, &oprep, 0},
{"repnz", 0, &oprep, 0},
{"rdmsr", 0, NULL, 0x0f32, 2},
{"rdpmc", 0, NULL, 0x0f33, 2},
{"rdtsc", 0, NULL, 0x0f31, 2},
{"rdtscp", 0, NULL, 0x0f01f9, 3},
{"ret", 0, &opret, 0},
{"retf", 0, &opretf, 0},
{"retw", 0, NULL, 0x66c3, 2},
{"rol", 0, &process_group_2, 0},
{"ror", 0, &process_group_2, 0},
{"rsm", 0, NULL, 0x0faa, 2},
{"sahf", 0, NULL, 0x9e, 1},
{"sal", 0, &process_group_2, 0},
{"salc", 0, NULL, 0xd6, 1},
{"sar", 0, &process_group_2, 0},
{"sbb", 0, &opsbb, 0},
{"scasb", 0, NULL, 0xae, 1},
{"scasd", 0, NULL, 0xaf, 1},
{"scasw", 0, NULL, 0x66af, 2},
{"seto", 0, &opset, 0},
{"setno", 0, &opset, 0},
{"setb", 0, &opset, 0},
{"setnae", 0, &opset, 0},
{"setc", 0, &opset, 0},
{"setnb", 0, &opset, 0},
{"setae", 0, &opset, 0},
{"setnc", 0, &opset, 0},
{"setz", 0, &opset, 0},
{"sete", 0, &opset, 0},
{"setnz", 0, &opset, 0},
{"setne", 0, &opset, 0},
{"setbe", 0, &opset, 0},
{"setna", 0, &opset, 0},
{"setnbe", 0, &opset, 0},
{"seta", 0, &opset, 0},
{"sets", 0, &opset, 0},
{"setns", 0, &opset, 0},
{"setp", 0, &opset, 0},
{"setpe", 0, &opset, 0},
{"setnp", 0, &opset, 0},
{"setpo", 0, &opset, 0},
{"setl", 0, &opset, 0},
{"setnge", 0, &opset, 0},
{"setnl", 0, &opset, 0},
{"setge", 0, &opset, 0},
{"setle", 0, &opset, 0},
{"setng", 0, &opset, 0},
{"setnle", 0, &opset, 0},
{"setg", 0, &opset, 0},
{"sfence", 0, NULL, 0x0faef8, 3},
{"sgdt", 0, &opsgdt, 0},
{"shl", 0, &process_group_2, 0},
{"shr", 0, &process_group_2, 0},
{"sidt", 0, &opsidt, 0},
{"sldt", 0, &opsldt, 0},
{"smsw", 0, &opsmsw, 0},
{"stc", 0, NULL, 0xf9, 1},
{"std", 0, NULL, 0xfd, 1},
{"stgi", 0, NULL, 0x0f01dc, 3},
{"sti", 0, NULL, 0xfb, 1},
{"stmxcsr", 0, &opstmxcsr, 0},
{"stosb", 0, &opstos, 0},
{"stosd", 0, &opstos, 0},
{"stosw", 0, &opstos, 0},
{"str", 0, &opstr, 0},
{"sub", 0, &opsub, 0},
{"swapgs", 0, NULL, 0x0f1ff8, 3},
{"syscall", 0, NULL, 0x0f05, 2},
{"sysenter", 0, NULL, 0x0f34, 2},
{"sysexit", 0, NULL, 0x0f35, 2},
{"sysret", 0, NULL, 0x0f07, 2},
{"ud2", 0, NULL, 0x0f0b, 2},
{"verr", 0, &opverr, 0},
{"verw", 0, &opverw, 0},
{"vmcall", 0, NULL, 0x0f01c1, 3},
{"vmclear", 0, &opvmclear, 0},
{"vmlaunch", 0, NULL, 0x0f01c2, 3},
{"vmload", 0, NULL, 0x0f01da, 3},
{"vmmcall", 0, NULL, 0x0f01d9, 3},
{"vmptrld", 0, &opvmptrld, 0},
{"vmptrst", 0, &opvmptrst, 0},
{"vmresume", 0, NULL, 0x0f01c3, 3},
{"vmrun", 0, NULL, 0x0f01d8, 3},
{"vmsave", 0, NULL, 0x0f01db, 3},
{"vmxoff", 0, NULL, 0x0f01c4, 3},
{"vmxon", 0, &opvmon, 0},
{"vzeroall", 0, NULL, 0xc5fc77, 3},
{"vzeroupper", 0, NULL, 0xc5f877, 3},
{"wait", 0, NULL, 0x9b, 1},
{"wbinvd", 0, NULL, 0x0f09, 2},
{"wrmsr", 0, NULL, 0x0f30, 2},
{"xadd", 0, &opxadd, 0},
{"xchg", 0, &opxchg, 0},
{"xgetbv", 0, NULL, 0x0f01d0, 3},
{"xlatb", 0, NULL, 0xd7, 1},
{"xor", 0, &opxor, 0},
{"xsetbv", 0, NULL, 0x0f01d1, 3},
{"test", 0, &optest, 0},
{"null", 0, NULL, 0, 0}
};
static x86newTokenType getToken(const char *str, size_t *begin, size_t *end) {
if (*begin > strlen (str)) {
return TT_EOF;
}
// Skip whitespace
while (begin && str[*begin] && isspace ((ut8)str[*begin])) {
++(*begin);
}
if (!str[*begin]) { // null byte
*end = *begin;
return TT_EOF;
}
if (isalpha ((ut8)str[*begin])) { // word token
*end = *begin;
while (end && str[*end] && isalnum ((ut8)str[*end])) {
++(*end);
}
return TT_WORD;
}
if (isdigit ((ut8)str[*begin])) { // number token
*end = *begin;
while (end && isalnum ((ut8)str[*end])) { // accept alphanumeric characters, because hex.
++(*end);
}
return TT_NUMBER;
} else { // special character: [, ], +, *, ...
*end = *begin + 1;
return TT_SPECIAL;
}
}
/**
* Get the register at position pos in str. Increase pos afterwards.
*/
static Register parseReg(RAsm *a, const char *str, size_t *pos, ut32 *type) {
int i;
// Must be the same order as in enum register_t
const char *regs[] = { "eax", "ecx", "edx", "ebx", "esp", "ebp", "esi", "edi", "eip", NULL };
const char *regsext[] = { "r8d", "r9d", "r10d", "r11d", "r12d", "r13d", "r14d", "r15d", NULL };
const char *regs8[] = { "al", "cl", "dl", "bl", "ah", "ch", "dh", "bh", NULL };
const char *regs16[] = { "ax", "cx", "dx", "bx", "sp", "bp", "si", "di", NULL };
const char *regs64[] = { "rax", "rcx", "rdx", "rbx", "rsp", "rbp", "rsi", "rdi", "rip", NULL};
const char *regs64ext[] = { "r8", "r9", "r10", "r11", "r12", "r13", "r14", "r15", NULL };
const char *sregs[] = { "es", "cs", "ss", "ds", "fs", "gs", NULL};
// Get token (especially the length)
size_t nextpos, length;
const char *token;
getToken (str, pos, &nextpos);
token = str + *pos;
length = nextpos - *pos;
*pos = nextpos;
// General purpose registers
if (length == 3 && token[0] == 'e') {
for (i = 0; regs[i]; i++) {
if (!r_str_ncasecmp (regs[i], token, length)) {
*type = (OT_GPREG & OT_REG (i)) | OT_DWORD;
return i;
}
}
}
if (length == 2 && (token[1] == 'l' || token[1] == 'h')) {
for (i = 0; regs8[i]; i++) {
if (!r_str_ncasecmp (regs8[i], token, length)) {
*type = (OT_GPREG & OT_REG (i)) | OT_BYTE;
return i;
}
}
}
if (length == 2) {
for (i = 0; regs16[i]; i++) {
if (!r_str_ncasecmp (regs16[i], token, length)) {
*type = (OT_GPREG & OT_REG (i)) | OT_WORD;
return i;
}
}
// This isn't working properly yet
for (i = 0; sregs[i]; i++) {
if (!r_str_ncasecmp (sregs[i], token, length)) {
*type = (OT_SEGMENTREG & OT_REG (i)) | OT_WORD;
return i;
}
}
}
if (token[0] == 'r') {
for (i = 0; regs64[i]; i++) {
if (!r_str_ncasecmp (regs64[i], token, length)) {
*type = (OT_GPREG & OT_REG (i)) | OT_QWORD;
a->bits = 64;
return i;
}
}
for (i = 0; regs64ext[i]; i++) {
if (!r_str_ncasecmp (regs64ext[i], token, length)) {
*type = (OT_GPREG & OT_REG (i)) | OT_QWORD;
a->bits = 64;
return i + 9;
}
}
for (i = 0; regsext[i]; i++) {
if (!r_str_ncasecmp (regsext[i], token, length)) {
*type = (OT_GPREG & OT_REG (i)) | OT_DWORD;
if (a->bits < 32) {
a->bits = 32;
}
return i + 9;
}
}
}
// Extended registers
if (!r_str_ncasecmp ("st", token, 2)) {
*type = (OT_FPUREG & ~OT_REGALL);
*pos = 3;
}
if (!r_str_ncasecmp ("mm", token, 2)) {
*type = (OT_MMXREG & ~OT_REGALL);
*pos = 3;
}
if (!r_str_ncasecmp ("xmm", token, 3)) {
*type = (OT_XMMREG & ~OT_REGALL);
*pos = 4;
}
// Now read number, possibly with parantheses
if (*type & (OT_FPUREG | OT_MMXREG | OT_XMMREG) & ~OT_REGALL) {
Register reg = X86R_UNDEFINED;
// pass by '(',if there is one
if (getToken (str, pos, &nextpos) == TT_SPECIAL && str[*pos] == '(') {
*pos = nextpos;
}
// read number
// const int maxreg = (a->bits == 64) ? 15 : 7;
if (getToken (str, pos, &nextpos) != TT_NUMBER ||
(reg = getnum (a, str + *pos)) > 7) {
if ((int)reg > 15) {
eprintf ("Too large register index!\n");
return X86R_UNDEFINED;
} else {
reg -= 8;
}
}
*pos = nextpos;
// pass by ')'
if (getToken (str, pos, &nextpos) == TT_SPECIAL && str[*pos] == ')') {
*pos = nextpos;
}
// Safety to prevent a shift bigger than 31. Reg
// should never be > 8 anyway
if (reg > 7) {
eprintf ("Too large register index!\n");
return X86R_UNDEFINED;
}
*type |= (OT_REG (reg) & ~OT_REGTYPE);
return reg;
}
return X86R_UNDEFINED;
}
static void parse_segment_offset(RAsm *a, const char *str, size_t *pos,
Operand *op, int reg_index) {
int nextpos = *pos;
char *c = strchr (str + nextpos, ':');
if (c) {
nextpos ++; // Skip the ':'
c = strchr (str + nextpos, '[');
if (c) {nextpos ++;} // Skip the '['
// Assign registers to match behaviour of OT_MEMORY type
op->regs[reg_index] = op->reg;
op->type |= OT_MEMORY;
op->offset_sign = 1;
char *p = strchr (str + nextpos, '-');
if (p) {
op->offset_sign = -1;
nextpos ++;
}
op->scale[reg_index] = getnum (a, str + nextpos);
op->offset = op->scale[reg_index];
}
}
// Parse operand
static int parseOperand(RAsm *a, const char *str, Operand *op, bool isrepop) {
size_t pos, nextpos = 0;
x86newTokenType last_type;
int size_token = 1;
bool explicit_size = false;
int reg_index = 0;
// Reset type
op->type = 0;
// Consume tokens denoting the operand size
while (size_token) {
pos = nextpos;
last_type = getToken (str, &pos, &nextpos);
// Token may indicate size: then skip
if (!r_str_ncasecmp (str + pos, "ptr", 3)) {
continue;
} else if (!r_str_ncasecmp (str + pos, "byte", 4)) {
op->type |= OT_MEMORY | OT_BYTE;
op->dest_size = OT_BYTE;
explicit_size = true;
} else if (!r_str_ncasecmp (str + pos, "word", 4)) {
op->type |= OT_MEMORY | OT_WORD;
op->dest_size = OT_WORD;
explicit_size = true;
} else if (!r_str_ncasecmp (str + pos, "dword", 5)) {
op->type |= OT_MEMORY | OT_DWORD;
op->dest_size = OT_DWORD;
explicit_size = true;
} else if (!r_str_ncasecmp (str + pos, "qword", 5)) {
op->type |= OT_MEMORY | OT_QWORD;
op->dest_size = OT_QWORD;
explicit_size = true;
} else if (!r_str_ncasecmp (str + pos, "oword", 5)) {
op->type |= OT_MEMORY | OT_OWORD;
op->dest_size = OT_OWORD;
explicit_size = true;
} else if (!r_str_ncasecmp (str + pos, "tbyte", 5)) {
op->type |= OT_MEMORY | OT_TBYTE;
op->dest_size = OT_TBYTE;
explicit_size = true;
} else { // the current token doesn't denote a size
size_token = 0;
}
}
// Next token: register, immediate, or '['
if (str[pos] == '[') {
// Don't care about size, if none is given.
if (!op->type) {
op->type = OT_MEMORY;
}
// At the moment, we only accept plain linear combinations:
// part := address | [factor *] register
// address := part {+ part}*
op->offset = op->scale[0] = op->scale[1] = 0;
ut64 temp = 1;
Register reg = X86R_UNDEFINED;
bool first_reg = true;
while (str[pos] != ']') {
if (pos > nextpos) {
// eprintf ("Error parsing instruction\n");
break;
}
pos = nextpos;
if (!str[pos]) {
break;
}
last_type = getToken (str, &pos, &nextpos);
if (last_type == TT_SPECIAL) {
if (str[pos] == '+' || str[pos] == '-' || str[pos] == ']') {
if (reg != X86R_UNDEFINED) {
op->regs[reg_index] = reg;
op->scale[reg_index] = temp;
++reg_index;
} else {
op->offset += temp;
op->regs[reg_index] = X86R_UNDEFINED;
}
temp = 1;
reg = X86R_UNDEFINED;
} else if (str[pos] == '*') {
// go to ], + or - to get scale
// Something to do here?
// Seems we are just ignoring '*' or assuming it implicitly.
}
}
else if (last_type == TT_WORD) {
ut32 reg_type = 0;
// We can't multiply registers
if (reg != X86R_UNDEFINED) {
op->type = 0; // Make the result invalid
}
// Reset nextpos: parseReg wants to parse from the beginning
nextpos = pos;
reg = parseReg (a, str, &nextpos, ®_type);
if (first_reg) {
op->extended = false;
if (reg > 8) {
op->extended = true;
op->reg = reg - 9;
}
first_reg = false;
} else if (reg > 8) {
op->reg = reg - 9;
}
if (reg_type & OT_REGTYPE & OT_SEGMENTREG) {
op->reg = reg;
op->type = reg_type;
parse_segment_offset (a, str, &nextpos, op, reg_index);
return nextpos;
}
// Still going to need to know the size if not specified
if (!explicit_size) {
op->type |= reg_type;
}
op->reg_size = reg_type;
op->explicit_size = explicit_size;
// Addressing only via general purpose registers
if (!(reg_type & OT_GPREG)) {
op->type = 0; // Make the result invalid
}
}
else {
char *p = strchr (str, '+');
op->offset_sign = 1;
if (!p) {
p = strchr (str, '-');
if (p) {
op->offset_sign = -1;
}
}
//with SIB notation, we need to consider the right sign
char * plus = strchr (str, '+');
char * minus = strchr (str, '-');
char * closeB = strchr (str, ']');
if (plus && minus && plus < closeB && minus < closeB) {
op->offset_sign = -1;
}
// If there's a scale, we don't want to parse out the
// scale with the offset (scale + offset) otherwise the scale
// will be the sum of the two. This splits the numbers
char *tmp;
tmp = malloc (strlen (str + pos) + 1);
strcpy (tmp, str + pos);
strtok (tmp, "+-");
st64 read = getnum (a, tmp);
free (tmp);
temp *= read;
}
}
} else if (last_type == TT_WORD) { // register
nextpos = pos;
RFlagItem *flag;
if (isrepop) {
op->is_good_flag = false;
strncpy (op->rep_op, str, MAX_REPOP_LENGTH - 1);
op->rep_op[MAX_REPOP_LENGTH - 1] = '\0';
return nextpos;
}
op->reg = parseReg (a, str, &nextpos, &op->type);
op->extended = false;
if (op->reg > 8) {
op->extended = true;
op->reg -= 9;
}
if (op->type & OT_REGTYPE & OT_SEGMENTREG) {
parse_segment_offset (a, str, &nextpos, op, reg_index);
return nextpos;
}
if (op->reg == X86R_UNDEFINED) {
op->is_good_flag = false;
if (a->num && a->num->value == 0) {
return nextpos;
}
op->type = OT_CONSTANT;
RCore *core = a->num? (RCore *)(a->num->userptr): NULL;
if (core && (flag = r_flag_get (core->flags, str))) {
op->is_good_flag = true;
}
char *p = strchr (str, '-');
if (p) {
op->sign = -1;
str = ++p;
}
op->immediate = getnum (a, str);
} else if (op->reg < X86R_UNDEFINED) {
strncpy (op->rep_op, str, MAX_REPOP_LENGTH - 1);
op->rep_op[MAX_REPOP_LENGTH - 1] = '\0';
}
} else { // immediate
// We don't know the size, so let's just set no size flag.
op->type = OT_CONSTANT;
op->sign = 1;
char *p = strchr (str, '-');
if (p) {
op->sign = -1;
str = ++p;
}
op->immediate = getnum (a, str);
}
return nextpos;
}
static int parseOpcode(RAsm *a, const char *op, Opcode *out) {
out->has_bnd = false;
bool isrepop = false;
if (!strncmp (op, "bnd ", 4)) {
out->has_bnd = true;
op += 4;
}
char *args = strchr (op, ' ');
out->mnemonic = args ? r_str_ndup (op, args - op) : strdup (op);
out->operands[0].type = out->operands[1].type = 0;
out->operands[0].extended = out->operands[1].extended = false;
out->operands[0].reg = out->operands[0].regs[0] = out->operands[0].regs[1] = X86R_UNDEFINED;
out->operands[1].reg = out->operands[1].regs[0] = out->operands[1].regs[1] = X86R_UNDEFINED;
out->operands[0].immediate = out->operands[1].immediate = 0;
out->operands[0].sign = out->operands[1].sign = 1;
out->operands[0].is_good_flag = out->operands[1].is_good_flag = true;
out->is_short = false;
out->operands_count = 0;
if (args) {
args++;
} else {
return 1;
}
if (!r_str_ncasecmp (args, "short", 5)) {
out->is_short = true;
args += 5;
}
if (!strncmp (out->mnemonic, "rep", 3)) {
isrepop = true;
}
parseOperand (a, args, &(out->operands[0]), isrepop);
out->operands_count = 1;
while (out->operands_count < MAX_OPERANDS) {
args = strchr (args, ',');
if (!args) {
break;
}
args++;
parseOperand (a, args, &(out->operands[out->operands_count]), isrepop);
out->operands_count++;
}
return 0;
}
static ut64 getnum(RAsm *a, const char *s) {
if (!s) {
return 0;
}
if (*s == '$') {
s++;
}
return r_num_math (a->num, s);
}
static int oprep(RAsm *a, ut8 *data, const Opcode *op) {
int l = 0;
LookupTable *lt_ptr;
int retval;
if (!strcmp (op->mnemonic, "rep") ||
!strcmp (op->mnemonic, "repe") ||
!strcmp (op->mnemonic, "repz")) {
data[l++] = 0xf3;
} else if (!strcmp (op->mnemonic, "repne") ||
!strcmp (op->mnemonic, "repnz")) {
data[l++] = 0xf2;
}
Opcode instr = {0};
parseOpcode (a, op->operands[0].rep_op, &instr);
for (lt_ptr = oplookup; strcmp (lt_ptr->mnemonic, "null"); lt_ptr++) {
if (!r_str_casecmp (instr.mnemonic, lt_ptr->mnemonic)) {
if (lt_ptr->opcode > 0) {
if (lt_ptr->only_x32 && a->bits == 64) {
return -1;
}
ut8 *ptr = (ut8 *)<_ptr->opcode;
int i = 0;
for (; i < lt_ptr->size; i++) {
data[i + l] = ptr[lt_ptr->size - (i + 1)];
}
free (instr.mnemonic);
return l + lt_ptr->size;
} else {
if (lt_ptr->opdo) {
data += l;
if (instr.has_bnd) {
data[l] = 0xf2;
data++;
}
retval = lt_ptr->opdo (a, data, &instr);
// if op supports bnd then the first byte will
// be 0xf2.
if (instr.has_bnd) {
retval++;
}
return l + retval;
}
break;
}
}
}
free (instr.mnemonic);
return -1;
}
static int assemble(RAsm *a, RAsmOp *ao, const char *str) {
ut8 __data[32] = {0};
ut8 *data = __data;
char op[128];
LookupTable *lt_ptr;
int retval = -1;
Opcode instr = {0};
strncpy (op, str, sizeof (op) - 1);
op[sizeof (op) - 1] = '\0';
parseOpcode (a, op, &instr);
for (lt_ptr = oplookup; strcmp (lt_ptr->mnemonic, "null"); lt_ptr++) {
if (!r_str_casecmp (instr.mnemonic, lt_ptr->mnemonic)) {
if (lt_ptr->opcode > 0) {
if (!lt_ptr->only_x32 || a->bits != 64) {
ut8 *ptr = (ut8 *)<_ptr->opcode;
int i = 0;
for (; i < lt_ptr->size; i++) {
data[i] = ptr[lt_ptr->size - (i + 1)];
}
retval = lt_ptr->size;
}
} else {
if (lt_ptr->opdo) {
if (instr.has_bnd) {
data[0] = 0xf2;
data ++;
}
retval = lt_ptr->opdo (a, data, &instr);
// if op supports bnd then the first byte will
// be 0xf2.
if (instr.has_bnd) {
retval++;
}
}
}
break;
}
}
r_asm_op_set_buf (ao, __data, retval);
free (instr.mnemonic);
return retval;
}
RAsmPlugin r_asm_plugin_x86_nz = {
.name = "x86.nz",
.desc = "x86 handmade assembler",
.license = "LGPL3",
.arch = "x86",
.bits = 16 | 32 | 64,
.endian = R_SYS_ENDIAN_LITTLE,
.assemble = &assemble
};
#ifndef CORELIB
R_API RLibStruct radare_plugin = {
.type = R_LIB_TYPE_ASM,
.data = &r_asm_plugin_x86_nz,
.version = R2_VERSION
};
#endif
| ./CrossVul/dataset_final_sorted/CWE-125/c/good_459_0 |
crossvul-cpp_data_bad_5302_0 | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% M M EEEEE TTTTT AAA %
% MM MM E T A A %
% M M M EEE T AAAAA %
% M M E T A A %
% M M EEEEE T A A %
% %
% %
% Read/Write Embedded Image Profiles. %
% %
% Software Design %
% William Radcliffe %
% July 2001 %
% %
% %
% 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/blob.h"
#include "MagickCore/blob-private.h"
#include "MagickCore/channel.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/module.h"
#include "MagickCore/profile.h"
#include "MagickCore/splay-tree.h"
#include "MagickCore/quantum-private.h"
#include "MagickCore/static.h"
#include "MagickCore/string_.h"
#include "MagickCore/string-private.h"
#include "MagickCore/token.h"
#include "MagickCore/utility.h"
/*
Forward declarations.
*/
static MagickBooleanType
WriteMETAImage(const ImageInfo *,Image *,ExceptionInfo *);
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% I s M E T A %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% IsMETA() returns MagickTrue if the image format type, identified by the
% magick string, is META.
%
% The format of the IsMETA method is:
%
% MagickBooleanType IsMETA(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.
%
%
*/
#ifdef IMPLEMENT_IS_FUNCTION
static MagickBooleanType IsMETA(const unsigned char *magick,const size_t length)
{
if (length < 4)
return(MagickFalse);
if (LocaleNCompare((char *) magick,"8BIM",4) == 0)
return(MagickTrue);
if (LocaleNCompare((char *) magick,"APP1",4) == 0)
return(MagickTrue);
if (LocaleNCompare((char *) magick,"\034\002",2) == 0)
return(MagickTrue);
return(MagickFalse);
}
#endif
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e a d M E T A I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ReadMETAImage() reads a META 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 ReadMETAImage method is:
%
% Image *ReadMETAImage(const ImageInfo *image_info,
% ExceptionInfo *exception)
%
% Decompression code contributed by Kyle Shorter.
%
% A description of each parameter follows:
%
% o image: Method ReadMETAImage 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 an ImageInfo structure.
%
% o exception: return any errors or warnings in this structure.
%
*/
typedef struct _html_code
{
const short
len;
const char
*code,
val;
} html_code;
static const html_code html_codes[] = {
#ifdef HANDLE_GT_LT
{ 4,"<",'<' },
{ 4,">",'>' },
#endif
{ 5,"&",'&' },
{ 6,""",'"' },
{ 6,"'",'\''}
};
static int stringnicmp(const char *p,const char *q,size_t n)
{
register ssize_t
i,
j;
if (p == q)
return(0);
if (p == (char *) NULL)
return(-1);
if (q == (char *) NULL)
return(1);
while ((*p != '\0') && (*q != '\0'))
{
if ((*p == '\0') || (*q == '\0'))
break;
i=(*p);
if (islower(i))
i=toupper(i);
j=(*q);
if (islower(j))
j=toupper(j);
if (i != j)
break;
n--;
if (n == 0)
break;
p++;
q++;
}
return(toupper((int) *p)-toupper((int) *q));
}
static int convertHTMLcodes(char *s, int len)
{
if (len <=0 || s==(char*) NULL || *s=='\0')
return 0;
if (s[1] == '#')
{
int val, o;
if (sscanf(s,"&#%d;",&val) == 1)
{
o = 3;
while (s[o] != ';')
{
o++;
if (o > 5)
break;
}
if (o < 6)
(void) memmove(s+1,s+1+o,strlen(s+1+o)+1);
*s = val;
return o;
}
}
else
{
int
i,
codes = (int) (sizeof(html_codes) / sizeof(html_code));
for (i=0; i < codes; i++)
{
if (html_codes[i].len <= len)
if (stringnicmp(s,html_codes[i].code,(size_t) html_codes[i].len) == 0)
{
(void) memmove(s+1,s+html_codes[i].len,
strlen(s+html_codes[i].len)+1);
*s=html_codes[i].val;
return html_codes[i].len-1;
}
}
}
return 0;
}
static char *super_fgets(char **b, int *blen, Image *file)
{
int
c,
len;
unsigned char
*p,
*q;
len=*blen;
p=(unsigned char *) (*b);
for (q=p; ; q++)
{
c=ReadBlobByte(file);
if (c == EOF || c == '\n')
break;
if ((q-p+1) >= (int) len)
{
int
tlen;
tlen=q-p;
len<<=1;
p=(unsigned char *) ResizeQuantumMemory(p,(size_t) len+2UL,sizeof(*p));
*b=(char *) p;
if (p == (unsigned char *) NULL)
break;
q=p+tlen;
}
*q=(unsigned char) c;
}
*blen=0;
if (p != (unsigned char *) NULL)
{
int
tlen;
tlen=q-p;
if (tlen == 0)
return (char *) NULL;
p[tlen] = '\0';
*blen=++tlen;
}
return((char *) p);
}
#define IPTC_ID 1028
#define THUMBNAIL_ID 1033
static ssize_t parse8BIM(Image *ifile, Image *ofile)
{
char
brkused,
quoted,
*line,
*token,
*newstr,
*name;
int
state,
next;
unsigned char
dataset;
unsigned int
recnum;
int
inputlen = MagickPathExtent;
MagickOffsetType
savedpos,
currentpos;
ssize_t
savedolen = 0L,
outputlen = 0L;
TokenInfo
*token_info;
dataset = 0;
recnum = 0;
line = (char *) AcquireQuantumMemory((size_t) inputlen,sizeof(*line));
if (line == (char *) NULL)
return(-1);
newstr = name = token = (char *) NULL;
savedpos = 0;
token_info=AcquireTokenInfo();
while (super_fgets(&line,&inputlen,ifile)!=NULL)
{
state=0;
next=0;
token=(char *) AcquireQuantumMemory((size_t) inputlen,sizeof(*token));
if (token == (char *) NULL)
break;
newstr=(char *) AcquireQuantumMemory((size_t) inputlen,sizeof(*newstr));
if (newstr == (char *) NULL)
break;
while (Tokenizer(token_info,0,token,(size_t) inputlen,line,"","=","\"",0,
&brkused,&next,"ed)==0)
{
if (state == 0)
{
int
state,
next;
char
brkused,
quoted;
state=0;
next=0;
while (Tokenizer(token_info,0,newstr,(size_t) inputlen,token,"","#",
"", 0,&brkused,&next,"ed)==0)
{
switch (state)
{
case 0:
if (strcmp(newstr,"8BIM")==0)
dataset = 255;
else
dataset = (unsigned char) StringToLong(newstr);
break;
case 1:
recnum = (unsigned int) StringToUnsignedLong(newstr);
break;
case 2:
name=(char *) AcquireQuantumMemory(strlen(newstr)+MagickPathExtent,
sizeof(*name));
if (name)
(void) strcpy(name,newstr);
break;
}
state++;
}
}
else
if (state == 1)
{
int
next;
ssize_t
len;
char
brkused,
quoted;
next=0;
len = (ssize_t) strlen(token);
while (Tokenizer(token_info,0,newstr,(size_t) inputlen,token,"","&",
"",0,&brkused,&next,"ed)==0)
{
if (brkused && next > 0)
{
char
*s = &token[next-1];
len -= (ssize_t) convertHTMLcodes(s,(int) strlen(s));
}
}
if (dataset == 255)
{
unsigned char
nlen = 0;
int
i;
if (savedolen > 0)
{
MagickOffsetType
offset;
ssize_t diff = outputlen - savedolen;
currentpos = TellBlob(ofile);
if (currentpos < 0)
return(-1);
offset=SeekBlob(ofile,savedpos,SEEK_SET);
if (offset < 0)
return(-1);
(void) WriteBlobMSBLong(ofile,(unsigned int) diff);
offset=SeekBlob(ofile,currentpos,SEEK_SET);
if (offset < 0)
return(-1);
savedolen = 0L;
}
if (outputlen & 1)
{
(void) WriteBlobByte(ofile,0x00);
outputlen++;
}
(void) WriteBlobString(ofile,"8BIM");
(void) WriteBlobMSBShort(ofile,(unsigned short) recnum);
outputlen += 6;
if (name)
nlen = (unsigned char) strlen(name);
(void) WriteBlobByte(ofile,nlen);
outputlen++;
for (i=0; i<nlen; i++)
(void) WriteBlobByte(ofile,(unsigned char) name[i]);
outputlen += nlen;
if ((nlen & 0x01) == 0)
{
(void) WriteBlobByte(ofile,0x00);
outputlen++;
}
if (recnum != IPTC_ID)
{
(void) WriteBlobMSBLong(ofile, (unsigned int) len);
outputlen += 4;
next=0;
outputlen += len;
while (len--)
(void) WriteBlobByte(ofile,(unsigned char) token[next++]);
if (outputlen & 1)
{
(void) WriteBlobByte(ofile,0x00);
outputlen++;
}
}
else
{
/* patch in a fake length for now and fix it later */
savedpos = TellBlob(ofile);
if (savedpos < 0)
return(-1);
(void) WriteBlobMSBLong(ofile,0xFFFFFFFFU);
outputlen += 4;
savedolen = outputlen;
}
}
else
{
if (len <= 0x7FFF)
{
(void) WriteBlobByte(ofile,0x1c);
(void) WriteBlobByte(ofile,(unsigned char) dataset);
(void) WriteBlobByte(ofile,(unsigned char) (recnum & 0xff));
(void) WriteBlobMSBShort(ofile,(unsigned short) len);
outputlen += 5;
next=0;
outputlen += len;
while (len--)
(void) WriteBlobByte(ofile,(unsigned char) token[next++]);
}
}
}
state++;
}
if (token != (char *) NULL)
token=DestroyString(token);
if (newstr != (char *) NULL)
newstr=DestroyString(newstr);
if (name != (char *) NULL)
name=DestroyString(name);
}
token_info=DestroyTokenInfo(token_info);
if (token != (char *) NULL)
token=DestroyString(token);
if (newstr != (char *) NULL)
newstr=DestroyString(newstr);
if (name != (char *) NULL)
name=DestroyString(name);
line=DestroyString(line);
if (savedolen > 0)
{
MagickOffsetType
offset;
ssize_t diff = outputlen - savedolen;
currentpos = TellBlob(ofile);
if (currentpos < 0)
return(-1);
offset=SeekBlob(ofile,savedpos,SEEK_SET);
if (offset < 0)
return(-1);
(void) WriteBlobMSBLong(ofile,(unsigned int) diff);
offset=SeekBlob(ofile,currentpos,SEEK_SET);
if (offset < 0)
return(-1);
savedolen = 0L;
}
return outputlen;
}
static char *super_fgets_w(char **b, int *blen, Image *file)
{
int
c,
len;
unsigned char
*p,
*q;
len=*blen;
p=(unsigned char *) (*b);
for (q=p; ; q++)
{
c=(int) ReadBlobLSBShort(file);
if ((c == -1) || (c == '\n'))
break;
if (EOFBlob(file))
break;
if ((q-p+1) >= (int) len)
{
int
tlen;
tlen=q-p;
len<<=1;
p=(unsigned char *) ResizeQuantumMemory(p,(size_t) (len+2),sizeof(*p));
*b=(char *) p;
if (p == (unsigned char *) NULL)
break;
q=p+tlen;
}
*q=(unsigned char) c;
}
*blen=0;
if ((*b) != (char *) NULL)
{
int
tlen;
tlen=q-p;
if (tlen == 0)
return (char *) NULL;
p[tlen] = '\0';
*blen=++tlen;
}
return((char *) p);
}
static ssize_t parse8BIMW(Image *ifile, Image *ofile)
{
char
brkused,
quoted,
*line,
*token,
*newstr,
*name;
int
state,
next;
unsigned char
dataset;
unsigned int
recnum;
int
inputlen = MagickPathExtent;
ssize_t
savedolen = 0L,
outputlen = 0L;
MagickOffsetType
savedpos,
currentpos;
TokenInfo
*token_info;
dataset = 0;
recnum = 0;
line=(char *) AcquireQuantumMemory((size_t) inputlen,sizeof(*line));
if (line == (char *) NULL)
return(-1);
newstr = name = token = (char *) NULL;
savedpos = 0;
token_info=AcquireTokenInfo();
while (super_fgets_w(&line,&inputlen,ifile) != NULL)
{
state=0;
next=0;
token=(char *) AcquireQuantumMemory((size_t) inputlen,sizeof(*token));
if (token == (char *) NULL)
break;
newstr=(char *) AcquireQuantumMemory((size_t) inputlen,sizeof(*newstr));
if (newstr == (char *) NULL)
break;
while (Tokenizer(token_info,0,token,(size_t) inputlen,line,"","=","\"",0,
&brkused,&next,"ed)==0)
{
if (state == 0)
{
int
state,
next;
char
brkused,
quoted;
state=0;
next=0;
while (Tokenizer(token_info,0,newstr,(size_t) inputlen,token,"","#",
"",0,&brkused,&next,"ed)==0)
{
switch (state)
{
case 0:
if (strcmp(newstr,"8BIM")==0)
dataset = 255;
else
dataset = (unsigned char) StringToLong(newstr);
break;
case 1:
recnum=(unsigned int) StringToUnsignedLong(newstr);
break;
case 2:
name=(char *) AcquireQuantumMemory(strlen(newstr)+MagickPathExtent,
sizeof(*name));
if (name)
(void) CopyMagickString(name,newstr,strlen(newstr)+MagickPathExtent);
break;
}
state++;
}
}
else
if (state == 1)
{
int
next;
ssize_t
len;
char
brkused,
quoted;
next=0;
len = (ssize_t) strlen(token);
while (Tokenizer(token_info,0,newstr,(size_t) inputlen,token,"","&",
"",0,&brkused,&next,"ed)==0)
{
if (brkused && next > 0)
{
char
*s = &token[next-1];
len -= (ssize_t) convertHTMLcodes(s,(int) strlen(s));
}
}
if (dataset == 255)
{
unsigned char
nlen = 0;
int
i;
if (savedolen > 0)
{
MagickOffsetType
offset;
ssize_t diff = outputlen - savedolen;
currentpos = TellBlob(ofile);
if (currentpos < 0)
return(-1);
offset=SeekBlob(ofile,savedpos,SEEK_SET);
if (offset < 0)
return(-1);
(void) WriteBlobMSBLong(ofile,(unsigned int) diff);
offset=SeekBlob(ofile,currentpos,SEEK_SET);
if (offset < 0)
return(-1);
savedolen = 0L;
}
if (outputlen & 1)
{
(void) WriteBlobByte(ofile,0x00);
outputlen++;
}
(void) WriteBlobString(ofile,"8BIM");
(void) WriteBlobMSBShort(ofile,(unsigned short) recnum);
outputlen += 6;
if (name)
nlen = (unsigned char) strlen(name);
(void) WriteBlobByte(ofile,(unsigned char) nlen);
outputlen++;
for (i=0; i<nlen; i++)
(void) WriteBlobByte(ofile,(unsigned char) name[i]);
outputlen += nlen;
if ((nlen & 0x01) == 0)
{
(void) WriteBlobByte(ofile,0x00);
outputlen++;
}
if (recnum != IPTC_ID)
{
(void) WriteBlobMSBLong(ofile,(unsigned int) len);
outputlen += 4;
next=0;
outputlen += len;
while (len--)
(void) WriteBlobByte(ofile,(unsigned char) token[next++]);
if (outputlen & 1)
{
(void) WriteBlobByte(ofile,0x00);
outputlen++;
}
}
else
{
/* patch in a fake length for now and fix it later */
savedpos = TellBlob(ofile);
if (savedpos < 0)
return(-1);
(void) WriteBlobMSBLong(ofile,0xFFFFFFFFU);
outputlen += 4;
savedolen = outputlen;
}
}
else
{
if (len <= 0x7FFF)
{
(void) WriteBlobByte(ofile,0x1c);
(void) WriteBlobByte(ofile,dataset);
(void) WriteBlobByte(ofile,(unsigned char) (recnum & 0xff));
(void) WriteBlobMSBShort(ofile,(unsigned short) len);
outputlen += 5;
next=0;
outputlen += len;
while (len--)
(void) WriteBlobByte(ofile,(unsigned char) token[next++]);
}
}
}
state++;
}
if (token != (char *) NULL)
token=DestroyString(token);
if (newstr != (char *) NULL)
newstr=DestroyString(newstr);
if (name != (char *) NULL)
name=DestroyString(name);
}
token_info=DestroyTokenInfo(token_info);
if (token != (char *) NULL)
token=DestroyString(token);
if (newstr != (char *) NULL)
newstr=DestroyString(newstr);
if (name != (char *) NULL)
name=DestroyString(name);
line=DestroyString(line);
if (savedolen > 0)
{
MagickOffsetType
offset;
ssize_t diff = outputlen - savedolen;
currentpos = TellBlob(ofile);
if (currentpos < 0)
return(-1);
offset=SeekBlob(ofile,savedpos,SEEK_SET);
if (offset < 0)
return(-1);
(void) WriteBlobMSBLong(ofile,(unsigned int) diff);
offset=SeekBlob(ofile,currentpos,SEEK_SET);
if (offset < 0)
return(-1);
savedolen = 0L;
}
return(outputlen);
}
/* some defines for the different JPEG block types */
#define M_SOF0 0xC0 /* Start Of Frame N */
#define M_SOF1 0xC1 /* N indicates which compression process */
#define M_SOF2 0xC2 /* Only SOF0-SOF2 are now in common use */
#define M_SOF3 0xC3
#define M_SOF5 0xC5 /* NB: codes C4 and CC are NOT SOF markers */
#define M_SOF6 0xC6
#define M_SOF7 0xC7
#define M_SOF9 0xC9
#define M_SOF10 0xCA
#define M_SOF11 0xCB
#define M_SOF13 0xCD
#define M_SOF14 0xCE
#define M_SOF15 0xCF
#define M_SOI 0xD8
#define M_EOI 0xD9 /* End Of Image (end of datastream) */
#define M_SOS 0xDA /* Start Of Scan (begins compressed data) */
#define M_APP0 0xe0
#define M_APP1 0xe1
#define M_APP2 0xe2
#define M_APP3 0xe3
#define M_APP4 0xe4
#define M_APP5 0xe5
#define M_APP6 0xe6
#define M_APP7 0xe7
#define M_APP8 0xe8
#define M_APP9 0xe9
#define M_APP10 0xea
#define M_APP11 0xeb
#define M_APP12 0xec
#define M_APP13 0xed
#define M_APP14 0xee
#define M_APP15 0xef
static int jpeg_transfer_1(Image *ifile, Image *ofile)
{
int c;
c = ReadBlobByte(ifile);
if (c == EOF)
return EOF;
(void) WriteBlobByte(ofile,(unsigned char) c);
return c;
}
#if defined(future)
static int jpeg_skip_1(Image *ifile)
{
int c;
c = ReadBlobByte(ifile);
if (c == EOF)
return EOF;
return c;
}
#endif
static int jpeg_read_remaining(Image *ifile, Image *ofile)
{
int c;
while ((c = jpeg_transfer_1(ifile, ofile)) != EOF)
continue;
return M_EOI;
}
static int jpeg_skip_variable(Image *ifile, Image *ofile)
{
unsigned int length;
int c1,c2;
if ((c1 = jpeg_transfer_1(ifile, ofile)) == EOF)
return M_EOI;
if ((c2 = jpeg_transfer_1(ifile, ofile)) == EOF)
return M_EOI;
length = (((unsigned char) c1) << 8) + ((unsigned char) c2);
length -= 2;
while (length--)
if (jpeg_transfer_1(ifile, ofile) == EOF)
return M_EOI;
return 0;
}
static int jpeg_skip_variable2(Image *ifile, Image *ofile)
{
unsigned int length;
int c1,c2;
(void) ofile;
if ((c1 = ReadBlobByte(ifile)) == EOF) return M_EOI;
if ((c2 = ReadBlobByte(ifile)) == EOF) return M_EOI;
length = (((unsigned char) c1) << 8) + ((unsigned char) c2);
length -= 2;
while (length--)
if (ReadBlobByte(ifile) == EOF)
return M_EOI;
return 0;
}
static int jpeg_nextmarker(Image *ifile, Image *ofile)
{
int c;
/* transfer anything until we hit 0xff */
do
{
c = ReadBlobByte(ifile);
if (c == EOF)
return M_EOI; /* we hit EOF */
else
if (c != 0xff)
(void) WriteBlobByte(ofile,(unsigned char) c);
} while (c != 0xff);
/* get marker byte, swallowing possible padding */
do
{
c = ReadBlobByte(ifile);
if (c == EOF)
return M_EOI; /* we hit EOF */
} while (c == 0xff);
return c;
}
#if defined(future)
static int jpeg_skip_till_marker(Image *ifile, int marker)
{
int c, i;
do
{
/* skip anything until we hit 0xff */
i = 0;
do
{
c = ReadBlobByte(ifile);
i++;
if (c == EOF)
return M_EOI; /* we hit EOF */
} while (c != 0xff);
/* get marker byte, swallowing possible padding */
do
{
c = ReadBlobByte(ifile);
if (c == EOF)
return M_EOI; /* we hit EOF */
} while (c == 0xff);
} while (c != marker);
return c;
}
#endif
/* Embed binary IPTC data into a JPEG image. */
static int jpeg_embed(Image *ifile, Image *ofile, Image *iptc)
{
unsigned int marker;
unsigned int done = 0;
unsigned int len;
int inx;
if (jpeg_transfer_1(ifile, ofile) != 0xFF)
return 0;
if (jpeg_transfer_1(ifile, ofile) != M_SOI)
return 0;
while (done == MagickFalse)
{
marker=(unsigned int) jpeg_nextmarker(ifile, ofile);
if (marker == M_EOI)
{ /* EOF */
break;
}
else
{
if (marker != M_APP13)
{
(void) WriteBlobByte(ofile,0xff);
(void) WriteBlobByte(ofile,(unsigned char) marker);
}
}
switch (marker)
{
case M_APP13:
/* we are going to write a new APP13 marker, so don't output the old one */
jpeg_skip_variable2(ifile, ofile);
break;
case M_APP0:
/* APP0 is in each and every JPEG, so when we hit APP0 we insert our new APP13! */
jpeg_skip_variable(ifile, ofile);
if (iptc != (Image *) NULL)
{
char
psheader[] = "\xFF\xED\0\0Photoshop 3.0\0" "8BIM\x04\x04\0\0\0\0";
len=(unsigned int) GetBlobSize(iptc);
if (len & 1)
len++; /* make the length even */
psheader[2]=(char) ((len+16)>>8);
psheader[3]=(char) ((len+16)&0xff);
for (inx = 0; inx < 18; inx++)
(void) WriteBlobByte(ofile,(unsigned char) psheader[inx]);
jpeg_read_remaining(iptc, ofile);
len=(unsigned int) GetBlobSize(iptc);
if (len & 1)
(void) WriteBlobByte(ofile,0);
}
break;
case M_SOS:
/* we hit data, no more marker-inserting can be done! */
jpeg_read_remaining(ifile, ofile);
done = 1;
break;
default:
jpeg_skip_variable(ifile, ofile);
break;
}
}
return 1;
}
/* handle stripping the APP13 data out of a JPEG */
#if defined(future)
static void jpeg_strip(Image *ifile, Image *ofile)
{
unsigned int marker;
marker = jpeg_skip_till_marker(ifile, M_SOI);
if (marker == M_SOI)
{
(void) WriteBlobByte(ofile,0xff);
(void) WriteBlobByte(ofile,M_SOI);
jpeg_read_remaining(ifile, ofile);
}
}
/* Extract any APP13 binary data into a file. */
static int jpeg_extract(Image *ifile, Image *ofile)
{
unsigned int marker;
unsigned int done = 0;
if (jpeg_skip_1(ifile) != 0xff)
return 0;
if (jpeg_skip_1(ifile) != M_SOI)
return 0;
while (done == MagickFalse)
{
marker = jpeg_skip_till_marker(ifile, M_APP13);
if (marker == M_APP13)
{
marker = jpeg_nextmarker(ifile, ofile);
break;
}
}
return 1;
}
#endif
static inline void CopyBlob(Image *source,Image *destination)
{
ssize_t
i;
unsigned char
*buffer;
ssize_t
count,
length;
buffer=(unsigned char *) AcquireQuantumMemory(MagickMaxBufferExtent,
sizeof(*buffer));
if (buffer != (unsigned char *) NULL)
{
i=0;
while ((length=ReadBlob(source,MagickMaxBufferExtent,buffer)) != 0)
{
count=0;
for (i=0; i < (ssize_t) length; i+=count)
{
count=WriteBlob(destination,(size_t) (length-i),buffer+i);
if (count <= 0)
break;
}
if (i < (ssize_t) length)
break;
}
buffer=(unsigned char *) RelinquishMagickMemory(buffer);
}
}
static Image *ReadMETAImage(const ImageInfo *image_info,
ExceptionInfo *exception)
{
Image
*buff,
*image;
MagickBooleanType
status;
StringInfo
*profile;
size_t
length;
void
*blob;
/*
Open file containing binary metadata
*/
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);
}
image->columns=1;
image->rows=1;
if (SetImageBackgroundColor(image,exception) == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
length=1;
if (LocaleNCompare(image_info->magick,"8BIM",4) == 0)
{
/*
Read 8BIM binary metadata.
*/
buff=AcquireImage((ImageInfo *) NULL,exception);
if (buff == (Image *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
blob=(unsigned char *) AcquireQuantumMemory(length,sizeof(unsigned char));
if (blob == (unsigned char *) NULL)
{
buff=DestroyImage(buff);
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
AttachBlob(buff->blob,blob,length);
if (LocaleCompare(image_info->magick,"8BIMTEXT") == 0)
{
length=(size_t) parse8BIM(image, buff);
if (length & 1)
(void) WriteBlobByte(buff,0x0);
}
else if (LocaleCompare(image_info->magick,"8BIMWTEXT") == 0)
{
length=(size_t) parse8BIMW(image, buff);
if (length & 1)
(void) WriteBlobByte(buff,0x0);
}
else
CopyBlob(image,buff);
profile=BlobToStringInfo(GetBlobStreamData(buff),(size_t)
GetBlobSize(buff));
if (profile == (StringInfo *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
status=SetImageProfile(image,"8bim",profile,exception);
profile=DestroyStringInfo(profile);
if (status == MagickFalse)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
blob=DetachBlob(buff->blob);
blob=(unsigned char *) RelinquishMagickMemory(blob);
buff=DestroyImage(buff);
}
if (LocaleNCompare(image_info->magick,"APP1",4) == 0)
{
char
name[MagickPathExtent];
(void) FormatLocaleString(name,MagickPathExtent,"APP%d",1);
buff=AcquireImage((ImageInfo *) NULL,exception);
if (buff == (Image *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
blob=(unsigned char *) AcquireQuantumMemory(length,sizeof(unsigned char));
if (blob == (unsigned char *) NULL)
{
buff=DestroyImage(buff);
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
AttachBlob(buff->blob,blob,length);
if (LocaleCompare(image_info->magick,"APP1JPEG") == 0)
{
Image
*iptc;
int
result;
if (image_info->profile == (void *) NULL)
{
blob=DetachBlob(buff->blob);
blob=RelinquishMagickMemory(blob);
buff=DestroyImage(buff);
ThrowReaderException(CoderError,"NoIPTCProfileAvailable");
}
profile=CloneStringInfo((StringInfo *) image_info->profile);
iptc=AcquireImage((ImageInfo *) NULL,exception);
if (iptc == (Image *) NULL)
{
blob=DetachBlob(buff->blob);
blob=RelinquishMagickMemory(blob);
buff=DestroyImage(buff);
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
AttachBlob(iptc->blob,GetStringInfoDatum(profile),
GetStringInfoLength(profile));
result=jpeg_embed(image,buff,iptc);
blob=DetachBlob(iptc->blob);
blob=RelinquishMagickMemory(blob);
iptc=DestroyImage(iptc);
if (result == 0)
{
blob=DetachBlob(buff->blob);
blob=RelinquishMagickMemory(blob);
buff=DestroyImage(buff);
ThrowReaderException(CoderError,"JPEGEmbeddingFailed");
}
}
else
CopyBlob(image,buff);
profile=BlobToStringInfo(GetBlobStreamData(buff),(size_t)
GetBlobSize(buff));
if (profile == (StringInfo *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
status=SetImageProfile(image,name,profile,exception);
profile=DestroyStringInfo(profile);
if (status == MagickFalse)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
blob=DetachBlob(buff->blob);
blob=RelinquishMagickMemory(blob);
buff=DestroyImage(buff);
}
if ((LocaleCompare(image_info->magick,"ICC") == 0) ||
(LocaleCompare(image_info->magick,"ICM") == 0))
{
buff=AcquireImage((ImageInfo *) NULL,exception);
if (buff == (Image *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
blob=(unsigned char *) AcquireQuantumMemory(length,sizeof(unsigned char));
if (blob == (unsigned char *) NULL)
{
buff=DestroyImage(buff);
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
AttachBlob(buff->blob,blob,length);
CopyBlob(image,buff);
profile=BlobToStringInfo(GetBlobStreamData(buff),(size_t)
GetBlobSize(buff));
if (profile == (StringInfo *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
(void) SetImageProfile(image,"icc",profile,exception);
profile=DestroyStringInfo(profile);
blob=DetachBlob(buff->blob);
blob=(unsigned char *) RelinquishMagickMemory(blob);
buff=DestroyImage(buff);
}
if (LocaleCompare(image_info->magick,"IPTC") == 0)
{
buff=AcquireImage((ImageInfo *) NULL,exception);
if (buff == (Image *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
blob=(unsigned char *) AcquireQuantumMemory(length,sizeof(unsigned char));
if (blob == (unsigned char *) NULL)
{
buff=DestroyImage(buff);
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
AttachBlob(buff->blob,blob,length);
CopyBlob(image,buff);
profile=BlobToStringInfo(GetBlobStreamData(buff),(size_t)
GetBlobSize(buff));
if (profile == (StringInfo *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
(void) SetImageProfile(image,"8bim",profile,exception);
profile=DestroyStringInfo(profile);
blob=DetachBlob(buff->blob);
blob=(unsigned char *) RelinquishMagickMemory(blob);
buff=DestroyImage(buff);
}
if (LocaleCompare(image_info->magick,"XMP") == 0)
{
buff=AcquireImage((ImageInfo *) NULL,exception);
if (buff == (Image *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
blob=(unsigned char *) AcquireQuantumMemory(length,sizeof(unsigned char));
if (blob == (unsigned char *) NULL)
{
buff=DestroyImage(buff);
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
AttachBlob(buff->blob,blob,length);
CopyBlob(image,buff);
profile=BlobToStringInfo(GetBlobStreamData(buff),(size_t)
GetBlobSize(buff));
if (profile == (StringInfo *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
(void) SetImageProfile(image,"xmp",profile,exception);
profile=DestroyStringInfo(profile);
blob=DetachBlob(buff->blob);
blob=(unsigned char *) RelinquishMagickMemory(blob);
buff=DestroyImage(buff);
}
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e g i s t e r M E T A I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% RegisterMETAImage() adds attributes for the META 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 RegisterMETAImage method is:
%
% size_t RegisterMETAImage(void)
%
*/
ModuleExport size_t RegisterMETAImage(void)
{
MagickInfo
*entry;
entry=AcquireMagickInfo("META","8BIM","Photoshop resource format");
entry->decoder=(DecodeImageHandler *) ReadMETAImage;
entry->encoder=(EncodeImageHandler *) WriteMETAImage;
entry->flags^=CoderAdjoinFlag;
entry->flags|=CoderStealthFlag;
entry->flags|=CoderSeekableStreamFlag;
(void) RegisterMagickInfo(entry);
entry=AcquireMagickInfo("META","8BIMTEXT","Photoshop resource text format");
entry->decoder=(DecodeImageHandler *) ReadMETAImage;
entry->encoder=(EncodeImageHandler *) WriteMETAImage;
entry->flags^=CoderAdjoinFlag;
entry->flags|=CoderStealthFlag;
entry->flags|=CoderSeekableStreamFlag;
(void) RegisterMagickInfo(entry);
entry=AcquireMagickInfo("META","8BIMWTEXT",
"Photoshop resource wide text format");
entry->decoder=(DecodeImageHandler *) ReadMETAImage;
entry->encoder=(EncodeImageHandler *) WriteMETAImage;
entry->flags^=CoderAdjoinFlag;
entry->flags|=CoderStealthFlag;
entry->flags|=CoderSeekableStreamFlag;
(void) RegisterMagickInfo(entry);
entry=AcquireMagickInfo("META","APP1","Raw application information");
entry->decoder=(DecodeImageHandler *) ReadMETAImage;
entry->encoder=(EncodeImageHandler *) WriteMETAImage;
entry->flags^=CoderAdjoinFlag;
entry->flags|=CoderStealthFlag;
entry->flags|=CoderSeekableStreamFlag;
(void) RegisterMagickInfo(entry);
entry=AcquireMagickInfo("META","APP1JPEG","Raw JPEG binary data");
entry->decoder=(DecodeImageHandler *) ReadMETAImage;
entry->encoder=(EncodeImageHandler *) WriteMETAImage;
entry->flags^=CoderAdjoinFlag;
entry->flags|=CoderStealthFlag;
entry->flags|=CoderSeekableStreamFlag;
(void) RegisterMagickInfo(entry);
entry=AcquireMagickInfo("META","EXIF","Exif digital camera binary data");
entry->decoder=(DecodeImageHandler *) ReadMETAImage;
entry->encoder=(EncodeImageHandler *) WriteMETAImage;
entry->flags^=CoderAdjoinFlag;
entry->flags|=CoderStealthFlag;
entry->flags|=CoderSeekableStreamFlag;
(void) RegisterMagickInfo(entry);
entry=AcquireMagickInfo("META","XMP","Adobe XML metadata");
entry->decoder=(DecodeImageHandler *) ReadMETAImage;
entry->encoder=(EncodeImageHandler *) WriteMETAImage;
entry->flags^=CoderAdjoinFlag;
entry->flags|=CoderStealthFlag;
entry->flags|=CoderSeekableStreamFlag;
(void) RegisterMagickInfo(entry);
entry=AcquireMagickInfo("META","ICM","ICC Color Profile");
entry->decoder=(DecodeImageHandler *) ReadMETAImage;
entry->encoder=(EncodeImageHandler *) WriteMETAImage;
entry->flags^=CoderAdjoinFlag;
entry->flags|=CoderStealthFlag;
entry->flags|=CoderSeekableStreamFlag;
(void) RegisterMagickInfo(entry);
entry=AcquireMagickInfo("META","ICC","ICC Color Profile");
entry->decoder=(DecodeImageHandler *) ReadMETAImage;
entry->encoder=(EncodeImageHandler *) WriteMETAImage;
entry->flags^=CoderAdjoinFlag;
entry->flags|=CoderStealthFlag;
entry->flags|=CoderSeekableStreamFlag;
(void) RegisterMagickInfo(entry);
entry=AcquireMagickInfo("META","IPTC","IPTC Newsphoto");
entry->decoder=(DecodeImageHandler *) ReadMETAImage;
entry->encoder=(EncodeImageHandler *) WriteMETAImage;
entry->flags^=CoderAdjoinFlag;
entry->flags|=CoderStealthFlag;
entry->flags|=CoderSeekableStreamFlag;
(void) RegisterMagickInfo(entry);
entry=AcquireMagickInfo("META","IPTCTEXT","IPTC Newsphoto text format");
entry->decoder=(DecodeImageHandler *) ReadMETAImage;
entry->encoder=(EncodeImageHandler *) WriteMETAImage;
entry->flags^=CoderAdjoinFlag;
entry->flags|=CoderStealthFlag;
entry->flags|=CoderSeekableStreamFlag;
(void) RegisterMagickInfo(entry);
entry=AcquireMagickInfo("META","IPTCWTEXT","IPTC Newsphoto text format");
entry->decoder=(DecodeImageHandler *) ReadMETAImage;
entry->encoder=(EncodeImageHandler *) WriteMETAImage;
entry->flags^=CoderAdjoinFlag;
entry->flags|=CoderStealthFlag;
entry->flags|=CoderSeekableStreamFlag;
(void) RegisterMagickInfo(entry);
return(MagickImageCoderSignature);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% U n r e g i s t e r M E T A I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% UnregisterMETAImage() removes format registrations made by the
% META module from the list of supported formats.
%
% The format of the UnregisterMETAImage method is:
%
% UnregisterMETAImage(void)
%
*/
ModuleExport void UnregisterMETAImage(void)
{
(void) UnregisterMagickInfo("8BIM");
(void) UnregisterMagickInfo("8BIMTEXT");
(void) UnregisterMagickInfo("8BIMWTEXT");
(void) UnregisterMagickInfo("EXIF");
(void) UnregisterMagickInfo("APP1");
(void) UnregisterMagickInfo("APP1JPEG");
(void) UnregisterMagickInfo("ICCTEXT");
(void) UnregisterMagickInfo("ICM");
(void) UnregisterMagickInfo("ICC");
(void) UnregisterMagickInfo("IPTC");
(void) UnregisterMagickInfo("IPTCTEXT");
(void) UnregisterMagickInfo("IPTCWTEXT");
(void) UnregisterMagickInfo("XMP");
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% W r i t e M E T A I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% WriteMETAImage() writes a META image to a file.
%
% The format of the WriteMETAImage method is:
%
% MagickBooleanType WriteMETAImage(const ImageInfo *image_info,
% Image *image,ExceptionInfo *exception)
%
% Compression code contributed by Kyle Shorter.
%
% A description of each parameter follows:
%
% o image_info: Specifies a pointer to an ImageInfo structure.
%
% o image: A pointer to a Image structure.
%
% o exception: return any errors or warnings in this structure.
%
*/
static size_t GetIPTCStream(unsigned char **info,size_t length)
{
int
c;
register ssize_t
i;
register unsigned char
*p;
size_t
extent,
info_length;
unsigned int
marker;
size_t
tag_length;
p=(*info);
extent=length;
if ((*p == 0x1c) && (*(p+1) == 0x02))
return(length);
/*
Extract IPTC from 8BIM resource block.
*/
while (extent >= 12)
{
if (strncmp((const char *) p,"8BIM",4))
break;
p+=4;
extent-=4;
marker=(unsigned int) (*p) << 8 | *(p+1);
p+=2;
extent-=2;
c=*p++;
extent--;
c|=0x01;
if ((size_t) c >= extent)
break;
p+=c;
extent-=c;
if (extent < 4)
break;
tag_length=(((size_t) *p) << 24) | (((size_t) *(p+1)) << 16) |
(((size_t) *(p+2)) << 8) | ((size_t) *(p+3));
p+=4;
extent-=4;
if (tag_length > extent)
break;
if (marker == IPTC_ID)
{
*info=p;
return(tag_length);
}
if ((tag_length & 0x01) != 0)
tag_length++;
p+=tag_length;
extent-=tag_length;
}
/*
Find the beginning of the IPTC info.
*/
p=(*info);
tag_length=0;
iptc_find:
info_length=0;
marker=MagickFalse;
while (length != 0)
{
c=(*p++);
length--;
if (length == 0)
break;
if (c == 0x1c)
{
p--;
*info=p; /* let the caller know were it is */
break;
}
}
/*
Determine the length of the IPTC info.
*/
while (length != 0)
{
c=(*p++);
length--;
if (length == 0)
break;
if (c == 0x1c)
marker=MagickTrue;
else
if (marker)
break;
else
continue;
info_length++;
/*
Found the 0x1c tag; skip the dataset and record number tags.
*/
c=(*p++); /* should be 2 */
length--;
if (length == 0)
break;
if ((info_length == 1) && (c != 2))
goto iptc_find;
info_length++;
c=(*p++); /* should be 0 */
length--;
if (length == 0)
break;
if ((info_length == 2) && (c != 0))
goto iptc_find;
info_length++;
/*
Decode the length of the block that follows - ssize_t or short format.
*/
c=(*p++);
length--;
if (length == 0)
break;
info_length++;
if ((c & 0x80) != 0)
{
/*
Long format.
*/
tag_length=0;
for (i=0; i < 4; i++)
{
tag_length<<=8;
tag_length|=(*p++);
length--;
if (length == 0)
break;
info_length++;
}
}
else
{
/*
Short format.
*/
tag_length=((long) c) << 8;
c=(*p++);
length--;
if (length == 0)
break;
info_length++;
tag_length|=(long) c;
}
if (tag_length > (length+1))
break;
p+=tag_length;
length-=tag_length;
if (length == 0)
break;
info_length+=tag_length;
}
return(info_length);
}
static void formatString(Image *ofile, const char *s, int len)
{
char
temp[MagickPathExtent];
(void) WriteBlobByte(ofile,'"');
for (; len > 0; len--, s++) {
int c = (*s) & 255;
switch (c) {
case '&':
(void) WriteBlobString(ofile,"&");
break;
#ifdef HANDLE_GT_LT
case '<':
(void) WriteBlobString(ofile,"<");
break;
case '>':
(void) WriteBlobString(ofile,">");
break;
#endif
case '"':
(void) WriteBlobString(ofile,""");
break;
default:
if (isprint(c))
(void) WriteBlobByte(ofile,(unsigned char) *s);
else
{
(void) FormatLocaleString(temp,MagickPathExtent,"&#%d;", c & 255);
(void) WriteBlobString(ofile,temp);
}
break;
}
}
#if defined(MAGICKCORE_WINDOWS_SUPPORT)
(void) WriteBlobString(ofile,"\"\r\n");
#else
#if defined(macintosh)
(void) WriteBlobString(ofile,"\"\r");
#else
(void) WriteBlobString(ofile,"\"\n");
#endif
#endif
}
typedef struct _tag_spec
{
const short
id;
const char
*name;
} tag_spec;
static const tag_spec tags[] = {
{ 5, "Image Name" },
{ 7, "Edit Status" },
{ 10, "Priority" },
{ 15, "Category" },
{ 20, "Supplemental Category" },
{ 22, "Fixture Identifier" },
{ 25, "Keyword" },
{ 30, "Release Date" },
{ 35, "Release Time" },
{ 40, "Special Instructions" },
{ 45, "Reference Service" },
{ 47, "Reference Date" },
{ 50, "Reference Number" },
{ 55, "Created Date" },
{ 60, "Created Time" },
{ 65, "Originating Program" },
{ 70, "Program Version" },
{ 75, "Object Cycle" },
{ 80, "Byline" },
{ 85, "Byline Title" },
{ 90, "City" },
{ 92, "Sub-Location" },
{ 95, "Province State" },
{ 100, "Country Code" },
{ 101, "Country" },
{ 103, "Original Transmission Reference" },
{ 105, "Headline" },
{ 110, "Credit" },
{ 115, "Source" },
{ 116, "Copyright String" },
{ 120, "Caption" },
{ 121, "Image Orientation" },
{ 122, "Caption Writer" },
{ 131, "Local Caption" },
{ 200, "Custom Field 1" },
{ 201, "Custom Field 2" },
{ 202, "Custom Field 3" },
{ 203, "Custom Field 4" },
{ 204, "Custom Field 5" },
{ 205, "Custom Field 6" },
{ 206, "Custom Field 7" },
{ 207, "Custom Field 8" },
{ 208, "Custom Field 9" },
{ 209, "Custom Field 10" },
{ 210, "Custom Field 11" },
{ 211, "Custom Field 12" },
{ 212, "Custom Field 13" },
{ 213, "Custom Field 14" },
{ 214, "Custom Field 15" },
{ 215, "Custom Field 16" },
{ 216, "Custom Field 17" },
{ 217, "Custom Field 18" },
{ 218, "Custom Field 19" },
{ 219, "Custom Field 20" }
};
static int formatIPTC(Image *ifile, Image *ofile)
{
char
temp[MagickPathExtent];
unsigned int
foundiptc,
tagsfound;
unsigned char
recnum,
dataset;
unsigned char
*readable,
*str;
ssize_t
tagindx,
taglen;
int
i,
tagcount = (int) (sizeof(tags) / sizeof(tag_spec));
int
c;
foundiptc = 0; /* found the IPTC-Header */
tagsfound = 0; /* number of tags found */
c = ReadBlobByte(ifile);
while (c != EOF)
{
if (c == 0x1c)
foundiptc = 1;
else
{
if (foundiptc)
return(-1);
else
{
c=0;
continue;
}
}
/* we found the 0x1c tag and now grab the dataset and record number tags */
c = ReadBlobByte(ifile);
if (c == EOF) return -1;
dataset = (unsigned char) c;
c = ReadBlobByte(ifile);
if (c == EOF) return -1;
recnum = (unsigned char) c;
/* try to match this record to one of the ones in our named table */
for (i=0; i< tagcount; i++)
{
if (tags[i].id == (short) recnum)
break;
}
if (i < tagcount)
readable = (unsigned char *) tags[i].name;
else
readable = (unsigned char *) "";
/*
We decode the length of the block that follows - ssize_t or short fmt.
*/
c=ReadBlobByte(ifile);
if (c == EOF) return -1;
if (c & (unsigned char) 0x80)
return 0;
else
{
int
c0;
c0=ReadBlobByte(ifile);
if (c0 == EOF) return -1;
taglen = (c << 8) | c0;
}
if (taglen < 0) return -1;
/* make a buffer to hold the tag datand snag it from the input stream */
str=(unsigned char *) AcquireQuantumMemory((size_t) (taglen+MagickPathExtent),
sizeof(*str));
if (str == (unsigned char *) NULL)
{
printf("MemoryAllocationFailed");
return 0;
}
for (tagindx=0; tagindx<taglen; tagindx++)
{
c=ReadBlobByte(ifile);
if (c == EOF) return -1;
str[tagindx] = (unsigned char) c;
}
str[taglen] = 0;
/* now finish up by formatting this binary data into ASCII equivalent */
if (strlen((char *)readable) > 0)
(void) FormatLocaleString(temp,MagickPathExtent,"%d#%d#%s=",
(unsigned int) dataset, (unsigned int) recnum, readable);
else
(void) FormatLocaleString(temp,MagickPathExtent,"%d#%d=",
(unsigned int) dataset,(unsigned int) recnum);
(void) WriteBlobString(ofile,temp);
formatString( ofile, (char *)str, taglen );
str=(unsigned char *) RelinquishMagickMemory(str);
tagsfound++;
c=ReadBlobByte(ifile);
}
return((int) tagsfound);
}
static int readWordFromBuffer(char **s, ssize_t *len)
{
unsigned char
buffer[2];
int
i,
c;
for (i=0; i<2; i++)
{
c = *(*s)++; (*len)--;
if (*len < 0) return -1;
buffer[i] = (unsigned char) c;
}
return (((int) buffer[ 0 ]) << 8) |
(((int) buffer[ 1 ]));
}
static int formatIPTCfromBuffer(Image *ofile, char *s, ssize_t len)
{
char
temp[MagickPathExtent];
unsigned int
foundiptc,
tagsfound;
unsigned char
recnum,
dataset;
unsigned char
*readable,
*str;
ssize_t
tagindx,
taglen;
int
i,
tagcount = (int) (sizeof(tags) / sizeof(tag_spec));
int
c;
foundiptc = 0; /* found the IPTC-Header */
tagsfound = 0; /* number of tags found */
while (len > 0)
{
c = *s++; len--;
if (c == 0x1c)
foundiptc = 1;
else
{
if (foundiptc)
return -1;
else
continue;
}
/*
We found the 0x1c tag and now grab the dataset and record number tags.
*/
c = *s++; len--;
if (len < 0) return -1;
dataset = (unsigned char) c;
c = *s++; len--;
if (len < 0) return -1;
recnum = (unsigned char) c;
/* try to match this record to one of the ones in our named table */
for (i=0; i< tagcount; i++)
if (tags[i].id == (short) recnum)
break;
if (i < tagcount)
readable=(unsigned char *) tags[i].name;
else
readable=(unsigned char *) "";
/*
We decode the length of the block that follows - ssize_t or short fmt.
*/
c=(*s++);
len--;
if (len < 0)
return(-1);
if (c & (unsigned char) 0x80)
return(0);
else
{
s--;
len++;
taglen=readWordFromBuffer(&s, &len);
}
if (taglen < 0)
return(-1);
if (taglen > 65535)
return(-1);
/* make a buffer to hold the tag datand snag it from the input stream */
str=(unsigned char *) AcquireQuantumMemory((size_t) (taglen+MagickPathExtent),
sizeof(*str));
if (str == (unsigned char *) NULL)
{
printf("MemoryAllocationFailed");
return 0;
}
for (tagindx=0; tagindx<taglen; tagindx++)
{
c = *s++; len--;
if (len < 0)
return(-1);
str[tagindx]=(unsigned char) c;
}
str[taglen]=0;
/* now finish up by formatting this binary data into ASCII equivalent */
if (strlen((char *)readable) > 0)
(void) FormatLocaleString(temp,MagickPathExtent,"%d#%d#%s=",
(unsigned int) dataset,(unsigned int) recnum, readable);
else
(void) FormatLocaleString(temp,MagickPathExtent,"%d#%d=",
(unsigned int) dataset,(unsigned int) recnum);
(void) WriteBlobString(ofile,temp);
formatString( ofile, (char *)str, taglen );
str=(unsigned char *) RelinquishMagickMemory(str);
tagsfound++;
}
return ((int) tagsfound);
}
static int format8BIM(Image *ifile, Image *ofile)
{
char
temp[MagickPathExtent];
unsigned int
foundOSType;
int
ID,
resCount,
i,
c;
ssize_t
count;
unsigned char
*PString,
*str;
resCount=0;
foundOSType=0; /* found the OSType */
(void) foundOSType;
c=ReadBlobByte(ifile);
while (c != EOF)
{
if (c == '8')
{
unsigned char
buffer[5];
buffer[0]=(unsigned char) c;
for (i=1; i<4; i++)
{
c=ReadBlobByte(ifile);
if (c == EOF)
return(-1);
buffer[i] = (unsigned char) c;
}
buffer[4]=0;
if (strcmp((const char *)buffer, "8BIM") == 0)
foundOSType=1;
else
continue;
}
else
{
c=ReadBlobByte(ifile);
continue;
}
/*
We found the OSType (8BIM) and now grab the ID, PString, and Size fields.
*/
ID=(int) ReadBlobMSBShort(ifile);
if (ID < 0)
return(-1);
{
unsigned char
plen;
c=ReadBlobByte(ifile);
if (c == EOF)
return(-1);
plen = (unsigned char) c;
PString=(unsigned char *) AcquireQuantumMemory((size_t) (plen+
MagickPathExtent),sizeof(*PString));
if (PString == (unsigned char *) NULL)
{
printf("MemoryAllocationFailed");
return 0;
}
for (i=0; i<plen; i++)
{
c=ReadBlobByte(ifile);
if (c == EOF) return -1;
PString[i] = (unsigned char) c;
}
PString[ plen ] = 0;
if ((plen & 0x01) == 0)
{
c=ReadBlobByte(ifile);
if (c == EOF)
return(-1);
}
}
count = (int) ReadBlobMSBLong(ifile);
if (count < 0) return -1;
/* make a buffer to hold the datand snag it from the input stream */
str=(unsigned char *) AcquireQuantumMemory((size_t) count,sizeof(*str));
if (str == (unsigned char *) NULL)
{
printf("MemoryAllocationFailed");
return 0;
}
for (i=0; i < (ssize_t) count; i++)
{
c=ReadBlobByte(ifile);
if (c == EOF)
return(-1);
str[i]=(unsigned char) c;
}
/* we currently skip thumbnails, since it does not make
* any sense preserving them in a real world application
*/
if (ID != THUMBNAIL_ID)
{
/* now finish up by formatting this binary data into
* ASCII equivalent
*/
if (strlen((const char *)PString) > 0)
(void) FormatLocaleString(temp,MagickPathExtent,"8BIM#%d#%s=",ID,
PString);
else
(void) FormatLocaleString(temp,MagickPathExtent,"8BIM#%d=",ID);
(void) WriteBlobString(ofile,temp);
if (ID == IPTC_ID)
{
formatString(ofile, "IPTC", 4);
formatIPTCfromBuffer(ofile, (char *)str, (ssize_t) count);
}
else
formatString(ofile, (char *)str, (ssize_t) count);
}
str=(unsigned char *) RelinquishMagickMemory(str);
PString=(unsigned char *) RelinquishMagickMemory(PString);
resCount++;
c=ReadBlobByte(ifile);
}
return resCount;
}
static MagickBooleanType WriteMETAImage(const ImageInfo *image_info,
Image *image,ExceptionInfo *exception)
{
const StringInfo
*profile;
MagickBooleanType
status;
size_t
length;
/*
Open 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);
length=0;
if (LocaleCompare(image_info->magick,"8BIM") == 0)
{
/*
Write 8BIM image.
*/
profile=GetImageProfile(image,"8bim");
if (profile == (StringInfo *) NULL)
ThrowWriterException(CoderError,"No8BIMDataIsAvailable");
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception);
if (status == MagickFalse)
return(status);
(void) WriteBlob(image,GetStringInfoLength(profile),
GetStringInfoDatum(profile));
(void) CloseBlob(image);
return(MagickTrue);
}
if (LocaleCompare(image_info->magick,"iptc") == 0)
{
size_t
length;
unsigned char
*info;
profile=GetImageProfile(image,"iptc");
if (profile == (StringInfo *) NULL)
profile=GetImageProfile(image,"8bim");
if (profile == (StringInfo *) NULL)
ThrowWriterException(CoderError,"No8BIMDataIsAvailable");
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception);
info=GetStringInfoDatum(profile);
length=GetStringInfoLength(profile);
length=GetIPTCStream(&info,length);
if (length == 0)
ThrowWriterException(CoderError,"NoIPTCProfileAvailable");
(void) WriteBlob(image,length,info);
(void) CloseBlob(image);
return(MagickTrue);
}
if (LocaleCompare(image_info->magick,"8BIMTEXT") == 0)
{
Image
*buff;
profile=GetImageProfile(image,"8bim");
if (profile == (StringInfo *) NULL)
ThrowWriterException(CoderError,"No8BIMDataIsAvailable");
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception);
if (status == MagickFalse)
return(status);
buff=AcquireImage((ImageInfo *) NULL,exception);
if (buff == (Image *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
AttachBlob(buff->blob,GetStringInfoDatum(profile),
GetStringInfoLength(profile));
format8BIM(buff,image);
(void) DetachBlob(buff->blob);
buff=DestroyImage(buff);
(void) CloseBlob(image);
return(MagickTrue);
}
if (LocaleCompare(image_info->magick,"8BIMWTEXT") == 0)
return(MagickFalse);
if (LocaleCompare(image_info->magick,"IPTCTEXT") == 0)
{
Image
*buff;
unsigned char
*info;
profile=GetImageProfile(image,"8bim");
if (profile == (StringInfo *) NULL)
ThrowWriterException(CoderError,"No8BIMDataIsAvailable");
info=GetStringInfoDatum(profile);
length=GetStringInfoLength(profile);
length=GetIPTCStream(&info,length);
if (length == 0)
ThrowWriterException(CoderError,"NoIPTCProfileAvailable");
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception);
if (status == MagickFalse)
return(status);
buff=AcquireImage((ImageInfo *) NULL,exception);
if (buff == (Image *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
AttachBlob(buff->blob,info,length);
formatIPTC(buff,image);
(void) DetachBlob(buff->blob);
buff=DestroyImage(buff);
(void) CloseBlob(image);
return(MagickTrue);
}
if (LocaleCompare(image_info->magick,"IPTCWTEXT") == 0)
return(MagickFalse);
if ((LocaleCompare(image_info->magick,"APP1") == 0) ||
(LocaleCompare(image_info->magick,"EXIF") == 0) ||
(LocaleCompare(image_info->magick,"XMP") == 0))
{
/*
(void) Write APP1 image.
*/
profile=GetImageProfile(image,image_info->magick);
if (profile == (StringInfo *) NULL)
ThrowWriterException(CoderError,"NoAPP1DataIsAvailable");
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception);
if (status == MagickFalse)
return(status);
(void) WriteBlob(image,GetStringInfoLength(profile),
GetStringInfoDatum(profile));
(void) CloseBlob(image);
return(MagickTrue);
}
if ((LocaleCompare(image_info->magick,"ICC") == 0) ||
(LocaleCompare(image_info->magick,"ICM") == 0))
{
/*
Write ICM image.
*/
profile=GetImageProfile(image,"icc");
if (profile == (StringInfo *) NULL)
ThrowWriterException(CoderError,"NoColorProfileIsAvailable");
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception);
if (status == MagickFalse)
return(status);
(void) WriteBlob(image,GetStringInfoLength(profile),
GetStringInfoDatum(profile));
(void) CloseBlob(image);
return(MagickTrue);
}
return(MagickFalse);
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_5302_0 |
crossvul-cpp_data_bad_2644_10 | /*
* Copyright (c) 1991, 1993, 1994, 1995, 1996, 1997
* The Regents of the University of California. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that: (1) source code distributions
* retain the above copyright notice and this paragraph in its entirety, (2)
* distributions including binary code include the above copyright notice and
* this paragraph in its entirety in the documentation or other materials
* provided with the distribution, and (3) all advertising materials mentioning
* features or use of this software display the following acknowledgement:
* ``This product includes software developed by the University of California,
* Lawrence Berkeley Laboratory and its contributors.'' Neither the name of
* the University nor the names of its contributors may be used to endorse
* or promote products derived from this software without specific prior
* written permission.
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
/* \summary: BSD loopback device printer */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <netdissect-stdinc.h>
#include <string.h>
#include "netdissect.h"
#include "af.h"
/*
* The DLT_NULL packet header is 4 bytes long. It contains a host-byte-order
* 32-bit integer that specifies the family, e.g. AF_INET.
*
* Note here that "host" refers to the host on which the packets were
* captured; that isn't necessarily *this* host.
*
* The OpenBSD DLT_LOOP packet header is the same, except that the integer
* is in network byte order.
*/
#define NULL_HDRLEN 4
/*
* Byte-swap a 32-bit number.
* ("htonl()" or "ntohl()" won't work - we want to byte-swap even on
* big-endian platforms.)
*/
#define SWAPLONG(y) \
((((y)&0xff)<<24) | (((y)&0xff00)<<8) | (((y)&0xff0000)>>8) | (((y)>>24)&0xff))
static inline void
null_hdr_print(netdissect_options *ndo, u_int family, u_int length)
{
if (!ndo->ndo_qflag) {
ND_PRINT((ndo, "AF %s (%u)",
tok2str(bsd_af_values,"Unknown",family),family));
} else {
ND_PRINT((ndo, "%s",
tok2str(bsd_af_values,"Unknown AF %u",family)));
}
ND_PRINT((ndo, ", length %u: ", length));
}
/*
* This is the top level routine of the printer. 'p' points
* to the ether header of the packet, 'h->ts' is the timestamp,
* 'h->len' is the length of the packet off the wire, and 'h->caplen'
* is the number of bytes actually captured.
*/
u_int
null_if_print(netdissect_options *ndo, const struct pcap_pkthdr *h, const u_char *p)
{
u_int length = h->len;
u_int caplen = h->caplen;
u_int family;
if (caplen < NULL_HDRLEN) {
ND_PRINT((ndo, "[|null]"));
return (NULL_HDRLEN);
}
memcpy((char *)&family, (const char *)p, sizeof(family));
/*
* This isn't necessarily in our host byte order; if this is
* a DLT_LOOP capture, it's in network byte order, and if
* this is a DLT_NULL capture from a machine with the opposite
* byte-order, it's in the opposite byte order from ours.
*
* If the upper 16 bits aren't all zero, assume it's byte-swapped.
*/
if ((family & 0xFFFF0000) != 0)
family = SWAPLONG(family);
if (ndo->ndo_eflag)
null_hdr_print(ndo, family, length);
length -= NULL_HDRLEN;
caplen -= NULL_HDRLEN;
p += NULL_HDRLEN;
switch (family) {
case BSD_AFNUM_INET:
ip_print(ndo, p, length);
break;
case BSD_AFNUM_INET6_BSD:
case BSD_AFNUM_INET6_FREEBSD:
case BSD_AFNUM_INET6_DARWIN:
ip6_print(ndo, p, length);
break;
case BSD_AFNUM_ISO:
isoclns_print(ndo, p, length, caplen);
break;
case BSD_AFNUM_APPLETALK:
atalk_print(ndo, p, length);
break;
case BSD_AFNUM_IPX:
ipx_print(ndo, p, length);
break;
default:
/* unknown AF_ value */
if (!ndo->ndo_eflag)
null_hdr_print(ndo, family, length + NULL_HDRLEN);
if (!ndo->ndo_suppress_default_print)
ND_DEFAULTPRINT(p, caplen);
}
return (NULL_HDRLEN);
}
/*
* Local Variables:
* c-style: whitesmith
* c-basic-offset: 8
* End:
*/
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_2644_10 |
crossvul-cpp_data_bad_4901_1 | /*
* DBD::mysql - DBI driver for the mysql database
*
* Copyright (c) 2004-2014 Patrick Galbraith
* Copyright (c) 2013-2014 Michiel Beijen
* Copyright (c) 2004-2007 Alexey Stroganov
* Copyright (c) 2003-2005 Rudolf Lippan
* Copyright (c) 1997-2003 Jochen Wiedmann
*
* You may distribute this under the terms of either the GNU General Public
* License or the Artistic License, as specified in the Perl README file.
*/
#ifdef WIN32
#include "windows.h"
#include "winsock.h"
#endif
#include "dbdimp.h"
#if defined(WIN32) && defined(WORD)
#undef WORD
typedef short WORD;
#endif
#ifdef WIN32
#define MIN min
#else
#ifndef MIN
#define MIN(a, b) ((a) < (b) ? (a) : (b))
#endif
#endif
#if MYSQL_ASYNC
# include <poll.h>
# include <errno.h>
# define ASYNC_CHECK_RETURN(h, value)\
if(imp_dbh->async_query_in_flight) {\
do_error(h, 2000, "Calling a synchronous function on an asynchronous handle", "HY000");\
return (value);\
}
#else
# define ASYNC_CHECK_RETURN(h, value)
#endif
static int parse_number(char *string, STRLEN len, char **end);
DBISTATE_DECLARE;
typedef struct sql_type_info_s
{
const char *type_name;
int data_type;
int column_size;
const char *literal_prefix;
const char *literal_suffix;
const char *create_params;
int nullable;
int case_sensitive;
int searchable;
int unsigned_attribute;
int fixed_prec_scale;
int auto_unique_value;
const char *local_type_name;
int minimum_scale;
int maximum_scale;
int num_prec_radix;
int sql_datatype;
int sql_datetime_sub;
int interval_precision;
int native_type;
int is_num;
} sql_type_info_t;
/*
This function manually counts the number of placeholders in an SQL statement,
used for emulated prepare statements < 4.1.3
*/
static int
count_params(imp_xxh_t *imp_xxh, pTHX_ char *statement, bool bind_comment_placeholders)
{
bool comment_end= false;
char* ptr= statement;
int num_params= 0;
int comment_length= 0;
char c;
if (DBIc_DBISTATE(imp_xxh)->debug >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh), ">count_params statement %s\n", statement);
while ( (c = *ptr++) )
{
switch (c) {
/* so, this is a -- comment, so let's burn up characters */
case '-':
{
if (bind_comment_placeholders)
{
c = *ptr++;
break;
}
else
{
comment_length= 1;
/* let's see if the next one is a dash */
c = *ptr++;
if (c == '-') {
/* if two dashes, ignore everything until newline */
while ((c = *ptr))
{
if (DBIc_DBISTATE(imp_xxh)->debug >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh), "%c\n", c);
ptr++;
comment_length++;
if (c == '\n')
{
comment_end= true;
break;
}
}
/*
if not comment_end, the comment never ended and we need to iterate
back to the beginning of where we started and let the database
handle whatever is in the statement
*/
if (! comment_end)
ptr-= comment_length;
}
/* otherwise, only one dash/hyphen, backtrack by one */
else
ptr--;
break;
}
}
/* c-type comments */
case '/':
{
if (bind_comment_placeholders)
{
c = *ptr++;
break;
}
else
{
c = *ptr++;
/* let's check if the next one is an asterisk */
if (c == '*')
{
comment_length= 0;
comment_end= false;
/* ignore everything until closing comment */
while ((c= *ptr))
{
ptr++;
comment_length++;
if (c == '*')
{
c = *ptr++;
/* alas, end of comment */
if (c == '/')
{
comment_end= true;
break;
}
/*
nope, just an asterisk, not so fast, not
end of comment, go back one
*/
else
ptr--;
}
}
/*
if the end of the comment was never found, we have
to backtrack to wherever we first started skipping
over the possible comment.
This means we will pass the statement to the database
to see its own fate and issue the error
*/
if (!comment_end)
ptr -= comment_length;
}
else
ptr--;
break;
}
}
case '`':
case '"':
case '\'':
/* Skip string */
{
char end_token = c;
while ((c = *ptr) && c != end_token)
{
if (c == '\\')
if (! *(++ptr))
continue;
++ptr;
}
if (c)
++ptr;
break;
}
case '?':
++num_params;
break;
default:
break;
}
}
return num_params;
}
/*
allocate memory in statement handle per number of placeholders
*/
static imp_sth_ph_t *alloc_param(int num_params)
{
imp_sth_ph_t *params;
if (num_params)
Newz(908, params, (unsigned int) num_params, imp_sth_ph_t);
else
params= NULL;
return params;
}
#if MYSQL_VERSION_ID >= SERVER_PREPARE_VERSION
/*
allocate memory in MYSQL_BIND bind structure per
number of placeholders
*/
static MYSQL_BIND *alloc_bind(int num_params)
{
MYSQL_BIND *bind;
if (num_params)
Newz(908, bind, (unsigned int) num_params, MYSQL_BIND);
else
bind= NULL;
return bind;
}
/*
allocate memory in fbind imp_sth_phb_t structure per
number of placeholders
*/
static imp_sth_phb_t *alloc_fbind(int num_params)
{
imp_sth_phb_t *fbind;
if (num_params)
Newz(908, fbind, (unsigned int) num_params, imp_sth_phb_t);
else
fbind= NULL;
return fbind;
}
/*
alloc memory for imp_sth_fbh_t fbuffer per number of fields
*/
static imp_sth_fbh_t *alloc_fbuffer(int num_fields)
{
imp_sth_fbh_t *fbh;
if (num_fields)
Newz(908, fbh, (unsigned int) num_fields, imp_sth_fbh_t);
else
fbh= NULL;
return fbh;
}
/*
free MYSQL_BIND bind struct
*/
static void free_bind(MYSQL_BIND *bind)
{
if (bind)
Safefree(bind);
}
/*
free imp_sth_phb_t fbind structure
*/
static void free_fbind(imp_sth_phb_t *fbind)
{
if (fbind)
Safefree(fbind);
}
/*
free imp_sth_fbh_t fbh structure
*/
static void free_fbuffer(imp_sth_fbh_t *fbh)
{
if (fbh)
Safefree(fbh);
}
#endif
/*
free statement param structure per num_params
*/
static void
free_param(pTHX_ imp_sth_ph_t *params, int num_params)
{
if (params)
{
int i;
for (i= 0; i < num_params; i++)
{
imp_sth_ph_t *ph= params+i;
if (ph->value)
{
(void) SvREFCNT_dec(ph->value);
ph->value= NULL;
}
}
Safefree(params);
}
}
/*
Convert a MySQL type to a type that perl can handle
NOTE: In the future we may want to return a struct with a lot of
information for each type
*/
static enum enum_field_types mysql_to_perl_type(enum enum_field_types type)
{
static enum enum_field_types enum_type;
switch (type) {
case MYSQL_TYPE_DOUBLE:
case MYSQL_TYPE_FLOAT:
enum_type= MYSQL_TYPE_DOUBLE;
break;
case MYSQL_TYPE_SHORT:
case MYSQL_TYPE_TINY:
case MYSQL_TYPE_LONG:
case MYSQL_TYPE_INT24:
case MYSQL_TYPE_YEAR:
#if IVSIZE >= 8
case MYSQL_TYPE_LONGLONG:
#endif
enum_type= MYSQL_TYPE_LONG;
break;
#if MYSQL_VERSION_ID > NEW_DATATYPE_VERSION
case MYSQL_TYPE_BIT:
enum_type= MYSQL_TYPE_BIT;
break;
#endif
#if MYSQL_VERSION_ID > NEW_DATATYPE_VERSION
case MYSQL_TYPE_NEWDECIMAL:
#endif
case MYSQL_TYPE_DECIMAL:
enum_type= MYSQL_TYPE_DECIMAL;
break;
#if IVSIZE < 8
case MYSQL_TYPE_LONGLONG:
#endif
case MYSQL_TYPE_DATE:
case MYSQL_TYPE_TIME:
case MYSQL_TYPE_DATETIME:
case MYSQL_TYPE_NEWDATE:
case MYSQL_TYPE_TIMESTAMP:
case MYSQL_TYPE_VAR_STRING:
#if MYSQL_VERSION_ID > NEW_DATATYPE_VERSION
case MYSQL_TYPE_VARCHAR:
#endif
case MYSQL_TYPE_STRING:
enum_type= MYSQL_TYPE_STRING;
break;
#if MYSQL_VERSION_ID > GEO_DATATYPE_VERSION
case MYSQL_TYPE_GEOMETRY:
#endif
case MYSQL_TYPE_BLOB:
case MYSQL_TYPE_TINY_BLOB:
enum_type= MYSQL_TYPE_BLOB;
break;
default:
enum_type= MYSQL_TYPE_STRING; /* MySQL can handle all types as strings */
}
return(enum_type);
}
#if defined(DBD_MYSQL_EMBEDDED)
/*
count embedded options
*/
int count_embedded_options(char *st)
{
int rc;
char c;
char *ptr;
ptr= st;
rc= 0;
if (st)
{
while ((c= *ptr++))
{
if (c == ',')
rc++;
}
rc++;
}
return rc;
}
/*
Free embedded options
*/
int free_embedded_options(char ** options_list, int options_count)
{
int i;
for (i= 0; i < options_count; i++)
{
if (options_list[i])
free(options_list[i]);
}
free(options_list);
return 1;
}
/*
Print out embedded option settings
*/
int print_embedded_options(PerlIO *stream, char ** options_list, int options_count)
{
int i;
for (i=0; i<options_count; i++)
{
if (options_list[i])
PerlIO_printf(stream,
"Embedded server, parameter[%d]=%s\n",
i, options_list[i]);
}
return 1;
}
/*
*/
char **fill_out_embedded_options(PerlIO *stream,
char *options,
int options_type,
int slen, int cnt)
{
int ind, len;
char c;
char *ptr;
char **options_list= NULL;
if (!(options_list= (char **) calloc(cnt, sizeof(char *))))
{
PerlIO_printf(stream,
"Initialize embedded server. Out of memory \n");
return NULL;
}
ptr= options;
ind= 0;
if (options_type == 0)
{
/* server_groups list NULL terminated */
options_list[cnt]= (char *) NULL;
}
if (options_type == 1)
{
/* first item in server_options list is ignored. fill it with \0 */
if (!(options_list[0]= calloc(1,sizeof(char))))
return NULL;
ind++;
}
while ((c= *ptr++))
{
slen--;
if (c == ',' || !slen)
{
len= ptr - options;
if (c == ',')
len--;
if (!(options_list[ind]=calloc(len+1,sizeof(char))))
return NULL;
strncpy(options_list[ind], options, len);
ind++;
options= ptr;
}
}
return options_list;
}
#endif
/*
constructs an SQL statement previously prepared with
actual values replacing placeholders
*/
static char *parse_params(
imp_xxh_t *imp_xxh,
pTHX_ MYSQL *sock,
char *statement,
STRLEN *slen_ptr,
imp_sth_ph_t* params,
int num_params,
bool bind_type_guessing,
bool bind_comment_placeholders)
{
bool comment_end= false;
char *salloc, *statement_ptr;
char *statement_ptr_end, *ptr, *valbuf;
char *cp, *end;
int alen, i;
int slen= *slen_ptr;
int limit_flag= 0;
int comment_length=0;
STRLEN vallen;
imp_sth_ph_t *ph;
if (DBIc_DBISTATE(imp_xxh)->debug >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh), ">parse_params statement %s\n", statement);
if (num_params == 0)
return NULL;
while (isspace(*statement))
{
++statement;
--slen;
}
/* Calculate the number of bytes being allocated for the statement */
alen= slen;
for (i= 0, ph= params; i < num_params; i++, ph++)
{
int defined= 0;
if (ph->value)
{
if (SvMAGICAL(ph->value))
mg_get(ph->value);
if (SvOK(ph->value))
defined=1;
}
if (!defined)
alen+= 3; /* Erase '?', insert 'NULL' */
else
{
valbuf= SvPV(ph->value, vallen);
alen+= 2+vallen+1;
/* this will most likely not happen since line 214 */
/* of mysql.xs hardcodes all types to SQL_VARCHAR */
if (!ph->type)
{
if (bind_type_guessing)
{
valbuf= SvPV(ph->value, vallen);
ph->type= SQL_INTEGER;
if (parse_number(valbuf, vallen, &end) != 0)
{
ph->type= SQL_VARCHAR;
}
}
else
ph->type= SQL_VARCHAR;
}
}
}
/* Allocate memory, why *2, well, because we have ptr and statement_ptr */
New(908, salloc, alen*2, char);
ptr= salloc;
i= 0;
/* Now create the statement string; compare count_params above */
statement_ptr_end= (statement_ptr= statement)+ slen;
while (statement_ptr < statement_ptr_end)
{
/* LIMIT should be the last part of the query, in most cases */
if (! limit_flag)
{
/*
it would be good to be able to handle any number of cases and orders
*/
if ((*statement_ptr == 'l' || *statement_ptr == 'L') &&
(!strncmp(statement_ptr+1, "imit ?", 6) ||
!strncmp(statement_ptr+1, "IMIT ?", 6)))
{
limit_flag = 1;
}
}
switch (*statement_ptr)
{
/* comment detection. Anything goes in a comment */
case '-':
{
if (bind_comment_placeholders)
{
*ptr++= *statement_ptr++;
break;
}
else
{
comment_length= 1;
comment_end= false;
*ptr++ = *statement_ptr++;
if (*statement_ptr == '-')
{
/* ignore everything until newline or end of string */
while (*statement_ptr)
{
comment_length++;
*ptr++ = *statement_ptr++;
if (!*statement_ptr || *statement_ptr == '\n')
{
comment_end= true;
break;
}
}
/* if not end of comment, go back to where we started, no end found */
if (! comment_end)
{
statement_ptr -= comment_length;
ptr -= comment_length;
}
}
break;
}
}
/* c-type comments */
case '/':
{
if (bind_comment_placeholders)
{
*ptr++= *statement_ptr++;
break;
}
else
{
comment_length= 1;
comment_end= false;
*ptr++ = *statement_ptr++;
if (*statement_ptr == '*')
{
/* use up characters everything until newline */
while (*statement_ptr)
{
*ptr++ = *statement_ptr++;
comment_length++;
if (!strncmp(statement_ptr, "*/", 2))
{
comment_length += 2;
comment_end= true;
break;
}
}
/* Go back to where started if comment end not found */
if (! comment_end)
{
statement_ptr -= comment_length;
ptr -= comment_length;
}
}
break;
}
}
case '`':
case '\'':
case '"':
/* Skip string */
{
char endToken = *statement_ptr++;
*ptr++ = endToken;
while (statement_ptr != statement_ptr_end &&
*statement_ptr != endToken)
{
if (*statement_ptr == '\\')
{
*ptr++ = *statement_ptr++;
if (statement_ptr == statement_ptr_end)
break;
}
*ptr++= *statement_ptr++;
}
if (statement_ptr != statement_ptr_end)
*ptr++= *statement_ptr++;
}
break;
case '?':
/* Insert parameter */
statement_ptr++;
if (i >= num_params)
{
break;
}
ph = params+ (i++);
if (!ph->value || !SvOK(ph->value))
{
*ptr++ = 'N';
*ptr++ = 'U';
*ptr++ = 'L';
*ptr++ = 'L';
}
else
{
int is_num = FALSE;
valbuf= SvPV(ph->value, vallen);
if (valbuf)
{
switch (ph->type)
{
case SQL_NUMERIC:
case SQL_DECIMAL:
case SQL_INTEGER:
case SQL_SMALLINT:
case SQL_FLOAT:
case SQL_REAL:
case SQL_DOUBLE:
case SQL_BIGINT:
case SQL_TINYINT:
is_num = TRUE;
break;
}
/* (note this sets *end, which we use if is_num) */
if ( parse_number(valbuf, vallen, &end) != 0 && is_num)
{
if (bind_type_guessing) {
/* .. not a number, so apparently we guessed wrong */
is_num = 0;
ph->type = SQL_VARCHAR;
}
}
/* we're at the end of the query, so any placeholders if */
/* after a LIMIT clause will be numbers and should not be quoted */
if (limit_flag == 1)
is_num = TRUE;
if (!is_num)
{
*ptr++ = '\'';
ptr += mysql_real_escape_string(sock, ptr, valbuf, vallen);
*ptr++ = '\'';
}
else
{
for (cp= valbuf; cp < end; cp++)
*ptr++= *cp;
}
}
}
break;
/* in case this is a nested LIMIT */
case ')':
limit_flag = 0;
*ptr++ = *statement_ptr++;
break;
default:
*ptr++ = *statement_ptr++;
break;
}
}
*slen_ptr = ptr - salloc;
*ptr++ = '\0';
return(salloc);
}
int bind_param(imp_sth_ph_t *ph, SV *value, IV sql_type)
{
dTHX;
if (ph->value)
{
if (SvMAGICAL(ph->value))
mg_get(ph->value);
(void) SvREFCNT_dec(ph->value);
}
ph->value= newSVsv(value);
if (sql_type)
ph->type = sql_type;
return TRUE;
}
static const sql_type_info_t SQL_GET_TYPE_INFO_values[]= {
{ "varchar", SQL_VARCHAR, 255, "'", "'", "max length",
1, 0, 3, 0, 0, 0, "variable length string",
0, 0, 0,
SQL_VARCHAR, 0, 0,
#if MYSQL_VERSION_ID < MYSQL_VERSION_5_0
FIELD_TYPE_VAR_STRING, 0,
#else
MYSQL_TYPE_STRING, 0,
#endif
},
{ "decimal", SQL_DECIMAL, 15, NULL, NULL, "precision,scale",
1, 0, 3, 0, 0, 0, "double",
0, 6, 2,
SQL_DECIMAL, 0, 0,
#if MYSQL_VERSION_ID < MYSQL_VERSION_5_0
FIELD_TYPE_DECIMAL, 1
#else
MYSQL_TYPE_DECIMAL, 1
#endif
},
{ "tinyint", SQL_TINYINT, 3, NULL, NULL, NULL,
1, 0, 3, 0, 0, 0, "Tiny integer",
0, 0, 10,
SQL_TINYINT, 0, 0,
#if MYSQL_VERSION_ID < MYSQL_VERSION_5_0
FIELD_TYPE_TINY, 1
#else
MYSQL_TYPE_TINY, 1
#endif
},
{ "smallint", SQL_SMALLINT, 5, NULL, NULL, NULL,
1, 0, 3, 0, 0, 0, "Short integer",
0, 0, 10,
SQL_SMALLINT, 0, 0,
#if MYSQL_VERSION_ID < MYSQL_VERSION_5_0
FIELD_TYPE_SHORT, 1
#else
MYSQL_TYPE_SHORT, 1
#endif
},
{ "integer", SQL_INTEGER, 10, NULL, NULL, NULL,
1, 0, 3, 0, 0, 0, "integer",
0, 0, 10,
SQL_INTEGER, 0, 0,
#if MYSQL_VERSION_ID < MYSQL_VERSION_5_0
FIELD_TYPE_LONG, 1
#else
MYSQL_TYPE_LONG, 1
#endif
},
{ "float", SQL_REAL, 7, NULL, NULL, NULL,
1, 0, 0, 0, 0, 0, "float",
0, 2, 10,
SQL_FLOAT, 0, 0,
#if MYSQL_VERSION_ID < MYSQL_VERSION_5_0
FIELD_TYPE_FLOAT, 1
#else
MYSQL_TYPE_FLOAT, 1
#endif
},
{ "double", SQL_FLOAT, 15, NULL, NULL, NULL,
1, 0, 3, 0, 0, 0, "double",
0, 4, 2,
SQL_FLOAT, 0, 0,
#if MYSQL_VERSION_ID < MYSQL_VERSION_5_0
FIELD_TYPE_DOUBLE, 1
#else
MYSQL_TYPE_DOUBLE, 1
#endif
},
{ "double", SQL_DOUBLE, 15, NULL, NULL, NULL,
1, 0, 3, 0, 0, 0, "double",
0, 4, 10,
SQL_DOUBLE, 0, 0,
#if MYSQL_VERSION_ID < MYSQL_VERSION_5_0
FIELD_TYPE_DOUBLE, 1
#else
MYSQL_TYPE_DOUBLE, 1
#endif
},
/*
FIELD_TYPE_NULL ?
*/
{ "timestamp", SQL_TIMESTAMP, 14, "'", "'", NULL,
0, 0, 3, 0, 0, 0, "timestamp",
0, 0, 0,
SQL_TIMESTAMP, 0, 0,
#if MYSQL_VERSION_ID < MYSQL_VERSION_5_0
FIELD_TYPE_TIMESTAMP, 0
#else
MYSQL_TYPE_TIMESTAMP, 0
#endif
},
{ "bigint", SQL_BIGINT, 19, NULL, NULL, NULL,
1, 0, 3, 0, 0, 0, "Longlong integer",
0, 0, 10,
SQL_BIGINT, 0, 0,
#if MYSQL_VERSION_ID < MYSQL_VERSION_5_0
FIELD_TYPE_LONGLONG, 1
#else
MYSQL_TYPE_LONGLONG, 1
#endif
},
{ "mediumint", SQL_INTEGER, 8, NULL, NULL, NULL,
1, 0, 3, 0, 0, 0, "Medium integer",
0, 0, 10,
SQL_INTEGER, 0, 0,
#if MYSQL_VERSION_ID < MYSQL_VERSION_5_0
FIELD_TYPE_INT24, 1
#else
MYSQL_TYPE_INT24, 1
#endif
},
{ "date", SQL_DATE, 10, "'", "'", NULL,
1, 0, 3, 0, 0, 0, "date",
0, 0, 0,
SQL_DATE, 0, 0,
#if MYSQL_VERSION_ID < MYSQL_VERSION_5_0
FIELD_TYPE_DATE, 0
#else
MYSQL_TYPE_DATE, 0
#endif
},
{ "time", SQL_TIME, 6, "'", "'", NULL,
1, 0, 3, 0, 0, 0, "time",
0, 0, 0,
SQL_TIME, 0, 0,
#if MYSQL_VERSION_ID < MYSQL_VERSION_5_0
FIELD_TYPE_TIME, 0
#else
MYSQL_TYPE_TIME, 0
#endif
},
{ "datetime", SQL_TIMESTAMP, 21, "'", "'", NULL,
1, 0, 3, 0, 0, 0, "datetime",
0, 0, 0,
SQL_TIMESTAMP, 0, 0,
#if MYSQL_VERSION_ID < MYSQL_VERSION_5_0
FIELD_TYPE_DATETIME, 0
#else
MYSQL_TYPE_DATETIME, 0
#endif
},
{ "year", SQL_SMALLINT, 4, NULL, NULL, NULL,
1, 0, 3, 0, 0, 0, "year",
0, 0, 10,
SQL_SMALLINT, 0, 0,
#if MYSQL_VERSION_ID < MYSQL_VERSION_5_0
FIELD_TYPE_YEAR, 0
#else
MYSQL_TYPE_YEAR, 0
#endif
},
{ "date", SQL_DATE, 10, "'", "'", NULL,
1, 0, 3, 0, 0, 0, "date",
0, 0, 0,
SQL_DATE, 0, 0,
#if MYSQL_VERSION_ID < MYSQL_VERSION_5_0
FIELD_TYPE_NEWDATE, 0
#else
MYSQL_TYPE_NEWDATE, 0
#endif
},
{ "enum", SQL_VARCHAR, 255, "'", "'", NULL,
1, 0, 1, 0, 0, 0, "enum(value1,value2,value3...)",
0, 0, 0,
0, 0, 0,
#if MYSQL_VERSION_ID < MYSQL_VERSION_5_0
FIELD_TYPE_ENUM, 0
#else
MYSQL_TYPE_ENUM, 0
#endif
},
{ "set", SQL_VARCHAR, 255, "'", "'", NULL,
1, 0, 1, 0, 0, 0, "set(value1,value2,value3...)",
0, 0, 0,
0, 0, 0,
#if MYSQL_VERSION_ID < MYSQL_VERSION_5_0
FIELD_TYPE_SET, 0
#else
MYSQL_TYPE_SET, 0
#endif
},
{ "blob", SQL_LONGVARBINARY, 65535, "'", "'", NULL,
1, 0, 3, 0, 0, 0, "binary large object (0-65535)",
0, 0, 0,
SQL_LONGVARBINARY, 0, 0,
#if MYSQL_VERSION_ID < MYSQL_VERSION_5_0
FIELD_TYPE_BLOB, 0
#else
MYSQL_TYPE_BLOB, 0
#endif
},
{ "tinyblob", SQL_VARBINARY, 255, "'", "'", NULL,
1, 0, 3, 0, 0, 0, "binary large object (0-255) ",
0, 0, 0,
SQL_VARBINARY, 0, 0,
#if MYSQL_VERSION_ID < MYSQL_VERSION_5_0
FIELD_TYPE_TINY_BLOB, 0
#else
FIELD_TYPE_TINY_BLOB, 0
#endif
},
{ "mediumblob", SQL_LONGVARBINARY, 16777215, "'", "'", NULL,
1, 0, 3, 0, 0, 0, "binary large object",
0, 0, 0,
SQL_LONGVARBINARY, 0, 0,
#if MYSQL_VERSION_ID < MYSQL_VERSION_5_0
FIELD_TYPE_MEDIUM_BLOB, 0
#else
MYSQL_TYPE_MEDIUM_BLOB, 0
#endif
},
{ "longblob", SQL_LONGVARBINARY, 2147483647, "'", "'", NULL,
1, 0, 3, 0, 0, 0, "binary large object, use mediumblob instead",
0, 0, 0,
SQL_LONGVARBINARY, 0, 0,
#if MYSQL_VERSION_ID < MYSQL_VERSION_5_0
FIELD_TYPE_LONG_BLOB, 0
#else
MYSQL_TYPE_LONG_BLOB, 0
#endif
},
{ "char", SQL_CHAR, 255, "'", "'", "max length",
1, 0, 3, 0, 0, 0, "string",
0, 0, 0,
SQL_CHAR, 0, 0,
#if MYSQL_VERSION_ID < MYSQL_VERSION_5_0
FIELD_TYPE_STRING, 0
#else
MYSQL_TYPE_STRING, 0
#endif
},
{ "decimal", SQL_NUMERIC, 15, NULL, NULL, "precision,scale",
1, 0, 3, 0, 0, 0, "double",
0, 6, 2,
SQL_NUMERIC, 0, 0,
#if MYSQL_VERSION_ID < MYSQL_VERSION_5_0
FIELD_TYPE_DECIMAL, 1
#else
MYSQL_TYPE_DECIMAL, 1
#endif
},
{ "tinyint unsigned", SQL_TINYINT, 3, NULL, NULL, NULL,
1, 0, 3, 1, 0, 0, "Tiny integer unsigned",
0, 0, 10,
SQL_TINYINT, 0, 0,
#if MYSQL_VERSION_ID < MYSQL_VERSION_5_0
FIELD_TYPE_TINY, 1
#else
MYSQL_TYPE_TINY, 1
#endif
},
{ "smallint unsigned", SQL_SMALLINT, 5, NULL, NULL, NULL,
1, 0, 3, 1, 0, 0, "Short integer unsigned",
0, 0, 10,
SQL_SMALLINT, 0, 0,
#if MYSQL_VERSION_ID < MYSQL_VERSION_5_0
FIELD_TYPE_SHORT, 1
#else
MYSQL_TYPE_SHORT, 1
#endif
},
{ "mediumint unsigned", SQL_INTEGER, 8, NULL, NULL, NULL,
1, 0, 3, 1, 0, 0, "Medium integer unsigned",
0, 0, 10,
SQL_INTEGER, 0, 0,
#if MYSQL_VERSION_ID < MYSQL_VERSION_5_0
FIELD_TYPE_INT24, 1
#else
MYSQL_TYPE_INT24, 1
#endif
},
{ "int unsigned", SQL_INTEGER, 10, NULL, NULL, NULL,
1, 0, 3, 1, 0, 0, "integer unsigned",
0, 0, 10,
SQL_INTEGER, 0, 0,
#if MYSQL_VERSION_ID < MYSQL_VERSION_5_0
FIELD_TYPE_LONG, 1
#else
MYSQL_TYPE_LONG, 1
#endif
},
{ "int", SQL_INTEGER, 10, NULL, NULL, NULL,
1, 0, 3, 0, 0, 0, "integer",
0, 0, 10,
SQL_INTEGER, 0, 0,
#if MYSQL_VERSION_ID < MYSQL_VERSION_5_0
FIELD_TYPE_LONG, 1
#else
MYSQL_TYPE_LONG, 1
#endif
},
{ "integer unsigned", SQL_INTEGER, 10, NULL, NULL, NULL,
1, 0, 3, 1, 0, 0, "integer",
0, 0, 10,
SQL_INTEGER, 0, 0,
#if MYSQL_VERSION_ID < MYSQL_VERSION_5_0
FIELD_TYPE_LONG, 1
#else
MYSQL_TYPE_LONG, 1
#endif
},
{ "bigint unsigned", SQL_BIGINT, 20, NULL, NULL, NULL,
1, 0, 3, 1, 0, 0, "Longlong integer unsigned",
0, 0, 10,
SQL_BIGINT, 0, 0,
#if MYSQL_VERSION_ID < MYSQL_VERSION_5_0
FIELD_TYPE_LONGLONG, 1
#else
MYSQL_TYPE_LONGLONG, 1
#endif
},
{ "text", SQL_LONGVARCHAR, 65535, "'", "'", NULL,
1, 0, 3, 0, 0, 0, "large text object (0-65535)",
0, 0, 0,
SQL_LONGVARCHAR, 0, 0,
#if MYSQL_VERSION_ID < MYSQL_VERSION_5_0
FIELD_TYPE_BLOB, 0
#else
MYSQL_TYPE_BLOB, 0
#endif
},
{ "mediumtext", SQL_LONGVARCHAR, 16777215, "'", "'", NULL,
1, 0, 3, 0, 0, 0, "large text object",
0, 0, 0,
SQL_LONGVARCHAR, 0, 0,
#if MYSQL_VERSION_ID < MYSQL_VERSION_5_0
FIELD_TYPE_MEDIUM_BLOB, 0
#else
MYSQL_TYPE_MEDIUM_BLOB, 0
#endif
},
{ "mediumint unsigned auto_increment", SQL_INTEGER, 8, NULL, NULL, NULL,
0, 0, 3, 1, 0, 1, "Medium integer unsigned auto_increment", 0, 0, 10,
#if MYSQL_VERSION_ID < MYSQL_VERSION_5_0
SQL_INTEGER, 0, 0, FIELD_TYPE_INT24, 1,
#else
SQL_INTEGER, 0, 0, MYSQL_TYPE_INT24, 1,
#endif
},
{ "tinyint unsigned auto_increment", SQL_TINYINT, 3, NULL, NULL, NULL,
0, 0, 3, 1, 0, 1, "tinyint unsigned auto_increment", 0, 0, 10,
#if MYSQL_VERSION_ID < MYSQL_VERSION_5_0
SQL_TINYINT, 0, 0, FIELD_TYPE_TINY, 1
#else
SQL_TINYINT, 0, 0, MYSQL_TYPE_TINY, 1
#endif
},
{ "smallint auto_increment", SQL_SMALLINT, 5, NULL, NULL, NULL,
0, 0, 3, 0, 0, 1, "smallint auto_increment", 0, 0, 10,
#if MYSQL_VERSION_ID < MYSQL_VERSION_5_0
SQL_SMALLINT, 0, 0, FIELD_TYPE_SHORT, 1
#else
SQL_SMALLINT, 0, 0, MYSQL_TYPE_SHORT, 1
#endif
},
{ "int unsigned auto_increment", SQL_INTEGER, 10, NULL, NULL, NULL,
0, 0, 3, 1, 0, 1, "integer unsigned auto_increment", 0, 0, 10,
#if MYSQL_VERSION_ID < MYSQL_VERSION_5_0
SQL_INTEGER, 0, 0, FIELD_TYPE_LONG, 1
#else
SQL_INTEGER, 0, 0, MYSQL_TYPE_LONG, 1
#endif
},
{ "mediumint", SQL_INTEGER, 7, NULL, NULL, NULL,
1, 0, 3, 0, 0, 0, "Medium integer", 0, 0, 10,
#if MYSQL_VERSION_ID < MYSQL_VERSION_5_0
SQL_INTEGER, 0, 0, FIELD_TYPE_INT24, 1
#else
SQL_INTEGER, 0, 0, MYSQL_TYPE_INT24, 1
#endif
},
{ "bit", SQL_BIT, 1, NULL, NULL, NULL,
1, 0, 3, 0, 0, 0, "char(1)", 0, 0, 0,
#if MYSQL_VERSION_ID < MYSQL_VERSION_5_0
SQL_BIT, 0, 0, FIELD_TYPE_TINY, 0
#else
SQL_BIT, 0, 0, MYSQL_TYPE_TINY, 0
#endif
},
{ "numeric", SQL_NUMERIC, 19, NULL, NULL, "precision,scale",
1, 0, 3, 0, 0, 0, "numeric", 0, 19, 10,
#if MYSQL_VERSION_ID < MYSQL_VERSION_5_0
SQL_NUMERIC, 0, 0, FIELD_TYPE_DECIMAL, 1,
#else
SQL_NUMERIC, 0, 0, MYSQL_TYPE_DECIMAL, 1,
#endif
},
{ "integer unsigned auto_increment", SQL_INTEGER, 10, NULL, NULL, NULL,
0, 0, 3, 1, 0, 1, "integer unsigned auto_increment", 0, 0, 10,
#if MYSQL_VERSION_ID < MYSQL_VERSION_5_0
SQL_INTEGER, 0, 0, FIELD_TYPE_LONG, 1,
#else
SQL_INTEGER, 0, 0, MYSQL_TYPE_LONG, 1,
#endif
},
{ "mediumint unsigned", SQL_INTEGER, 8, NULL, NULL, NULL,
1, 0, 3, 1, 0, 0, "Medium integer unsigned", 0, 0, 10,
#if MYSQL_VERSION_ID < MYSQL_VERSION_5_0
SQL_INTEGER, 0, 0, FIELD_TYPE_INT24, 1
#else
SQL_INTEGER, 0, 0, MYSQL_TYPE_INT24, 1
#endif
},
{ "smallint unsigned auto_increment", SQL_SMALLINT, 5, NULL, NULL, NULL,
0, 0, 3, 1, 0, 1, "smallint unsigned auto_increment", 0, 0, 10,
#if MYSQL_VERSION_ID < MYSQL_VERSION_5_0
SQL_SMALLINT, 0, 0, FIELD_TYPE_SHORT, 1
#else
SQL_SMALLINT, 0, 0, MYSQL_TYPE_SHORT, 1
#endif
},
{ "int auto_increment", SQL_INTEGER, 10, NULL, NULL, NULL,
0, 0, 3, 0, 0, 1, "integer auto_increment", 0, 0, 10,
#if MYSQL_VERSION_ID < MYSQL_VERSION_5_0
SQL_INTEGER, 0, 0, FIELD_TYPE_LONG, 1
#else
SQL_INTEGER, 0, 0, MYSQL_TYPE_LONG, 1
#endif
},
{ "long varbinary", SQL_LONGVARBINARY, 16777215, "0x", NULL, NULL,
1, 0, 3, 0, 0, 0, "mediumblob", 0, 0, 0,
#if MYSQL_VERSION_ID < MYSQL_VERSION_5_0
SQL_LONGVARBINARY, 0, 0, FIELD_TYPE_LONG_BLOB, 0
#else
SQL_LONGVARBINARY, 0, 0, MYSQL_TYPE_LONG_BLOB, 0
#endif
},
{ "double auto_increment", SQL_FLOAT, 15, NULL, NULL, NULL,
0, 0, 3, 0, 0, 1, "double auto_increment", 0, 4, 2,
#if MYSQL_VERSION_ID < MYSQL_VERSION_5_0
SQL_FLOAT, 0, 0, FIELD_TYPE_DOUBLE, 1
#else
SQL_FLOAT, 0, 0, MYSQL_TYPE_DOUBLE, 1
#endif
},
{ "double auto_increment", SQL_DOUBLE, 15, NULL, NULL, NULL,
0, 0, 3, 0, 0, 1, "double auto_increment", 0, 4, 10,
#if MYSQL_VERSION_ID < MYSQL_VERSION_5_0
SQL_DOUBLE, 0, 0, FIELD_TYPE_DOUBLE, 1
#else
SQL_DOUBLE, 0, 0, MYSQL_TYPE_DOUBLE, 1
#endif
},
{ "integer auto_increment", SQL_INTEGER, 10, NULL, NULL, NULL,
0, 0, 3, 0, 0, 1, "integer auto_increment", 0, 0, 10,
#if MYSQL_VERSION_ID < MYSQL_VERSION_5_0
SQL_INTEGER, 0, 0, FIELD_TYPE_LONG, 1,
#else
SQL_INTEGER, 0, 0, MYSQL_TYPE_LONG, 1,
#endif
},
{ "bigint auto_increment", SQL_BIGINT, 19, NULL, NULL, NULL,
0, 0, 3, 0, 0, 1, "bigint auto_increment", 0, 0, 10,
#if MYSQL_VERSION_ID < MYSQL_VERSION_5_0
SQL_BIGINT, 0, 0, FIELD_TYPE_LONGLONG, 1
#else
SQL_BIGINT, 0, 0, MYSQL_TYPE_LONGLONG, 1
#endif
},
{ "bit auto_increment", SQL_BIT, 1, NULL, NULL, NULL,
0, 0, 3, 0, 0, 1, "char(1) auto_increment", 0, 0, 0,
#if MYSQL_VERSION_ID < MYSQL_VERSION_5_0
SQL_BIT, 0, 0, FIELD_TYPE_TINY, 1
#else
SQL_BIT, 0, 0, MYSQL_TYPE_TINY, 1
#endif
},
{ "mediumint auto_increment", SQL_INTEGER, 7, NULL, NULL, NULL,
0, 0, 3, 0, 0, 1, "Medium integer auto_increment", 0, 0, 10,
#if MYSQL_VERSION_ID < MYSQL_VERSION_5_0
SQL_INTEGER, 0, 0, FIELD_TYPE_INT24, 1
#else
SQL_INTEGER, 0, 0, MYSQL_TYPE_INT24, 1
#endif
},
{ "float auto_increment", SQL_REAL, 7, NULL, NULL, NULL,
0, 0, 0, 0, 0, 1, "float auto_increment", 0, 2, 10,
#if MYSQL_VERSION_ID < MYSQL_VERSION_5_0
SQL_FLOAT, 0, 0, FIELD_TYPE_FLOAT, 1
#else
SQL_FLOAT, 0, 0, MYSQL_TYPE_FLOAT, 1
#endif
},
{ "long varchar", SQL_LONGVARCHAR, 16777215, "'", "'", NULL,
1, 0, 3, 0, 0, 0, "mediumtext", 0, 0, 0,
#if MYSQL_VERSION_ID < MYSQL_VERSION_5_0
SQL_LONGVARCHAR, 0, 0, FIELD_TYPE_MEDIUM_BLOB, 1
#else
SQL_LONGVARCHAR, 0, 0, MYSQL_TYPE_MEDIUM_BLOB, 1
#endif
},
{ "tinyint auto_increment", SQL_TINYINT, 3, NULL, NULL, NULL,
0, 0, 3, 0, 0, 1, "tinyint auto_increment", 0, 0, 10,
#if MYSQL_VERSION_ID < MYSQL_VERSION_5_0
SQL_TINYINT, 0, 0, FIELD_TYPE_TINY, 1
#else
SQL_TINYINT, 0, 0, MYSQL_TYPE_TINY, 1
#endif
},
{ "bigint unsigned auto_increment", SQL_BIGINT, 20, NULL, NULL, NULL,
0, 0, 3, 1, 0, 1, "bigint unsigned auto_increment", 0, 0, 10,
#if MYSQL_VERSION_ID < MYSQL_VERSION_5_0
SQL_BIGINT, 0, 0, FIELD_TYPE_LONGLONG, 1
#else
SQL_BIGINT, 0, 0, MYSQL_TYPE_LONGLONG, 1
#endif
},
/* END MORE STUFF */
};
/*
static const sql_type_info_t* native2sql (int t)
*/
static const sql_type_info_t *native2sql(int t)
{
switch (t) {
case FIELD_TYPE_VAR_STRING: return &SQL_GET_TYPE_INFO_values[0];
case FIELD_TYPE_DECIMAL: return &SQL_GET_TYPE_INFO_values[1];
#ifdef FIELD_TYPE_NEWDECIMAL
case FIELD_TYPE_NEWDECIMAL: return &SQL_GET_TYPE_INFO_values[1];
#endif
case FIELD_TYPE_TINY: return &SQL_GET_TYPE_INFO_values[2];
case FIELD_TYPE_SHORT: return &SQL_GET_TYPE_INFO_values[3];
case FIELD_TYPE_LONG: return &SQL_GET_TYPE_INFO_values[4];
case FIELD_TYPE_FLOAT: return &SQL_GET_TYPE_INFO_values[5];
/* 6 */
case FIELD_TYPE_DOUBLE: return &SQL_GET_TYPE_INFO_values[7];
case FIELD_TYPE_TIMESTAMP: return &SQL_GET_TYPE_INFO_values[8];
case FIELD_TYPE_LONGLONG: return &SQL_GET_TYPE_INFO_values[9];
case FIELD_TYPE_INT24: return &SQL_GET_TYPE_INFO_values[10];
case FIELD_TYPE_DATE: return &SQL_GET_TYPE_INFO_values[11];
case FIELD_TYPE_TIME: return &SQL_GET_TYPE_INFO_values[12];
case FIELD_TYPE_DATETIME: return &SQL_GET_TYPE_INFO_values[13];
case FIELD_TYPE_YEAR: return &SQL_GET_TYPE_INFO_values[14];
case FIELD_TYPE_NEWDATE: return &SQL_GET_TYPE_INFO_values[15];
case FIELD_TYPE_ENUM: return &SQL_GET_TYPE_INFO_values[16];
case FIELD_TYPE_SET: return &SQL_GET_TYPE_INFO_values[17];
case FIELD_TYPE_BLOB: return &SQL_GET_TYPE_INFO_values[18];
case FIELD_TYPE_TINY_BLOB: return &SQL_GET_TYPE_INFO_values[19];
case FIELD_TYPE_MEDIUM_BLOB: return &SQL_GET_TYPE_INFO_values[20];
case FIELD_TYPE_LONG_BLOB: return &SQL_GET_TYPE_INFO_values[21];
case FIELD_TYPE_STRING: return &SQL_GET_TYPE_INFO_values[22];
default: return &SQL_GET_TYPE_INFO_values[0];
}
}
#define SQL_GET_TYPE_INFO_num \
(sizeof(SQL_GET_TYPE_INFO_values)/sizeof(sql_type_info_t))
/***************************************************************************
*
* Name: dbd_init
*
* Purpose: Called when the driver is installed by DBI
*
* Input: dbistate - pointer to the DBI state variable, used for some
* DBI internal things
*
* Returns: Nothing
*
**************************************************************************/
void dbd_init(dbistate_t* dbistate)
{
dTHX;
DBISTATE_INIT;
}
/**************************************************************************
*
* Name: do_error, do_warn
*
* Purpose: Called to associate an error code and an error message
* to some handle
*
* Input: h - the handle in error condition
* rc - the error code
* what - the error message
*
* Returns: Nothing
*
**************************************************************************/
void do_error(SV* h, int rc, const char* what, const char* sqlstate)
{
dTHX;
D_imp_xxh(h);
STRLEN lna;
SV *errstr;
SV *errstate;
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh), "\t\t--> do_error\n");
errstr= DBIc_ERRSTR(imp_xxh);
sv_setiv(DBIc_ERR(imp_xxh), (IV)rc); /* set err early */
sv_setpv(errstr, what);
#if MYSQL_VERSION_ID >= SQL_STATE_VERSION
if (sqlstate)
{
errstate= DBIc_STATE(imp_xxh);
sv_setpvn(errstate, sqlstate, 5);
}
#endif
/* NO EFFECT DBIh_EVENT2(h, ERROR_event, DBIc_ERR(imp_xxh), errstr); */
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh), "%s error %d recorded: %s\n",
what, rc, SvPV(errstr,lna));
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh), "\t\t<-- do_error\n");
}
/*
void do_warn(SV* h, int rc, char* what)
*/
void do_warn(SV* h, int rc, char* what)
{
dTHX;
D_imp_xxh(h);
STRLEN lna;
SV *errstr = DBIc_ERRSTR(imp_xxh);
sv_setiv(DBIc_ERR(imp_xxh), (IV)rc); /* set err early */
sv_setpv(errstr, what);
/* NO EFFECT DBIh_EVENT2(h, WARN_event, DBIc_ERR(imp_xxh), errstr);*/
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh), "%s warning %d recorded: %s\n",
what, rc, SvPV(errstr,lna));
warn("%s", what);
}
#if defined(DBD_MYSQL_EMBEDDED)
#define DBD_MYSQL_NAMESPACE "DBD::mysqlEmb::QUIET";
#else
#define DBD_MYSQL_NAMESPACE "DBD::mysql::QUIET";
#endif
#define doquietwarn(s) \
{ \
SV* sv = perl_get_sv(DBD_MYSQL_NAMESPACE, FALSE); \
if (!sv || !SvTRUE(sv)) { \
warn s; \
} \
}
/***************************************************************************
*
* Name: mysql_dr_connect
*
* Purpose: Replacement for mysql_connect
*
* Input: MYSQL* sock - Pointer to a MYSQL structure being
* initialized
* char* mysql_socket - Name of a UNIX socket being used
* or NULL
* char* host - Host name being used or NULL for localhost
* char* port - Port number being used or NULL for default
* char* user - User name being used or NULL
* char* password - Password being used or NULL
* char* dbname - Database name being used or NULL
* char* imp_dbh - Pointer to internal dbh structure
*
* Returns: The sock argument for success, NULL otherwise;
* you have to call do_error in the latter case.
*
**************************************************************************/
MYSQL *mysql_dr_connect(
SV* dbh,
MYSQL* sock,
char* mysql_socket,
char* host,
char* port,
char* user,
char* password,
char* dbname,
imp_dbh_t *imp_dbh)
{
int portNr;
unsigned int client_flag;
MYSQL* result;
dTHX;
D_imp_xxh(dbh);
/* per Monty, already in client.c in API */
/* but still not exist in libmysqld.c */
#if defined(DBD_MYSQL_EMBEDDED)
if (host && !*host) host = NULL;
#endif
portNr= (port && *port) ? atoi(port) : 0;
/* already in client.c in API */
/* if (user && !*user) user = NULL; */
/* if (password && !*password) password = NULL; */
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh),
"imp_dbh->mysql_dr_connect: host = |%s|, port = %d," \
" uid = %s, pwd = %s\n",
host ? host : "NULL", portNr,
user ? user : "NULL",
password ? password : "NULL");
{
#if defined(DBD_MYSQL_EMBEDDED)
if (imp_dbh)
{
D_imp_drh_from_dbh;
SV* sv = DBIc_IMP_DATA(imp_dbh);
if (sv && SvROK(sv))
{
SV** svp;
STRLEN lna;
char * options;
int server_args_cnt= 0;
int server_groups_cnt= 0;
int rc= 0;
char ** server_args = NULL;
char ** server_groups = NULL;
HV* hv = (HV*) SvRV(sv);
if (SvTYPE(hv) != SVt_PVHV)
return NULL;
if (!imp_drh->embedded.state)
{
/* Init embedded server */
if ((svp = hv_fetch(hv, "mysql_embedded_groups", 21, FALSE)) &&
*svp && SvTRUE(*svp))
{
options = SvPV(*svp, lna);
imp_drh->embedded.groups=newSVsv(*svp);
if ((server_groups_cnt=count_embedded_options(options)))
{
/* number of server_groups always server_groups+1 */
server_groups=fill_out_embedded_options(DBIc_LOGPIO(imp_xxh), options, 0,
(int)lna, ++server_groups_cnt);
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
{
PerlIO_printf(DBIc_LOGPIO(imp_xxh),
"Groups names passed to embedded server:\n");
print_embedded_options(DBIc_LOGPIO(imp_xxh), server_groups, server_groups_cnt);
}
}
}
if ((svp = hv_fetch(hv, "mysql_embedded_options", 22, FALSE)) &&
*svp && SvTRUE(*svp))
{
options = SvPV(*svp, lna);
imp_drh->embedded.args=newSVsv(*svp);
if ((server_args_cnt=count_embedded_options(options)))
{
/* number of server_options always server_options+1 */
server_args=fill_out_embedded_options(DBIc_LOGPIO(imp_xxh), options, 1, (int)lna, ++server_args_cnt);
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
{
PerlIO_printf(DBIc_LOGPIO(imp_xxh), "Server options passed to embedded server:\n");
print_embedded_options(DBIc_LOGPIO(imp_xxh), server_args, server_args_cnt);
}
}
}
if (mysql_server_init(server_args_cnt, server_args, server_groups))
{
do_warn(dbh, AS_ERR_EMBEDDED, "Embedded server was not started. \
Could not initialize environment.");
return NULL;
}
imp_drh->embedded.state=1;
if (server_args_cnt)
free_embedded_options(server_args, server_args_cnt);
if (server_groups_cnt)
free_embedded_options(server_groups, server_groups_cnt);
}
else
{
/*
* Check if embedded parameters passed to connect() differ from
* first ones
*/
if ( ((svp = hv_fetch(hv, "mysql_embedded_groups", 21, FALSE)) &&
*svp && SvTRUE(*svp)))
rc =+ abs(sv_cmp(*svp, imp_drh->embedded.groups));
if ( ((svp = hv_fetch(hv, "mysql_embedded_options", 22, FALSE)) &&
*svp && SvTRUE(*svp)) )
rc =+ abs(sv_cmp(*svp, imp_drh->embedded.args));
if (rc)
{
do_warn(dbh, AS_ERR_EMBEDDED,
"Embedded server was already started. You cannot pass init\
parameters to embedded server once");
return NULL;
}
}
}
}
#endif
#ifdef MYSQL_NO_CLIENT_FOUND_ROWS
client_flag = 0;
#else
client_flag = CLIENT_FOUND_ROWS;
#endif
mysql_init(sock);
if (imp_dbh)
{
SV* sv = DBIc_IMP_DATA(imp_dbh);
DBIc_set(imp_dbh, DBIcf_AutoCommit, TRUE);
if (sv && SvROK(sv))
{
HV* hv = (HV*) SvRV(sv);
SV** svp;
STRLEN lna;
/* thanks to Peter John Edwards for mysql_init_command */
if ((svp = hv_fetch(hv, "mysql_init_command", 18, FALSE)) &&
*svp && SvTRUE(*svp))
{
char* df = SvPV(*svp, lna);
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh),
"imp_dbh->mysql_dr_connect: Setting" \
" init command (%s).\n", df);
mysql_options(sock, MYSQL_INIT_COMMAND, df);
}
if ((svp = hv_fetch(hv, "mysql_compression", 17, FALSE)) &&
*svp && SvTRUE(*svp))
{
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh),
"imp_dbh->mysql_dr_connect: Enabling" \
" compression.\n");
mysql_options(sock, MYSQL_OPT_COMPRESS, NULL);
}
if ((svp = hv_fetch(hv, "mysql_connect_timeout", 21, FALSE))
&& *svp && SvTRUE(*svp))
{
int to = SvIV(*svp);
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh),
"imp_dbh->mysql_dr_connect: Setting" \
" connect timeout (%d).\n",to);
mysql_options(sock, MYSQL_OPT_CONNECT_TIMEOUT,
(const char *)&to);
}
if ((svp = hv_fetch(hv, "mysql_write_timeout", 19, FALSE))
&& *svp && SvTRUE(*svp))
{
int to = SvIV(*svp);
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh),
"imp_dbh->mysql_dr_connect: Setting" \
" write timeout (%d).\n",to);
mysql_options(sock, MYSQL_OPT_WRITE_TIMEOUT,
(const char *)&to);
}
if ((svp = hv_fetch(hv, "mysql_read_timeout", 18, FALSE))
&& *svp && SvTRUE(*svp))
{
int to = SvIV(*svp);
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh),
"imp_dbh->mysql_dr_connect: Setting" \
" read timeout (%d).\n",to);
mysql_options(sock, MYSQL_OPT_READ_TIMEOUT,
(const char *)&to);
}
if ((svp = hv_fetch(hv, "mysql_skip_secure_auth", 22, FALSE)) &&
*svp && SvTRUE(*svp))
{
my_bool secauth = 0;
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh),
"imp_dbh->mysql_dr_connect: Skipping" \
" secure auth\n");
mysql_options(sock, MYSQL_SECURE_AUTH, &secauth);
}
if ((svp = hv_fetch(hv, "mysql_read_default_file", 23, FALSE)) &&
*svp && SvTRUE(*svp))
{
char* df = SvPV(*svp, lna);
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh),
"imp_dbh->mysql_dr_connect: Reading" \
" default file %s.\n", df);
mysql_options(sock, MYSQL_READ_DEFAULT_FILE, df);
}
if ((svp = hv_fetch(hv, "mysql_read_default_group", 24,
FALSE)) &&
*svp && SvTRUE(*svp)) {
char* gr = SvPV(*svp, lna);
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh),
"imp_dbh->mysql_dr_connect: Using" \
" default group %s.\n", gr);
mysql_options(sock, MYSQL_READ_DEFAULT_GROUP, gr);
}
#if (MYSQL_VERSION_ID >= 50606)
if ((svp = hv_fetch(hv, "mysql_conn_attrs", 16, FALSE)) && *svp) {
HV* attrs = (HV*) SvRV(*svp);
HE* entry = NULL;
I32 num_entries = hv_iterinit(attrs);
while (num_entries && (entry = hv_iternext(attrs))) {
I32 retlen = 0;
char *attr_name = hv_iterkey(entry, &retlen);
SV *sv_attr_val = hv_iterval(attrs, entry);
char *attr_val = SvPV(sv_attr_val, lna);
mysql_options4(sock, MYSQL_OPT_CONNECT_ATTR_ADD, attr_name, attr_val);
}
}
#endif
if ((svp = hv_fetch(hv, "mysql_client_found_rows", 23, FALSE)) && *svp)
{
if (SvTRUE(*svp))
client_flag |= CLIENT_FOUND_ROWS;
else
client_flag &= ~CLIENT_FOUND_ROWS;
}
if ((svp = hv_fetch(hv, "mysql_use_result", 16, FALSE)) && *svp)
{
imp_dbh->use_mysql_use_result = SvTRUE(*svp);
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh),
"imp_dbh->use_mysql_use_result: %d\n",
imp_dbh->use_mysql_use_result);
}
if ((svp = hv_fetch(hv, "mysql_bind_type_guessing", 24, TRUE)) && *svp)
{
imp_dbh->bind_type_guessing= SvTRUE(*svp);
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh),
"imp_dbh->bind_type_guessing: %d\n",
imp_dbh->bind_type_guessing);
}
if ((svp = hv_fetch(hv, "mysql_bind_comment_placeholders", 31, FALSE)) && *svp)
{
imp_dbh->bind_comment_placeholders = SvTRUE(*svp);
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh),
"imp_dbh->bind_comment_placeholders: %d\n",
imp_dbh->bind_comment_placeholders);
}
if ((svp = hv_fetch(hv, "mysql_no_autocommit_cmd", 23, FALSE)) && *svp)
{
imp_dbh->no_autocommit_cmd= SvTRUE(*svp);
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh),
"imp_dbh->no_autocommit_cmd: %d\n",
imp_dbh->no_autocommit_cmd);
}
#if FABRIC_SUPPORT
if ((svp = hv_fetch(hv, "mysql_use_fabric", 16, FALSE)) &&
*svp && SvTRUE(*svp))
{
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh),
"imp_dbh->use_fabric: Enabling use of" \
" MySQL Fabric.\n");
mysql_options(sock, MYSQL_OPT_USE_FABRIC, NULL);
}
#endif
#if defined(CLIENT_MULTI_STATEMENTS)
if ((svp = hv_fetch(hv, "mysql_multi_statements", 22, FALSE)) && *svp)
{
if (SvTRUE(*svp))
client_flag |= CLIENT_MULTI_STATEMENTS;
else
client_flag &= ~CLIENT_MULTI_STATEMENTS;
}
#endif
#if MYSQL_VERSION_ID >=SERVER_PREPARE_VERSION
/* took out client_flag |= CLIENT_PROTOCOL_41; */
/* because libmysql.c already sets this no matter what */
if ((svp = hv_fetch(hv, "mysql_server_prepare", 20, FALSE))
&& *svp)
{
if (SvTRUE(*svp))
{
client_flag |= CLIENT_PROTOCOL_41;
imp_dbh->use_server_side_prepare = TRUE;
}
else
{
client_flag &= ~CLIENT_PROTOCOL_41;
imp_dbh->use_server_side_prepare = FALSE;
}
}
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh),
"imp_dbh->use_server_side_prepare: %d\n",
imp_dbh->use_server_side_prepare);
#endif
/* HELMUT */
#if defined(sv_utf8_decode) && MYSQL_VERSION_ID >=SERVER_PREPARE_VERSION
if ((svp = hv_fetch(hv, "mysql_enable_utf8mb4", 20, FALSE)) && *svp && SvTRUE(*svp)) {
mysql_options(sock, MYSQL_SET_CHARSET_NAME, "utf8mb4");
}
else if ((svp = hv_fetch(hv, "mysql_enable_utf8", 17, FALSE)) && *svp) {
/* Do not touch imp_dbh->enable_utf8 as we are called earlier
* than it is set and mysql_options() must be before:
* mysql_real_connect()
*/
mysql_options(sock, MYSQL_SET_CHARSET_NAME,
(SvTRUE(*svp) ? "utf8" : "latin1"));
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh),
"mysql_options: MYSQL_SET_CHARSET_NAME=%s\n",
(SvTRUE(*svp) ? "utf8" : "latin1"));
}
#endif
#if defined(DBD_MYSQL_WITH_SSL) && !defined(DBD_MYSQL_EMBEDDED) && \
(defined(CLIENT_SSL) || (MYSQL_VERSION_ID >= 40000))
if ((svp = hv_fetch(hv, "mysql_ssl", 9, FALSE)) && *svp)
{
if (SvTRUE(*svp))
{
char *client_key = NULL;
char *client_cert = NULL;
char *ca_file = NULL;
char *ca_path = NULL;
char *cipher = NULL;
STRLEN lna;
#if MYSQL_VERSION_ID >= SSL_VERIFY_VERSION && MYSQL_VERSION_ID <= SSL_LAST_VERIFY_VERSION
/*
New code to utilise MySQLs new feature that verifies that the
server's hostname that the client connects to matches that of
the certificate
*/
my_bool ssl_verify_true = 0;
if ((svp = hv_fetch(hv, "mysql_ssl_verify_server_cert", 28, FALSE)) && *svp)
ssl_verify_true = SvTRUE(*svp);
#endif
if ((svp = hv_fetch(hv, "mysql_ssl_client_key", 20, FALSE)) && *svp)
client_key = SvPV(*svp, lna);
if ((svp = hv_fetch(hv, "mysql_ssl_client_cert", 21, FALSE)) &&
*svp)
client_cert = SvPV(*svp, lna);
if ((svp = hv_fetch(hv, "mysql_ssl_ca_file", 17, FALSE)) &&
*svp)
ca_file = SvPV(*svp, lna);
if ((svp = hv_fetch(hv, "mysql_ssl_ca_path", 17, FALSE)) &&
*svp)
ca_path = SvPV(*svp, lna);
if ((svp = hv_fetch(hv, "mysql_ssl_cipher", 16, FALSE)) &&
*svp)
cipher = SvPV(*svp, lna);
mysql_ssl_set(sock, client_key, client_cert, ca_file,
ca_path, cipher);
#if MYSQL_VERSION_ID >= SSL_VERIFY_VERSION && MYSQL_VERSION_ID <= SSL_LAST_VERIFY_VERSION
mysql_options(sock, MYSQL_OPT_SSL_VERIFY_SERVER_CERT, &ssl_verify_true);
#endif
client_flag |= CLIENT_SSL;
}
}
#endif
#if (MYSQL_VERSION_ID >= 32349)
/*
* MySQL 3.23.49 disables LOAD DATA LOCAL by default. Use
* mysql_local_infile=1 in the DSN to enable it.
*/
if ((svp = hv_fetch( hv, "mysql_local_infile", 18, FALSE)) && *svp)
{
unsigned int flag = SvTRUE(*svp);
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh),
"imp_dbh->mysql_dr_connect: Using" \
" local infile %u.\n", flag);
mysql_options(sock, MYSQL_OPT_LOCAL_INFILE, (const char *) &flag);
}
#endif
}
}
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh), "imp_dbh->mysql_dr_connect: client_flags = %d\n",
client_flag);
#if MYSQL_VERSION_ID >= MULTIPLE_RESULT_SET_VERSION
client_flag|= CLIENT_MULTI_RESULTS;
#endif
result = mysql_real_connect(sock, host, user, password, dbname,
portNr, mysql_socket, client_flag);
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh), "imp_dbh->mysql_dr_connect: <-");
if (result)
{
#if MYSQL_VERSION_ID >=SERVER_PREPARE_VERSION
/* connection succeeded. */
/* imp_dbh == NULL when mysql_dr_connect() is called from mysql.xs
functions (_admin_internal(),_ListDBs()). */
if (!(result->client_flag & CLIENT_PROTOCOL_41) && imp_dbh)
imp_dbh->use_server_side_prepare = FALSE;
#endif
#if MYSQL_ASYNC
if(imp_dbh) {
imp_dbh->async_query_in_flight = NULL;
}
#endif
/*
we turn off Mysql's auto reconnect and handle re-connecting ourselves
so that we can keep track of when this happens.
*/
result->reconnect=0;
}
else {
/*
sock was allocated with mysql_init()
fixes: https://rt.cpan.org/Ticket/Display.html?id=86153
Safefree(sock);
rurban: No, we still need this handle later in mysql_dr_error().
RT #97625. It will be freed as imp_dbh->pmysql in dbd_db_destroy(),
which is called by the DESTROY handler.
*/
}
return result;
}
}
/*
safe_hv_fetch
*/
static char *safe_hv_fetch(pTHX_ HV *hv, const char *name, int name_length)
{
SV** svp;
STRLEN len;
char *res= NULL;
if ((svp= hv_fetch(hv, name, name_length, FALSE)))
{
res= SvPV(*svp, len);
if (!len)
res= NULL;
}
return res;
}
/*
Frontend for mysql_dr_connect
*/
static int my_login(pTHX_ SV* dbh, imp_dbh_t *imp_dbh)
{
SV* sv;
HV* hv;
char* dbname;
char* host;
char* port;
char* user;
char* password;
char* mysql_socket;
int result;
D_imp_xxh(dbh);
/* TODO- resolve this so that it is set only if DBI is 1.607 */
#define TAKE_IMP_DATA_VERSION 1
#if TAKE_IMP_DATA_VERSION
if (DBIc_has(imp_dbh, DBIcf_IMPSET))
{ /* eg from take_imp_data() */
if (DBIc_has(imp_dbh, DBIcf_ACTIVE))
{
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh), "my_login skip connect\n");
/* tell our parent we've adopted an active child */
++DBIc_ACTIVE_KIDS(DBIc_PARENT_COM(imp_dbh));
return TRUE;
}
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh),
"my_login IMPSET but not ACTIVE so connect not skipped\n");
}
#endif
sv = DBIc_IMP_DATA(imp_dbh);
if (!sv || !SvROK(sv))
return FALSE;
hv = (HV*) SvRV(sv);
if (SvTYPE(hv) != SVt_PVHV)
return FALSE;
host= safe_hv_fetch(aTHX_ hv, "host", 4);
port= safe_hv_fetch(aTHX_ hv, "port", 4);
user= safe_hv_fetch(aTHX_ hv, "user", 4);
password= safe_hv_fetch(aTHX_ hv, "password", 8);
dbname= safe_hv_fetch(aTHX_ hv, "database", 8);
mysql_socket= safe_hv_fetch(aTHX_ hv, "mysql_socket", 12);
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh),
"imp_dbh->my_login : dbname = %s, uid = %s, pwd = %s," \
"host = %s, port = %s\n",
dbname ? dbname : "NULL",
user ? user : "NULL",
password ? password : "NULL",
host ? host : "NULL",
port ? port : "NULL");
if (!imp_dbh->pmysql) {
Newz(908, imp_dbh->pmysql, 1, MYSQL);
}
result = mysql_dr_connect(dbh, imp_dbh->pmysql, mysql_socket, host, port, user,
password, dbname, imp_dbh) ? TRUE : FALSE;
return result;
}
/**************************************************************************
*
* Name: dbd_db_login
*
* Purpose: Called for connecting to a database and logging in.
*
* Input: dbh - database handle being initialized
* imp_dbh - drivers private database handle data
* dbname - the database we want to log into; may be like
* "dbname:host" or "dbname:host:port"
* user - user name to connect as
* password - password to connect with
*
* Returns: TRUE for success, FALSE otherwise; do_error has already
* been called in the latter case
*
**************************************************************************/
int dbd_db_login(SV* dbh, imp_dbh_t* imp_dbh, char* dbname, char* user,
char* password) {
#ifdef dTHR
dTHR;
#endif
dTHX;
D_imp_xxh(dbh);
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh),
"imp_dbh->connect: dsn = %s, uid = %s, pwd = %s\n",
dbname ? dbname : "NULL",
user ? user : "NULL",
password ? password : "NULL");
imp_dbh->stats.auto_reconnects_ok= 0;
imp_dbh->stats.auto_reconnects_failed= 0;
imp_dbh->bind_type_guessing= FALSE;
imp_dbh->bind_comment_placeholders= FALSE;
imp_dbh->has_transactions= TRUE;
/* Safer we flip this to TRUE perl side if we detect a mod_perl env. */
imp_dbh->auto_reconnect = FALSE;
/* HELMUT */
#if defined(sv_utf8_decode) && MYSQL_VERSION_ID >=SERVER_PREPARE_VERSION
imp_dbh->enable_utf8 = FALSE; /* initialize mysql_enable_utf8 */
imp_dbh->enable_utf8mb4 = FALSE; /* initialize mysql_enable_utf8mb4 */
#endif
if (!my_login(aTHX_ dbh, imp_dbh))
{
if(imp_dbh->pmysql) {
do_error(dbh, mysql_errno(imp_dbh->pmysql),
mysql_error(imp_dbh->pmysql) ,mysql_sqlstate(imp_dbh->pmysql));
Safefree(imp_dbh->pmysql);
}
return FALSE;
}
/*
* Tell DBI, that dbh->disconnect should be called for this handle
*/
DBIc_ACTIVE_on(imp_dbh);
/* Tell DBI, that dbh->destroy should be called for this handle */
DBIc_on(imp_dbh, DBIcf_IMPSET);
return TRUE;
}
/***************************************************************************
*
* Name: dbd_db_commit
* dbd_db_rollback
*
* Purpose: You guess what they should do.
*
* Input: dbh - database handle being committed or rolled back
* imp_dbh - drivers private database handle data
*
* Returns: TRUE for success, FALSE otherwise; do_error has already
* been called in the latter case
*
**************************************************************************/
int
dbd_db_commit(SV* dbh, imp_dbh_t* imp_dbh)
{
if (DBIc_has(imp_dbh, DBIcf_AutoCommit))
return FALSE;
ASYNC_CHECK_RETURN(dbh, FALSE);
if (imp_dbh->has_transactions)
{
#if MYSQL_VERSION_ID < SERVER_PREPARE_VERSION
if (mysql_real_query(imp_dbh->pmysql, "COMMIT", 6))
#else
if (mysql_commit(imp_dbh->pmysql))
#endif
{
do_error(dbh, mysql_errno(imp_dbh->pmysql), mysql_error(imp_dbh->pmysql)
,mysql_sqlstate(imp_dbh->pmysql));
return FALSE;
}
}
else
do_warn(dbh, JW_ERR_NOT_IMPLEMENTED,
"Commit ineffective because transactions are not available");
return TRUE;
}
/*
dbd_db_rollback
*/
int
dbd_db_rollback(SV* dbh, imp_dbh_t* imp_dbh) {
/* croak, if not in AutoCommit mode */
if (DBIc_has(imp_dbh, DBIcf_AutoCommit))
return FALSE;
ASYNC_CHECK_RETURN(dbh, FALSE);
if (imp_dbh->has_transactions)
{
#if MYSQL_VERSION_ID < SERVER_PREPARE_VERSION
if (mysql_real_query(imp_dbh->pmysql, "ROLLBACK", 8))
#else
if (mysql_rollback(imp_dbh->pmysql))
#endif
{
do_error(dbh, mysql_errno(imp_dbh->pmysql),
mysql_error(imp_dbh->pmysql) ,mysql_sqlstate(imp_dbh->pmysql));
return FALSE;
}
}
else
do_error(dbh, JW_ERR_NOT_IMPLEMENTED,
"Rollback ineffective because transactions are not available" ,NULL);
return TRUE;
}
/*
***************************************************************************
*
* Name: dbd_db_disconnect
*
* Purpose: Disconnect a database handle from its database
*
* Input: dbh - database handle being disconnected
* imp_dbh - drivers private database handle data
*
* Returns: TRUE for success, FALSE otherwise; do_error has already
* been called in the latter case
*
**************************************************************************/
int dbd_db_disconnect(SV* dbh, imp_dbh_t* imp_dbh)
{
#ifdef dTHR
dTHR;
#endif
dTHX;
D_imp_xxh(dbh);
/* We assume that disconnect will always work */
/* since most errors imply already disconnected. */
DBIc_ACTIVE_off(imp_dbh);
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh), "imp_dbh->pmysql: %p\n",
imp_dbh->pmysql);
mysql_close(imp_dbh->pmysql );
/* We don't free imp_dbh since a reference still exists */
/* The DESTROY method is the only one to 'free' memory. */
return TRUE;
}
/***************************************************************************
*
* Name: dbd_discon_all
*
* Purpose: Disconnect all database handles at shutdown time
*
* Input: dbh - database handle being disconnected
* imp_dbh - drivers private database handle data
*
* Returns: TRUE for success, FALSE otherwise; do_error has already
* been called in the latter case
*
**************************************************************************/
int dbd_discon_all (SV *drh, imp_drh_t *imp_drh) {
#if defined(dTHR)
dTHR;
#endif
dTHX;
D_imp_xxh(drh);
#if defined(DBD_MYSQL_EMBEDDED)
if (imp_drh->embedded.state)
{
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh), "Stop embedded server\n");
mysql_server_end();
if (imp_drh->embedded.groups)
{
(void) SvREFCNT_dec(imp_drh->embedded.groups);
imp_drh->embedded.groups = NULL;
}
if (imp_drh->embedded.args)
{
(void) SvREFCNT_dec(imp_drh->embedded.args);
imp_drh->embedded.args = NULL;
}
}
#else
mysql_server_end();
#endif
/* The disconnect_all concept is flawed and needs more work */
if (!PL_dirty && !SvTRUE(perl_get_sv("DBI::PERL_ENDING",0))) {
sv_setiv(DBIc_ERR(imp_drh), (IV)1);
sv_setpv(DBIc_ERRSTR(imp_drh),
(char*)"disconnect_all not implemented");
/* NO EFFECT DBIh_EVENT2(drh, ERROR_event,
DBIc_ERR(imp_drh), DBIc_ERRSTR(imp_drh)); */
return FALSE;
}
PL_perl_destruct_level = 0;
return FALSE;
}
/****************************************************************************
*
* Name: dbd_db_destroy
*
* Purpose: Our part of the dbh destructor
*
* Input: dbh - database handle being destroyed
* imp_dbh - drivers private database handle data
*
* Returns: Nothing
*
**************************************************************************/
void dbd_db_destroy(SV* dbh, imp_dbh_t* imp_dbh) {
/*
* Being on the safe side never hurts ...
*/
if (DBIc_ACTIVE(imp_dbh))
{
if (imp_dbh->has_transactions)
{
if (!DBIc_has(imp_dbh, DBIcf_AutoCommit))
#if MYSQL_VERSION_ID < SERVER_PREPARE_VERSION
if ( mysql_real_query(imp_dbh->pmysql, "ROLLBACK", 8))
#else
if (mysql_rollback(imp_dbh->pmysql))
#endif
do_error(dbh, TX_ERR_ROLLBACK,"ROLLBACK failed" ,NULL);
}
dbd_db_disconnect(dbh, imp_dbh);
}
Safefree(imp_dbh->pmysql);
/* Tell DBI, that dbh->destroy must no longer be called */
DBIc_off(imp_dbh, DBIcf_IMPSET);
}
/*
***************************************************************************
*
* Name: dbd_db_STORE_attrib
*
* Purpose: Function for storing dbh attributes; we currently support
* just nothing. :-)
*
* Input: dbh - database handle being modified
* imp_dbh - drivers private database handle data
* keysv - the attribute name
* valuesv - the attribute value
*
* Returns: TRUE for success, FALSE otherwise
*
**************************************************************************/
int
dbd_db_STORE_attrib(
SV* dbh,
imp_dbh_t* imp_dbh,
SV* keysv,
SV* valuesv
)
{
dTHX;
STRLEN kl;
char *key = SvPV(keysv, kl);
SV *cachesv = Nullsv;
int cacheit = FALSE;
const bool bool_value = SvTRUE(valuesv);
if (kl==10 && strEQ(key, "AutoCommit"))
{
if (imp_dbh->has_transactions)
{
bool oldval = DBIc_has(imp_dbh,DBIcf_AutoCommit) ? 1 : 0;
if (bool_value == oldval)
return TRUE;
/* if setting AutoCommit on ... */
if (!imp_dbh->no_autocommit_cmd)
{
if (
#if MYSQL_VERSION_ID >=SERVER_PREPARE_VERSION
mysql_autocommit(imp_dbh->pmysql, bool_value)
#else
mysql_real_query(imp_dbh->pmysql,
bool_value ? "SET AUTOCOMMIT=1" : "SET AUTOCOMMIT=0",
16)
#endif
)
{
do_error(dbh, TX_ERR_AUTOCOMMIT,
bool_value ?
"Turning on AutoCommit failed" :
"Turning off AutoCommit failed"
,NULL);
return TRUE; /* TRUE means we handled it - important to avoid spurious errors */
}
}
DBIc_set(imp_dbh, DBIcf_AutoCommit, bool_value);
}
else
{
/*
* We do support neither transactions nor "AutoCommit".
* But we stub it. :-)
*/
if (!bool_value)
{
do_error(dbh, JW_ERR_NOT_IMPLEMENTED,
"Transactions not supported by database" ,NULL);
croak("Transactions not supported by database");
}
}
}
else if (kl == 16 && strEQ(key,"mysql_use_result"))
imp_dbh->use_mysql_use_result = bool_value;
else if (kl == 20 && strEQ(key,"mysql_auto_reconnect"))
imp_dbh->auto_reconnect = bool_value;
else if (kl == 20 && strEQ(key, "mysql_server_prepare"))
imp_dbh->use_server_side_prepare = bool_value;
else if (kl == 23 && strEQ(key,"mysql_no_autocommit_cmd"))
imp_dbh->no_autocommit_cmd = bool_value;
else if (kl == 24 && strEQ(key,"mysql_bind_type_guessing"))
imp_dbh->bind_type_guessing = bool_value;
else if (kl == 31 && strEQ(key,"mysql_bind_comment_placeholders"))
imp_dbh->bind_type_guessing = bool_value;
#if defined(sv_utf8_decode) && MYSQL_VERSION_ID >=SERVER_PREPARE_VERSION
else if (kl == 17 && strEQ(key, "mysql_enable_utf8"))
imp_dbh->enable_utf8 = bool_value;
else if (kl == 20 && strEQ(key, "mysql_enable_utf8mb4"))
imp_dbh->enable_utf8mb4 = bool_value;
#endif
#if FABRIC_SUPPORT
else if (kl == 22 && strEQ(key, "mysql_fabric_opt_group"))
mysql_options(imp_dbh->pmysql, FABRIC_OPT_GROUP, (void *)SvPVbyte_nolen(valuesv));
else if (kl == 29 && strEQ(key, "mysql_fabric_opt_default_mode"))
{
if (SvOK(valuesv)) {
STRLEN len;
const char *str = SvPVbyte(valuesv, len);
if ( len == 0 || ( len == 2 && (strnEQ(str, "ro", 3) || strnEQ(str, "rw", 3)) ) )
mysql_options(imp_dbh->pmysql, FABRIC_OPT_DEFAULT_MODE, len == 0 ? NULL : str);
else
croak("Valid settings for FABRIC_OPT_DEFAULT_MODE are 'ro', 'rw', or undef/empty string");
}
else {
mysql_options(imp_dbh->pmysql, FABRIC_OPT_DEFAULT_MODE, NULL);
}
}
else if (kl == 21 && strEQ(key, "mysql_fabric_opt_mode"))
{
STRLEN len;
const char *str = SvPVbyte(valuesv, len);
if (len != 2 || (strnNE(str, "ro", 3) && strnNE(str, "rw", 3)))
croak("Valid settings for FABRIC_OPT_MODE are 'ro' or 'rw'");
mysql_options(imp_dbh->pmysql, FABRIC_OPT_MODE, str);
}
else if (kl == 34 && strEQ(key, "mysql_fabric_opt_group_credentials"))
{
croak("'fabric_opt_group_credentials' is not supported");
}
#endif
else
return FALSE; /* Unknown key */
if (cacheit) /* cache value for later DBI 'quick' fetch? */
(void)hv_store((HV*)SvRV(dbh), key, kl, cachesv, 0);
return TRUE;
}
/***************************************************************************
*
* Name: dbd_db_FETCH_attrib
*
* Purpose: Function for fetching dbh attributes
*
* Input: dbh - database handle being queried
* imp_dbh - drivers private database handle data
* keysv - the attribute name
*
* Returns: An SV*, if successful; NULL otherwise
*
* Notes: Do not forget to call sv_2mortal in the former case!
*
**************************************************************************/
static SV*
my_ulonglong2str(pTHX_ my_ulonglong val)
{
char buf[64];
char *ptr = buf + sizeof(buf) - 1;
if (val == 0)
return newSVpvn("0", 1);
*ptr = '\0';
while (val > 0)
{
*(--ptr) = ('0' + (val % 10));
val = val / 10;
}
return newSVpvn(ptr, (buf+ sizeof(buf) - 1) - ptr);
}
SV* dbd_db_FETCH_attrib(SV *dbh, imp_dbh_t *imp_dbh, SV *keysv)
{
dTHX;
STRLEN kl;
char *key = SvPV(keysv, kl);
SV* result = NULL;
dbh= dbh;
switch (*key) {
case 'A':
if (strEQ(key, "AutoCommit"))
{
if (imp_dbh->has_transactions)
return sv_2mortal(boolSV(DBIc_has(imp_dbh,DBIcf_AutoCommit)));
/* Default */
return &PL_sv_yes;
}
break;
}
if (strncmp(key, "mysql_", 6) == 0) {
key = key+6;
kl = kl-6;
}
/* MONTY: Check if kl should not be used or used everywhere */
switch(*key) {
case 'a':
if (kl == strlen("auto_reconnect") && strEQ(key, "auto_reconnect"))
result= sv_2mortal(newSViv(imp_dbh->auto_reconnect));
break;
case 'b':
if (kl == strlen("bind_type_guessing") &&
strEQ(key, "bind_type_guessing"))
{
result = sv_2mortal(newSViv(imp_dbh->bind_type_guessing));
}
else if (kl == strlen("bind_comment_placeholders") &&
strEQ(key, "bind_comment_placeholders"))
{
result = sv_2mortal(newSViv(imp_dbh->bind_comment_placeholders));
}
break;
case 'c':
if (kl == 10 && strEQ(key, "clientinfo"))
{
const char* clientinfo = mysql_get_client_info();
result= clientinfo ?
sv_2mortal(newSVpvn(clientinfo, strlen(clientinfo))) : &PL_sv_undef;
}
else if (kl == 13 && strEQ(key, "clientversion"))
{
result= sv_2mortal(my_ulonglong2str(aTHX_ mysql_get_client_version()));
}
break;
case 'e':
if (strEQ(key, "errno"))
result= sv_2mortal(newSViv((IV)mysql_errno(imp_dbh->pmysql)));
else if ( strEQ(key, "error") || strEQ(key, "errmsg"))
{
/* Note that errmsg is obsolete, as of 2.09! */
const char* msg = mysql_error(imp_dbh->pmysql);
result= sv_2mortal(newSVpvn(msg, strlen(msg)));
}
/* HELMUT */
#if defined(sv_utf8_decode) && MYSQL_VERSION_ID >=SERVER_PREPARE_VERSION
else if (kl == strlen("enable_utf8mb4") && strEQ(key, "enable_utf8mb4"))
result = sv_2mortal(newSViv(imp_dbh->enable_utf8mb4));
else if (kl == strlen("enable_utf8") && strEQ(key, "enable_utf8"))
result = sv_2mortal(newSViv(imp_dbh->enable_utf8));
#endif
break;
case 'd':
if (strEQ(key, "dbd_stats"))
{
HV* hv = newHV();
(void)hv_store(
hv,
"auto_reconnects_ok",
strlen("auto_reconnects_ok"),
newSViv(imp_dbh->stats.auto_reconnects_ok),
0
);
(void)hv_store(
hv,
"auto_reconnects_failed",
strlen("auto_reconnects_failed"),
newSViv(imp_dbh->stats.auto_reconnects_failed),
0
);
result= sv_2mortal((newRV_noinc((SV*)hv)));
}
case 'h':
if (strEQ(key, "hostinfo"))
{
const char* hostinfo = mysql_get_host_info(imp_dbh->pmysql);
result= hostinfo ?
sv_2mortal(newSVpvn(hostinfo, strlen(hostinfo))) : &PL_sv_undef;
}
break;
case 'i':
if (strEQ(key, "info"))
{
const char* info = mysql_info(imp_dbh->pmysql);
result= info ? sv_2mortal(newSVpvn(info, strlen(info))) : &PL_sv_undef;
}
else if (kl == 8 && strEQ(key, "insertid"))
/* We cannot return an IV, because the insertid is a long. */
result= sv_2mortal(my_ulonglong2str(aTHX_ mysql_insert_id(imp_dbh->pmysql)));
break;
case 'n':
if (kl == strlen("no_autocommit_cmd") &&
strEQ(key, "no_autocommit_cmd"))
result = sv_2mortal(newSViv(imp_dbh->no_autocommit_cmd));
break;
case 'p':
if (kl == 9 && strEQ(key, "protoinfo"))
result= sv_2mortal(newSViv(mysql_get_proto_info(imp_dbh->pmysql)));
break;
case 's':
if (kl == 10 && strEQ(key, "serverinfo")) {
const char* serverinfo = mysql_get_server_info(imp_dbh->pmysql);
result= serverinfo ?
sv_2mortal(newSVpvn(serverinfo, strlen(serverinfo))) : &PL_sv_undef;
}
else if (kl == 13 && strEQ(key, "serverversion"))
result= sv_2mortal(my_ulonglong2str(aTHX_ mysql_get_server_version(imp_dbh->pmysql)));
else if (strEQ(key, "sock"))
result= sv_2mortal(newSViv(PTR2IV(imp_dbh->pmysql)));
else if (strEQ(key, "sockfd"))
result= sv_2mortal(newSViv((IV) imp_dbh->pmysql->net.fd));
else if (strEQ(key, "stat"))
{
const char* stats = mysql_stat(imp_dbh->pmysql);
result= stats ?
sv_2mortal(newSVpvn(stats, strlen(stats))) : &PL_sv_undef;
}
else if (strEQ(key, "stats"))
{
/* Obsolete, as of 2.09 */
const char* stats = mysql_stat(imp_dbh->pmysql);
result= stats ?
sv_2mortal(newSVpvn(stats, strlen(stats))) : &PL_sv_undef;
}
else if (kl == 14 && strEQ(key,"server_prepare"))
result= sv_2mortal(newSViv((IV) imp_dbh->use_server_side_prepare));
break;
case 't':
if (kl == 9 && strEQ(key, "thread_id"))
result= sv_2mortal(newSViv(mysql_thread_id(imp_dbh->pmysql)));
break;
case 'w':
if (kl == 13 && strEQ(key, "warning_count"))
result= sv_2mortal(newSViv(mysql_warning_count(imp_dbh->pmysql)));
break;
case 'u':
if (strEQ(key, "use_result"))
{
result= sv_2mortal(newSViv((IV) imp_dbh->use_mysql_use_result));
}
break;
}
if (result== NULL)
return Nullsv;
return result;
}
/*
**************************************************************************
*
* Name: dbd_st_prepare
*
* Purpose: Called for preparing an SQL statement; our part of the
* statement handle constructor
*
* Input: sth - statement handle being initialized
* imp_sth - drivers private statement handle data
* statement - pointer to string with SQL statement
* attribs - statement attributes, currently not in use
*
* Returns: TRUE for success, FALSE otherwise; do_error will
* be called in the latter case
*
**************************************************************************/
int
dbd_st_prepare(
SV *sth,
imp_sth_t *imp_sth,
char *statement,
SV *attribs)
{
int i;
SV **svp;
dTHX;
#if MYSQL_VERSION_ID >= SERVER_PREPARE_VERSION
#if MYSQL_VERSION_ID < CALL_PLACEHOLDER_VERSION
char *str_ptr, *str_last_ptr;
#if MYSQL_VERSION_ID < LIMIT_PLACEHOLDER_VERSION
int limit_flag=0;
#endif
#endif
int col_type, prepare_retval;
MYSQL_BIND *bind, *bind_end;
imp_sth_phb_t *fbind;
#endif
D_imp_xxh(sth);
D_imp_dbh_from_sth;
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh),
"\t-> dbd_st_prepare MYSQL_VERSION_ID %d, SQL statement: %s\n",
MYSQL_VERSION_ID, statement);
#if MYSQL_VERSION_ID >= SERVER_PREPARE_VERSION
/* Set default value of 'mysql_server_prepare' attribute for sth from dbh */
imp_sth->use_server_side_prepare= imp_dbh->use_server_side_prepare;
if (attribs)
{
svp= DBD_ATTRIB_GET_SVP(attribs, "mysql_server_prepare", 20);
imp_sth->use_server_side_prepare = (svp) ?
SvTRUE(*svp) : imp_dbh->use_server_side_prepare;
svp = DBD_ATTRIB_GET_SVP(attribs, "async", 5);
if(svp && SvTRUE(*svp)) {
#if MYSQL_ASYNC
imp_sth->is_async = TRUE;
imp_sth->use_server_side_prepare = FALSE;
#else
do_error(sth, 2000,
"Async support was not built into this version of DBD::mysql", "HY000");
return 0;
#endif
}
}
imp_sth->fetch_done= 0;
#endif
imp_sth->done_desc= 0;
imp_sth->result= NULL;
imp_sth->currow= 0;
/* Set default value of 'mysql_use_result' attribute for sth from dbh */
svp= DBD_ATTRIB_GET_SVP(attribs, "mysql_use_result", 16);
imp_sth->use_mysql_use_result= svp ?
SvTRUE(*svp) : imp_dbh->use_mysql_use_result;
for (i= 0; i < AV_ATTRIB_LAST; i++)
imp_sth->av_attr[i]= Nullav;
/*
Clean-up previous result set(s) for sth to prevent
'Commands out of sync' error
*/
mysql_st_free_result_sets(sth, imp_sth);
#if MYSQL_VERSION_ID >= SERVER_PREPARE_VERSION && MYSQL_VERSION_ID < CALL_PLACEHOLDER_VERSION
if (imp_sth->use_server_side_prepare)
{
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh),
"\t\tuse_server_side_prepare set, check restrictions\n");
/*
This code is here because placeholder support is not implemented for
statements with :-
1. LIMIT < 5.0.7
2. CALL < 5.5.3 (Added support for out & inout parameters)
In these cases we have to disable server side prepared statements
NOTE: These checks could cause a false positive on statements which
include columns / table names that match "call " or " limit "
*/
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh),
#if MYSQL_VERSION_ID < LIMIT_PLACEHOLDER_VERSION
"\t\tneed to test for LIMIT & CALL\n");
#else
"\t\tneed to test for restrictions\n");
#endif
str_last_ptr = statement + strlen(statement);
for (str_ptr= statement; str_ptr < str_last_ptr; str_ptr++)
{
#if MYSQL_VERSION_ID < LIMIT_PLACEHOLDER_VERSION
/*
Place holders not supported in LIMIT's
*/
if (limit_flag)
{
if (*str_ptr == '?')
{
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh),
"\t\tLIMIT and ? found, set to use_server_side_prepare=0\n");
/* ... then we do not want to try server side prepare (use emulation) */
imp_sth->use_server_side_prepare= 0;
break;
}
}
else if (str_ptr < str_last_ptr - 6 &&
isspace(*(str_ptr + 0)) &&
tolower(*(str_ptr + 1)) == 'l' &&
tolower(*(str_ptr + 2)) == 'i' &&
tolower(*(str_ptr + 3)) == 'm' &&
tolower(*(str_ptr + 4)) == 'i' &&
tolower(*(str_ptr + 5)) == 't' &&
isspace(*(str_ptr + 6)))
{
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh), "LIMIT set limit flag to 1\n");
limit_flag= 1;
}
#endif
/*
Place holders not supported in CALL's
*/
if (str_ptr < str_last_ptr - 4 &&
tolower(*(str_ptr + 0)) == 'c' &&
tolower(*(str_ptr + 1)) == 'a' &&
tolower(*(str_ptr + 2)) == 'l' &&
tolower(*(str_ptr + 3)) == 'l' &&
isspace(*(str_ptr + 4)))
{
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh), "Disable PS mode for CALL()\n");
imp_sth->use_server_side_prepare= 0;
break;
}
}
}
#endif
#if MYSQL_VERSION_ID >= SERVER_PREPARE_VERSION
if (imp_sth->use_server_side_prepare)
{
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh),
"\t\tuse_server_side_prepare set\n");
/* do we really need this? If we do, we should return, not just continue */
if (imp_sth->stmt)
fprintf(stderr,
"ERROR: Trying to prepare new stmt while we have \
already not closed one \n");
imp_sth->stmt= mysql_stmt_init(imp_dbh->pmysql);
if (! imp_sth->stmt)
{
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh),
"\t\tERROR: Unable to return MYSQL_STMT structure \
from mysql_stmt_init(): ERROR NO: %d ERROR MSG:%s\n",
mysql_errno(imp_dbh->pmysql),
mysql_error(imp_dbh->pmysql));
}
prepare_retval= mysql_stmt_prepare(imp_sth->stmt,
statement,
strlen(statement));
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh),
"\t\tmysql_stmt_prepare returned %d\n",
prepare_retval);
if (prepare_retval)
{
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh),
"\t\tmysql_stmt_prepare %d %s\n",
mysql_stmt_errno(imp_sth->stmt),
mysql_stmt_error(imp_sth->stmt));
/* For commands that are not supported by server side prepared statement
mechanism lets try to pass them through regular API */
if (mysql_stmt_errno(imp_sth->stmt) == ER_UNSUPPORTED_PS)
{
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh),
"\t\tSETTING imp_sth->use_server_side_prepare to 0\n");
imp_sth->use_server_side_prepare= 0;
}
else
{
do_error(sth, mysql_stmt_errno(imp_sth->stmt),
mysql_stmt_error(imp_sth->stmt),
mysql_sqlstate(imp_dbh->pmysql));
mysql_stmt_close(imp_sth->stmt);
imp_sth->stmt= NULL;
return FALSE;
}
}
else
{
DBIc_NUM_PARAMS(imp_sth)= mysql_stmt_param_count(imp_sth->stmt);
/* mysql_stmt_param_count */
if (DBIc_NUM_PARAMS(imp_sth) > 0)
{
int has_statement_fields= imp_sth->stmt->fields != 0;
/* Allocate memory for bind variables */
imp_sth->bind= alloc_bind(DBIc_NUM_PARAMS(imp_sth));
imp_sth->fbind= alloc_fbind(DBIc_NUM_PARAMS(imp_sth));
imp_sth->has_been_bound= 0;
/* Initialize ph variables with NULL values */
for (i= 0,
bind= imp_sth->bind,
fbind= imp_sth->fbind,
bind_end= bind+DBIc_NUM_PARAMS(imp_sth);
bind < bind_end ;
bind++, fbind++, i++ )
{
/*
if this statement has a result set, field types will be
correctly identified. If there is no result set, such as
with an INSERT, fields will not be defined, and all buffer_type
will default to MYSQL_TYPE_VAR_STRING
*/
col_type= (has_statement_fields ?
imp_sth->stmt->fields[i].type : MYSQL_TYPE_STRING);
bind->buffer_type= mysql_to_perl_type(col_type);
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh), "\t\tmysql_to_perl_type returned %d\n", col_type);
bind->buffer= NULL;
bind->length= &(fbind->length);
bind->is_null= (char*) &(fbind->is_null);
fbind->is_null= 1;
fbind->length= 0;
}
}
}
}
#endif
#if MYSQL_VERSION_ID >= SERVER_PREPARE_VERSION
/* Count the number of parameters (driver, vs server-side) */
if (imp_sth->use_server_side_prepare == 0)
DBIc_NUM_PARAMS(imp_sth) = count_params((imp_xxh_t *)imp_dbh, aTHX_ statement,
imp_dbh->bind_comment_placeholders);
#else
DBIc_NUM_PARAMS(imp_sth) = count_params((imp_xxh_t *)imp_dbh, aTHX_ statement,
imp_dbh->bind_comment_placeholders);
#endif
/* Allocate memory for parameters */
imp_sth->params= alloc_param(DBIc_NUM_PARAMS(imp_sth));
DBIc_IMPSET_on(imp_sth);
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh), "\t<- dbd_st_prepare\n");
return 1;
}
/***************************************************************************
* Name: dbd_st_free_result_sets
*
* Purpose: Clean-up single or multiple result sets (if any)
*
* Inputs: sth - Statement handle
* imp_sth - driver's private statement handle
*
* Returns: 1 ok
* 0 error
*************************************************************************/
int mysql_st_free_result_sets (SV * sth, imp_sth_t * imp_sth)
{
dTHX;
D_imp_dbh_from_sth;
D_imp_xxh(sth);
int next_result_rc= -1;
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh), "\t>- dbd_st_free_result_sets\n");
#if MYSQL_VERSION_ID >= MULTIPLE_RESULT_SET_VERSION
do
{
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh), "\t<- dbd_st_free_result_sets RC %d\n", next_result_rc);
if (next_result_rc == 0)
{
if (!(imp_sth->result = mysql_use_result(imp_dbh->pmysql)))
{
/* Check for possible error */
if (mysql_field_count(imp_dbh->pmysql))
{
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh), "\t<- dbd_st_free_result_sets ERROR: %s\n",
mysql_error(imp_dbh->pmysql));
do_error(sth, mysql_errno(imp_dbh->pmysql), mysql_error(imp_dbh->pmysql),
mysql_sqlstate(imp_dbh->pmysql));
return 0;
}
}
}
if (imp_sth->result)
{
mysql_free_result(imp_sth->result);
imp_sth->result=NULL;
}
} while ((next_result_rc=mysql_next_result(imp_dbh->pmysql))==0);
if (next_result_rc > 0)
{
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh), "\t<- dbd_st_free_result_sets: Error while processing multi-result set: %s\n",
mysql_error(imp_dbh->pmysql));
do_error(sth, mysql_errno(imp_dbh->pmysql), mysql_error(imp_dbh->pmysql),
mysql_sqlstate(imp_dbh->pmysql));
}
#else
if (imp_sth->result)
{
mysql_free_result(imp_sth->result);
imp_sth->result=NULL;
}
#endif
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh), "\t<- dbd_st_free_result_sets\n");
return 1;
}
#if MYSQL_VERSION_ID >= MULTIPLE_RESULT_SET_VERSION
/***************************************************************************
* Name: dbd_st_more_results
*
* Purpose: Move onto the next result set (if any)
*
* Inputs: sth - Statement handle
* imp_sth - driver's private statement handle
*
* Returns: 1 if there are more results sets
* 0 if there are not
* -1 for errors.
*************************************************************************/
int dbd_st_more_results(SV* sth, imp_sth_t* imp_sth)
{
dTHX;
D_imp_dbh_from_sth;
D_imp_xxh(sth);
int use_mysql_use_result=imp_sth->use_mysql_use_result;
int next_result_return_code, i;
MYSQL* svsock= imp_dbh->pmysql;
if (!SvROK(sth) || SvTYPE(SvRV(sth)) != SVt_PVHV)
croak("Expected hash array");
if (!mysql_more_results(svsock))
{
/* No more pending result set(s)*/
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh),
"\n <- dbs_st_more_results no more results\n");
return 0;
}
if (imp_sth->use_server_side_prepare)
{
do_warn(sth, JW_ERR_NOT_IMPLEMENTED,
"Processing of multiple result set is not possible with server side prepare");
return 0;
}
/*
* Free cached array attributes
*/
for (i= 0; i < AV_ATTRIB_LAST; i++)
{
if (imp_sth->av_attr[i])
SvREFCNT_dec(imp_sth->av_attr[i]);
imp_sth->av_attr[i]= Nullav;
}
/* Release previous MySQL result*/
if (imp_sth->result)
mysql_free_result(imp_sth->result);
if (DBIc_ACTIVE(imp_sth))
DBIc_ACTIVE_off(imp_sth);
next_result_return_code= mysql_next_result(svsock);
imp_sth->warning_count = mysql_warning_count(imp_dbh->pmysql);
/*
mysql_next_result returns
0 if there are more results
-1 if there are no more results
>0 if there was an error
*/
if (next_result_return_code > 0)
{
do_error(sth, mysql_errno(svsock), mysql_error(svsock),
mysql_sqlstate(svsock));
return 0;
}
else if(next_result_return_code == -1)
{
return 0;
}
else
{
/* Store the result from the Query */
imp_sth->result = use_mysql_use_result ?
mysql_use_result(svsock) : mysql_store_result(svsock);
if (mysql_errno(svsock))
{
do_error(sth, mysql_errno(svsock), mysql_error(svsock),
mysql_sqlstate(svsock));
return 0;
}
imp_sth->row_num= mysql_affected_rows(imp_dbh->pmysql);
if (imp_sth->result == NULL)
{
/* No "real" rowset*/
DBIc_NUM_FIELDS(imp_sth)= 0; /* for DBI <= 1.53 */
DBIS->set_attr_k(sth, sv_2mortal(newSVpvn("NUM_OF_FIELDS",13)), 0,
sv_2mortal(newSViv(0)));
return 1;
}
else
{
/* We have a new rowset */
imp_sth->currow=0;
/* delete cached handle attributes */
/* XXX should be driven by a list to ease maintenance */
(void)hv_delete((HV*)SvRV(sth), "NAME", 4, G_DISCARD);
(void)hv_delete((HV*)SvRV(sth), "NULLABLE", 8, G_DISCARD);
(void)hv_delete((HV*)SvRV(sth), "NUM_OF_FIELDS", 13, G_DISCARD);
(void)hv_delete((HV*)SvRV(sth), "PRECISION", 9, G_DISCARD);
(void)hv_delete((HV*)SvRV(sth), "SCALE", 5, G_DISCARD);
(void)hv_delete((HV*)SvRV(sth), "TYPE", 4, G_DISCARD);
(void)hv_delete((HV*)SvRV(sth), "mysql_insertid", 14, G_DISCARD);
(void)hv_delete((HV*)SvRV(sth), "mysql_is_auto_increment", 23, G_DISCARD);
(void)hv_delete((HV*)SvRV(sth), "mysql_is_blob", 13, G_DISCARD);
(void)hv_delete((HV*)SvRV(sth), "mysql_is_key", 12, G_DISCARD);
(void)hv_delete((HV*)SvRV(sth), "mysql_is_num", 12, G_DISCARD);
(void)hv_delete((HV*)SvRV(sth), "mysql_is_pri_key", 16, G_DISCARD);
(void)hv_delete((HV*)SvRV(sth), "mysql_length", 12, G_DISCARD);
(void)hv_delete((HV*)SvRV(sth), "mysql_max_length", 16, G_DISCARD);
(void)hv_delete((HV*)SvRV(sth), "mysql_table", 11, G_DISCARD);
(void)hv_delete((HV*)SvRV(sth), "mysql_type", 10, G_DISCARD);
(void)hv_delete((HV*)SvRV(sth), "mysql_type_name", 15, G_DISCARD);
(void)hv_delete((HV*)SvRV(sth), "mysql_warning_count", 20, G_DISCARD);
/* Adjust NUM_OF_FIELDS - which also adjusts the row buffer size */
DBIc_NUM_FIELDS(imp_sth)= 0; /* for DBI <= 1.53 */
DBIc_DBISTATE(imp_sth)->set_attr_k(sth, sv_2mortal(newSVpvn("NUM_OF_FIELDS",13)), 0,
sv_2mortal(newSViv(mysql_num_fields(imp_sth->result)))
);
DBIc_ACTIVE_on(imp_sth);
imp_sth->done_desc = 0;
}
imp_dbh->pmysql->net.last_errno= 0;
return 1;
}
}
#endif
/**************************************************************************
*
* Name: mysql_st_internal_execute
*
* Purpose: Internal version for executing a statement, called both from
* within the "do" and the "execute" method.
*
* Inputs: h - object handle, for storing error messages
* statement - query being executed
* attribs - statement attributes, currently ignored
* num_params - number of parameters being bound
* params - parameter array
* result - where to store results, if any
* svsock - socket connected to the database
*
**************************************************************************/
my_ulonglong mysql_st_internal_execute(
SV *h, /* could be sth or dbh */
SV *statement,
SV *attribs,
int num_params,
imp_sth_ph_t *params,
MYSQL_RES **result,
MYSQL *svsock,
int use_mysql_use_result
)
{
dTHX;
bool bind_type_guessing= FALSE;
bool bind_comment_placeholders= TRUE;
STRLEN slen;
char *sbuf = SvPV(statement, slen);
char *table;
char *salloc;
int htype;
#if MYSQL_ASYNC
bool async = FALSE;
#endif
my_ulonglong rows= 0;
/* thank you DBI.c for this info! */
D_imp_xxh(h);
attribs= attribs;
htype= DBIc_TYPE(imp_xxh);
/*
It is important to import imp_dbh properly according to the htype
that it is! Also, one might ask why bind_type_guessing is assigned
in each block. Well, it's because D_imp_ macros called in these
blocks make it so imp_dbh is not "visible" or defined outside of the
if/else (when compiled, it fails for imp_dbh not being defined).
*/
/* h is a dbh */
if (htype == DBIt_DB)
{
D_imp_dbh(h);
/* if imp_dbh is not available, it causes segfault (proper) on OpenBSD */
if (imp_dbh && imp_dbh->bind_type_guessing)
{
bind_type_guessing= imp_dbh->bind_type_guessing;
bind_comment_placeholders= bind_comment_placeholders;
}
#if MYSQL_ASYNC
async = (bool) (imp_dbh->async_query_in_flight != NULL);
#endif
}
/* h is a sth */
else
{
D_imp_sth(h);
D_imp_dbh_from_sth;
/* if imp_dbh is not available, it causes segfault (proper) on OpenBSD */
if (imp_dbh)
{
bind_type_guessing= imp_dbh->bind_type_guessing;
bind_comment_placeholders= imp_dbh->bind_comment_placeholders;
}
#if MYSQL_ASYNC
async = imp_sth->is_async;
if(async) {
imp_dbh->async_query_in_flight = imp_sth;
} else {
imp_dbh->async_query_in_flight = NULL;
}
#endif
}
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh), "mysql_st_internal_execute MYSQL_VERSION_ID %d\n",
MYSQL_VERSION_ID );
salloc= parse_params(imp_xxh,
aTHX_ svsock,
sbuf,
&slen,
params,
num_params,
bind_type_guessing,
bind_comment_placeholders);
if (salloc)
{
sbuf= salloc;
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh), "Binding parameters: %s\n", sbuf);
}
if (slen >= 11 && (!strncmp(sbuf, "listfields ", 11) ||
!strncmp(sbuf, "LISTFIELDS ", 11)))
{
/* remove pre-space */
slen-= 10;
sbuf+= 10;
while (slen && isspace(*sbuf)) { --slen; ++sbuf; }
if (!slen)
{
do_error(h, JW_ERR_QUERY, "Missing table name" ,NULL);
return -2;
}
if (!(table= malloc(slen+1)))
{
do_error(h, JW_ERR_MEM, "Out of memory" ,NULL);
return -2;
}
strncpy(table, sbuf, slen);
sbuf= table;
while (slen && !isspace(*sbuf))
{
--slen;
++sbuf;
}
*sbuf++= '\0';
*result= mysql_list_fields(svsock, table, NULL);
free(table);
if (!(*result))
{
do_error(h, mysql_errno(svsock), mysql_error(svsock)
,mysql_sqlstate(svsock));
return -2;
}
return 0;
}
#if MYSQL_ASYNC
if(async) {
if((mysql_send_query(svsock, sbuf, slen)) &&
(!mysql_db_reconnect(h) ||
(mysql_send_query(svsock, sbuf, slen))))
{
rows = -2;
} else {
rows = 0;
}
} else {
#endif
if ((mysql_real_query(svsock, sbuf, slen)) &&
(!mysql_db_reconnect(h) ||
(mysql_real_query(svsock, sbuf, slen))))
{
rows = -2;
} else {
/** Store the result from the Query */
*result= use_mysql_use_result ?
mysql_use_result(svsock) : mysql_store_result(svsock);
if (mysql_errno(svsock))
rows = -2;
else if (*result)
rows = mysql_num_rows(*result);
else {
rows = mysql_affected_rows(svsock);
/* mysql_affected_rows(): -1 indicates that the query returned an error */
if (rows == (my_ulonglong)-1)
rows = -2;
}
}
#if MYSQL_ASYNC
}
#endif
if (salloc)
Safefree(salloc);
if(rows == (my_ulonglong)-2) {
do_error(h, mysql_errno(svsock), mysql_error(svsock),
mysql_sqlstate(svsock));
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh), "IGNORING ERROR errno %d\n", mysql_errno(svsock));
}
return(rows);
}
/**************************************************************************
*
* Name: mysql_st_internal_execute41
*
* Purpose: Internal version for executing a prepared statement, called both
* from within the "do" and the "execute" method.
* MYSQL 4.1 API
*
*
* Inputs: h - object handle, for storing error messages
* statement - query being executed
* attribs - statement attributes, currently ignored
* num_params - number of parameters being bound
* params - parameter array
* result - where to store results, if any
* svsock - socket connected to the database
*
**************************************************************************/
#if MYSQL_VERSION_ID >= SERVER_PREPARE_VERSION
my_ulonglong mysql_st_internal_execute41(
SV *sth,
int num_params,
MYSQL_RES **result,
MYSQL_STMT *stmt,
MYSQL_BIND *bind,
int *has_been_bound
)
{
int i;
enum enum_field_types enum_type;
dTHX;
int execute_retval;
my_ulonglong rows=0;
D_imp_xxh(sth);
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh),
"\t-> mysql_st_internal_execute41\n");
/* free result if exists */
if (*result)
{
mysql_free_result(*result);
*result= 0;
}
/*
If were performed any changes with ph variables
we have to rebind them
*/
if (num_params > 0 && !(*has_been_bound))
{
if (mysql_stmt_bind_param(stmt,bind))
goto error;
*has_been_bound= 1;
}
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh),
"\t\tmysql_st_internal_execute41 calling mysql_execute with %d num_params\n",
num_params);
execute_retval= mysql_stmt_execute(stmt);
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh),
"\t\tmysql_stmt_execute returned %d\n",
execute_retval);
if (execute_retval)
goto error;
/*
This statement does not return a result set (INSERT, UPDATE...)
*/
if (!(*result= mysql_stmt_result_metadata(stmt)))
{
if (mysql_stmt_errno(stmt))
goto error;
rows= mysql_stmt_affected_rows(stmt);
/* mysql_stmt_affected_rows(): -1 indicates that the query returned an error */
if (rows == (my_ulonglong)-1)
goto error;
}
/*
This statement returns a result set (SELECT...)
*/
else
{
for (i = mysql_stmt_field_count(stmt) - 1; i >=0; --i) {
enum_type = mysql_to_perl_type(stmt->fields[i].type);
if (enum_type != MYSQL_TYPE_DOUBLE && enum_type != MYSQL_TYPE_LONG && enum_type != MYSQL_TYPE_BIT)
{
/* mysql_stmt_store_result to update MYSQL_FIELD->max_length */
my_bool on = 1;
mysql_stmt_attr_set(stmt, STMT_ATTR_UPDATE_MAX_LENGTH, &on);
break;
}
}
/* Get the total rows affected and return */
if (mysql_stmt_store_result(stmt))
goto error;
else
rows= mysql_stmt_num_rows(stmt);
}
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh),
"\t<- mysql_internal_execute_41 returning %llu rows\n",
rows);
return(rows);
error:
if (*result)
{
mysql_free_result(*result);
*result= 0;
}
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh),
" errno %d err message %s\n",
mysql_stmt_errno(stmt),
mysql_stmt_error(stmt));
do_error(sth, mysql_stmt_errno(stmt), mysql_stmt_error(stmt),
mysql_stmt_sqlstate(stmt));
mysql_stmt_reset(stmt);
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh),
"\t<- mysql_st_internal_execute41\n");
return -2;
}
#endif
/***************************************************************************
*
* Name: dbd_st_execute
*
* Purpose: Called for preparing an SQL statement; our part of the
* statement handle constructor
*
* Input: sth - statement handle being initialized
* imp_sth - drivers private statement handle data
*
* Returns: TRUE for success, FALSE otherwise; do_error will
* be called in the latter case
*
**************************************************************************/
int dbd_st_execute(SV* sth, imp_sth_t* imp_sth)
{
dTHX;
char actual_row_num[64];
int i;
SV **statement;
D_imp_dbh_from_sth;
D_imp_xxh(sth);
#if defined (dTHR)
dTHR;
#endif
ASYNC_CHECK_RETURN(sth, -2);
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh),
" -> dbd_st_execute for %p\n", sth);
if (!SvROK(sth) || SvTYPE(SvRV(sth)) != SVt_PVHV)
croak("Expected hash array");
/* Free cached array attributes */
for (i= 0; i < AV_ATTRIB_LAST; i++)
{
if (imp_sth->av_attr[i])
SvREFCNT_dec(imp_sth->av_attr[i]);
imp_sth->av_attr[i]= Nullav;
}
statement= hv_fetch((HV*) SvRV(sth), "Statement", 9, FALSE);
/*
Clean-up previous result set(s) for sth to prevent
'Commands out of sync' error
*/
mysql_st_free_result_sets (sth, imp_sth);
#if MYSQL_VERSION_ID >= SERVER_PREPARE_VERSION
if (imp_sth->use_server_side_prepare && ! imp_sth->use_mysql_use_result)
{
imp_sth->row_num= mysql_st_internal_execute41(
sth,
DBIc_NUM_PARAMS(imp_sth),
&imp_sth->result,
imp_sth->stmt,
imp_sth->bind,
&imp_sth->has_been_bound
);
}
else {
#endif
imp_sth->row_num= mysql_st_internal_execute(
sth,
*statement,
NULL,
DBIc_NUM_PARAMS(imp_sth),
imp_sth->params,
&imp_sth->result,
imp_dbh->pmysql,
imp_sth->use_mysql_use_result
);
#if MYSQL_ASYNC
if(imp_dbh->async_query_in_flight) {
DBIc_ACTIVE_on(imp_sth);
return 0;
}
#endif
}
if (imp_sth->row_num+1 != (my_ulonglong)-1)
{
if (!imp_sth->result)
{
imp_sth->insertid= mysql_insert_id(imp_dbh->pmysql);
#if MYSQL_VERSION_ID >= MULTIPLE_RESULT_SET_VERSION
if (mysql_more_results(imp_dbh->pmysql))
DBIc_ACTIVE_on(imp_sth);
#endif
}
else
{
/** Store the result in the current statement handle */
DBIc_NUM_FIELDS(imp_sth)= mysql_num_fields(imp_sth->result);
DBIc_ACTIVE_on(imp_sth);
if (!imp_sth->use_server_side_prepare)
imp_sth->done_desc= 0;
imp_sth->fetch_done= 0;
}
}
imp_sth->warning_count = mysql_warning_count(imp_dbh->pmysql);
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
{
/*
PerlIO_printf doesn't always handle imp_sth->row_num %llu
consistently!!
*/
sprintf(actual_row_num, "%llu", imp_sth->row_num);
PerlIO_printf(DBIc_LOGPIO(imp_xxh),
" <- dbd_st_execute returning imp_sth->row_num %s\n",
actual_row_num);
}
return (int)imp_sth->row_num;
}
/**************************************************************************
*
* Name: dbd_describe
*
* Purpose: Called from within the fetch method to describe the result
*
* Input: sth - statement handle being initialized
* imp_sth - our part of the statement handle, there's no
* need for supplying both; Tim just doesn't remove it
*
* Returns: TRUE for success, FALSE otherwise; do_error will
* be called in the latter case
*
**************************************************************************/
int dbd_describe(SV* sth, imp_sth_t* imp_sth)
{
dTHX;
D_imp_xxh(sth);
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh), "\t--> dbd_describe\n");
#if MYSQL_VERSION_ID >= SERVER_PREPARE_VERSION
if (imp_sth->use_server_side_prepare)
{
int i;
int col_type;
int num_fields= DBIc_NUM_FIELDS(imp_sth);
imp_sth_fbh_t *fbh;
MYSQL_BIND *buffer;
MYSQL_FIELD *fields;
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh), "\t\tdbd_describe() num_fields %d\n",
num_fields);
if (imp_sth->done_desc)
return TRUE;
if (!num_fields || !imp_sth->result)
{
/* no metadata */
do_error(sth, JW_ERR_SEQUENCE,
"no metadata information while trying describe result set",
NULL);
return 0;
}
/* allocate fields buffers */
if ( !(imp_sth->fbh= alloc_fbuffer(num_fields))
|| !(imp_sth->buffer= alloc_bind(num_fields)) )
{
/* Out of memory */
do_error(sth, JW_ERR_SEQUENCE,
"Out of memory in dbd_sescribe()",NULL);
return 0;
}
fields= mysql_fetch_fields(imp_sth->result);
for (
fbh= imp_sth->fbh, buffer= (MYSQL_BIND*)imp_sth->buffer, i= 0;
i < num_fields;
i++, fbh++, buffer++
)
{
/* get the column type */
col_type = fields ? fields[i].type : MYSQL_TYPE_STRING;
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
{
PerlIO_printf(DBIc_LOGPIO(imp_xxh),"\t\ti %d col_type %d fbh->length %lu\n",
i, col_type, fbh->length);
PerlIO_printf(DBIc_LOGPIO(imp_xxh),
"\t\tfields[i].length %lu fields[i].max_length %lu fields[i].type %d fields[i].charsetnr %d\n",
fields[i].length, fields[i].max_length, fields[i].type,
fields[i].charsetnr);
}
fbh->charsetnr = fields[i].charsetnr;
#if MYSQL_VERSION_ID < FIELD_CHARSETNR_VERSION
fbh->flags = fields[i].flags;
#endif
buffer->buffer_type= mysql_to_perl_type(col_type);
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh), "\t\tmysql_to_perl_type returned %d\n",
col_type);
buffer->length= &(fbh->length);
buffer->is_null= (my_bool*) &(fbh->is_null);
buffer->error= (my_bool*) &(fbh->error);
switch (buffer->buffer_type) {
case MYSQL_TYPE_DOUBLE:
buffer->buffer_length= sizeof(fbh->ddata);
buffer->buffer= (char*) &fbh->ddata;
break;
case MYSQL_TYPE_LONG:
buffer->buffer_length= sizeof(fbh->ldata);
buffer->buffer= (char*) &fbh->ldata;
buffer->is_unsigned= (fields[i].flags & UNSIGNED_FLAG) ? 1 : 0;
break;
case MYSQL_TYPE_BIT:
buffer->buffer_length= 8;
Newz(908, fbh->data, buffer->buffer_length, char);
buffer->buffer= (char *) fbh->data;
break;
default:
buffer->buffer_length= fields[i].max_length ? fields[i].max_length : 1;
Newz(908, fbh->data, buffer->buffer_length, char);
buffer->buffer= (char *) fbh->data;
}
}
if (mysql_stmt_bind_result(imp_sth->stmt, imp_sth->buffer))
{
do_error(sth, mysql_stmt_errno(imp_sth->stmt),
mysql_stmt_error(imp_sth->stmt),
mysql_stmt_sqlstate(imp_sth->stmt));
return 0;
}
}
#endif
imp_sth->done_desc= 1;
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh), "\t<- dbd_describe\n");
return TRUE;
}
/**************************************************************************
*
* Name: dbd_st_fetch
*
* Purpose: Called for fetching a result row
*
* Input: sth - statement handle being initialized
* imp_sth - drivers private statement handle data
*
* Returns: array of columns; the array is allocated by DBI via
* DBIc_DBISTATE(imp_sth)->get_fbav(imp_sth), even the values
* of the array are prepared, we just need to modify them
* appropriately
*
**************************************************************************/
AV*
dbd_st_fetch(SV *sth, imp_sth_t* imp_sth)
{
dTHX;
int num_fields, ChopBlanks, i, rc;
unsigned long *lengths;
AV *av;
int av_length, av_readonly;
MYSQL_ROW cols;
D_imp_dbh_from_sth;
MYSQL* svsock= imp_dbh->pmysql;
imp_sth_fbh_t *fbh;
D_imp_xxh(sth);
#if MYSQL_VERSION_ID >=SERVER_PREPARE_VERSION
MYSQL_BIND *buffer;
#endif
MYSQL_FIELD *fields;
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh), "\t-> dbd_st_fetch\n");
#if MYSQL_ASYNC
if(imp_dbh->async_query_in_flight) {
if(mysql_db_async_result(sth, &imp_sth->result) <= 0) {
return Nullav;
}
}
#endif
#if MYSQL_VERSION_ID >=SERVER_PREPARE_VERSION
if (imp_sth->use_server_side_prepare)
{
if (!DBIc_ACTIVE(imp_sth) )
{
do_error(sth, JW_ERR_SEQUENCE, "no statement executing\n",NULL);
return Nullav;
}
if (imp_sth->fetch_done)
{
do_error(sth, JW_ERR_SEQUENCE, "fetch() but fetch already done",NULL);
return Nullav;
}
if (!imp_sth->done_desc)
{
if (!dbd_describe(sth, imp_sth))
{
do_error(sth, JW_ERR_SEQUENCE, "Error while describe result set.",
NULL);
return Nullav;
}
}
}
#endif
ChopBlanks = DBIc_is(imp_sth, DBIcf_ChopBlanks);
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh),
"\t\tdbd_st_fetch for %p, chopblanks %d\n",
sth, ChopBlanks);
if (!imp_sth->result)
{
do_error(sth, JW_ERR_SEQUENCE, "fetch() without execute()" ,NULL);
return Nullav;
}
/* fix from 2.9008 */
imp_dbh->pmysql->net.last_errno = 0;
#if MYSQL_VERSION_ID >=SERVER_PREPARE_VERSION
if (imp_sth->use_server_side_prepare)
{
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh), "\t\tdbd_st_fetch calling mysql_fetch\n");
if ((rc= mysql_stmt_fetch(imp_sth->stmt)))
{
if (rc == 1)
do_error(sth, mysql_stmt_errno(imp_sth->stmt),
mysql_stmt_error(imp_sth->stmt),
mysql_stmt_sqlstate(imp_sth->stmt));
#if MYSQL_VERSION_ID >= MYSQL_VERSION_5_0
if (rc == MYSQL_DATA_TRUNCATED) {
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh), "\t\tdbd_st_fetch data truncated\n");
goto process;
}
#endif
if (rc == MYSQL_NO_DATA)
{
/* Update row_num to affected_rows value */
imp_sth->row_num= mysql_stmt_affected_rows(imp_sth->stmt);
imp_sth->fetch_done=1;
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh), "\t\tdbd_st_fetch no data\n");
}
dbd_st_finish(sth, imp_sth);
return Nullav;
}
process:
imp_sth->currow++;
av= DBIc_DBISTATE(imp_sth)->get_fbav(imp_sth);
num_fields=mysql_stmt_field_count(imp_sth->stmt);
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh),
"\t\tdbd_st_fetch called mysql_fetch, rc %d num_fields %d\n",
rc, num_fields);
for (
buffer= imp_sth->buffer,
fbh= imp_sth->fbh,
i= 0;
i < num_fields;
i++,
fbh++,
buffer++
)
{
SV *sv= AvARRAY(av)[i]; /* Note: we (re)use the SV in the AV */
STRLEN len;
/* This is wrong, null is not being set correctly
* This is not the way to determine length (this would break blobs!)
*/
if (fbh->is_null)
(void) SvOK_off(sv); /* Field is NULL, return undef */
else
{
/* In case of BLOB/TEXT fields we allocate only 8192 bytes
in dbd_describe() for data. Here we know real size of field
so we should increase buffer size and refetch column value
*/
if (fbh->length > buffer->buffer_length || fbh->error)
{
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh),
"\t\tRefetch BLOB/TEXT column: %d, length: %lu, error: %d\n",
i, fbh->length, fbh->error);
Renew(fbh->data, fbh->length, char);
buffer->buffer_length= fbh->length;
buffer->buffer= (char *) fbh->data;
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) {
int j;
int m = MIN(*buffer->length, buffer->buffer_length);
char *ptr = (char*)buffer->buffer;
PerlIO_printf(DBIc_LOGPIO(imp_xxh),"\t\tbefore buffer->buffer: ");
for (j = 0; j < m; j++) {
PerlIO_printf(DBIc_LOGPIO(imp_xxh), "%c", *ptr++);
}
PerlIO_printf(DBIc_LOGPIO(imp_xxh),"\n");
}
/*TODO: Use offset instead of 0 to fetch only remain part of data*/
if (mysql_stmt_fetch_column(imp_sth->stmt, buffer , i, 0))
do_error(sth, mysql_stmt_errno(imp_sth->stmt),
mysql_stmt_error(imp_sth->stmt),
mysql_stmt_sqlstate(imp_sth->stmt));
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) {
int j;
int m = MIN(*buffer->length, buffer->buffer_length);
char *ptr = (char*)buffer->buffer;
PerlIO_printf(DBIc_LOGPIO(imp_xxh),"\t\tafter buffer->buffer: ");
for (j = 0; j < m; j++) {
PerlIO_printf(DBIc_LOGPIO(imp_xxh), "%c", *ptr++);
}
PerlIO_printf(DBIc_LOGPIO(imp_xxh),"\n");
}
}
/* This does look a lot like Georg's PHP driver doesn't it? --Brian */
/* Credit due to Georg - mysqli_api.c ;) --PMG */
switch (buffer->buffer_type) {
case MYSQL_TYPE_DOUBLE:
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh), "\t\tst_fetch double data %f\n", fbh->ddata);
sv_setnv(sv, fbh->ddata);
break;
case MYSQL_TYPE_LONG:
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh), "\t\tst_fetch int data %"IVdf", unsigned? %d\n",
fbh->ldata, buffer->is_unsigned);
if (buffer->is_unsigned)
sv_setuv(sv, fbh->ldata);
else
sv_setiv(sv, fbh->ldata);
break;
case MYSQL_TYPE_BIT:
sv_setpvn(sv, fbh->data, fbh->length);
break;
default:
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh), "\t\tERROR IN st_fetch_string");
len= fbh->length;
/* ChopBlanks server-side prepared statement */
if (ChopBlanks)
{
/*
see bottom of:
http://www.mysql.org/doc/refman/5.0/en/c-api-datatypes.html
*/
if (fbh->charsetnr != 63)
while (len && fbh->data[len-1] == ' ') { --len; }
}
/* END OF ChopBlanks */
sv_setpvn(sv, fbh->data, len);
/* UTF8 */
/*HELMUT*/
#if defined(sv_utf8_decode) && MYSQL_VERSION_ID >=SERVER_PREPARE_VERSION
#if MYSQL_VERSION_ID >= FIELD_CHARSETNR_VERSION
/* SHOW COLLATION WHERE Id = 63; -- 63 == charset binary, collation binary */
if ((imp_dbh->enable_utf8 || imp_dbh->enable_utf8mb4) && fbh->charsetnr != 63)
#else
if ((imp_dbh->enable_utf8 || imp_dbh->enable_utf8mb4) && !(fbh->flags & BINARY_FLAG))
#endif
sv_utf8_decode(sv);
#endif
/* END OF UTF8 */
break;
}
}
}
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh), "\t<- dbd_st_fetch, %d cols\n", num_fields);
return av;
}
else
{
#endif
imp_sth->currow++;
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
{
PerlIO_printf(DBIc_LOGPIO(imp_xxh), "\tdbd_st_fetch result set details\n");
PerlIO_printf(DBIc_LOGPIO(imp_xxh), "\timp_sth->result=%p\n", imp_sth->result);
PerlIO_printf(DBIc_LOGPIO(imp_xxh), "\tmysql_num_fields=%u\n",
mysql_num_fields(imp_sth->result));
PerlIO_printf(DBIc_LOGPIO(imp_xxh), "\tmysql_num_rows=%llu\n",
mysql_num_rows(imp_sth->result));
PerlIO_printf(DBIc_LOGPIO(imp_xxh), "\tmysql_affected_rows=%llu\n",
mysql_affected_rows(imp_dbh->pmysql));
PerlIO_printf(DBIc_LOGPIO(imp_xxh), "\tdbd_st_fetch for %p, currow= %d\n",
sth,imp_sth->currow);
}
if (!(cols= mysql_fetch_row(imp_sth->result)))
{
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
{
PerlIO_printf(DBIc_LOGPIO(imp_xxh), "\tdbd_st_fetch, no more rows to fetch");
}
if (mysql_errno(imp_dbh->pmysql))
do_error(sth, mysql_errno(imp_dbh->pmysql),
mysql_error(imp_dbh->pmysql),
mysql_sqlstate(imp_dbh->pmysql));
#if MYSQL_VERSION_ID >= MULTIPLE_RESULT_SET_VERSION
if (!mysql_more_results(svsock))
#endif
dbd_st_finish(sth, imp_sth);
return Nullav;
}
num_fields= mysql_num_fields(imp_sth->result);
fields= mysql_fetch_fields(imp_sth->result);
lengths= mysql_fetch_lengths(imp_sth->result);
if ((av= DBIc_FIELDS_AV(imp_sth)) != Nullav)
{
av_length= av_len(av)+1;
if (av_length != num_fields) /* Resize array if necessary */
{
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh), "\t<- dbd_st_fetch, size of results array(%d) != num_fields(%d)\n",
av_length, num_fields);
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh), "\t<- dbd_st_fetch, result fields(%d)\n",
DBIc_NUM_FIELDS(imp_sth));
av_readonly = SvREADONLY(av);
if (av_readonly)
SvREADONLY_off( av ); /* DBI sets this readonly */
while (av_length < num_fields)
{
av_store(av, av_length++, newSV(0));
}
while (av_length > num_fields)
{
SvREFCNT_dec(av_pop(av));
av_length--;
}
if (av_readonly)
SvREADONLY_on(av);
}
}
av= DBIc_DBISTATE(imp_sth)->get_fbav(imp_sth);
for (i= 0; i < num_fields; ++i)
{
char *col= cols[i];
SV *sv= AvARRAY(av)[i]; /* Note: we (re)use the SV in the AV */
if (col)
{
STRLEN len= lengths[i];
if (ChopBlanks)
{
while (len && col[len-1] == ' ')
{ --len; }
}
/* Set string value returned from mysql server */
sv_setpvn(sv, col, len);
switch (mysql_to_perl_type(fields[i].type)) {
case MYSQL_TYPE_DOUBLE:
/* Coerce to dobule and set scalar as NV */
(void) SvNV(sv);
SvNOK_only(sv);
break;
case MYSQL_TYPE_LONG:
/* Coerce to integer and set scalar as UV resp. IV */
if (fields[i].flags & UNSIGNED_FLAG)
{
(void) SvUV(sv);
SvIOK_only_UV(sv);
}
else
{
(void) SvIV(sv);
SvIOK_only(sv);
}
break;
#if MYSQL_VERSION_ID > NEW_DATATYPE_VERSION
case MYSQL_TYPE_BIT:
/* Let it as binary string */
break;
#endif
default:
/* UTF8 */
/*HELMUT*/
#if defined(sv_utf8_decode) && MYSQL_VERSION_ID >=SERVER_PREPARE_VERSION
/* see bottom of: http://www.mysql.org/doc/refman/5.0/en/c-api-datatypes.html */
if ((imp_dbh->enable_utf8 || imp_dbh->enable_utf8mb4) && fields[i].charsetnr != 63)
sv_utf8_decode(sv);
#endif
/* END OF UTF8 */
break;
}
}
else
(void) SvOK_off(sv); /* Field is NULL, return undef */
}
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh), "\t<- dbd_st_fetch, %d cols\n", num_fields);
return av;
#if MYSQL_VERSION_ID >= SERVER_PREPARE_VERSION
}
#endif
}
#if MYSQL_VERSION_ID >= SERVER_PREPARE_VERSION
/*
We have to fetch all data from stmt
There is may be useful for 2 cases:
1. st_finish when we have undef statement
2. call st_execute again when we have some unfetched data in stmt
*/
int mysql_st_clean_cursor(SV* sth, imp_sth_t* imp_sth) {
if (DBIc_ACTIVE(imp_sth) && dbd_describe(sth, imp_sth) &&
!imp_sth->fetch_done)
mysql_stmt_free_result(imp_sth->stmt);
return 1;
}
#endif
/***************************************************************************
*
* Name: dbd_st_finish
*
* Purpose: Called for freeing a mysql result
*
* Input: sth - statement handle being finished
* imp_sth - drivers private statement handle data
*
* Returns: TRUE for success, FALSE otherwise; do_error() will
* be called in the latter case
*
**************************************************************************/
int dbd_st_finish(SV* sth, imp_sth_t* imp_sth) {
dTHX;
D_imp_xxh(sth);
#if defined (dTHR)
dTHR;
#endif
#if MYSQL_ASYNC
D_imp_dbh_from_sth;
if(imp_dbh->async_query_in_flight) {
mysql_db_async_result(sth, &imp_sth->result);
}
#endif
#if MYSQL_VERSION_ID >= SERVER_PREPARE_VERSION
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
{
PerlIO_printf(DBIc_LOGPIO(imp_xxh), "\n--> dbd_st_finish\n");
}
if (imp_sth->use_server_side_prepare)
{
if (imp_sth && imp_sth->stmt)
{
if (!mysql_st_clean_cursor(sth, imp_sth))
{
do_error(sth, JW_ERR_SEQUENCE,
"Error happened while tried to clean up stmt",NULL);
return 0;
}
}
}
#endif
/*
Cancel further fetches from this cursor.
We don't close the cursor till DESTROY.
The application may re execute it.
*/
if (imp_sth && DBIc_ACTIVE(imp_sth))
{
/*
Clean-up previous result set(s) for sth to prevent
'Commands out of sync' error
*/
mysql_st_free_result_sets(sth, imp_sth);
}
DBIc_ACTIVE_off(imp_sth);
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
{
PerlIO_printf(DBIc_LOGPIO(imp_xxh), "\n<-- dbd_st_finish\n");
}
return 1;
}
/**************************************************************************
*
* Name: dbd_st_destroy
*
* Purpose: Our part of the statement handles destructor
*
* Input: sth - statement handle being destroyed
* imp_sth - drivers private statement handle data
*
* Returns: Nothing
*
**************************************************************************/
void dbd_st_destroy(SV *sth, imp_sth_t *imp_sth) {
dTHX;
D_imp_xxh(sth);
#if defined (dTHR)
dTHR;
#endif
int i;
#if MYSQL_VERSION_ID >= SERVER_PREPARE_VERSION
imp_sth_fbh_t *fbh;
int n;
n= DBIc_NUM_PARAMS(imp_sth);
if (n)
{
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh), "\tFreeing %d parameters, bind %p fbind %p\n",
n, imp_sth->bind, imp_sth->fbind);
free_bind(imp_sth->bind);
free_fbind(imp_sth->fbind);
}
fbh= imp_sth->fbh;
if (fbh)
{
n = DBIc_NUM_FIELDS(imp_sth);
i = 0;
while (i < n)
{
if (fbh[i].data) Safefree(fbh[i].data);
++i;
}
free_fbuffer(fbh);
if (imp_sth->buffer)
free_bind(imp_sth->buffer);
}
if (imp_sth->stmt)
{
if (mysql_stmt_close(imp_sth->stmt))
{
do_error(DBIc_PARENT_H(imp_sth), mysql_stmt_errno(imp_sth->stmt),
mysql_stmt_error(imp_sth->stmt),
mysql_stmt_sqlstate(imp_sth->stmt));
}
}
#endif
/* dbd_st_finish has already been called by .xs code if needed. */
/* Free values allocated by dbd_bind_ph */
if (imp_sth->params)
{
free_param(aTHX_ imp_sth->params, DBIc_NUM_PARAMS(imp_sth));
imp_sth->params= NULL;
}
/* Free cached array attributes */
for (i= 0; i < AV_ATTRIB_LAST; i++)
{
if (imp_sth->av_attr[i])
SvREFCNT_dec(imp_sth->av_attr[i]);
imp_sth->av_attr[i]= Nullav;
}
/* let DBI know we've done it */
DBIc_IMPSET_off(imp_sth);
}
/*
**************************************************************************
*
* Name: dbd_st_STORE_attrib
*
* Purpose: Modifies a statement handles attributes; we currently
* support just nothing
*
* Input: sth - statement handle being destroyed
* imp_sth - drivers private statement handle data
* keysv - attribute name
* valuesv - attribute value
*
* Returns: TRUE for success, FALSE otherwise; do_error will
* be called in the latter case
*
**************************************************************************/
int
dbd_st_STORE_attrib(
SV *sth,
imp_sth_t *imp_sth,
SV *keysv,
SV *valuesv
)
{
dTHX;
STRLEN(kl);
char *key= SvPV(keysv, kl);
int retval= FALSE;
D_imp_xxh(sth);
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh),
"\t\t-> dbd_st_STORE_attrib for %p, key %s\n",
sth, key);
if (strEQ(key, "mysql_use_result"))
{
imp_sth->use_mysql_use_result= SvTRUE(valuesv);
}
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh),
"\t\t<- dbd_st_STORE_attrib for %p, result %d\n",
sth, retval);
return retval;
}
/*
**************************************************************************
*
* Name: dbd_st_FETCH_internal
*
* Purpose: Retrieves a statement handles array attributes; we use
* a separate function, because creating the array
* attributes shares much code and it aids in supporting
* enhanced features like caching.
*
* Input: sth - statement handle; may even be a database handle,
* in which case this will be used for storing error
* messages only. This is only valid, if cacheit (the
* last argument) is set to TRUE.
* what - internal attribute number
* res - pointer to a DBMS result
* cacheit - TRUE, if results may be cached in the sth.
*
* Returns: RV pointing to result array in case of success, NULL
* otherwise; do_error has already been called in the latter
* case.
*
**************************************************************************/
#ifndef IS_KEY
#define IS_KEY(A) (((A) & (PRI_KEY_FLAG | UNIQUE_KEY_FLAG | MULTIPLE_KEY_FLAG)) != 0)
#endif
#if !defined(IS_AUTO_INCREMENT) && defined(AUTO_INCREMENT_FLAG)
#define IS_AUTO_INCREMENT(A) (((A) & AUTO_INCREMENT_FLAG) != 0)
#endif
SV*
dbd_st_FETCH_internal(
SV *sth,
int what,
MYSQL_RES *res,
int cacheit
)
{
dTHX;
D_imp_sth(sth);
AV *av= Nullav;
MYSQL_FIELD *curField;
/* Are we asking for a legal value? */
if (what < 0 || what >= AV_ATTRIB_LAST)
do_error(sth, JW_ERR_NOT_IMPLEMENTED, "Not implemented", NULL);
/* Return cached value, if possible */
else if (cacheit && imp_sth->av_attr[what])
av= imp_sth->av_attr[what];
/* Does this sth really have a result? */
else if (!res)
do_error(sth, JW_ERR_NOT_ACTIVE,
"statement contains no result" ,NULL);
/* Do the real work. */
else
{
av= newAV();
mysql_field_seek(res, 0);
while ((curField= mysql_fetch_field(res)))
{
SV *sv;
switch(what) {
case AV_ATTRIB_NAME:
sv= newSVpvn(curField->name, strlen(curField->name));
break;
case AV_ATTRIB_TABLE:
sv= newSVpvn(curField->table, strlen(curField->table));
break;
case AV_ATTRIB_TYPE:
sv= newSViv((int) curField->type);
break;
case AV_ATTRIB_SQL_TYPE:
sv= newSViv((int) native2sql(curField->type)->data_type);
break;
case AV_ATTRIB_IS_PRI_KEY:
sv= boolSV(IS_PRI_KEY(curField->flags));
break;
case AV_ATTRIB_IS_NOT_NULL:
sv= boolSV(IS_NOT_NULL(curField->flags));
break;
case AV_ATTRIB_NULLABLE:
sv= boolSV(!IS_NOT_NULL(curField->flags));
break;
case AV_ATTRIB_LENGTH:
sv= newSViv((int) curField->length);
break;
case AV_ATTRIB_IS_NUM:
sv= newSViv((int) native2sql(curField->type)->is_num);
break;
case AV_ATTRIB_TYPE_NAME:
sv= newSVpv((char*) native2sql(curField->type)->type_name, 0);
break;
case AV_ATTRIB_MAX_LENGTH:
sv= newSViv((int) curField->max_length);
break;
case AV_ATTRIB_IS_AUTO_INCREMENT:
#if defined(AUTO_INCREMENT_FLAG)
sv= boolSV(IS_AUTO_INCREMENT(curField->flags));
break;
#else
croak("AUTO_INCREMENT_FLAG is not supported on this machine");
#endif
case AV_ATTRIB_IS_KEY:
sv= boolSV(IS_KEY(curField->flags));
break;
case AV_ATTRIB_IS_BLOB:
sv= boolSV(IS_BLOB(curField->flags));
break;
case AV_ATTRIB_SCALE:
sv= newSViv((int) curField->decimals);
break;
case AV_ATTRIB_PRECISION:
sv= newSViv((int) (curField->length > curField->max_length) ?
curField->length : curField->max_length);
break;
default:
sv= &PL_sv_undef;
break;
}
av_push(av, sv);
}
/* Ensure that this value is kept, decremented in
* dbd_st_destroy and dbd_st_execute. */
if (!cacheit)
return sv_2mortal(newRV_noinc((SV*)av));
imp_sth->av_attr[what]= av;
}
if (av == Nullav)
return &PL_sv_undef;
return sv_2mortal(newRV_inc((SV*)av));
}
/*
**************************************************************************
*
* Name: dbd_st_FETCH_attrib
*
* Purpose: Retrieves a statement handles attributes
*
* Input: sth - statement handle being destroyed
* imp_sth - drivers private statement handle data
* keysv - attribute name
*
* Returns: NULL for an unknown attribute, "undef" for error,
* attribute value otherwise.
*
**************************************************************************/
#define ST_FETCH_AV(what) \
dbd_st_FETCH_internal(sth, (what), imp_sth->result, TRUE)
SV* dbd_st_FETCH_attrib(
SV *sth,
imp_sth_t *imp_sth,
SV *keysv
)
{
dTHX;
STRLEN(kl);
char *key= SvPV(keysv, kl);
SV *retsv= Nullsv;
D_imp_xxh(sth);
if (kl < 2)
return Nullsv;
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh),
" -> dbd_st_FETCH_attrib for %p, key %s\n",
sth, key);
switch (*key) {
case 'N':
if (strEQ(key, "NAME"))
retsv= ST_FETCH_AV(AV_ATTRIB_NAME);
else if (strEQ(key, "NULLABLE"))
retsv= ST_FETCH_AV(AV_ATTRIB_NULLABLE);
break;
case 'P':
if (strEQ(key, "PRECISION"))
retsv= ST_FETCH_AV(AV_ATTRIB_PRECISION);
if (strEQ(key, "ParamValues"))
{
HV *pvhv= newHV();
if (DBIc_NUM_PARAMS(imp_sth))
{
int n;
char key[100];
I32 keylen;
for (n= 0; n < DBIc_NUM_PARAMS(imp_sth); n++)
{
keylen= sprintf(key, "%d", n);
(void)hv_store(pvhv, key,
keylen, newSVsv(imp_sth->params[n].value), 0);
}
}
retsv= sv_2mortal(newRV_noinc((SV*)pvhv));
}
break;
case 'S':
if (strEQ(key, "SCALE"))
retsv= ST_FETCH_AV(AV_ATTRIB_SCALE);
break;
case 'T':
if (strEQ(key, "TYPE"))
retsv= ST_FETCH_AV(AV_ATTRIB_SQL_TYPE);
break;
case 'm':
switch (kl) {
case 10:
if (strEQ(key, "mysql_type"))
retsv= ST_FETCH_AV(AV_ATTRIB_TYPE);
break;
case 11:
if (strEQ(key, "mysql_table"))
retsv= ST_FETCH_AV(AV_ATTRIB_TABLE);
break;
case 12:
if ( strEQ(key, "mysql_is_key"))
retsv= ST_FETCH_AV(AV_ATTRIB_IS_KEY);
else if (strEQ(key, "mysql_is_num"))
retsv= ST_FETCH_AV(AV_ATTRIB_IS_NUM);
else if (strEQ(key, "mysql_length"))
retsv= ST_FETCH_AV(AV_ATTRIB_LENGTH);
else if (strEQ(key, "mysql_result"))
retsv= sv_2mortal(newSViv(PTR2IV(imp_sth->result)));
break;
case 13:
if (strEQ(key, "mysql_is_blob"))
retsv= ST_FETCH_AV(AV_ATTRIB_IS_BLOB);
break;
case 14:
if (strEQ(key, "mysql_insertid"))
{
/* We cannot return an IV, because the insertid is a long. */
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh), "INSERT ID %llu\n", imp_sth->insertid);
return sv_2mortal(my_ulonglong2str(aTHX_ imp_sth->insertid));
}
break;
case 15:
if (strEQ(key, "mysql_type_name"))
retsv = ST_FETCH_AV(AV_ATTRIB_TYPE_NAME);
break;
case 16:
if ( strEQ(key, "mysql_is_pri_key"))
retsv= ST_FETCH_AV(AV_ATTRIB_IS_PRI_KEY);
else if (strEQ(key, "mysql_max_length"))
retsv= ST_FETCH_AV(AV_ATTRIB_MAX_LENGTH);
else if (strEQ(key, "mysql_use_result"))
retsv= boolSV(imp_sth->use_mysql_use_result);
break;
case 19:
if (strEQ(key, "mysql_warning_count"))
retsv= sv_2mortal(newSViv((IV) imp_sth->warning_count));
break;
case 20:
if (strEQ(key, "mysql_server_prepare"))
#if MYSQL_VERSION_ID >= SERVER_PREPARE_VERSION
retsv= sv_2mortal(newSViv((IV) imp_sth->use_server_side_prepare));
#else
retsv= boolSV(0);
#endif
break;
case 23:
if (strEQ(key, "mysql_is_auto_increment"))
retsv = ST_FETCH_AV(AV_ATTRIB_IS_AUTO_INCREMENT);
break;
}
break;
}
return retsv;
}
/***************************************************************************
*
* Name: dbd_st_blob_read
*
* Purpose: Used for blob reads if the statement handles "LongTruncOk"
* attribute (currently not supported by DBD::mysql)
*
* Input: SV* - statement handle from which a blob will be fetched
* imp_sth - drivers private statement handle data
* field - field number of the blob (note, that a row may
* contain more than one blob)
* offset - the offset of the field, where to start reading
* len - maximum number of bytes to read
* destrv - RV* that tells us where to store
* destoffset - destination offset
*
* Returns: TRUE for success, FALSE otherwise; do_error will
* be called in the latter case
*
**************************************************************************/
int dbd_st_blob_read (
SV *sth,
imp_sth_t *imp_sth,
int field,
long offset,
long len,
SV *destrv,
long destoffset)
{
/* quell warnings */
sth= sth;
imp_sth=imp_sth;
field= field;
offset= offset;
len= len;
destrv= destrv;
destoffset= destoffset;
return FALSE;
}
/***************************************************************************
*
* Name: dbd_bind_ph
*
* Purpose: Binds a statement value to a parameter
*
* Input: sth - statement handle
* imp_sth - drivers private statement handle data
* param - parameter number, counting starts with 1
* value - value being inserted for parameter "param"
* sql_type - SQL type of the value
* attribs - bind parameter attributes, currently this must be
* one of the values SQL_CHAR, ...
* inout - TRUE, if parameter is an output variable (currently
* this is not supported)
* maxlen - ???
*
* Returns: TRUE for success, FALSE otherwise
*
**************************************************************************/
int dbd_bind_ph(SV *sth, imp_sth_t *imp_sth, SV *param, SV *value,
IV sql_type, SV *attribs, int is_inout, IV maxlen) {
dTHX;
int rc;
int param_num= SvIV(param);
int idx= param_num - 1;
char *err_msg;
D_imp_xxh(sth);
#if MYSQL_VERSION_ID >= SERVER_PREPARE_VERSION
STRLEN slen;
char *buffer= NULL;
int buffer_is_null= 0;
int buffer_length= slen;
unsigned int buffer_type= 0;
#endif
D_imp_dbh_from_sth;
ASYNC_CHECK_RETURN(sth, FALSE);
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh),
" Called: dbd_bind_ph\n");
attribs= attribs;
maxlen= maxlen;
if (param_num <= 0 || param_num > DBIc_NUM_PARAMS(imp_sth))
{
do_error(sth, JW_ERR_ILLEGAL_PARAM_NUM, "Illegal parameter number", NULL);
return FALSE;
}
/*
This fixes the bug whereby no warning was issued upon binding a
defined non-numeric as numeric
*/
if (SvOK(value) &&
(sql_type == SQL_NUMERIC ||
sql_type == SQL_DECIMAL ||
sql_type == SQL_INTEGER ||
sql_type == SQL_SMALLINT ||
sql_type == SQL_FLOAT ||
sql_type == SQL_REAL ||
sql_type == SQL_DOUBLE) )
{
if (! looks_like_number(value))
{
err_msg = SvPVX(sv_2mortal(newSVpvf(
"Binding non-numeric field %d, value %s as a numeric!",
param_num, neatsvpv(value,0))));
do_error(sth, JW_ERR_ILLEGAL_PARAM_NUM, err_msg, NULL);
}
}
if (is_inout)
{
do_error(sth, JW_ERR_NOT_IMPLEMENTED, "Output parameters not implemented", NULL);
return FALSE;
}
rc = bind_param(&imp_sth->params[idx], value, sql_type);
#if MYSQL_VERSION_ID >= SERVER_PREPARE_VERSION
if (imp_sth->use_server_side_prepare)
{
switch(sql_type) {
case SQL_NUMERIC:
case SQL_INTEGER:
case SQL_SMALLINT:
case SQL_BIGINT:
case SQL_TINYINT:
buffer_type= MYSQL_TYPE_LONG;
break;
case SQL_DOUBLE:
case SQL_DECIMAL:
case SQL_FLOAT:
case SQL_REAL:
buffer_type= MYSQL_TYPE_DOUBLE;
break;
case SQL_CHAR:
case SQL_VARCHAR:
case SQL_DATE:
case SQL_TIME:
case SQL_TIMESTAMP:
case SQL_LONGVARCHAR:
case SQL_BINARY:
case SQL_VARBINARY:
case SQL_LONGVARBINARY:
buffer_type= MYSQL_TYPE_BLOB;
break;
default:
buffer_type= MYSQL_TYPE_STRING;
}
buffer_is_null = !(SvOK(imp_sth->params[idx].value) && imp_sth->params[idx].value);
if (! buffer_is_null) {
switch(buffer_type) {
case MYSQL_TYPE_LONG:
/* INT */
if (!SvIOK(imp_sth->params[idx].value) && DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh), "\t\tTRY TO BIND AN INT NUMBER\n");
buffer_length = sizeof imp_sth->fbind[idx].numeric_val.lval;
imp_sth->fbind[idx].numeric_val.lval= SvIV(imp_sth->params[idx].value);
buffer=(void*)&(imp_sth->fbind[idx].numeric_val.lval);
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh),
" SCALAR type %"IVdf" ->%"IVdf"<- IS A INT NUMBER\n",
sql_type, *(IV *)buffer);
break;
case MYSQL_TYPE_DOUBLE:
if (!SvNOK(imp_sth->params[idx].value) && DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh), "\t\tTRY TO BIND A FLOAT NUMBER\n");
buffer_length = sizeof imp_sth->fbind[idx].numeric_val.dval;
imp_sth->fbind[idx].numeric_val.dval= SvNV(imp_sth->params[idx].value);
buffer=(char*)&(imp_sth->fbind[idx].numeric_val.dval);
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh),
" SCALAR type %"IVdf" ->%f<- IS A FLOAT NUMBER\n",
sql_type, (double)(*buffer));
break;
case MYSQL_TYPE_BLOB:
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh),
" SCALAR type BLOB\n");
break;
case MYSQL_TYPE_STRING:
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh),
" SCALAR type STRING %"IVdf", buffertype=%d\n", sql_type, buffer_type);
break;
default:
croak("Bug in DBD::Mysql file dbdimp.c#dbd_bind_ph: do not know how to handle unknown buffer type.");
}
if (buffer_type == MYSQL_TYPE_STRING || buffer_type == MYSQL_TYPE_BLOB)
{
buffer= SvPV(imp_sth->params[idx].value, slen);
buffer_length= slen;
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh),
" SCALAR type %"IVdf" ->length %d<- IS A STRING or BLOB\n",
sql_type, buffer_length);
}
}
else
{
/*case: buffer_is_null != 0*/
buffer= NULL;
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh),
" SCALAR NULL VALUE: buffer type is: %d\n", buffer_type);
}
/* Type of column was changed. Force to rebind */
if (imp_sth->bind[idx].buffer_type != buffer_type) {
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh),
" FORCE REBIND: buffer type changed from %d to %d, sql-type=%"IVdf"\n",
(int) imp_sth->bind[idx].buffer_type, buffer_type, sql_type);
imp_sth->has_been_bound = 0;
}
/* prepare has been called */
if (imp_sth->has_been_bound)
{
imp_sth->stmt->params[idx].buffer= buffer;
imp_sth->stmt->params[idx].buffer_length= buffer_length;
}
imp_sth->bind[idx].buffer_type= buffer_type;
imp_sth->bind[idx].buffer= buffer;
imp_sth->bind[idx].buffer_length= buffer_length;
imp_sth->fbind[idx].length= buffer_length;
imp_sth->fbind[idx].is_null= buffer_is_null;
}
#endif
return rc;
}
/***************************************************************************
*
* Name: mysql_db_reconnect
*
* Purpose: If the server has disconnected, try to reconnect.
*
* Input: h - database or statement handle
*
* Returns: TRUE for success, FALSE otherwise
*
**************************************************************************/
int mysql_db_reconnect(SV* h)
{
dTHX;
D_imp_xxh(h);
imp_dbh_t* imp_dbh;
MYSQL save_socket;
if (DBIc_TYPE(imp_xxh) == DBIt_ST)
{
imp_dbh = (imp_dbh_t*) DBIc_PARENT_COM(imp_xxh);
h = DBIc_PARENT_H(imp_xxh);
}
else
imp_dbh= (imp_dbh_t*) imp_xxh;
if (mysql_errno(imp_dbh->pmysql) != CR_SERVER_GONE_ERROR)
/* Other error */
return FALSE;
if (!DBIc_has(imp_dbh, DBIcf_AutoCommit) || !imp_dbh->auto_reconnect)
{
/* We never reconnect if AutoCommit is turned off.
* Otherwise we might get an inconsistent transaction
* state.
*/
return FALSE;
}
/* my_login will blow away imp_dbh->mysql so we save a copy of
* imp_dbh->mysql and put it back where it belongs if the reconnect
* fail. Think server is down & reconnect fails but the application eval{}s
* the execute, so next time $dbh->quote() gets called, instant SIGSEGV!
*/
save_socket= *(imp_dbh->pmysql);
memcpy (&save_socket, imp_dbh->pmysql,sizeof(save_socket));
memset (imp_dbh->pmysql,0,sizeof(*(imp_dbh->pmysql)));
/* we should disconnect the db handle before reconnecting, this will
* prevent my_login from thinking it's adopting an active child which
* would prevent the handle from actually reconnecting
*/
if (!dbd_db_disconnect(h, imp_dbh) || !my_login(aTHX_ h, imp_dbh))
{
do_error(h, mysql_errno(imp_dbh->pmysql), mysql_error(imp_dbh->pmysql),
mysql_sqlstate(imp_dbh->pmysql));
memcpy (imp_dbh->pmysql, &save_socket, sizeof(save_socket));
++imp_dbh->stats.auto_reconnects_failed;
return FALSE;
}
/*
* Tell DBI, that dbh->disconnect should be called for this handle
*/
DBIc_ACTIVE_on(imp_dbh);
++imp_dbh->stats.auto_reconnects_ok;
return TRUE;
}
/**************************************************************************
*
* Name: dbd_db_type_info_all
*
* Purpose: Implements $dbh->type_info_all
*
* Input: dbh - database handle
* imp_sth - drivers private database handle data
*
* Returns: RV to AV of types
*
**************************************************************************/
#define PV_PUSH(c) \
if (c) { \
sv= newSVpv((char*) (c), 0); \
SvREADONLY_on(sv); \
} else { \
sv= &PL_sv_undef; \
} \
av_push(row, sv);
#define IV_PUSH(i) sv= newSViv((i)); SvREADONLY_on(sv); av_push(row, sv);
AV *dbd_db_type_info_all(SV *dbh, imp_dbh_t *imp_dbh)
{
dTHX;
AV *av= newAV();
AV *row;
HV *hv;
SV *sv;
int i;
const char *cols[] = {
"TYPE_NAME",
"DATA_TYPE",
"COLUMN_SIZE",
"LITERAL_PREFIX",
"LITERAL_SUFFIX",
"CREATE_PARAMS",
"NULLABLE",
"CASE_SENSITIVE",
"SEARCHABLE",
"UNSIGNED_ATTRIBUTE",
"FIXED_PREC_SCALE",
"AUTO_UNIQUE_VALUE",
"LOCAL_TYPE_NAME",
"MINIMUM_SCALE",
"MAXIMUM_SCALE",
"NUM_PREC_RADIX",
"SQL_DATATYPE",
"SQL_DATETIME_SUB",
"INTERVAL_PRECISION",
"mysql_native_type",
"mysql_is_num"
};
dbh= dbh;
imp_dbh= imp_dbh;
hv= newHV();
av_push(av, newRV_noinc((SV*) hv));
for (i= 0; i < (int)(sizeof(cols) / sizeof(const char*)); i++)
{
if (!hv_store(hv, (char*) cols[i], strlen(cols[i]), newSViv(i), 0))
{
SvREFCNT_dec((SV*) av);
return Nullav;
}
}
for (i= 0; i < (int)SQL_GET_TYPE_INFO_num; i++)
{
const sql_type_info_t *t= &SQL_GET_TYPE_INFO_values[i];
row= newAV();
av_push(av, newRV_noinc((SV*) row));
PV_PUSH(t->type_name);
IV_PUSH(t->data_type);
IV_PUSH(t->column_size);
PV_PUSH(t->literal_prefix);
PV_PUSH(t->literal_suffix);
PV_PUSH(t->create_params);
IV_PUSH(t->nullable);
IV_PUSH(t->case_sensitive);
IV_PUSH(t->searchable);
IV_PUSH(t->unsigned_attribute);
IV_PUSH(t->fixed_prec_scale);
IV_PUSH(t->auto_unique_value);
PV_PUSH(t->local_type_name);
IV_PUSH(t->minimum_scale);
IV_PUSH(t->maximum_scale);
if (t->num_prec_radix)
{
IV_PUSH(t->num_prec_radix);
}
else
av_push(row, &PL_sv_undef);
IV_PUSH(t->sql_datatype); /* SQL_DATATYPE*/
IV_PUSH(t->sql_datetime_sub); /* SQL_DATETIME_SUB*/
IV_PUSH(t->interval_precision); /* INTERVAL_PERCISION */
IV_PUSH(t->native_type);
IV_PUSH(t->is_num);
}
return av;
}
/*
dbd_db_quote
Properly quotes a value
*/
SV* dbd_db_quote(SV *dbh, SV *str, SV *type)
{
dTHX;
SV *result;
if (SvGMAGICAL(str))
mg_get(str);
if (!SvOK(str))
result= newSVpvn("NULL", 4);
else
{
char *ptr, *sptr;
STRLEN len;
D_imp_dbh(dbh);
if (type && SvMAGICAL(type))
mg_get(type);
if (type && SvOK(type))
{
int i;
int tp= SvIV(type);
for (i= 0; i < (int)SQL_GET_TYPE_INFO_num; i++)
{
const sql_type_info_t *t= &SQL_GET_TYPE_INFO_values[i];
if (t->data_type == tp)
{
if (!t->literal_prefix)
return Nullsv;
break;
}
}
}
ptr= SvPV(str, len);
result= newSV(len*2+3);
#ifdef SvUTF8
if (SvUTF8(str)) SvUTF8_on(result);
#endif
sptr= SvPVX(result);
*sptr++ = '\'';
sptr+= mysql_real_escape_string(imp_dbh->pmysql, sptr,
ptr, len);
*sptr++= '\'';
SvPOK_on(result);
SvCUR_set(result, sptr - SvPVX(result));
/* Never hurts NUL terminating a Per string */
*sptr++= '\0';
}
return result;
}
#ifdef DBD_MYSQL_INSERT_ID_IS_GOOD
SV *mysql_db_last_insert_id(SV *dbh, imp_dbh_t *imp_dbh,
SV *catalog, SV *schema, SV *table, SV *field, SV *attr)
{
dTHX;
/* all these non-op settings are to stifle OS X compile warnings */
imp_dbh= imp_dbh;
dbh= dbh;
catalog= catalog;
schema= schema;
table= table;
field= field;
attr= attr;
ASYNC_CHECK_RETURN(dbh, &PL_sv_undef);
return sv_2mortal(my_ulonglong2str(aTHX_ mysql_insert_id(imp_dbh->pmysql)));
}
#endif
#if MYSQL_ASYNC
int mysql_db_async_result(SV* h, MYSQL_RES** resp)
{
dTHX;
D_imp_xxh(h);
imp_dbh_t* dbh;
MYSQL* svsock = NULL;
MYSQL_RES* _res;
int retval = 0;
int htype;
if(! resp) {
resp = &_res;
}
htype = DBIc_TYPE(imp_xxh);
if(htype == DBIt_DB) {
D_imp_dbh(h);
dbh = imp_dbh;
} else {
D_imp_sth(h);
D_imp_dbh_from_sth;
dbh = imp_dbh;
}
if(! dbh->async_query_in_flight) {
do_error(h, 2000, "Gathering asynchronous results for a synchronous handle", "HY000");
return -1;
}
if(dbh->async_query_in_flight != imp_xxh) {
do_error(h, 2000, "Gathering async_query_in_flight results for the wrong handle", "HY000");
return -1;
}
dbh->async_query_in_flight = NULL;
svsock= dbh->pmysql;
retval= mysql_read_query_result(svsock);
if(! retval) {
*resp= mysql_store_result(svsock);
if (mysql_errno(svsock))
do_error(h, mysql_errno(svsock), mysql_error(svsock), mysql_sqlstate(svsock));
if (!*resp)
retval= mysql_affected_rows(svsock);
else {
retval= mysql_num_rows(*resp);
if(resp == &_res) {
mysql_free_result(*resp);
}
}
if(htype == DBIt_ST) {
D_imp_sth(h);
D_imp_dbh_from_sth;
if((my_ulonglong)retval+1 != (my_ulonglong)-1) {
if(! *resp) {
imp_sth->insertid= mysql_insert_id(svsock);
#if MYSQL_VERSION_ID >= MULTIPLE_RESULT_SET_VERSION
if(! mysql_more_results(svsock))
DBIc_ACTIVE_off(imp_sth);
#endif
} else {
DBIc_NUM_FIELDS(imp_sth)= mysql_num_fields(imp_sth->result);
imp_sth->done_desc= 0;
imp_sth->fetch_done= 0;
}
}
imp_sth->warning_count = mysql_warning_count(imp_dbh->pmysql);
}
} else {
do_error(h, mysql_errno(svsock), mysql_error(svsock),
mysql_sqlstate(svsock));
return -1;
}
return retval;
}
int mysql_db_async_ready(SV* h)
{
dTHX;
D_imp_xxh(h);
imp_dbh_t* dbh;
int htype;
htype = DBIc_TYPE(imp_xxh);
if(htype == DBIt_DB) {
D_imp_dbh(h);
dbh = imp_dbh;
} else {
D_imp_sth(h);
D_imp_dbh_from_sth;
dbh = imp_dbh;
}
if(dbh->async_query_in_flight) {
if(dbh->async_query_in_flight == imp_xxh) {
struct pollfd fds;
int retval;
fds.fd = dbh->pmysql->net.fd;
fds.events = POLLIN;
retval = poll(&fds, 1, 0);
if(retval < 0) {
do_error(h, errno, strerror(errno), "HY000");
}
return retval;
} else {
do_error(h, 2000, "Calling mysql_async_ready on the wrong handle", "HY000");
return -1;
}
} else {
do_error(h, 2000, "Handle is not in asynchronous mode", "HY000");
return -1;
}
}
#endif
static int parse_number(char *string, STRLEN len, char **end)
{
int seen_neg;
int seen_dec;
int seen_e;
int seen_plus;
int seen_digit;
char *cp;
seen_neg= seen_dec= seen_e= seen_plus= seen_digit= 0;
if (len <= 0) {
len= strlen(string);
}
cp= string;
/* Skip leading whitespace */
while (*cp && isspace(*cp))
cp++;
for ( ; *cp; cp++)
{
if ('-' == *cp)
{
if (seen_neg >= 2)
{
/*
third '-'. number can contains two '-'.
because -1e-10 is valid number */
break;
}
seen_neg += 1;
}
else if ('.' == *cp)
{
if (seen_dec)
{
/* second '.' */
break;
}
seen_dec= 1;
}
else if ('e' == *cp)
{
if (seen_e)
{
/* second 'e' */
break;
}
seen_e= 1;
}
else if ('+' == *cp)
{
if (seen_plus)
{
/* second '+' */
break;
}
seen_plus= 1;
}
else if (!isdigit(*cp))
{
/* Not sure why this was changed */
/* seen_digit= 1; */
break;
}
}
*end= cp;
/* length 0 -> not a number */
/* Need to revisit this */
/*if (len == 0 || cp - string < (int) len || seen_digit == 0) {*/
if (len == 0 || cp - string < (int) len) {
return -1;
}
return 0;
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_4901_1 |
crossvul-cpp_data_bad_4791_0 | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% M M AAA TTTTT L AAA BBBB %
% MM MM A A T L A A B B %
% M M M AAAAA T L AAAAA BBBB %
% M M A A T L A A B B %
% M M A A T LLLLL A A BBBB %
% %
% %
% Read MATLAB Image Format %
% %
% Software Design %
% Jaroslav Fojtik %
% 2001-2008 %
% %
% %
% Permission is hereby granted, free of charge, to any person obtaining a %
% copy of this software and associated documentation files ("ImageMagick"), %
% to deal in ImageMagick without restriction, including without limitation %
% the rights to use, copy, modify, merge, publish, distribute, sublicense, %
% and/or sell copies of ImageMagick, and to permit persons to whom the %
% ImageMagick is furnished to do so, subject to the following conditions: %
% %
% The above copyright notice and this permission notice shall be included in %
% all copies or substantial portions of ImageMagick. %
% %
% The software is provided "as is", without warranty of any kind, express or %
% implied, including but not limited to the warranties of merchantability, %
% fitness for a particular purpose and noninfringement. In no event shall %
% ImageMagick Studio be liable for any claim, damages or other liability, %
% whether in an action of contract, tort or otherwise, arising from, out of %
% or in connection with ImageMagick or the use or other dealings in %
% ImageMagick. %
% %
% Except as contained in this notice, the name of the ImageMagick Studio %
% shall not be used in advertising or otherwise to promote the sale, use or %
% other dealings in ImageMagick without prior written authorization from the %
% ImageMagick Studio. %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%
*/
/*
Include declarations.
*/
#include "magick/studio.h"
#include "magick/attribute.h"
#include "magick/blob.h"
#include "magick/blob-private.h"
#include "magick/cache.h"
#include "magick/color-private.h"
#include "magick/colormap.h"
#include "magick/colorspace-private.h"
#include "magick/distort.h"
#include "magick/exception.h"
#include "magick/exception-private.h"
#include "magick/image.h"
#include "magick/image-private.h"
#include "magick/list.h"
#include "magick/magick.h"
#include "magick/memory_.h"
#include "magick/monitor.h"
#include "magick/monitor-private.h"
#include "magick/option.h"
#include "magick/pixel.h"
#include "magick/pixel-accessor.h"
#include "magick/quantum-private.h"
#include "magick/resource_.h"
#include "magick/static.h"
#include "magick/string_.h"
#include "magick/module.h"
#include "magick/transform.h"
#include "magick/utility-private.h"
#if defined(MAGICKCORE_ZLIB_DELEGATE)
#include "zlib.h"
#endif
/*
Forward declaration.
*/
static MagickBooleanType
WriteMATImage(const ImageInfo *,Image *);
/* Auto coloring method, sorry this creates some artefact inside data
MinReal+j*MaxComplex = red MaxReal+j*MaxComplex = black
MinReal+j*0 = white MaxReal+j*0 = black
MinReal+j*MinComplex = blue MaxReal+j*MinComplex = black
*/
typedef struct
{
char identific[124];
unsigned short Version;
char EndianIndicator[2];
unsigned long DataType;
unsigned long ObjectSize;
unsigned long unknown1;
unsigned long unknown2;
unsigned short unknown5;
unsigned char StructureFlag;
unsigned char StructureClass;
unsigned long unknown3;
unsigned long unknown4;
unsigned long DimFlag;
unsigned long SizeX;
unsigned long SizeY;
unsigned short Flag1;
unsigned short NameFlag;
}
MATHeader;
static const char *MonthsTab[12]={"Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"};
static const char *DayOfWTab[7]={"Sun","Mon","Tue","Wed","Thu","Fri","Sat"};
static const char *OsDesc=
#ifdef __WIN32__
"PCWIN";
#else
#ifdef __APPLE__
"MAC";
#else
"LNX86";
#endif
#endif
typedef enum
{
miINT8 = 1, /* 8 bit signed */
miUINT8, /* 8 bit unsigned */
miINT16, /* 16 bit signed */
miUINT16, /* 16 bit unsigned */
miINT32, /* 32 bit signed */
miUINT32, /* 32 bit unsigned */
miSINGLE, /* IEEE 754 single precision float */
miRESERVE1,
miDOUBLE, /* IEEE 754 double precision float */
miRESERVE2,
miRESERVE3,
miINT64, /* 64 bit signed */
miUINT64, /* 64 bit unsigned */
miMATRIX, /* MATLAB array */
miCOMPRESSED, /* Compressed Data */
miUTF8, /* Unicode UTF-8 Encoded Character Data */
miUTF16, /* Unicode UTF-16 Encoded Character Data */
miUTF32 /* Unicode UTF-32 Encoded Character Data */
} mat5_data_type;
typedef enum
{
mxCELL_CLASS=1, /* cell array */
mxSTRUCT_CLASS, /* structure */
mxOBJECT_CLASS, /* object */
mxCHAR_CLASS, /* character array */
mxSPARSE_CLASS, /* sparse array */
mxDOUBLE_CLASS, /* double precision array */
mxSINGLE_CLASS, /* single precision floating point */
mxINT8_CLASS, /* 8 bit signed integer */
mxUINT8_CLASS, /* 8 bit unsigned integer */
mxINT16_CLASS, /* 16 bit signed integer */
mxUINT16_CLASS, /* 16 bit unsigned integer */
mxINT32_CLASS, /* 32 bit signed integer */
mxUINT32_CLASS, /* 32 bit unsigned integer */
mxINT64_CLASS, /* 64 bit signed integer */
mxUINT64_CLASS, /* 64 bit unsigned integer */
mxFUNCTION_CLASS /* Function handle */
} arrayclasstype;
#define FLAG_COMPLEX 0x8
#define FLAG_GLOBAL 0x4
#define FLAG_LOGICAL 0x2
static const QuantumType z2qtype[4] = {GrayQuantum, BlueQuantum, GreenQuantum, RedQuantum};
static void InsertComplexDoubleRow(double *p, int y, Image * image, double MinVal,
double MaxVal)
{
ExceptionInfo
*exception;
double f;
int x;
register PixelPacket *q;
if (MinVal == 0)
MinVal = -1;
if (MaxVal == 0)
MaxVal = 1;
exception=(&image->exception);
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
return;
for (x = 0; x < (ssize_t) image->columns; x++)
{
if (*p > 0)
{
f = (*p / MaxVal) * (QuantumRange - GetPixelRed(q));
if (f + GetPixelRed(q) > QuantumRange)
SetPixelRed(q,QuantumRange);
else
SetPixelRed(q,GetPixelRed(q)+(int) f);
if ((int) f / 2.0 > GetPixelGreen(q))
{
SetPixelGreen(q,0);
SetPixelBlue(q,0);
}
else
{
SetPixelBlue(q,GetPixelBlue(q)-(int) (f/2.0));
SetPixelGreen(q,GetPixelBlue(q));
}
}
if (*p < 0)
{
f = (*p / MaxVal) * (QuantumRange - GetPixelBlue(q));
if (f + GetPixelBlue(q) > QuantumRange)
SetPixelBlue(q,QuantumRange);
else
SetPixelBlue(q,GetPixelBlue(q)+(int) f);
if ((int) f / 2.0 > q->green)
{
SetPixelRed(q,0);
SetPixelGreen(q,0);
}
else
{
SetPixelRed(q,GetPixelRed(q)-(int) (f/2.0));
SetPixelGreen(q,GetPixelRed(q));
}
}
p++;
q++;
}
if (!SyncAuthenticPixels(image,exception))
return;
return;
}
static void InsertComplexFloatRow(float *p, int y, Image * image, double MinVal,
double MaxVal)
{
ExceptionInfo
*exception;
double f;
int x;
register PixelPacket *q;
if (MinVal == 0)
MinVal = -1;
if (MaxVal == 0)
MaxVal = 1;
exception=(&image->exception);
q = QueueAuthenticPixels(image, 0, y, image->columns, 1,exception);
if (q == (PixelPacket *) NULL)
return;
for (x = 0; x < (ssize_t) image->columns; x++)
{
if (*p > 0)
{
f = (*p / MaxVal) * (QuantumRange - GetPixelRed(q));
if (f + GetPixelRed(q) > QuantumRange)
SetPixelRed(q,QuantumRange);
else
SetPixelRed(q,GetPixelRed(q)+(int) f);
if ((int) f / 2.0 > GetPixelGreen(q))
{
SetPixelGreen(q,0);
SetPixelBlue(q,0);
}
else
{
SetPixelBlue(q,GetPixelBlue(q)-(int) (f/2.0));
SetPixelGreen(q,GetPixelBlue(q));
}
}
if (*p < 0)
{
f = (*p / MaxVal) * (QuantumRange - GetPixelBlue(q));
if (f + GetPixelBlue(q) > QuantumRange)
SetPixelBlue(q,QuantumRange);
else
SetPixelBlue(q,GetPixelBlue(q)+(int) f);
if ((int) f / 2.0 > q->green)
{
SetPixelGreen(q,0);
SetPixelRed(q,0);
}
else
{
SetPixelRed(q,GetPixelRed(q)-(int) (f/2.0));
SetPixelGreen(q,GetPixelRed(q));
}
}
p++;
q++;
}
if (!SyncAuthenticPixels(image,exception))
return;
return;
}
/************** READERS ******************/
/* This function reads one block of floats*/
static void ReadBlobFloatsLSB(Image * image, size_t len, float *data)
{
while (len >= 4)
{
*data++ = ReadBlobFloat(image);
len -= sizeof(float);
}
if (len > 0)
(void) SeekBlob(image, len, SEEK_CUR);
}
static void ReadBlobFloatsMSB(Image * image, size_t len, float *data)
{
while (len >= 4)
{
*data++ = ReadBlobFloat(image);
len -= sizeof(float);
}
if (len > 0)
(void) SeekBlob(image, len, SEEK_CUR);
}
/* This function reads one block of doubles*/
static void ReadBlobDoublesLSB(Image * image, size_t len, double *data)
{
while (len >= 8)
{
*data++ = ReadBlobDouble(image);
len -= sizeof(double);
}
if (len > 0)
(void) SeekBlob(image, len, SEEK_CUR);
}
static void ReadBlobDoublesMSB(Image * image, size_t len, double *data)
{
while (len >= 8)
{
*data++ = ReadBlobDouble(image);
len -= sizeof(double);
}
if (len > 0)
(void) SeekBlob(image, len, SEEK_CUR);
}
/* Calculate minimum and maximum from a given block of data */
static void CalcMinMax(Image *image, int endian_indicator, int SizeX, int SizeY, size_t CellType, unsigned ldblk, void *BImgBuff, double *Min, double *Max)
{
MagickOffsetType filepos;
int i, x;
void (*ReadBlobDoublesXXX)(Image * image, size_t len, double *data);
void (*ReadBlobFloatsXXX)(Image * image, size_t len, float *data);
double *dblrow;
float *fltrow;
if (endian_indicator == LSBEndian)
{
ReadBlobDoublesXXX = ReadBlobDoublesLSB;
ReadBlobFloatsXXX = ReadBlobFloatsLSB;
}
else /* MI */
{
ReadBlobDoublesXXX = ReadBlobDoublesMSB;
ReadBlobFloatsXXX = ReadBlobFloatsMSB;
}
filepos = TellBlob(image); /* Please note that file seeking occurs only in the case of doubles */
for (i = 0; i < SizeY; i++)
{
if (CellType==miDOUBLE)
{
ReadBlobDoublesXXX(image, ldblk, (double *)BImgBuff);
dblrow = (double *)BImgBuff;
if (i == 0)
{
*Min = *Max = *dblrow;
}
for (x = 0; x < SizeX; x++)
{
if (*Min > *dblrow)
*Min = *dblrow;
if (*Max < *dblrow)
*Max = *dblrow;
dblrow++;
}
}
if (CellType==miSINGLE)
{
ReadBlobFloatsXXX(image, ldblk, (float *)BImgBuff);
fltrow = (float *)BImgBuff;
if (i == 0)
{
*Min = *Max = *fltrow;
}
for (x = 0; x < (ssize_t) SizeX; x++)
{
if (*Min > *fltrow)
*Min = *fltrow;
if (*Max < *fltrow)
*Max = *fltrow;
fltrow++;
}
}
}
(void) SeekBlob(image, filepos, SEEK_SET);
}
static void FixSignedValues(PixelPacket *q, int y)
{
while(y-->0)
{
/* Please note that negative values will overflow
Q=8; QuantumRange=255: <0;127> + 127+1 = <128; 255>
<-1;-128> + 127+1 = <0; 127> */
SetPixelRed(q,GetPixelRed(q)+QuantumRange/2+1);
SetPixelGreen(q,GetPixelGreen(q)+QuantumRange/2+1);
SetPixelBlue(q,GetPixelBlue(q)+QuantumRange/2+1);
q++;
}
}
/** Fix whole row of logical/binary data. It means pack it. */
static void FixLogical(unsigned char *Buff,int ldblk)
{
unsigned char mask=128;
unsigned char *BuffL = Buff;
unsigned char val = 0;
while(ldblk-->0)
{
if(*Buff++ != 0)
val |= mask;
mask >>= 1;
if(mask==0)
{
*BuffL++ = val;
val = 0;
mask = 128;
}
}
*BuffL = val;
}
#if defined(MAGICKCORE_ZLIB_DELEGATE)
static voidpf AcquireZIPMemory(voidpf context,unsigned int items,
unsigned int size)
{
(void) context;
return((voidpf) AcquireQuantumMemory(items,size));
}
static void RelinquishZIPMemory(voidpf context,voidpf memory)
{
(void) context;
memory=RelinquishMagickMemory(memory);
}
#endif
#if defined(MAGICKCORE_ZLIB_DELEGATE)
/** This procedure decompreses an image block for a new MATLAB format. */
static Image *DecompressBlock(Image *orig, MagickOffsetType Size, ImageInfo *clone_info, ExceptionInfo *exception)
{
Image *image2;
void *CacheBlock, *DecompressBlock;
z_stream zip_info;
FILE *mat_file;
size_t magick_size;
size_t extent;
int file;
int status;
if(clone_info==NULL) return NULL;
if(clone_info->file) /* Close file opened from previous transaction. */
{
fclose(clone_info->file);
clone_info->file = NULL;
(void) remove_utf8(clone_info->filename);
}
CacheBlock = AcquireQuantumMemory((size_t)((Size<16384)?Size:16384),sizeof(unsigned char *));
if(CacheBlock==NULL) return NULL;
DecompressBlock = AcquireQuantumMemory((size_t)(4096),sizeof(unsigned char *));
if(DecompressBlock==NULL)
{
RelinquishMagickMemory(CacheBlock);
return NULL;
}
mat_file=0;
file = AcquireUniqueFileResource(clone_info->filename);
if (file != -1)
mat_file = fdopen(file,"w");
if(!mat_file)
{
RelinquishMagickMemory(CacheBlock);
RelinquishMagickMemory(DecompressBlock);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),"Gannot create file stream for PS image");
return NULL;
}
zip_info.zalloc=AcquireZIPMemory;
zip_info.zfree=RelinquishZIPMemory;
zip_info.opaque = (voidpf) NULL;
inflateInit(&zip_info);
/* zip_info.next_out = 8*4;*/
zip_info.avail_in = 0;
zip_info.total_out = 0;
while(Size>0 && !EOFBlob(orig))
{
magick_size = ReadBlob(orig, (Size<16384)?Size:16384, (unsigned char *) CacheBlock);
zip_info.next_in = (Bytef *) CacheBlock;
zip_info.avail_in = (uInt) magick_size;
while(zip_info.avail_in>0)
{
zip_info.avail_out = 4096;
zip_info.next_out = (Bytef *) DecompressBlock;
status = inflate(&zip_info,Z_NO_FLUSH);
extent=fwrite(DecompressBlock, 4096-zip_info.avail_out, 1, mat_file);
(void) extent;
if(status == Z_STREAM_END) goto DblBreak;
}
Size -= magick_size;
}
DblBreak:
inflateEnd(&zip_info);
(void)fclose(mat_file);
RelinquishMagickMemory(CacheBlock);
RelinquishMagickMemory(DecompressBlock);
if((clone_info->file=fopen(clone_info->filename,"rb"))==NULL) goto UnlinkFile;
if( (image2 = AcquireImage(clone_info))==NULL ) goto EraseFile;
status = OpenBlob(clone_info,image2,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
DeleteImageFromList(&image2);
EraseFile:
fclose(clone_info->file);
clone_info->file = NULL;
UnlinkFile:
(void) remove_utf8(clone_info->filename);
return NULL;
}
return image2;
}
#endif
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e a d M A T L A B i m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ReadMATImage() reads an MAT X image file and returns it. It
% allocates the memory necessary for the new Image structure and returns a
% pointer to the new image.
%
% The format of the ReadMATImage method is:
%
% Image *ReadMATImage(const ImageInfo *image_info,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: Method ReadMATImage returns a pointer to the image after
% reading. A null image is returned if there is a memory shortage or if
% the image cannot be read.
%
% o image_info: Specifies a pointer to a ImageInfo structure.
%
% o exception: return any errors or warnings in this structure.
%
*/
static Image *ReadMATImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
Image *image, *image2=NULL,
*rotated_image;
PixelPacket *q;
unsigned int status;
MATHeader MATLAB_HDR;
size_t size;
size_t CellType;
QuantumInfo *quantum_info;
ImageInfo *clone_info;
int i;
ssize_t ldblk;
unsigned char *BImgBuff = NULL;
double MinVal, MaxVal;
size_t Unknown6;
unsigned z, z2;
unsigned Frames;
int logging;
int sample_size;
MagickOffsetType filepos=0x80;
BlobInfo *blob;
size_t one;
unsigned int (*ReadBlobXXXLong)(Image *image);
unsigned short (*ReadBlobXXXShort)(Image *image);
void (*ReadBlobDoublesXXX)(Image * image, size_t len, double *data);
void (*ReadBlobFloatsXXX)(Image * image, size_t len, float *data);
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
logging = LogMagickEvent(CoderEvent,GetMagickModule(),"enter");
/*
Open image file.
*/
image = AcquireImage(image_info);
status = OpenBlob(image_info, image, ReadBinaryBlobMode, exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Read MATLAB image.
*/
clone_info=CloneImageInfo(image_info);
if(ReadBlob(image,124,(unsigned char *) &MATLAB_HDR.identific) != 124)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
MATLAB_HDR.Version = ReadBlobLSBShort(image);
if(ReadBlob(image,2,(unsigned char *) &MATLAB_HDR.EndianIndicator) != 2)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule()," Endian %c%c",
MATLAB_HDR.EndianIndicator[0],MATLAB_HDR.EndianIndicator[1]);
if (!strncmp(MATLAB_HDR.EndianIndicator, "IM", 2))
{
ReadBlobXXXLong = ReadBlobLSBLong;
ReadBlobXXXShort = ReadBlobLSBShort;
ReadBlobDoublesXXX = ReadBlobDoublesLSB;
ReadBlobFloatsXXX = ReadBlobFloatsLSB;
image->endian = LSBEndian;
}
else if (!strncmp(MATLAB_HDR.EndianIndicator, "MI", 2))
{
ReadBlobXXXLong = ReadBlobMSBLong;
ReadBlobXXXShort = ReadBlobMSBShort;
ReadBlobDoublesXXX = ReadBlobDoublesMSB;
ReadBlobFloatsXXX = ReadBlobFloatsMSB;
image->endian = MSBEndian;
}
else
goto MATLAB_KO; /* unsupported endian */
if (strncmp(MATLAB_HDR.identific, "MATLAB", 6))
MATLAB_KO: ThrowReaderException(CorruptImageError,"ImproperImageHeader");
filepos = TellBlob(image);
while(!EOFBlob(image)) /* object parser loop */
{
Frames = 1;
(void) SeekBlob(image,filepos,SEEK_SET);
/* printf("pos=%X\n",TellBlob(image)); */
MATLAB_HDR.DataType = ReadBlobXXXLong(image);
if(EOFBlob(image)) break;
MATLAB_HDR.ObjectSize = ReadBlobXXXLong(image);
if(EOFBlob(image)) break;
filepos += MATLAB_HDR.ObjectSize + 4 + 4;
image2 = image;
#if defined(MAGICKCORE_ZLIB_DELEGATE)
if(MATLAB_HDR.DataType == miCOMPRESSED)
{
image2 = DecompressBlock(image,MATLAB_HDR.ObjectSize,clone_info,exception);
if(image2==NULL) continue;
MATLAB_HDR.DataType = ReadBlobXXXLong(image2); /* replace compressed object type. */
}
#endif
if(MATLAB_HDR.DataType!=miMATRIX) continue; /* skip another objects. */
MATLAB_HDR.unknown1 = ReadBlobXXXLong(image2);
MATLAB_HDR.unknown2 = ReadBlobXXXLong(image2);
MATLAB_HDR.unknown5 = ReadBlobXXXLong(image2);
MATLAB_HDR.StructureClass = MATLAB_HDR.unknown5 & 0xFF;
MATLAB_HDR.StructureFlag = (MATLAB_HDR.unknown5>>8) & 0xFF;
MATLAB_HDR.unknown3 = ReadBlobXXXLong(image2);
if(image!=image2)
MATLAB_HDR.unknown4 = ReadBlobXXXLong(image2); /* ??? don't understand why ?? */
MATLAB_HDR.unknown4 = ReadBlobXXXLong(image2);
MATLAB_HDR.DimFlag = ReadBlobXXXLong(image2);
MATLAB_HDR.SizeX = ReadBlobXXXLong(image2);
MATLAB_HDR.SizeY = ReadBlobXXXLong(image2);
switch(MATLAB_HDR.DimFlag)
{
case 8: z2=z=1; break; /* 2D matrix*/
case 12: z2=z = ReadBlobXXXLong(image2); /* 3D matrix RGB*/
Unknown6 = ReadBlobXXXLong(image2);
(void) Unknown6;
if(z!=3) ThrowReaderException(CoderError, "MultidimensionalMatricesAreNotSupported");
break;
case 16: z2=z = ReadBlobXXXLong(image2); /* 4D matrix animation */
if(z!=3 && z!=1)
ThrowReaderException(CoderError, "MultidimensionalMatricesAreNotSupported");
Frames = ReadBlobXXXLong(image2);
break;
default: ThrowReaderException(CoderError, "MultidimensionalMatricesAreNotSupported");
}
MATLAB_HDR.Flag1 = ReadBlobXXXShort(image2);
MATLAB_HDR.NameFlag = ReadBlobXXXShort(image2);
if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),
"MATLAB_HDR.StructureClass %d",MATLAB_HDR.StructureClass);
if (MATLAB_HDR.StructureClass != mxCHAR_CLASS &&
MATLAB_HDR.StructureClass != mxSINGLE_CLASS && /* float + complex float */
MATLAB_HDR.StructureClass != mxDOUBLE_CLASS && /* double + complex double */
MATLAB_HDR.StructureClass != mxINT8_CLASS &&
MATLAB_HDR.StructureClass != mxUINT8_CLASS && /* uint8 + uint8 3D */
MATLAB_HDR.StructureClass != mxINT16_CLASS &&
MATLAB_HDR.StructureClass != mxUINT16_CLASS && /* uint16 + uint16 3D */
MATLAB_HDR.StructureClass != mxINT32_CLASS &&
MATLAB_HDR.StructureClass != mxUINT32_CLASS && /* uint32 + uint32 3D */
MATLAB_HDR.StructureClass != mxINT64_CLASS &&
MATLAB_HDR.StructureClass != mxUINT64_CLASS) /* uint64 + uint64 3D */
ThrowReaderException(CoderError,"UnsupportedCellTypeInTheMatrix");
switch (MATLAB_HDR.NameFlag)
{
case 0:
size = ReadBlobXXXLong(image2); /* Object name string size */
size = 4 * (ssize_t) ((size + 3 + 1) / 4);
(void) SeekBlob(image2, size, SEEK_CUR);
break;
case 1:
case 2:
case 3:
case 4:
(void) ReadBlob(image2, 4, (unsigned char *) &size); /* Object name string */
break;
default:
goto MATLAB_KO;
}
CellType = ReadBlobXXXLong(image2); /* Additional object type */
if (logging)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"MATLAB_HDR.CellType: %.20g",(double) CellType);
(void) ReadBlob(image2, 4, (unsigned char *) &size); /* data size */
NEXT_FRAME:
switch (CellType)
{
case miINT8:
case miUINT8:
sample_size = 8;
if(MATLAB_HDR.StructureFlag & FLAG_LOGICAL)
image->depth = 1;
else
image->depth = 8; /* Byte type cell */
ldblk = (ssize_t) MATLAB_HDR.SizeX;
break;
case miINT16:
case miUINT16:
sample_size = 16;
image->depth = 16; /* Word type cell */
ldblk = (ssize_t) (2 * MATLAB_HDR.SizeX);
break;
case miINT32:
case miUINT32:
sample_size = 32;
image->depth = 32; /* Dword type cell */
ldblk = (ssize_t) (4 * MATLAB_HDR.SizeX);
break;
case miINT64:
case miUINT64:
sample_size = 64;
image->depth = 64; /* Qword type cell */
ldblk = (ssize_t) (8 * MATLAB_HDR.SizeX);
break;
case miSINGLE:
sample_size = 32;
image->depth = 32; /* double type cell */
(void) SetImageOption(clone_info,"quantum:format","floating-point");
if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX)
{ /* complex float type cell */
}
ldblk = (ssize_t) (4 * MATLAB_HDR.SizeX);
break;
case miDOUBLE:
sample_size = 64;
image->depth = 64; /* double type cell */
(void) SetImageOption(clone_info,"quantum:format","floating-point");
DisableMSCWarning(4127)
if (sizeof(double) != 8)
RestoreMSCWarning
ThrowReaderException(CoderError, "IncompatibleSizeOfDouble");
if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX)
{ /* complex double type cell */
}
ldblk = (ssize_t) (8 * MATLAB_HDR.SizeX);
break;
default:
ThrowReaderException(CoderError, "UnsupportedCellTypeInTheMatrix");
}
(void) sample_size;
image->columns = MATLAB_HDR.SizeX;
image->rows = MATLAB_HDR.SizeY;
quantum_info=AcquireQuantumInfo(clone_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
one=1;
image->colors = one << image->depth;
if (image->columns == 0 || image->rows == 0)
goto MATLAB_KO;
/* Image is gray when no complex flag is set and 2D Matrix */
if ((MATLAB_HDR.DimFlag == 8) &&
((MATLAB_HDR.StructureFlag & FLAG_COMPLEX) == 0))
{
SetImageColorspace(image,GRAYColorspace);
image->type=GrayscaleType;
}
/*
If ping is true, then only set image size and colors without
reading any image data.
*/
if (image_info->ping)
{
size_t temp = image->columns;
image->columns = image->rows;
image->rows = temp;
goto done_reading; /* !!!!!! BAD !!!! */
}
status=SetImageExtent(image,image->columns,image->rows);
if (status == MagickFalse)
{
InheritException(exception,&image->exception);
return(DestroyImageList(image));
}
/* ----- Load raster data ----- */
BImgBuff = (unsigned char *) AcquireQuantumMemory((size_t) (ldblk),sizeof(double)); /* Ldblk was set in the check phase */
if (BImgBuff == NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
MinVal = 0;
MaxVal = 0;
if (CellType==miDOUBLE || CellType==miSINGLE) /* Find Min and Max Values for floats */
{
CalcMinMax(image2, image_info->endian, MATLAB_HDR.SizeX, MATLAB_HDR.SizeY, CellType, ldblk, BImgBuff, &quantum_info->minimum, &quantum_info->maximum);
}
/* Main loop for reading all scanlines */
if(z==1) z=0; /* read grey scanlines */
/* else read color scanlines */
do
{
for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++)
{
q=GetAuthenticPixels(image,0,MATLAB_HDR.SizeY-i-1,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
{
if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),
" MAT set image pixels returns unexpected NULL on a row %u.", (unsigned)(MATLAB_HDR.SizeY-i-1));
goto done_reading; /* Skip image rotation, when cannot set image pixels */
}
if(ReadBlob(image2,ldblk,(unsigned char *)BImgBuff) != (ssize_t) ldblk)
{
if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),
" MAT cannot read scanrow %u from a file.", (unsigned)(MATLAB_HDR.SizeY-i-1));
goto ExitLoop;
}
if((CellType==miINT8 || CellType==miUINT8) && (MATLAB_HDR.StructureFlag & FLAG_LOGICAL))
{
FixLogical((unsigned char *)BImgBuff,ldblk);
if(ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,z2qtype[z],BImgBuff,exception) <= 0)
{
ImportQuantumPixelsFailed:
if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),
" MAT failed to ImportQuantumPixels for a row %u", (unsigned)(MATLAB_HDR.SizeY-i-1));
break;
}
}
else
{
if(ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,z2qtype[z],BImgBuff,exception) <= 0)
goto ImportQuantumPixelsFailed;
if (z<=1 && /* fix only during a last pass z==0 || z==1 */
(CellType==miINT8 || CellType==miINT16 || CellType==miINT32 || CellType==miINT64))
FixSignedValues(q,MATLAB_HDR.SizeX);
}
if (!SyncAuthenticPixels(image,exception))
{
if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),
" MAT failed to sync image pixels for a row %u", (unsigned)(MATLAB_HDR.SizeY-i-1));
goto ExitLoop;
}
}
} while(z-- >= 2);
ExitLoop:
/* Read complex part of numbers here */
if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX)
{ /* Find Min and Max Values for complex parts of floats */
CellType = ReadBlobXXXLong(image2); /* Additional object type */
i = ReadBlobXXXLong(image2); /* size of a complex part - toss away*/
if (CellType==miDOUBLE || CellType==miSINGLE)
{
CalcMinMax(image2, image_info->endian, MATLAB_HDR.SizeX, MATLAB_HDR.SizeY, CellType, ldblk, BImgBuff, &MinVal, &MaxVal);
}
if (CellType==miDOUBLE)
for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++)
{
ReadBlobDoublesXXX(image2, ldblk, (double *)BImgBuff);
InsertComplexDoubleRow((double *)BImgBuff, i, image, MinVal, MaxVal);
}
if (CellType==miSINGLE)
for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++)
{
ReadBlobFloatsXXX(image2, ldblk, (float *)BImgBuff);
InsertComplexFloatRow((float *)BImgBuff, i, image, MinVal, MaxVal);
}
}
/* Image is gray when no complex flag is set and 2D Matrix AGAIN!!! */
if ((MATLAB_HDR.DimFlag == 8) &&
((MATLAB_HDR.StructureFlag & FLAG_COMPLEX) == 0))
image->type=GrayscaleType;
if (image->depth == 1)
image->type=BilevelType;
if(image2==image)
image2 = NULL; /* Remove shadow copy to an image before rotation. */
/* Rotate image. */
rotated_image = RotateImage(image, 90.0, exception);
if (rotated_image != (Image *) NULL)
{
/* Remove page offsets added by RotateImage */
rotated_image->page.x=0;
rotated_image->page.y=0;
blob = rotated_image->blob;
rotated_image->blob = image->blob;
rotated_image->colors = image->colors;
image->blob = blob;
AppendImageToList(&image,rotated_image);
DeleteImageFromList(&image);
}
done_reading:
if(image2!=NULL)
if(image2!=image)
{
DeleteImageFromList(&image2);
if(clone_info)
{
if(clone_info->file)
{
fclose(clone_info->file);
clone_info->file = NULL;
(void) remove_utf8(clone_info->filename);
}
}
}
/* Allocate next image structure. */
AcquireNextImage(image_info,image);
if (image->next == (Image *) NULL) break;
image=SyncNextImageInList(image);
image->columns=image->rows=0;
image->colors=0;
/* row scan buffer is no longer needed */
RelinquishMagickMemory(BImgBuff);
BImgBuff = NULL;
if(--Frames>0)
{
z = z2;
if(image2==NULL) image2 = image;
goto NEXT_FRAME;
}
if(image2!=NULL)
if(image2!=image) /* Does shadow temporary decompressed image exist? */
{
/* CloseBlob(image2); */
DeleteImageFromList(&image2);
if(clone_info)
{
if(clone_info->file)
{
fclose(clone_info->file);
clone_info->file = NULL;
(void) unlink(clone_info->filename);
}
}
}
}
clone_info=DestroyImageInfo(clone_info);
RelinquishMagickMemory(BImgBuff);
CloseBlob(image);
{
Image *p;
ssize_t scene=0;
/*
Rewind list, removing any empty images while rewinding.
*/
p=image;
image=NULL;
while (p != (Image *) NULL)
{
Image *tmp=p;
if ((p->rows == 0) || (p->columns == 0)) {
p=p->previous;
DeleteImageFromList(&tmp);
} else {
image=p;
p=p->previous;
}
}
/*
Fix scene numbers
*/
for (p=image; p != (Image *) NULL; p=p->next)
p->scene=scene++;
}
if(clone_info != NULL) /* cleanup garbage file from compression */
{
if(clone_info->file)
{
fclose(clone_info->file);
clone_info->file = NULL;
(void) remove_utf8(clone_info->filename);
}
DestroyImageInfo(clone_info);
clone_info = NULL;
}
if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),"return");
if(image==NULL)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
return (image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e g i s t e r M A T I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Method RegisterMATImage adds attributes for the MAT image format to
% the list of supported formats. The attributes include the image format
% tag, a method to read and/or write the format, whether the format
% supports the saving of more than one frame to the same file or blob,
% whether the format supports native in-memory I/O, and a brief
% description of the format.
%
% The format of the RegisterMATImage method is:
%
% size_t RegisterMATImage(void)
%
*/
ModuleExport size_t RegisterMATImage(void)
{
MagickInfo
*entry;
entry=SetMagickInfo("MAT");
entry->decoder=(DecodeImageHandler *) ReadMATImage;
entry->encoder=(EncodeImageHandler *) WriteMATImage;
entry->blob_support=MagickFalse;
entry->seekable_stream=MagickTrue;
entry->description=AcquireString("MATLAB level 5 image format");
entry->module=AcquireString("MAT");
(void) RegisterMagickInfo(entry);
return(MagickImageCoderSignature);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% U n r e g i s t e r M A T I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Method UnregisterMATImage removes format registrations made by the
% MAT module from the list of supported formats.
%
% The format of the UnregisterMATImage method is:
%
% UnregisterMATImage(void)
%
*/
ModuleExport void UnregisterMATImage(void)
{
(void) UnregisterMagickInfo("MAT");
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% W r i t e M A T L A B I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Function WriteMATImage writes an Matlab matrix to a file.
%
% The format of the WriteMATImage method is:
%
% unsigned int WriteMATImage(const ImageInfo *image_info,Image *image)
%
% A description of each parameter follows.
%
% o status: Function WriteMATImage return True if the image is written.
% False is returned is there is a memory shortage or if the image file
% fails to write.
%
% o image_info: Specifies a pointer to a ImageInfo structure.
%
% o image: A pointer to an Image structure.
%
*/
static MagickBooleanType WriteMATImage(const ImageInfo *image_info,Image *image)
{
ExceptionInfo
*exception;
ssize_t y;
unsigned z;
const PixelPacket *p;
unsigned int status;
int logging;
size_t DataSize;
char padding;
char MATLAB_HDR[0x80];
time_t current_time;
struct tm local_time;
unsigned char *pixels;
int is_gray;
MagickOffsetType
scene;
QuantumInfo
*quantum_info;
/*
Open output image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
assert(image != (Image *) NULL);
assert(image->signature == MagickSignature);
logging=LogMagickEvent(CoderEvent,GetMagickModule(),"enter MAT");
(void) logging;
status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception);
if (status == MagickFalse)
return(MagickFalse);
image->depth=8;
current_time=time((time_t *) NULL);
#if defined(MAGICKCORE_HAVE_LOCALTIME_R)
(void) localtime_r(¤t_time,&local_time);
#else
(void) memcpy(&local_time,localtime(¤t_time),sizeof(local_time));
#endif
(void) memset(MATLAB_HDR,' ',MagickMin(sizeof(MATLAB_HDR),124));
FormatLocaleString(MATLAB_HDR,sizeof(MATLAB_HDR),
"MATLAB 5.0 MAT-file, Platform: %s, Created on: %s %s %2d %2d:%2d:%2d %d",
OsDesc,DayOfWTab[local_time.tm_wday],MonthsTab[local_time.tm_mon],
local_time.tm_mday,local_time.tm_hour,local_time.tm_min,
local_time.tm_sec,local_time.tm_year+1900);
MATLAB_HDR[0x7C]=0;
MATLAB_HDR[0x7D]=1;
MATLAB_HDR[0x7E]='I';
MATLAB_HDR[0x7F]='M';
(void) WriteBlob(image,sizeof(MATLAB_HDR),(unsigned char *) MATLAB_HDR);
scene=0;
do
{
(void) TransformImageColorspace(image,sRGBColorspace);
is_gray = SetImageGray(image,&image->exception);
z = is_gray ? 0 : 3;
/*
Store MAT header.
*/
DataSize = image->rows /*Y*/ * image->columns /*X*/;
if(!is_gray) DataSize *= 3 /*Z*/;
padding=((unsigned char)(DataSize-1) & 0x7) ^ 0x7;
(void) WriteBlobLSBLong(image, miMATRIX);
(void) WriteBlobLSBLong(image, (unsigned int) DataSize+padding+(is_gray ? 48 : 56));
(void) WriteBlobLSBLong(image, 0x6); /* 0x88 */
(void) WriteBlobLSBLong(image, 0x8); /* 0x8C */
(void) WriteBlobLSBLong(image, 0x6); /* 0x90 */
(void) WriteBlobLSBLong(image, 0);
(void) WriteBlobLSBLong(image, 0x5); /* 0x98 */
(void) WriteBlobLSBLong(image, is_gray ? 0x8 : 0xC); /* 0x9C - DimFlag */
(void) WriteBlobLSBLong(image, (unsigned int) image->rows); /* x: 0xA0 */
(void) WriteBlobLSBLong(image, (unsigned int) image->columns); /* y: 0xA4 */
if(!is_gray)
{
(void) WriteBlobLSBLong(image, 3); /* z: 0xA8 */
(void) WriteBlobLSBLong(image, 0);
}
(void) WriteBlobLSBShort(image, 1); /* 0xB0 */
(void) WriteBlobLSBShort(image, 1); /* 0xB2 */
(void) WriteBlobLSBLong(image, 'M'); /* 0xB4 */
(void) WriteBlobLSBLong(image, 0x2); /* 0xB8 */
(void) WriteBlobLSBLong(image, (unsigned int) DataSize); /* 0xBC */
/*
Store image data.
*/
exception=(&image->exception);
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
pixels=GetQuantumPixels(quantum_info);
do
{
for (y=0; y < (ssize_t)image->columns; y++)
{
p=GetVirtualPixels(image,y,0,1,image->rows,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
(void) ExportQuantumPixels(image,(const CacheView *) NULL,quantum_info,
z2qtype[z],pixels,exception);
(void) WriteBlob(image,image->rows,pixels);
}
if (!SyncAuthenticPixels(image,exception))
break;
} while(z-- >= 2);
while(padding-->0) (void) WriteBlobByte(image,0);
quantum_info=DestroyQuantumInfo(quantum_info);
if (GetNextImageInList(image) == (Image *) NULL)
break;
image=SyncNextImageInList(image);
status=SetImageProgress(image,SaveImagesTag,scene++,
GetImageListLength(image));
if (status == MagickFalse)
break;
} while (image_info->adjoin != MagickFalse);
(void) CloseBlob(image);
return(MagickTrue);
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_4791_0 |
crossvul-cpp_data_good_949_0 | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% AAA N N N N OOO TTTTT AAA TTTTT EEEEE %
% A A NN N NN N O O T A A T E %
% AAAAA N N N N N N O O T AAAAA T EEE %
% A A N NN N NN O O T A A T E %
% A A N N N N OOO T A A T EEEEE %
% %
% %
% MagickCore Image Annotation Methods %
% %
% Software Design %
% Cristy %
% July 1992 %
% %
% %
% Copyright 1999-2019 ImageMagick Studio LLC, a non-profit organization %
% dedicated to making software imaging solutions freely available. %
% %
% You may not use this file except in compliance with the License. You may %
% obtain a copy of the License at %
% %
% https://imagemagick.org/script/license.php %
% %
% Unless required by applicable law or agreed to in writing, software %
% distributed under the License is distributed on an "AS IS" BASIS, %
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %
% See the License for the specific language governing permissions and %
% limitations under the License. %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Digital Applications (www.digapp.com) contributed the stroked text algorithm.
% It was written by Leonard Rosenthol.
%
%
*/
/*
Include declarations.
*/
#include "MagickCore/studio.h"
#include "MagickCore/annotate.h"
#include "MagickCore/annotate-private.h"
#include "MagickCore/attribute.h"
#include "MagickCore/cache-private.h"
#include "MagickCore/cache-view.h"
#include "MagickCore/channel.h"
#include "MagickCore/client.h"
#include "MagickCore/color.h"
#include "MagickCore/color-private.h"
#include "MagickCore/colorspace-private.h"
#include "MagickCore/composite.h"
#include "MagickCore/composite-private.h"
#include "MagickCore/constitute.h"
#include "MagickCore/draw.h"
#include "MagickCore/draw-private.h"
#include "MagickCore/enhance.h"
#include "MagickCore/exception.h"
#include "MagickCore/exception-private.h"
#include "MagickCore/gem.h"
#include "MagickCore/geometry.h"
#include "MagickCore/image-private.h"
#include "MagickCore/log.h"
#include "MagickCore/quantum.h"
#include "MagickCore/quantum-private.h"
#include "MagickCore/pixel-accessor.h"
#include "MagickCore/property.h"
#include "MagickCore/resource_.h"
#include "MagickCore/semaphore.h"
#include "MagickCore/statistic.h"
#include "MagickCore/string_.h"
#include "MagickCore/token.h"
#include "MagickCore/token-private.h"
#include "MagickCore/transform.h"
#include "MagickCore/transform-private.h"
#include "MagickCore/type.h"
#include "MagickCore/utility.h"
#include "MagickCore/utility-private.h"
#include "MagickCore/xwindow.h"
#include "MagickCore/xwindow-private.h"
#if defined(MAGICKCORE_FREETYPE_DELEGATE)
#if defined(__MINGW32__)
# undef interface
#endif
#include <ft2build.h>
#if defined(FT_FREETYPE_H)
# include FT_FREETYPE_H
#else
# include <freetype/freetype.h>
#endif
#if defined(FT_GLYPH_H)
# include FT_GLYPH_H
#else
# include <freetype/ftglyph.h>
#endif
#if defined(FT_OUTLINE_H)
# include FT_OUTLINE_H
#else
# include <freetype/ftoutln.h>
#endif
#if defined(FT_BBOX_H)
# include FT_BBOX_H
#else
# include <freetype/ftbbox.h>
#endif /* defined(FT_BBOX_H) */
#endif
#if defined(MAGICKCORE_RAQM_DELEGATE)
#include <raqm.h>
#endif
typedef struct _GraphemeInfo
{
size_t
index,
x_offset,
x_advance,
y_offset;
size_t
cluster;
} GraphemeInfo;
/*
Annotate semaphores.
*/
static SemaphoreInfo
*annotate_semaphore = (SemaphoreInfo *) NULL;
/*
Forward declarations.
*/
static MagickBooleanType
RenderType(Image *,const DrawInfo *,const PointInfo *,TypeMetric *,
ExceptionInfo *),
RenderPostscript(Image *,const DrawInfo *,const PointInfo *,TypeMetric *,
ExceptionInfo *),
RenderFreetype(Image *,const DrawInfo *,const char *,const PointInfo *,
TypeMetric *,ExceptionInfo *),
RenderX11(Image *,const DrawInfo *,const PointInfo *,TypeMetric *,
ExceptionInfo *);
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ A n n o t a t e C o m p o n e n t G e n e s i s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% AnnotateComponentGenesis() instantiates the annotate component.
%
% The format of the AnnotateComponentGenesis method is:
%
% MagickBooleanType AnnotateComponentGenesis(void)
%
*/
MagickPrivate MagickBooleanType AnnotateComponentGenesis(void)
{
if (annotate_semaphore == (SemaphoreInfo *) NULL)
annotate_semaphore=AcquireSemaphoreInfo();
return(MagickTrue);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ A n n o t a t e C o m p o n e n t T e r m i n u s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% AnnotateComponentTerminus() destroys the annotate component.
%
% The format of the AnnotateComponentTerminus method is:
%
% AnnotateComponentTerminus(void)
%
*/
MagickPrivate void AnnotateComponentTerminus(void)
{
if (annotate_semaphore == (SemaphoreInfo *) NULL)
ActivateSemaphoreInfo(&annotate_semaphore);
RelinquishSemaphoreInfo(&annotate_semaphore);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% A n n o t a t e I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% AnnotateImage() annotates an image with text.
%
% The format of the AnnotateImage method is:
%
% MagickBooleanType AnnotateImage(Image *image,DrawInfo *draw_info,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o draw_info: the draw info.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType AnnotateImage(Image *image,
const DrawInfo *draw_info,ExceptionInfo *exception)
{
char
*p,
primitive[MagickPathExtent],
*text,
**textlist;
DrawInfo
*annotate,
*annotate_info;
GeometryInfo
geometry_info;
MagickBooleanType
status;
PointInfo
offset;
RectangleInfo
geometry;
register ssize_t
i;
TypeMetric
metrics;
size_t
height,
number_lines;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(draw_info != (DrawInfo *) NULL);
assert(draw_info->signature == MagickCoreSignature);
if (draw_info->text == (char *) NULL)
return(MagickFalse);
if (*draw_info->text == '\0')
return(MagickTrue);
annotate=CloneDrawInfo((ImageInfo *) NULL,draw_info);
text=annotate->text;
annotate->text=(char *) NULL;
annotate_info=CloneDrawInfo((ImageInfo *) NULL,draw_info);
number_lines=1;
for (p=text; *p != '\0'; p++)
if (*p == '\n')
number_lines++;
textlist=AcquireQuantumMemory(number_lines+1,sizeof(*textlist));
if (textlist == (char **) NULL)
{
annotate_info=DestroyDrawInfo(annotate_info);
annotate=DestroyDrawInfo(annotate);
text=DestroyString(text);
return(MagickFalse);
}
p=text;
for (i=0; i < number_lines; i++)
{
char
*q;
textlist[i]=p;
for (q=p; *q != '\0'; q++)
if ((*q == '\r') || (*q == '\n'))
break;
if (*q == '\r')
{
*q='\0';
q++;
}
*q='\0';
p=q+1;
}
textlist[i]=(char *) NULL;
SetGeometry(image,&geometry);
SetGeometryInfo(&geometry_info);
if (annotate_info->geometry != (char *) NULL)
{
(void) ParsePageGeometry(image,annotate_info->geometry,&geometry,
exception);
(void) ParseGeometry(annotate_info->geometry,&geometry_info);
}
if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse)
{
annotate_info=DestroyDrawInfo(annotate_info);
annotate=DestroyDrawInfo(annotate);
textlist=(char **) RelinquishMagickMemory(textlist);
text=DestroyString(text);
return(MagickFalse);
}
if (IsGrayColorspace(image->colorspace) != MagickFalse)
(void) SetImageColorspace(image,sRGBColorspace,exception);
status=MagickTrue;
(void) memset(&metrics,0,sizeof(metrics));
for (i=0; textlist[i] != (char *) NULL; i++)
{
if (*textlist[i] == '\0')
continue;
/*
Position text relative to image.
*/
annotate_info->affine.tx=geometry_info.xi-image->page.x;
annotate_info->affine.ty=geometry_info.psi-image->page.y;
(void) CloneString(&annotate->text,textlist[i]);
if ((metrics.width == 0) || (annotate->gravity != NorthWestGravity))
(void) GetTypeMetrics(image,annotate,&metrics,exception);
height=(ssize_t) (metrics.ascent-metrics.descent+
draw_info->interline_spacing+0.5);
switch (annotate->gravity)
{
case UndefinedGravity:
default:
{
offset.x=annotate_info->affine.tx+i*annotate_info->affine.ry*height;
offset.y=annotate_info->affine.ty+i*annotate_info->affine.sy*height;
break;
}
case NorthWestGravity:
{
offset.x=(geometry.width == 0 ? -1.0 : 1.0)*annotate_info->affine.tx+i*
annotate_info->affine.ry*height+annotate_info->affine.ry*
(metrics.ascent+metrics.descent);
offset.y=(geometry.height == 0 ? -1.0 : 1.0)*annotate_info->affine.ty+i*
annotate_info->affine.sy*height+annotate_info->affine.sy*
metrics.ascent;
break;
}
case NorthGravity:
{
offset.x=(geometry.width == 0 ? -1.0 : 1.0)*annotate_info->affine.tx+
geometry.width/2.0+i*annotate_info->affine.ry*height-
annotate_info->affine.sx*metrics.width/2.0+annotate_info->affine.ry*
(metrics.ascent+metrics.descent);
offset.y=(geometry.height == 0 ? -1.0 : 1.0)*annotate_info->affine.ty+i*
annotate_info->affine.sy*height+annotate_info->affine.sy*
metrics.ascent-annotate_info->affine.rx*metrics.width/2.0;
break;
}
case NorthEastGravity:
{
offset.x=(geometry.width == 0 ? 1.0 : -1.0)*annotate_info->affine.tx+
geometry.width+i*annotate_info->affine.ry*height-
annotate_info->affine.sx*metrics.width+annotate_info->affine.ry*
(metrics.ascent+metrics.descent)-1.0;
offset.y=(geometry.height == 0 ? -1.0 : 1.0)*annotate_info->affine.ty+i*
annotate_info->affine.sy*height+annotate_info->affine.sy*
metrics.ascent-annotate_info->affine.rx*metrics.width;
break;
}
case WestGravity:
{
offset.x=(geometry.width == 0 ? -1.0 : 1.0)*annotate_info->affine.tx+i*
annotate_info->affine.ry*height+annotate_info->affine.ry*
(metrics.ascent+metrics.descent-(number_lines-1.0)*height)/2.0;
offset.y=(geometry.height == 0 ? -1.0 : 1.0)*annotate_info->affine.ty+
geometry.height/2.0+i*annotate_info->affine.sy*height+
annotate_info->affine.sy*(metrics.ascent+metrics.descent-
(number_lines-1.0)*height)/2.0;
break;
}
case CenterGravity:
{
offset.x=(geometry.width == 0 ? -1.0 : 1.0)*annotate_info->affine.tx+
geometry.width/2.0+i*annotate_info->affine.ry*height-
annotate_info->affine.sx*metrics.width/2.0+annotate_info->affine.ry*
(metrics.ascent+metrics.descent-(number_lines-1.0)*height)/2.0;
offset.y=(geometry.height == 0 ? -1.0 : 1.0)*annotate_info->affine.ty+
geometry.height/2.0+i*annotate_info->affine.sy*height-
annotate_info->affine.rx*metrics.width/2.0+annotate_info->affine.sy*
(metrics.ascent+metrics.descent-(number_lines-1.0)*height)/2.0;
break;
}
case EastGravity:
{
offset.x=(geometry.width == 0 ? 1.0 : -1.0)*annotate_info->affine.tx+
geometry.width+i*annotate_info->affine.ry*height-
annotate_info->affine.sx*metrics.width+
annotate_info->affine.ry*(metrics.ascent+metrics.descent-
(number_lines-1.0)*height)/2.0-1.0;
offset.y=(geometry.height == 0 ? -1.0 : 1.0)*annotate_info->affine.ty+
geometry.height/2.0+i*annotate_info->affine.sy*height-
annotate_info->affine.rx*metrics.width+
annotate_info->affine.sy*(metrics.ascent+metrics.descent-
(number_lines-1.0)*height)/2.0;
break;
}
case SouthWestGravity:
{
offset.x=(geometry.width == 0 ? -1.0 : 1.0)*annotate_info->affine.tx+i*
annotate_info->affine.ry*height-annotate_info->affine.ry*
(number_lines-1.0)*height;
offset.y=(geometry.height == 0 ? 1.0 : -1.0)*annotate_info->affine.ty+
geometry.height+i*annotate_info->affine.sy*height-
annotate_info->affine.sy*(number_lines-1.0)*height+metrics.descent;
break;
}
case SouthGravity:
{
offset.x=(geometry.width == 0 ? -1.0 : 1.0)*annotate_info->affine.tx+
geometry.width/2.0+i*annotate_info->affine.ry*height-
annotate_info->affine.sx*metrics.width/2.0-
annotate_info->affine.ry*(number_lines-1.0)*height/2.0;
offset.y=(geometry.height == 0 ? 1.0 : -1.0)*annotate_info->affine.ty+
geometry.height+i*annotate_info->affine.sy*height-
annotate_info->affine.rx*metrics.width/2.0-
annotate_info->affine.sy*(number_lines-1.0)*height+metrics.descent;
break;
}
case SouthEastGravity:
{
offset.x=(geometry.width == 0 ? 1.0 : -1.0)*annotate_info->affine.tx+
geometry.width+i*annotate_info->affine.ry*height-
annotate_info->affine.sx*metrics.width-
annotate_info->affine.ry*(number_lines-1.0)*height-1.0;
offset.y=(geometry.height == 0 ? 1.0 : -1.0)*annotate_info->affine.ty+
geometry.height+i*annotate_info->affine.sy*height-
annotate_info->affine.rx*metrics.width-
annotate_info->affine.sy*(number_lines-1.0)*height+metrics.descent;
break;
}
}
switch (annotate->align)
{
case LeftAlign:
{
offset.x=annotate_info->affine.tx+i*annotate_info->affine.ry*height;
offset.y=annotate_info->affine.ty+i*annotate_info->affine.sy*height;
break;
}
case CenterAlign:
{
offset.x=annotate_info->affine.tx+i*annotate_info->affine.ry*height-
annotate_info->affine.sx*metrics.width/2.0;
offset.y=annotate_info->affine.ty+i*annotate_info->affine.sy*height-
annotate_info->affine.rx*metrics.width/2.0;
break;
}
case RightAlign:
{
offset.x=annotate_info->affine.tx+i*annotate_info->affine.ry*height-
annotate_info->affine.sx*metrics.width;
offset.y=annotate_info->affine.ty+i*annotate_info->affine.sy*height-
annotate_info->affine.rx*metrics.width;
break;
}
default:
break;
}
if (draw_info->undercolor.alpha != TransparentAlpha)
{
DrawInfo
*undercolor_info;
/*
Text box.
*/
undercolor_info=CloneDrawInfo((ImageInfo *) NULL,(DrawInfo *) NULL);
undercolor_info->fill=draw_info->undercolor;
undercolor_info->affine=draw_info->affine;
undercolor_info->affine.tx=offset.x-draw_info->affine.ry*metrics.ascent;
undercolor_info->affine.ty=offset.y-draw_info->affine.sy*metrics.ascent;
(void) FormatLocaleString(primitive,MagickPathExtent,
"rectangle 0.0,0.0 %g,%g",metrics.origin.x,(double) height);
(void) CloneString(&undercolor_info->primitive,primitive);
(void) DrawImage(image,undercolor_info,exception);
(void) DestroyDrawInfo(undercolor_info);
}
annotate_info->affine.tx=offset.x;
annotate_info->affine.ty=offset.y;
(void) FormatLocaleString(primitive,MagickPathExtent,"stroke-width %g "
"line 0,0 %g,0",metrics.underline_thickness,metrics.width);
if (annotate->decorate == OverlineDecoration)
{
annotate_info->affine.ty-=(draw_info->affine.sy*(metrics.ascent+
metrics.descent-metrics.underline_position));
(void) CloneString(&annotate_info->primitive,primitive);
(void) DrawImage(image,annotate_info,exception);
}
else
if (annotate->decorate == UnderlineDecoration)
{
annotate_info->affine.ty-=(draw_info->affine.sy*
metrics.underline_position);
(void) CloneString(&annotate_info->primitive,primitive);
(void) DrawImage(image,annotate_info,exception);
}
/*
Annotate image with text.
*/
status=RenderType(image,annotate,&offset,&metrics,exception);
if (status == MagickFalse)
break;
if (annotate->decorate == LineThroughDecoration)
{
annotate_info->affine.ty-=(draw_info->affine.sy*(height+
metrics.underline_position+metrics.descent)/2.0);
(void) CloneString(&annotate_info->primitive,primitive);
(void) DrawImage(image,annotate_info,exception);
}
}
/*
Relinquish resources.
*/
annotate_info=DestroyDrawInfo(annotate_info);
annotate=DestroyDrawInfo(annotate);
textlist=(char **) RelinquishMagickMemory(textlist);
text=DestroyString(text);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% F o r m a t M a g i c k C a p t i o n %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% FormatMagickCaption() formats a caption so that it fits within the image
% width. It returns the number of lines in the formatted caption.
%
% The format of the FormatMagickCaption method is:
%
% ssize_t FormatMagickCaption(Image *image,DrawInfo *draw_info,
% const MagickBooleanType split,TypeMetric *metrics,char **caption,
% ExceptionInfo *exception)
%
% A description of each parameter follows.
%
% o image: The image.
%
% o draw_info: the draw info.
%
% o split: when no convenient line breaks-- insert newline.
%
% o metrics: Return the font metrics in this structure.
%
% o caption: the caption.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport ssize_t FormatMagickCaption(Image *image,DrawInfo *draw_info,
const MagickBooleanType split,TypeMetric *metrics,char **caption,
ExceptionInfo *exception)
{
MagickBooleanType
status;
register char
*p,
*q,
*s;
register ssize_t
i;
size_t
width;
ssize_t
n;
q=draw_info->text;
s=(char *) NULL;
for (p=(*caption); GetUTFCode(p) != 0; p+=GetUTFOctets(p))
{
if (IsUTFSpace(GetUTFCode(p)) != MagickFalse)
s=p;
if (GetUTFCode(p) == '\n')
{
q=draw_info->text;
continue;
}
for (i=0; i < (ssize_t) GetUTFOctets(p); i++)
*q++=(*(p+i));
*q='\0';
status=GetTypeMetrics(image,draw_info,metrics,exception);
if (status == MagickFalse)
break;
width=(size_t) floor(metrics->width+draw_info->stroke_width+0.5);
if (width <= image->columns)
continue;
if (s != (char *) NULL)
{
*s='\n';
p=s;
}
else
if (split != MagickFalse)
{
/*
No convenient line breaks-- insert newline.
*/
n=p-(*caption);
if ((n > 0) && ((*caption)[n-1] != '\n'))
{
char
*target;
target=AcquireString(*caption);
CopyMagickString(target,*caption,n+1);
ConcatenateMagickString(target,"\n",strlen(*caption)+1);
ConcatenateMagickString(target,p,strlen(*caption)+2);
(void) DestroyString(*caption);
*caption=target;
p=(*caption)+n;
}
}
q=draw_info->text;
s=(char *) NULL;
}
n=0;
for (p=(*caption); GetUTFCode(p) != 0; p+=GetUTFOctets(p))
if (GetUTFCode(p) == '\n')
n++;
return(n);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% G e t M u l t i l i n e T y p e M e t r i c s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetMultilineTypeMetrics() returns the following information for the
% specified font and text:
%
% character width
% character height
% ascender
% descender
% text width
% text height
% maximum horizontal advance
% bounds: x1
% bounds: y1
% bounds: x2
% bounds: y2
% origin: x
% origin: y
% underline position
% underline thickness
%
% This method is like GetTypeMetrics() but it returns the maximum text width
% and height for multiple lines of text.
%
% The format of the GetMultilineTypeMetrics method is:
%
% MagickBooleanType GetMultilineTypeMetrics(Image *image,
% const DrawInfo *draw_info,TypeMetric *metrics,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o draw_info: the draw info.
%
% o metrics: Return the font metrics in this structure.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType GetMultilineTypeMetrics(Image *image,
const DrawInfo *draw_info,TypeMetric *metrics,ExceptionInfo *exception)
{
char
**textlist;
DrawInfo
*annotate_info;
MagickBooleanType
status;
register ssize_t
i;
size_t
height,
count;
TypeMetric
extent;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(draw_info != (DrawInfo *) NULL);
assert(draw_info->text != (char *) NULL);
assert(draw_info->signature == MagickCoreSignature);
if (*draw_info->text == '\0')
return(MagickFalse);
annotate_info=CloneDrawInfo((ImageInfo *) NULL,draw_info);
annotate_info->text=DestroyString(annotate_info->text);
/*
Convert newlines to multiple lines of text.
*/
textlist=StringToStrings(draw_info->text,&count);
if (textlist == (char **) NULL)
return(MagickFalse);
annotate_info->render=MagickFalse;
annotate_info->direction=UndefinedDirection;
(void) memset(metrics,0,sizeof(*metrics));
(void) memset(&extent,0,sizeof(extent));
/*
Find the widest of the text lines.
*/
annotate_info->text=textlist[0];
status=GetTypeMetrics(image,annotate_info,&extent,exception);
*metrics=extent;
height=(count*(size_t) (metrics->ascent-metrics->descent+
0.5)+(count-1)*draw_info->interline_spacing);
if (AcquireMagickResource(HeightResource,height) == MagickFalse)
{
(void) ThrowMagickException(exception,GetMagickModule(),ImageError,
"WidthOrHeightExceedsLimit","`%s'",image->filename);
status=MagickFalse;
}
else
{
for (i=1; i < (ssize_t) count; i++)
{
annotate_info->text=textlist[i];
status=GetTypeMetrics(image,annotate_info,&extent,exception);
if (status == MagickFalse)
break;
if (extent.width > metrics->width)
*metrics=extent;
if (AcquireMagickResource(WidthResource,extent.width) == MagickFalse)
{
(void) ThrowMagickException(exception,GetMagickModule(),ImageError,
"WidthOrHeightExceedsLimit","`%s'",image->filename);
status=MagickFalse;
break;
}
}
metrics->height=(double) height;
}
/*
Relinquish resources.
*/
annotate_info->text=(char *) NULL;
annotate_info=DestroyDrawInfo(annotate_info);
for (i=0; i < (ssize_t) count; i++)
textlist[i]=DestroyString(textlist[i]);
textlist=(char **) RelinquishMagickMemory(textlist);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% G e t T y p e M e t r i c s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetTypeMetrics() returns the following information for the specified font
% and text:
%
% character width
% character height
% ascender
% descender
% text width
% text height
% maximum horizontal advance
% bounds: x1
% bounds: y1
% bounds: x2
% bounds: y2
% origin: x
% origin: y
% underline position
% underline thickness
%
% The format of the GetTypeMetrics method is:
%
% MagickBooleanType GetTypeMetrics(Image *image,const DrawInfo *draw_info,
% TypeMetric *metrics,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o draw_info: the draw info.
%
% o metrics: Return the font metrics in this structure.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType GetTypeMetrics(Image *image,
const DrawInfo *draw_info,TypeMetric *metrics,ExceptionInfo *exception)
{
DrawInfo
*annotate_info;
MagickBooleanType
status;
PointInfo
offset;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(draw_info != (DrawInfo *) NULL);
assert(draw_info->text != (char *) NULL);
assert(draw_info->signature == MagickCoreSignature);
annotate_info=CloneDrawInfo((ImageInfo *) NULL,draw_info);
annotate_info->render=MagickFalse;
annotate_info->direction=UndefinedDirection;
(void) memset(metrics,0,sizeof(*metrics));
offset.x=0.0;
offset.y=0.0;
status=RenderType(image,annotate_info,&offset,metrics,exception);
if (image->debug != MagickFalse)
(void) LogMagickEvent(AnnotateEvent,GetMagickModule(),"Metrics: text: %s; "
"width: %g; height: %g; ascent: %g; descent: %g; max advance: %g; "
"bounds: %g,%g %g,%g; origin: %g,%g; pixels per em: %g,%g; "
"underline position: %g; underline thickness: %g",annotate_info->text,
metrics->width,metrics->height,metrics->ascent,metrics->descent,
metrics->max_advance,metrics->bounds.x1,metrics->bounds.y1,
metrics->bounds.x2,metrics->bounds.y2,metrics->origin.x,metrics->origin.y,
metrics->pixels_per_em.x,metrics->pixels_per_em.y,
metrics->underline_position,metrics->underline_thickness);
annotate_info=DestroyDrawInfo(annotate_info);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ R e n d e r T y p e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% RenderType() renders text on the image. It also returns the bounding box of
% the text relative to the image.
%
% The format of the RenderType method is:
%
% MagickBooleanType RenderType(Image *image,DrawInfo *draw_info,
% const PointInfo *offset,TypeMetric *metrics,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o draw_info: the draw info.
%
% o offset: (x,y) location of text relative to image.
%
% o metrics: bounding box of text.
%
% o exception: return any errors or warnings in this structure.
%
*/
static MagickBooleanType RenderType(Image *image,const DrawInfo *draw_info,
const PointInfo *offset,TypeMetric *metrics,ExceptionInfo *exception)
{
const TypeInfo
*type_info;
DrawInfo
*annotate_info;
MagickBooleanType
status;
type_info=(const TypeInfo *) NULL;
if (draw_info->font != (char *) NULL)
{
if (*draw_info->font == '@')
{
status=RenderFreetype(image,draw_info,draw_info->encoding,offset,
metrics,exception);
return(status);
}
if (*draw_info->font == '-')
return(RenderX11(image,draw_info,offset,metrics,exception));
if (*draw_info->font == '^')
return(RenderPostscript(image,draw_info,offset,metrics,exception));
if (IsPathAccessible(draw_info->font) != MagickFalse)
{
status=RenderFreetype(image,draw_info,draw_info->encoding,offset,
metrics,exception);
return(status);
}
type_info=GetTypeInfo(draw_info->font,exception);
if (type_info == (const TypeInfo *) NULL)
(void) ThrowMagickException(exception,GetMagickModule(),TypeWarning,
"UnableToReadFont","`%s'",draw_info->font);
}
if ((type_info == (const TypeInfo *) NULL) &&
(draw_info->family != (const char *) NULL))
{
type_info=GetTypeInfoByFamily(draw_info->family,draw_info->style,
draw_info->stretch,draw_info->weight,exception);
if (type_info == (const TypeInfo *) NULL)
{
char
**family;
int
number_families;
register ssize_t
i;
/*
Parse font family list.
*/
family=StringToArgv(draw_info->family,&number_families);
for (i=1; i < (ssize_t) number_families; i++)
{
type_info=GetTypeInfoByFamily(family[i],draw_info->style,
draw_info->stretch,draw_info->weight,exception);
if (type_info != (const TypeInfo *) NULL)
break;
}
for (i=0; i < (ssize_t) number_families; i++)
family[i]=DestroyString(family[i]);
family=(char **) RelinquishMagickMemory(family);
if (type_info == (const TypeInfo *) NULL)
(void) ThrowMagickException(exception,GetMagickModule(),TypeWarning,
"UnableToReadFont","`%s'",draw_info->family);
}
}
if (type_info == (const TypeInfo *) NULL)
type_info=GetTypeInfoByFamily("Arial",draw_info->style,
draw_info->stretch,draw_info->weight,exception);
if (type_info == (const TypeInfo *) NULL)
type_info=GetTypeInfoByFamily("Helvetica",draw_info->style,
draw_info->stretch,draw_info->weight,exception);
if (type_info == (const TypeInfo *) NULL)
type_info=GetTypeInfoByFamily("Century Schoolbook",draw_info->style,
draw_info->stretch,draw_info->weight,exception);
if (type_info == (const TypeInfo *) NULL)
type_info=GetTypeInfoByFamily("Sans",draw_info->style,
draw_info->stretch,draw_info->weight,exception);
if (type_info == (const TypeInfo *) NULL)
type_info=GetTypeInfoByFamily((const char *) NULL,draw_info->style,
draw_info->stretch,draw_info->weight,exception);
if (type_info == (const TypeInfo *) NULL)
type_info=GetTypeInfo("*",exception);
if (type_info == (const TypeInfo *) NULL)
{
status=RenderFreetype(image,draw_info,draw_info->encoding,offset,metrics,
exception);
return(status);
}
annotate_info=CloneDrawInfo((ImageInfo *) NULL,draw_info);
annotate_info->face=type_info->face;
if (type_info->metrics != (char *) NULL)
(void) CloneString(&annotate_info->metrics,type_info->metrics);
if (type_info->glyphs != (char *) NULL)
(void) CloneString(&annotate_info->font,type_info->glyphs);
status=RenderFreetype(image,annotate_info,type_info->encoding,offset,metrics,
exception);
annotate_info=DestroyDrawInfo(annotate_info);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ R e n d e r F r e e t y p e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% RenderFreetype() renders text on the image with a Truetype font. It also
% returns the bounding box of the text relative to the image.
%
% The format of the RenderFreetype method is:
%
% MagickBooleanType RenderFreetype(Image *image,DrawInfo *draw_info,
% const char *encoding,const PointInfo *offset,TypeMetric *metrics,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o draw_info: the draw info.
%
% o encoding: the font encoding.
%
% o offset: (x,y) location of text relative to image.
%
% o metrics: bounding box of text.
%
% o exception: return any errors or warnings in this structure.
%
*/
#if defined(MAGICKCORE_FREETYPE_DELEGATE)
static size_t ComplexTextLayout(const Image *image,const DrawInfo *draw_info,
const char *text,const size_t length,const FT_Face face,const FT_Int32 flags,
GraphemeInfo **grapheme,ExceptionInfo *exception)
{
#if defined(MAGICKCORE_RAQM_DELEGATE)
const char
*features;
raqm_t
*rq;
raqm_glyph_t
*glyphs;
register ssize_t
i;
size_t
extent;
extent=0;
rq=raqm_create();
if (rq == (raqm_t *) NULL)
goto cleanup;
if (raqm_set_text_utf8(rq,text,length) == 0)
goto cleanup;
if (raqm_set_par_direction(rq,(raqm_direction_t) draw_info->direction) == 0)
goto cleanup;
if (raqm_set_freetype_face(rq,face) == 0)
goto cleanup;
features=GetImageProperty(image,"type:features",exception);
if (features != (const char *) NULL)
{
char
breaker,
quote,
*token;
int
next,
status_token;
TokenInfo
*token_info;
next=0;
token_info=AcquireTokenInfo();
token=AcquireString("");
status_token=Tokenizer(token_info,0,token,50,features,"",",","",'\0',
&breaker,&next,"e);
while (status_token == 0)
{
raqm_add_font_feature(rq,token,strlen(token));
status_token=Tokenizer(token_info,0,token,50,features,"",",","",'\0',
&breaker,&next,"e);
}
token_info=DestroyTokenInfo(token_info);
token=DestroyString(token);
}
if (raqm_layout(rq) == 0)
goto cleanup;
glyphs=raqm_get_glyphs(rq,&extent);
if (glyphs == (raqm_glyph_t *) NULL)
{
extent=0;
goto cleanup;
}
*grapheme=(GraphemeInfo *) AcquireQuantumMemory(extent,sizeof(**grapheme));
if (*grapheme == (GraphemeInfo *) NULL)
{
extent=0;
goto cleanup;
}
for (i=0; i < (ssize_t) extent; i++)
{
(*grapheme)[i].index=glyphs[i].index;
(*grapheme)[i].x_offset=glyphs[i].x_offset;
(*grapheme)[i].x_advance=glyphs[i].x_advance;
(*grapheme)[i].y_offset=glyphs[i].y_offset;
(*grapheme)[i].cluster=glyphs[i].cluster;
}
cleanup:
raqm_destroy(rq);
return(extent);
#else
const char
*p;
FT_Error
ft_status;
register ssize_t
i;
ssize_t
last_glyph;
/*
Simple layout for bi-directional text (right-to-left or left-to-right).
*/
magick_unreferenced(image);
magick_unreferenced(exception);
*grapheme=(GraphemeInfo *) AcquireQuantumMemory(length+1,sizeof(**grapheme));
if (*grapheme == (GraphemeInfo *) NULL)
return(0);
last_glyph=0;
p=text;
for (i=0; GetUTFCode(p) != 0; p+=GetUTFOctets(p), i++)
{
(*grapheme)[i].index=(ssize_t) FT_Get_Char_Index(face,GetUTFCode(p));
(*grapheme)[i].x_offset=0;
(*grapheme)[i].y_offset=0;
if (((*grapheme)[i].index != 0) && (last_glyph != 0))
{
if (FT_HAS_KERNING(face))
{
FT_Vector
kerning;
ft_status=FT_Get_Kerning(face,(FT_UInt) last_glyph,(FT_UInt)
(*grapheme)[i].index,ft_kerning_default,&kerning);
if (ft_status == 0)
(*grapheme)[i-1].x_advance+=(FT_Pos) ((draw_info->direction ==
RightToLeftDirection ? -1.0 : 1.0)*kerning.x);
}
}
ft_status=FT_Load_Glyph(face,(FT_UInt) (*grapheme)[i].index,flags);
(*grapheme)[i].x_advance=face->glyph->advance.x;
(*grapheme)[i].cluster=p-text;
last_glyph=(*grapheme)[i].index;
}
return((size_t) i);
#endif
}
static int TraceCubicBezier(FT_Vector *p,FT_Vector *q,FT_Vector *to,
DrawInfo *draw_info)
{
AffineMatrix
affine;
char
path[MagickPathExtent];
affine=draw_info->affine;
(void) FormatLocaleString(path,MagickPathExtent,"C%g,%g %g,%g %g,%g",
affine.tx+p->x/64.0,affine.ty-p->y/64.0,affine.tx+q->x/64.0,affine.ty-
q->y/64.0,affine.tx+to->x/64.0,affine.ty-to->y/64.0);
(void) ConcatenateString(&draw_info->primitive,path);
return(0);
}
static int TraceLineTo(FT_Vector *to,DrawInfo *draw_info)
{
AffineMatrix
affine;
char
path[MagickPathExtent];
affine=draw_info->affine;
(void) FormatLocaleString(path,MagickPathExtent,"L%g,%g",affine.tx+to->x/64.0,
affine.ty-to->y/64.0);
(void) ConcatenateString(&draw_info->primitive,path);
return(0);
}
static int TraceMoveTo(FT_Vector *to,DrawInfo *draw_info)
{
AffineMatrix
affine;
char
path[MagickPathExtent];
affine=draw_info->affine;
(void) FormatLocaleString(path,MagickPathExtent,"M%g,%g",affine.tx+to->x/64.0,
affine.ty-to->y/64.0);
(void) ConcatenateString(&draw_info->primitive,path);
return(0);
}
static int TraceQuadraticBezier(FT_Vector *control,FT_Vector *to,
DrawInfo *draw_info)
{
AffineMatrix
affine;
char
path[MagickPathExtent];
affine=draw_info->affine;
(void) FormatLocaleString(path,MagickPathExtent,"Q%g,%g %g,%g",affine.tx+
control->x/64.0,affine.ty-control->y/64.0,affine.tx+to->x/64.0,affine.ty-
to->y/64.0);
(void) ConcatenateString(&draw_info->primitive,path);
return(0);
}
static MagickBooleanType RenderFreetype(Image *image,const DrawInfo *draw_info,
const char *encoding,const PointInfo *offset,TypeMetric *metrics,
ExceptionInfo *exception)
{
#if !defined(FT_OPEN_PATHNAME)
#define FT_OPEN_PATHNAME ft_open_pathname
#endif
typedef struct _GlyphInfo
{
FT_UInt
id;
FT_Vector
origin;
FT_Glyph
image;
} GlyphInfo;
const char
*value;
DrawInfo
*annotate_info;
FT_BBox
bounds;
FT_BitmapGlyph
bitmap;
FT_Encoding
encoding_type;
FT_Error
ft_status;
FT_Face
face;
FT_Int32
flags;
FT_Library
library;
FT_Matrix
affine;
FT_Open_Args
args;
FT_Vector
origin;
GlyphInfo
glyph,
last_glyph;
GraphemeInfo
*grapheme;
MagickBooleanType
status;
PointInfo
point,
resolution;
register char
*p;
register ssize_t
i;
size_t
length;
ssize_t
code,
y;
static FT_Outline_Funcs
OutlineMethods =
{
(FT_Outline_MoveTo_Func) TraceMoveTo,
(FT_Outline_LineTo_Func) TraceLineTo,
(FT_Outline_ConicTo_Func) TraceQuadraticBezier,
(FT_Outline_CubicTo_Func) TraceCubicBezier,
0, 0
};
unsigned char
*utf8;
/*
Initialize Truetype library.
*/
ft_status=FT_Init_FreeType(&library);
if (ft_status != 0)
ThrowBinaryException(TypeError,"UnableToInitializeFreetypeLibrary",
image->filename);
args.flags=FT_OPEN_PATHNAME;
if (draw_info->font == (char *) NULL)
args.pathname=ConstantString("helvetica");
else
if (*draw_info->font != '@')
args.pathname=ConstantString(draw_info->font);
else
args.pathname=ConstantString(draw_info->font+1);
face=(FT_Face) NULL;
ft_status=FT_Open_Face(library,&args,(long) draw_info->face,&face);
if (ft_status != 0)
{
(void) FT_Done_FreeType(library);
(void) ThrowMagickException(exception,GetMagickModule(),TypeError,
"UnableToReadFont","`%s'",args.pathname);
args.pathname=DestroyString(args.pathname);
return(MagickFalse);
}
args.pathname=DestroyString(args.pathname);
if ((draw_info->metrics != (char *) NULL) &&
(IsPathAccessible(draw_info->metrics) != MagickFalse))
(void) FT_Attach_File(face,draw_info->metrics);
encoding_type=FT_ENCODING_UNICODE;
ft_status=FT_Select_Charmap(face,encoding_type);
if ((ft_status != 0) && (face->num_charmaps != 0))
ft_status=FT_Set_Charmap(face,face->charmaps[0]);
if (encoding != (const char *) NULL)
{
if (LocaleCompare(encoding,"AdobeCustom") == 0)
encoding_type=FT_ENCODING_ADOBE_CUSTOM;
if (LocaleCompare(encoding,"AdobeExpert") == 0)
encoding_type=FT_ENCODING_ADOBE_EXPERT;
if (LocaleCompare(encoding,"AdobeStandard") == 0)
encoding_type=FT_ENCODING_ADOBE_STANDARD;
if (LocaleCompare(encoding,"AppleRoman") == 0)
encoding_type=FT_ENCODING_APPLE_ROMAN;
if (LocaleCompare(encoding,"BIG5") == 0)
encoding_type=FT_ENCODING_BIG5;
#if defined(FT_ENCODING_PRC)
if (LocaleCompare(encoding,"GB2312") == 0)
encoding_type=FT_ENCODING_PRC;
#endif
#if defined(FT_ENCODING_JOHAB)
if (LocaleCompare(encoding,"Johab") == 0)
encoding_type=FT_ENCODING_JOHAB;
#endif
#if defined(FT_ENCODING_ADOBE_LATIN_1)
if (LocaleCompare(encoding,"Latin-1") == 0)
encoding_type=FT_ENCODING_ADOBE_LATIN_1;
#endif
#if defined(FT_ENCODING_ADOBE_LATIN_2)
if (LocaleCompare(encoding,"Latin-2") == 0)
encoding_type=FT_ENCODING_OLD_LATIN_2;
#endif
if (LocaleCompare(encoding,"None") == 0)
encoding_type=FT_ENCODING_NONE;
if (LocaleCompare(encoding,"SJIScode") == 0)
encoding_type=FT_ENCODING_SJIS;
if (LocaleCompare(encoding,"Symbol") == 0)
encoding_type=FT_ENCODING_MS_SYMBOL;
if (LocaleCompare(encoding,"Unicode") == 0)
encoding_type=FT_ENCODING_UNICODE;
if (LocaleCompare(encoding,"Wansung") == 0)
encoding_type=FT_ENCODING_WANSUNG;
ft_status=FT_Select_Charmap(face,encoding_type);
if (ft_status != 0)
{
(void) FT_Done_Face(face);
(void) FT_Done_FreeType(library);
ThrowBinaryException(TypeError,"UnrecognizedFontEncoding",encoding);
}
}
/*
Set text size.
*/
resolution.x=DefaultResolution;
resolution.y=DefaultResolution;
if (draw_info->density != (char *) NULL)
{
GeometryInfo
geometry_info;
MagickStatusType
geometry_flags;
geometry_flags=ParseGeometry(draw_info->density,&geometry_info);
resolution.x=geometry_info.rho;
resolution.y=geometry_info.sigma;
if ((geometry_flags & SigmaValue) == 0)
resolution.y=resolution.x;
}
ft_status=FT_Set_Char_Size(face,(FT_F26Dot6) (64.0*draw_info->pointsize),
(FT_F26Dot6) (64.0*draw_info->pointsize),(FT_UInt) resolution.x,
(FT_UInt) resolution.y);
if (ft_status != 0)
{
(void) FT_Done_Face(face);
(void) FT_Done_FreeType(library);
ThrowBinaryException(TypeError,"UnableToReadFont",draw_info->font);
}
metrics->pixels_per_em.x=face->size->metrics.x_ppem;
metrics->pixels_per_em.y=face->size->metrics.y_ppem;
metrics->ascent=(double) face->size->metrics.ascender/64.0;
metrics->descent=(double) face->size->metrics.descender/64.0;
metrics->width=0;
metrics->origin.x=0;
metrics->origin.y=0;
metrics->height=(double) face->size->metrics.height/64.0;
metrics->max_advance=0.0;
if (face->size->metrics.max_advance > MagickEpsilon)
metrics->max_advance=(double) face->size->metrics.max_advance/64.0;
metrics->bounds.x1=0.0;
metrics->bounds.y1=metrics->descent;
metrics->bounds.x2=metrics->ascent+metrics->descent;
metrics->bounds.y2=metrics->ascent+metrics->descent;
metrics->underline_position=face->underline_position/64.0;
metrics->underline_thickness=face->underline_thickness/64.0;
if ((draw_info->text == (char *) NULL) || (*draw_info->text == '\0'))
{
(void) FT_Done_Face(face);
(void) FT_Done_FreeType(library);
return(MagickTrue);
}
/*
Compute bounding box.
*/
if (image->debug != MagickFalse)
(void) LogMagickEvent(AnnotateEvent,GetMagickModule(),"Font %s; "
"font-encoding %s; text-encoding %s; pointsize %g",
draw_info->font != (char *) NULL ? draw_info->font : "none",
encoding != (char *) NULL ? encoding : "none",
draw_info->encoding != (char *) NULL ? draw_info->encoding : "none",
draw_info->pointsize);
flags=FT_LOAD_DEFAULT;
if (draw_info->render == MagickFalse)
flags=FT_LOAD_NO_BITMAP;
if (draw_info->text_antialias == MagickFalse)
flags|=FT_LOAD_TARGET_MONO;
else
{
#if defined(FT_LOAD_TARGET_LIGHT)
flags|=FT_LOAD_TARGET_LIGHT;
#elif defined(FT_LOAD_TARGET_LCD)
flags|=FT_LOAD_TARGET_LCD;
#endif
}
value=GetImageProperty(image,"type:hinting",exception);
if ((value != (const char *) NULL) && (LocaleCompare(value,"off") == 0))
flags|=FT_LOAD_NO_HINTING;
glyph.id=0;
glyph.image=NULL;
last_glyph.id=0;
last_glyph.image=NULL;
origin.x=0;
origin.y=0;
affine.xx=65536L;
affine.yx=0L;
affine.xy=0L;
affine.yy=65536L;
if (draw_info->render != MagickFalse)
{
affine.xx=(FT_Fixed) (65536L*draw_info->affine.sx+0.5);
affine.yx=(FT_Fixed) (-65536L*draw_info->affine.rx+0.5);
affine.xy=(FT_Fixed) (-65536L*draw_info->affine.ry+0.5);
affine.yy=(FT_Fixed) (65536L*draw_info->affine.sy+0.5);
}
annotate_info=CloneDrawInfo((ImageInfo *) NULL,draw_info);
if (annotate_info->dash_pattern != (double *) NULL)
annotate_info->dash_pattern[0]=0.0;
(void) CloneString(&annotate_info->primitive,"path '");
status=MagickTrue;
if (draw_info->render != MagickFalse)
{
if (image->storage_class != DirectClass)
(void) SetImageStorageClass(image,DirectClass,exception);
if (image->alpha_trait == UndefinedPixelTrait)
(void) SetImageAlphaChannel(image,OpaqueAlphaChannel,exception);
}
point.x=0.0;
point.y=0.0;
for (p=draw_info->text; GetUTFCode(p) != 0; p+=GetUTFOctets(p))
if (GetUTFCode(p) < 0)
break;
utf8=(unsigned char *) NULL;
if (GetUTFCode(p) == 0)
p=draw_info->text;
else
{
utf8=ConvertLatin1ToUTF8((unsigned char *) draw_info->text);
if (utf8 != (unsigned char *) NULL)
p=(char *) utf8;
}
grapheme=(GraphemeInfo *) NULL;
length=ComplexTextLayout(image,draw_info,p,strlen(p),face,flags,&grapheme,
exception);
code=0;
for (i=0; i < (ssize_t) length; i++)
{
FT_Outline
outline;
/*
Render UTF-8 sequence.
*/
glyph.id=(FT_UInt) grapheme[i].index;
if (glyph.id == 0)
glyph.id=FT_Get_Char_Index(face,' ');
if ((glyph.id != 0) && (last_glyph.id != 0))
origin.x+=(FT_Pos) (64.0*draw_info->kerning);
glyph.origin=origin;
glyph.origin.x+=(FT_Pos) grapheme[i].x_offset;
glyph.origin.y+=(FT_Pos) grapheme[i].y_offset;
glyph.image=0;
ft_status=FT_Load_Glyph(face,glyph.id,flags);
if (ft_status != 0)
continue;
ft_status=FT_Get_Glyph(face->glyph,&glyph.image);
if (ft_status != 0)
continue;
outline=((FT_OutlineGlyph) glyph.image)->outline;
ft_status=FT_Outline_Get_BBox(&outline,&bounds);
if (ft_status != 0)
continue;
if ((p == draw_info->text) || (bounds.xMin < metrics->bounds.x1))
if (bounds.xMin != 0)
metrics->bounds.x1=(double) bounds.xMin;
if ((p == draw_info->text) || (bounds.yMin < metrics->bounds.y1))
if (bounds.yMin != 0)
metrics->bounds.y1=(double) bounds.yMin;
if ((p == draw_info->text) || (bounds.xMax > metrics->bounds.x2))
if (bounds.xMax != 0)
metrics->bounds.x2=(double) bounds.xMax;
if ((p == draw_info->text) || (bounds.yMax > metrics->bounds.y2))
if (bounds.yMax != 0)
metrics->bounds.y2=(double) bounds.yMax;
if (((draw_info->stroke.alpha != TransparentAlpha) ||
(draw_info->stroke_pattern != (Image *) NULL)) &&
((status != MagickFalse) && (draw_info->render != MagickFalse)))
{
/*
Trace the glyph.
*/
annotate_info->affine.tx=glyph.origin.x/64.0;
annotate_info->affine.ty=(-glyph.origin.y/64.0);
if ((outline.n_contours > 0) && (outline.n_points > 0))
ft_status=FT_Outline_Decompose(&outline,&OutlineMethods,
annotate_info);
}
FT_Vector_Transform(&glyph.origin,&affine);
(void) FT_Glyph_Transform(glyph.image,&affine,&glyph.origin);
ft_status=FT_Glyph_To_Bitmap(&glyph.image,ft_render_mode_normal,
(FT_Vector *) NULL,MagickTrue);
if (ft_status != 0)
continue;
bitmap=(FT_BitmapGlyph) glyph.image;
point.x=offset->x+bitmap->left;
if (bitmap->bitmap.pixel_mode == ft_pixel_mode_mono)
point.x=offset->x+(origin.x >> 6);
point.y=offset->y-bitmap->top;
if (draw_info->render != MagickFalse)
{
CacheView
*image_view;
MagickBooleanType
transparent_fill;
register unsigned char
*r;
/*
Rasterize the glyph.
*/
transparent_fill=((draw_info->fill.alpha == TransparentAlpha) &&
(draw_info->fill_pattern == (Image *) NULL) &&
(draw_info->stroke.alpha == TransparentAlpha) &&
(draw_info->stroke_pattern == (Image *) NULL)) ? MagickTrue :
MagickFalse;
image_view=AcquireAuthenticCacheView(image,exception);
r=bitmap->bitmap.buffer;
for (y=0; y < (ssize_t) bitmap->bitmap.rows; y++)
{
double
fill_opacity;
MagickBooleanType
active,
sync;
PixelInfo
fill_color;
register Quantum
*magick_restrict q;
register ssize_t
x;
ssize_t
n,
x_offset,
y_offset;
if (status == MagickFalse)
continue;
x_offset=(ssize_t) ceil(point.x-0.5);
y_offset=(ssize_t) ceil(point.y+y-0.5);
if ((y_offset < 0) || (y_offset >= (ssize_t) image->rows))
continue;
q=(Quantum *) NULL;
if ((x_offset < 0) || (x_offset >= (ssize_t) image->columns))
active=MagickFalse;
else
{
q=GetCacheViewAuthenticPixels(image_view,x_offset,y_offset,
bitmap->bitmap.width,1,exception);
active=q != (Quantum *) NULL ? MagickTrue : MagickFalse;
}
n=y*bitmap->bitmap.pitch-1;
for (x=0; x < (ssize_t) bitmap->bitmap.width; x++)
{
n++;
x_offset++;
if ((x_offset < 0) || (x_offset >= (ssize_t) image->columns))
{
if (q != (Quantum *) NULL)
q+=GetPixelChannels(image);
continue;
}
if (bitmap->bitmap.pixel_mode != ft_pixel_mode_mono)
fill_opacity=(double) (r[n])/(bitmap->bitmap.num_grays-1);
else
fill_opacity=((r[(x >> 3)+y*bitmap->bitmap.pitch] &
(1 << (~x & 0x07)))) == 0 ? 0.0 : 1.0;
if (draw_info->text_antialias == MagickFalse)
fill_opacity=fill_opacity >= 0.5 ? 1.0 : 0.0;
if (active == MagickFalse)
q=GetCacheViewAuthenticPixels(image_view,x_offset,y_offset,1,1,
exception);
if (q == (Quantum *) NULL)
continue;
if (transparent_fill == MagickFalse)
{
GetPixelInfo(image,&fill_color);
GetFillColor(draw_info,x_offset,y_offset,&fill_color,exception);
fill_opacity=fill_opacity*fill_color.alpha;
CompositePixelOver(image,&fill_color,fill_opacity,q,
GetPixelAlpha(image,q),q);
}
else
{
double
Sa,
Da;
Da=1.0-(QuantumScale*GetPixelAlpha(image,q));
Sa=fill_opacity;
fill_opacity=(1.0-RoundToUnity(Sa+Da-Sa*Da))*QuantumRange;
SetPixelAlpha(image,fill_opacity,q);
}
if (active == MagickFalse)
{
sync=SyncCacheViewAuthenticPixels(image_view,exception);
if (sync == MagickFalse)
status=MagickFalse;
}
q+=GetPixelChannels(image);
}
sync=SyncCacheViewAuthenticPixels(image_view,exception);
if (sync == MagickFalse)
status=MagickFalse;
}
image_view=DestroyCacheView(image_view);
if (((draw_info->stroke.alpha != TransparentAlpha) ||
(draw_info->stroke_pattern != (Image *) NULL)) &&
(status != MagickFalse))
{
/*
Draw text stroke.
*/
annotate_info->linejoin=RoundJoin;
annotate_info->affine.tx=offset->x;
annotate_info->affine.ty=offset->y;
(void) ConcatenateString(&annotate_info->primitive,"'");
if (strlen(annotate_info->primitive) > 7)
(void) DrawImage(image,annotate_info,exception);
(void) CloneString(&annotate_info->primitive,"path '");
}
}
if ((fabs(draw_info->interword_spacing) >= MagickEpsilon) &&
(IsUTFSpace(GetUTFCode(p+grapheme[i].cluster)) != MagickFalse) &&
(IsUTFSpace(code) == MagickFalse))
origin.x+=(FT_Pos) (64.0*draw_info->interword_spacing);
else
origin.x+=(FT_Pos) grapheme[i].x_advance;
metrics->origin.x=(double) origin.x;
metrics->origin.y=(double) origin.y;
if (metrics->origin.x > metrics->width)
metrics->width=metrics->origin.x;
if (last_glyph.image != 0)
{
FT_Done_Glyph(last_glyph.image);
last_glyph.image=0;
}
last_glyph=glyph;
code=GetUTFCode(p+grapheme[i].cluster);
}
if (grapheme != (GraphemeInfo *) NULL)
grapheme=(GraphemeInfo *) RelinquishMagickMemory(grapheme);
if (utf8 != (unsigned char *) NULL)
utf8=(unsigned char *) RelinquishMagickMemory(utf8);
if (glyph.image != 0)
{
FT_Done_Glyph(glyph.image);
glyph.image=0;
}
/*
Determine font metrics.
*/
metrics->bounds.x1/=64.0;
metrics->bounds.y1/=64.0;
metrics->bounds.x2/=64.0;
metrics->bounds.y2/=64.0;
metrics->origin.x/=64.0;
metrics->origin.y/=64.0;
metrics->width/=64.0;
/*
Relinquish resources.
*/
annotate_info=DestroyDrawInfo(annotate_info);
(void) FT_Done_Face(face);
(void) FT_Done_FreeType(library);
return(status);
}
#else
static MagickBooleanType RenderFreetype(Image *image,const DrawInfo *draw_info,
const char *magick_unused(encoding),const PointInfo *offset,
TypeMetric *metrics,ExceptionInfo *exception)
{
(void) ThrowMagickException(exception,GetMagickModule(),
MissingDelegateWarning,"DelegateLibrarySupportNotBuiltIn","'%s' (Freetype)",
draw_info->font != (char *) NULL ? draw_info->font : "none");
return(RenderPostscript(image,draw_info,offset,metrics,exception));
}
#endif
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ R e n d e r P o s t s c r i p t %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% RenderPostscript() renders text on the image with a Postscript font. It
% also returns the bounding box of the text relative to the image.
%
% The format of the RenderPostscript method is:
%
% MagickBooleanType RenderPostscript(Image *image,DrawInfo *draw_info,
% const PointInfo *offset,TypeMetric *metrics,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o draw_info: the draw info.
%
% o offset: (x,y) location of text relative to image.
%
% o metrics: bounding box of text.
%
% o exception: return any errors or warnings in this structure.
%
*/
static char *EscapeParenthesis(const char *source)
{
char
*destination;
register char
*q;
register const char
*p;
size_t
length;
assert(source != (const char *) NULL);
length=0;
for (p=source; *p != '\0'; p++)
{
if ((*p == '\\') || (*p == '(') || (*p == ')'))
{
if (~length < 1)
ThrowFatalException(ResourceLimitFatalError,"UnableToEscapeString");
length++;
}
length++;
}
destination=(char *) NULL;
if (~length >= (MagickPathExtent-1))
destination=(char *) AcquireQuantumMemory(length+MagickPathExtent,
sizeof(*destination));
if (destination == (char *) NULL)
ThrowFatalException(ResourceLimitFatalError,"UnableToEscapeString");
*destination='\0';
q=destination;
for (p=source; *p != '\0'; p++)
{
if ((*p == '\\') || (*p == '(') || (*p == ')'))
*q++='\\';
*q++=(*p);
}
*q='\0';
return(destination);
}
static MagickBooleanType RenderPostscript(Image *image,
const DrawInfo *draw_info,const PointInfo *offset,TypeMetric *metrics,
ExceptionInfo *exception)
{
char
filename[MagickPathExtent],
geometry[MagickPathExtent],
*text;
FILE
*file;
Image
*annotate_image;
ImageInfo
*annotate_info;
int
unique_file;
MagickBooleanType
identity;
PointInfo
extent,
point,
resolution;
register ssize_t
i;
size_t
length;
ssize_t
y;
/*
Render label with a Postscript font.
*/
if (image->debug != MagickFalse)
(void) LogMagickEvent(AnnotateEvent,GetMagickModule(),
"Font %s; pointsize %g",draw_info->font != (char *) NULL ?
draw_info->font : "none",draw_info->pointsize);
file=(FILE *) NULL;
unique_file=AcquireUniqueFileResource(filename);
if (unique_file != -1)
file=fdopen(unique_file,"wb");
if ((unique_file == -1) || (file == (FILE *) NULL))
{
ThrowFileException(exception,FileOpenError,"UnableToOpenFile",filename);
return(MagickFalse);
}
(void) FormatLocaleFile(file,"%%!PS-Adobe-3.0\n");
(void) FormatLocaleFile(file,"/ReencodeType\n");
(void) FormatLocaleFile(file,"{\n");
(void) FormatLocaleFile(file," findfont dup length\n");
(void) FormatLocaleFile(file,
" dict begin { 1 index /FID ne {def} {pop pop} ifelse } forall\n");
(void) FormatLocaleFile(file,
" /Encoding ISOLatin1Encoding def currentdict end definefont pop\n");
(void) FormatLocaleFile(file,"} bind def\n");
/*
Sample to compute bounding box.
*/
identity=(fabs(draw_info->affine.sx-draw_info->affine.sy) < MagickEpsilon) &&
(fabs(draw_info->affine.rx) < MagickEpsilon) &&
(fabs(draw_info->affine.ry) < MagickEpsilon) ? MagickTrue : MagickFalse;
extent.x=0.0;
extent.y=0.0;
length=strlen(draw_info->text);
for (i=0; i <= (ssize_t) (length+2); i++)
{
point.x=fabs(draw_info->affine.sx*i*draw_info->pointsize+
draw_info->affine.ry*2.0*draw_info->pointsize);
point.y=fabs(draw_info->affine.rx*i*draw_info->pointsize+
draw_info->affine.sy*2.0*draw_info->pointsize);
if (point.x > extent.x)
extent.x=point.x;
if (point.y > extent.y)
extent.y=point.y;
}
(void) FormatLocaleFile(file,"%g %g moveto\n",identity != MagickFalse ? 0.0 :
extent.x/2.0,extent.y/2.0);
(void) FormatLocaleFile(file,"%g %g scale\n",draw_info->pointsize,
draw_info->pointsize);
if ((draw_info->font == (char *) NULL) || (*draw_info->font == '\0') ||
(strchr(draw_info->font,'/') != (char *) NULL))
(void) FormatLocaleFile(file,
"/Times-Roman-ISO dup /Times-Roman ReencodeType findfont setfont\n");
else
(void) FormatLocaleFile(file,
"/%s-ISO dup /%s ReencodeType findfont setfont\n",draw_info->font,
draw_info->font);
(void) FormatLocaleFile(file,"[%g %g %g %g 0 0] concat\n",
draw_info->affine.sx,-draw_info->affine.rx,-draw_info->affine.ry,
draw_info->affine.sy);
text=EscapeParenthesis(draw_info->text);
if (identity == MagickFalse)
(void) FormatLocaleFile(file,"(%s) stringwidth pop -0.5 mul -0.5 rmoveto\n",
text);
(void) FormatLocaleFile(file,"(%s) show\n",text);
text=DestroyString(text);
(void) FormatLocaleFile(file,"showpage\n");
(void) fclose(file);
(void) FormatLocaleString(geometry,MagickPathExtent,"%.20gx%.20g+0+0!",
floor(extent.x+0.5),floor(extent.y+0.5));
annotate_info=AcquireImageInfo();
(void) FormatLocaleString(annotate_info->filename,MagickPathExtent,"ps:%s",
filename);
(void) CloneString(&annotate_info->page,geometry);
if (draw_info->density != (char *) NULL)
(void) CloneString(&annotate_info->density,draw_info->density);
annotate_info->antialias=draw_info->text_antialias;
annotate_image=ReadImage(annotate_info,exception);
CatchException(exception);
annotate_info=DestroyImageInfo(annotate_info);
(void) RelinquishUniqueFileResource(filename);
if (annotate_image == (Image *) NULL)
return(MagickFalse);
(void) NegateImage(annotate_image,MagickFalse,exception);
resolution.x=DefaultResolution;
resolution.y=DefaultResolution;
if (draw_info->density != (char *) NULL)
{
GeometryInfo
geometry_info;
MagickStatusType
flags;
flags=ParseGeometry(draw_info->density,&geometry_info);
resolution.x=geometry_info.rho;
resolution.y=geometry_info.sigma;
if ((flags & SigmaValue) == 0)
resolution.y=resolution.x;
}
if (identity == MagickFalse)
(void) TransformImage(&annotate_image,"0x0",(char *) NULL,exception);
else
{
RectangleInfo
crop_info;
crop_info=GetImageBoundingBox(annotate_image,exception);
crop_info.height=(size_t) ((resolution.y/DefaultResolution)*
ExpandAffine(&draw_info->affine)*draw_info->pointsize+0.5);
crop_info.y=(ssize_t) ceil((resolution.y/DefaultResolution)*extent.y/8.0-
0.5);
(void) FormatLocaleString(geometry,MagickPathExtent,
"%.20gx%.20g%+.20g%+.20g",(double) crop_info.width,(double)
crop_info.height,(double) crop_info.x,(double) crop_info.y);
(void) TransformImage(&annotate_image,geometry,(char *) NULL,exception);
}
metrics->pixels_per_em.x=(resolution.y/DefaultResolution)*
ExpandAffine(&draw_info->affine)*draw_info->pointsize;
metrics->pixels_per_em.y=metrics->pixels_per_em.x;
metrics->ascent=metrics->pixels_per_em.x;
metrics->descent=metrics->pixels_per_em.y/-5.0;
metrics->width=(double) annotate_image->columns/
ExpandAffine(&draw_info->affine);
metrics->height=1.152*metrics->pixels_per_em.x;
metrics->max_advance=metrics->pixels_per_em.x;
metrics->bounds.x1=0.0;
metrics->bounds.y1=metrics->descent;
metrics->bounds.x2=metrics->ascent+metrics->descent;
metrics->bounds.y2=metrics->ascent+metrics->descent;
metrics->underline_position=(-2.0);
metrics->underline_thickness=1.0;
if (draw_info->render == MagickFalse)
{
annotate_image=DestroyImage(annotate_image);
return(MagickTrue);
}
if (draw_info->fill.alpha != TransparentAlpha)
{
CacheView
*annotate_view;
MagickBooleanType
sync;
PixelInfo
fill_color;
/*
Render fill color.
*/
if (image->alpha_trait == UndefinedPixelTrait)
(void) SetImageAlphaChannel(image,OpaqueAlphaChannel,exception);
if (annotate_image->alpha_trait == UndefinedPixelTrait)
(void) SetImageAlphaChannel(annotate_image,OpaqueAlphaChannel,
exception);
fill_color=draw_info->fill;
annotate_view=AcquireAuthenticCacheView(annotate_image,exception);
for (y=0; y < (ssize_t) annotate_image->rows; y++)
{
register ssize_t
x;
register Quantum
*magick_restrict q;
q=GetCacheViewAuthenticPixels(annotate_view,0,y,annotate_image->columns,
1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) annotate_image->columns; x++)
{
GetFillColor(draw_info,x,y,&fill_color,exception);
SetPixelAlpha(annotate_image,ClampToQuantum((((double) QuantumScale*
GetPixelIntensity(annotate_image,q)*fill_color.alpha))),q);
SetPixelRed(annotate_image,fill_color.red,q);
SetPixelGreen(annotate_image,fill_color.green,q);
SetPixelBlue(annotate_image,fill_color.blue,q);
q+=GetPixelChannels(annotate_image);
}
sync=SyncCacheViewAuthenticPixels(annotate_view,exception);
if (sync == MagickFalse)
break;
}
annotate_view=DestroyCacheView(annotate_view);
(void) CompositeImage(image,annotate_image,OverCompositeOp,MagickTrue,
(ssize_t) ceil(offset->x-0.5),(ssize_t) ceil(offset->y-(metrics->ascent+
metrics->descent)-0.5),exception);
}
annotate_image=DestroyImage(annotate_image);
return(MagickTrue);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ R e n d e r X 1 1 %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% RenderX11() renders text on the image with an X11 font. It also returns the
% bounding box of the text relative to the image.
%
% The format of the RenderX11 method is:
%
% MagickBooleanType RenderX11(Image *image,DrawInfo *draw_info,
% const PointInfo *offset,TypeMetric *metrics,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o draw_info: the draw info.
%
% o offset: (x,y) location of text relative to image.
%
% o metrics: bounding box of text.
%
% o exception: return any errors or warnings in this structure.
%
*/
static MagickBooleanType RenderX11(Image *image,const DrawInfo *draw_info,
const PointInfo *offset,TypeMetric *metrics,ExceptionInfo *exception)
{
MagickBooleanType
status;
if (annotate_semaphore == (SemaphoreInfo *) NULL)
ActivateSemaphoreInfo(&annotate_semaphore);
LockSemaphoreInfo(annotate_semaphore);
status=XRenderImage(image,draw_info,offset,metrics,exception);
UnlockSemaphoreInfo(annotate_semaphore);
return(status);
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/good_949_0 |
crossvul-cpp_data_bad_4856_2 | /* $Id$ */
/*
* Copyright (c) 1996-1997 Sam Leffler
* Copyright (c) 1996 Pixar
*
* 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
* Pixar, 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 Pixar, 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 PIXAR, 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.
*/
#include "tiffiop.h"
#ifdef PIXARLOG_SUPPORT
/*
* TIFF Library.
* PixarLog Compression Support
*
* Contributed by Dan McCoy.
*
* PixarLog film support uses the TIFF library to store companded
* 11 bit values into a tiff file, which are compressed using the
* zip compressor.
*
* The codec can take as input and produce as output 32-bit IEEE float values
* as well as 16-bit or 8-bit unsigned integer values.
*
* On writing any of the above are converted into the internal
* 11-bit log format. In the case of 8 and 16 bit values, the
* input is assumed to be unsigned linear color values that represent
* the range 0-1. In the case of IEEE values, the 0-1 range is assumed to
* be the normal linear color range, in addition over 1 values are
* accepted up to a value of about 25.0 to encode "hot" highlights and such.
* The encoding is lossless for 8-bit values, slightly lossy for the
* other bit depths. The actual color precision should be better
* than the human eye can perceive with extra room to allow for
* error introduced by further image computation. As with any quantized
* color format, it is possible to perform image calculations which
* expose the quantization error. This format should certainly be less
* susceptible to such errors than standard 8-bit encodings, but more
* susceptible than straight 16-bit or 32-bit encodings.
*
* On reading the internal format is converted to the desired output format.
* The program can request which format it desires by setting the internal
* pseudo tag TIFFTAG_PIXARLOGDATAFMT to one of these possible values:
* PIXARLOGDATAFMT_FLOAT = provide IEEE float values.
* PIXARLOGDATAFMT_16BIT = provide unsigned 16-bit integer values
* PIXARLOGDATAFMT_8BIT = provide unsigned 8-bit integer values
*
* alternately PIXARLOGDATAFMT_8BITABGR provides unsigned 8-bit integer
* values with the difference that if there are exactly three or four channels
* (rgb or rgba) it swaps the channel order (bgr or abgr).
*
* PIXARLOGDATAFMT_11BITLOG provides the internal encoding directly
* packed in 16-bit values. However no tools are supplied for interpreting
* these values.
*
* "hot" (over 1.0) areas written in floating point get clamped to
* 1.0 in the integer data types.
*
* When the file is closed after writing, the bit depth and sample format
* are set always to appear as if 8-bit data has been written into it.
* That way a naive program unaware of the particulars of the encoding
* gets the format it is most likely able to handle.
*
* The codec does it's own horizontal differencing step on the coded
* values so the libraries predictor stuff should be turned off.
* The codec also handle byte swapping the encoded values as necessary
* since the library does not have the information necessary
* to know the bit depth of the raw unencoded buffer.
*
* NOTE: This decoder does not appear to update tif_rawcp, and tif_rawcc.
* This can cause problems with the implementation of CHUNKY_STRIP_READ_SUPPORT
* as noted in http://trac.osgeo.org/gdal/ticket/3894. FrankW - Jan'11
*/
#include "tif_predict.h"
#include "zlib.h"
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
/* Tables for converting to/from 11 bit coded values */
#define TSIZE 2048 /* decode table size (11-bit tokens) */
#define TSIZEP1 2049 /* Plus one for slop */
#define ONE 1250 /* token value of 1.0 exactly */
#define RATIO 1.004 /* nominal ratio for log part */
#define CODE_MASK 0x7ff /* 11 bits. */
static float Fltsize;
static float LogK1, LogK2;
#define REPEAT(n, op) { int i; i=n; do { i--; op; } while (i>0); }
static void
horizontalAccumulateF(uint16 *wp, int n, int stride, float *op,
float *ToLinearF)
{
register unsigned int cr, cg, cb, ca, mask;
register float t0, t1, t2, t3;
if (n >= stride) {
mask = CODE_MASK;
if (stride == 3) {
t0 = ToLinearF[cr = (wp[0] & mask)];
t1 = ToLinearF[cg = (wp[1] & mask)];
t2 = ToLinearF[cb = (wp[2] & mask)];
op[0] = t0;
op[1] = t1;
op[2] = t2;
n -= 3;
while (n > 0) {
wp += 3;
op += 3;
n -= 3;
t0 = ToLinearF[(cr += wp[0]) & mask];
t1 = ToLinearF[(cg += wp[1]) & mask];
t2 = ToLinearF[(cb += wp[2]) & mask];
op[0] = t0;
op[1] = t1;
op[2] = t2;
}
} else if (stride == 4) {
t0 = ToLinearF[cr = (wp[0] & mask)];
t1 = ToLinearF[cg = (wp[1] & mask)];
t2 = ToLinearF[cb = (wp[2] & mask)];
t3 = ToLinearF[ca = (wp[3] & mask)];
op[0] = t0;
op[1] = t1;
op[2] = t2;
op[3] = t3;
n -= 4;
while (n > 0) {
wp += 4;
op += 4;
n -= 4;
t0 = ToLinearF[(cr += wp[0]) & mask];
t1 = ToLinearF[(cg += wp[1]) & mask];
t2 = ToLinearF[(cb += wp[2]) & mask];
t3 = ToLinearF[(ca += wp[3]) & mask];
op[0] = t0;
op[1] = t1;
op[2] = t2;
op[3] = t3;
}
} else {
REPEAT(stride, *op = ToLinearF[*wp&mask]; wp++; op++)
n -= stride;
while (n > 0) {
REPEAT(stride,
wp[stride] += *wp; *op = ToLinearF[*wp&mask]; wp++; op++)
n -= stride;
}
}
}
}
static void
horizontalAccumulate12(uint16 *wp, int n, int stride, int16 *op,
float *ToLinearF)
{
register unsigned int cr, cg, cb, ca, mask;
register float t0, t1, t2, t3;
#define SCALE12 2048.0F
#define CLAMP12(t) (((t) < 3071) ? (uint16) (t) : 3071)
if (n >= stride) {
mask = CODE_MASK;
if (stride == 3) {
t0 = ToLinearF[cr = (wp[0] & mask)] * SCALE12;
t1 = ToLinearF[cg = (wp[1] & mask)] * SCALE12;
t2 = ToLinearF[cb = (wp[2] & mask)] * SCALE12;
op[0] = CLAMP12(t0);
op[1] = CLAMP12(t1);
op[2] = CLAMP12(t2);
n -= 3;
while (n > 0) {
wp += 3;
op += 3;
n -= 3;
t0 = ToLinearF[(cr += wp[0]) & mask] * SCALE12;
t1 = ToLinearF[(cg += wp[1]) & mask] * SCALE12;
t2 = ToLinearF[(cb += wp[2]) & mask] * SCALE12;
op[0] = CLAMP12(t0);
op[1] = CLAMP12(t1);
op[2] = CLAMP12(t2);
}
} else if (stride == 4) {
t0 = ToLinearF[cr = (wp[0] & mask)] * SCALE12;
t1 = ToLinearF[cg = (wp[1] & mask)] * SCALE12;
t2 = ToLinearF[cb = (wp[2] & mask)] * SCALE12;
t3 = ToLinearF[ca = (wp[3] & mask)] * SCALE12;
op[0] = CLAMP12(t0);
op[1] = CLAMP12(t1);
op[2] = CLAMP12(t2);
op[3] = CLAMP12(t3);
n -= 4;
while (n > 0) {
wp += 4;
op += 4;
n -= 4;
t0 = ToLinearF[(cr += wp[0]) & mask] * SCALE12;
t1 = ToLinearF[(cg += wp[1]) & mask] * SCALE12;
t2 = ToLinearF[(cb += wp[2]) & mask] * SCALE12;
t3 = ToLinearF[(ca += wp[3]) & mask] * SCALE12;
op[0] = CLAMP12(t0);
op[1] = CLAMP12(t1);
op[2] = CLAMP12(t2);
op[3] = CLAMP12(t3);
}
} else {
REPEAT(stride, t0 = ToLinearF[*wp&mask] * SCALE12;
*op = CLAMP12(t0); wp++; op++)
n -= stride;
while (n > 0) {
REPEAT(stride,
wp[stride] += *wp; t0 = ToLinearF[wp[stride]&mask]*SCALE12;
*op = CLAMP12(t0); wp++; op++)
n -= stride;
}
}
}
}
static void
horizontalAccumulate16(uint16 *wp, int n, int stride, uint16 *op,
uint16 *ToLinear16)
{
register unsigned int cr, cg, cb, ca, mask;
if (n >= stride) {
mask = CODE_MASK;
if (stride == 3) {
op[0] = ToLinear16[cr = (wp[0] & mask)];
op[1] = ToLinear16[cg = (wp[1] & mask)];
op[2] = ToLinear16[cb = (wp[2] & mask)];
n -= 3;
while (n > 0) {
wp += 3;
op += 3;
n -= 3;
op[0] = ToLinear16[(cr += wp[0]) & mask];
op[1] = ToLinear16[(cg += wp[1]) & mask];
op[2] = ToLinear16[(cb += wp[2]) & mask];
}
} else if (stride == 4) {
op[0] = ToLinear16[cr = (wp[0] & mask)];
op[1] = ToLinear16[cg = (wp[1] & mask)];
op[2] = ToLinear16[cb = (wp[2] & mask)];
op[3] = ToLinear16[ca = (wp[3] & mask)];
n -= 4;
while (n > 0) {
wp += 4;
op += 4;
n -= 4;
op[0] = ToLinear16[(cr += wp[0]) & mask];
op[1] = ToLinear16[(cg += wp[1]) & mask];
op[2] = ToLinear16[(cb += wp[2]) & mask];
op[3] = ToLinear16[(ca += wp[3]) & mask];
}
} else {
REPEAT(stride, *op = ToLinear16[*wp&mask]; wp++; op++)
n -= stride;
while (n > 0) {
REPEAT(stride,
wp[stride] += *wp; *op = ToLinear16[*wp&mask]; wp++; op++)
n -= stride;
}
}
}
}
/*
* Returns the log encoded 11-bit values with the horizontal
* differencing undone.
*/
static void
horizontalAccumulate11(uint16 *wp, int n, int stride, uint16 *op)
{
register unsigned int cr, cg, cb, ca, mask;
if (n >= stride) {
mask = CODE_MASK;
if (stride == 3) {
op[0] = wp[0]; op[1] = wp[1]; op[2] = wp[2];
cr = wp[0]; cg = wp[1]; cb = wp[2];
n -= 3;
while (n > 0) {
wp += 3;
op += 3;
n -= 3;
op[0] = (uint16)((cr += wp[0]) & mask);
op[1] = (uint16)((cg += wp[1]) & mask);
op[2] = (uint16)((cb += wp[2]) & mask);
}
} else if (stride == 4) {
op[0] = wp[0]; op[1] = wp[1];
op[2] = wp[2]; op[3] = wp[3];
cr = wp[0]; cg = wp[1]; cb = wp[2]; ca = wp[3];
n -= 4;
while (n > 0) {
wp += 4;
op += 4;
n -= 4;
op[0] = (uint16)((cr += wp[0]) & mask);
op[1] = (uint16)((cg += wp[1]) & mask);
op[2] = (uint16)((cb += wp[2]) & mask);
op[3] = (uint16)((ca += wp[3]) & mask);
}
} else {
REPEAT(stride, *op = *wp&mask; wp++; op++)
n -= stride;
while (n > 0) {
REPEAT(stride,
wp[stride] += *wp; *op = *wp&mask; wp++; op++)
n -= stride;
}
}
}
}
static void
horizontalAccumulate8(uint16 *wp, int n, int stride, unsigned char *op,
unsigned char *ToLinear8)
{
register unsigned int cr, cg, cb, ca, mask;
if (n >= stride) {
mask = CODE_MASK;
if (stride == 3) {
op[0] = ToLinear8[cr = (wp[0] & mask)];
op[1] = ToLinear8[cg = (wp[1] & mask)];
op[2] = ToLinear8[cb = (wp[2] & mask)];
n -= 3;
while (n > 0) {
n -= 3;
wp += 3;
op += 3;
op[0] = ToLinear8[(cr += wp[0]) & mask];
op[1] = ToLinear8[(cg += wp[1]) & mask];
op[2] = ToLinear8[(cb += wp[2]) & mask];
}
} else if (stride == 4) {
op[0] = ToLinear8[cr = (wp[0] & mask)];
op[1] = ToLinear8[cg = (wp[1] & mask)];
op[2] = ToLinear8[cb = (wp[2] & mask)];
op[3] = ToLinear8[ca = (wp[3] & mask)];
n -= 4;
while (n > 0) {
n -= 4;
wp += 4;
op += 4;
op[0] = ToLinear8[(cr += wp[0]) & mask];
op[1] = ToLinear8[(cg += wp[1]) & mask];
op[2] = ToLinear8[(cb += wp[2]) & mask];
op[3] = ToLinear8[(ca += wp[3]) & mask];
}
} else {
REPEAT(stride, *op = ToLinear8[*wp&mask]; wp++; op++)
n -= stride;
while (n > 0) {
REPEAT(stride,
wp[stride] += *wp; *op = ToLinear8[*wp&mask]; wp++; op++)
n -= stride;
}
}
}
}
static void
horizontalAccumulate8abgr(uint16 *wp, int n, int stride, unsigned char *op,
unsigned char *ToLinear8)
{
register unsigned int cr, cg, cb, ca, mask;
register unsigned char t0, t1, t2, t3;
if (n >= stride) {
mask = CODE_MASK;
if (stride == 3) {
op[0] = 0;
t1 = ToLinear8[cb = (wp[2] & mask)];
t2 = ToLinear8[cg = (wp[1] & mask)];
t3 = ToLinear8[cr = (wp[0] & mask)];
op[1] = t1;
op[2] = t2;
op[3] = t3;
n -= 3;
while (n > 0) {
n -= 3;
wp += 3;
op += 4;
op[0] = 0;
t1 = ToLinear8[(cb += wp[2]) & mask];
t2 = ToLinear8[(cg += wp[1]) & mask];
t3 = ToLinear8[(cr += wp[0]) & mask];
op[1] = t1;
op[2] = t2;
op[3] = t3;
}
} else if (stride == 4) {
t0 = ToLinear8[ca = (wp[3] & mask)];
t1 = ToLinear8[cb = (wp[2] & mask)];
t2 = ToLinear8[cg = (wp[1] & mask)];
t3 = ToLinear8[cr = (wp[0] & mask)];
op[0] = t0;
op[1] = t1;
op[2] = t2;
op[3] = t3;
n -= 4;
while (n > 0) {
n -= 4;
wp += 4;
op += 4;
t0 = ToLinear8[(ca += wp[3]) & mask];
t1 = ToLinear8[(cb += wp[2]) & mask];
t2 = ToLinear8[(cg += wp[1]) & mask];
t3 = ToLinear8[(cr += wp[0]) & mask];
op[0] = t0;
op[1] = t1;
op[2] = t2;
op[3] = t3;
}
} else {
REPEAT(stride, *op = ToLinear8[*wp&mask]; wp++; op++)
n -= stride;
while (n > 0) {
REPEAT(stride,
wp[stride] += *wp; *op = ToLinear8[*wp&mask]; wp++; op++)
n -= stride;
}
}
}
}
/*
* State block for each open TIFF
* file using PixarLog compression/decompression.
*/
typedef struct {
TIFFPredictorState predict;
z_stream stream;
tmsize_t tbuf_size; /* only set/used on reading for now */
uint16 *tbuf;
uint16 stride;
int state;
int user_datafmt;
int quality;
#define PLSTATE_INIT 1
TIFFVSetMethod vgetparent; /* super-class method */
TIFFVSetMethod vsetparent; /* super-class method */
float *ToLinearF;
uint16 *ToLinear16;
unsigned char *ToLinear8;
uint16 *FromLT2;
uint16 *From14; /* Really for 16-bit data, but we shift down 2 */
uint16 *From8;
} PixarLogState;
static int
PixarLogMakeTables(PixarLogState *sp)
{
/*
* We make several tables here to convert between various external
* representations (float, 16-bit, and 8-bit) and the internal
* 11-bit companded representation. The 11-bit representation has two
* distinct regions. A linear bottom end up through .018316 in steps
* of about .000073, and a region of constant ratio up to about 25.
* These floating point numbers are stored in the main table ToLinearF.
* All other tables are derived from this one. The tables (and the
* ratios) are continuous at the internal seam.
*/
int nlin, lt2size;
int i, j;
double b, c, linstep, v;
float *ToLinearF;
uint16 *ToLinear16;
unsigned char *ToLinear8;
uint16 *FromLT2;
uint16 *From14; /* Really for 16-bit data, but we shift down 2 */
uint16 *From8;
c = log(RATIO);
nlin = (int)(1./c); /* nlin must be an integer */
c = 1./nlin;
b = exp(-c*ONE); /* multiplicative scale factor [b*exp(c*ONE) = 1] */
linstep = b*c*exp(1.);
LogK1 = (float)(1./c); /* if (v >= 2) token = k1*log(v*k2) */
LogK2 = (float)(1./b);
lt2size = (int)(2./linstep) + 1;
FromLT2 = (uint16 *)_TIFFmalloc(lt2size*sizeof(uint16));
From14 = (uint16 *)_TIFFmalloc(16384*sizeof(uint16));
From8 = (uint16 *)_TIFFmalloc(256*sizeof(uint16));
ToLinearF = (float *)_TIFFmalloc(TSIZEP1 * sizeof(float));
ToLinear16 = (uint16 *)_TIFFmalloc(TSIZEP1 * sizeof(uint16));
ToLinear8 = (unsigned char *)_TIFFmalloc(TSIZEP1 * sizeof(unsigned char));
if (FromLT2 == NULL || From14 == NULL || From8 == NULL ||
ToLinearF == NULL || ToLinear16 == NULL || ToLinear8 == NULL) {
if (FromLT2) _TIFFfree(FromLT2);
if (From14) _TIFFfree(From14);
if (From8) _TIFFfree(From8);
if (ToLinearF) _TIFFfree(ToLinearF);
if (ToLinear16) _TIFFfree(ToLinear16);
if (ToLinear8) _TIFFfree(ToLinear8);
sp->FromLT2 = NULL;
sp->From14 = NULL;
sp->From8 = NULL;
sp->ToLinearF = NULL;
sp->ToLinear16 = NULL;
sp->ToLinear8 = NULL;
return 0;
}
j = 0;
for (i = 0; i < nlin; i++) {
v = i * linstep;
ToLinearF[j++] = (float)v;
}
for (i = nlin; i < TSIZE; i++)
ToLinearF[j++] = (float)(b*exp(c*i));
ToLinearF[2048] = ToLinearF[2047];
for (i = 0; i < TSIZEP1; i++) {
v = ToLinearF[i]*65535.0 + 0.5;
ToLinear16[i] = (v > 65535.0) ? 65535 : (uint16)v;
v = ToLinearF[i]*255.0 + 0.5;
ToLinear8[i] = (v > 255.0) ? 255 : (unsigned char)v;
}
j = 0;
for (i = 0; i < lt2size; i++) {
if ((i*linstep)*(i*linstep) > ToLinearF[j]*ToLinearF[j+1])
j++;
FromLT2[i] = (uint16)j;
}
/*
* Since we lose info anyway on 16-bit data, we set up a 14-bit
* table and shift 16-bit values down two bits on input.
* saves a little table space.
*/
j = 0;
for (i = 0; i < 16384; i++) {
while ((i/16383.)*(i/16383.) > ToLinearF[j]*ToLinearF[j+1])
j++;
From14[i] = (uint16)j;
}
j = 0;
for (i = 0; i < 256; i++) {
while ((i/255.)*(i/255.) > ToLinearF[j]*ToLinearF[j+1])
j++;
From8[i] = (uint16)j;
}
Fltsize = (float)(lt2size/2);
sp->ToLinearF = ToLinearF;
sp->ToLinear16 = ToLinear16;
sp->ToLinear8 = ToLinear8;
sp->FromLT2 = FromLT2;
sp->From14 = From14;
sp->From8 = From8;
return 1;
}
#define DecoderState(tif) ((PixarLogState*) (tif)->tif_data)
#define EncoderState(tif) ((PixarLogState*) (tif)->tif_data)
static int PixarLogEncode(TIFF* tif, uint8* bp, tmsize_t cc, uint16 s);
static int PixarLogDecode(TIFF* tif, uint8* op, tmsize_t occ, uint16 s);
#define PIXARLOGDATAFMT_UNKNOWN -1
static int
PixarLogGuessDataFmt(TIFFDirectory *td)
{
int guess = PIXARLOGDATAFMT_UNKNOWN;
int format = td->td_sampleformat;
/* If the user didn't tell us his datafmt,
* take our best guess from the bitspersample.
*/
switch (td->td_bitspersample) {
case 32:
if (format == SAMPLEFORMAT_IEEEFP)
guess = PIXARLOGDATAFMT_FLOAT;
break;
case 16:
if (format == SAMPLEFORMAT_VOID || format == SAMPLEFORMAT_UINT)
guess = PIXARLOGDATAFMT_16BIT;
break;
case 12:
if (format == SAMPLEFORMAT_VOID || format == SAMPLEFORMAT_INT)
guess = PIXARLOGDATAFMT_12BITPICIO;
break;
case 11:
if (format == SAMPLEFORMAT_VOID || format == SAMPLEFORMAT_UINT)
guess = PIXARLOGDATAFMT_11BITLOG;
break;
case 8:
if (format == SAMPLEFORMAT_VOID || format == SAMPLEFORMAT_UINT)
guess = PIXARLOGDATAFMT_8BIT;
break;
}
return guess;
}
static tmsize_t
multiply_ms(tmsize_t m1, tmsize_t m2)
{
tmsize_t bytes = m1 * m2;
if (m1 && bytes / m1 != m2)
bytes = 0;
return bytes;
}
static tmsize_t
add_ms(tmsize_t m1, tmsize_t m2)
{
tmsize_t bytes = m1 + m2;
/* if either input is zero, assume overflow already occurred */
if (m1 == 0 || m2 == 0)
bytes = 0;
else if (bytes <= m1 || bytes <= m2)
bytes = 0;
return bytes;
}
static int
PixarLogFixupTags(TIFF* tif)
{
(void) tif;
return (1);
}
static int
PixarLogSetupDecode(TIFF* tif)
{
static const char module[] = "PixarLogSetupDecode";
TIFFDirectory *td = &tif->tif_dir;
PixarLogState* sp = DecoderState(tif);
tmsize_t tbuf_size;
assert(sp != NULL);
/* Make sure no byte swapping happens on the data
* after decompression. */
tif->tif_postdecode = _TIFFNoPostDecode;
/* for some reason, we can't do this in TIFFInitPixarLog */
sp->stride = (td->td_planarconfig == PLANARCONFIG_CONTIG ?
td->td_samplesperpixel : 1);
tbuf_size = multiply_ms(multiply_ms(multiply_ms(sp->stride, td->td_imagewidth),
td->td_rowsperstrip), sizeof(uint16));
/* add one more stride in case input ends mid-stride */
tbuf_size = add_ms(tbuf_size, sizeof(uint16) * sp->stride);
if (tbuf_size == 0)
return (0); /* TODO: this is an error return without error report through TIFFErrorExt */
sp->tbuf = (uint16 *) _TIFFmalloc(tbuf_size);
if (sp->tbuf == NULL)
return (0);
sp->tbuf_size = tbuf_size;
if (sp->user_datafmt == PIXARLOGDATAFMT_UNKNOWN)
sp->user_datafmt = PixarLogGuessDataFmt(td);
if (sp->user_datafmt == PIXARLOGDATAFMT_UNKNOWN) {
TIFFErrorExt(tif->tif_clientdata, module,
"PixarLog compression can't handle bits depth/data format combination (depth: %d)",
td->td_bitspersample);
return (0);
}
if (inflateInit(&sp->stream) != Z_OK) {
TIFFErrorExt(tif->tif_clientdata, module, "%s", sp->stream.msg ? sp->stream.msg : "(null)");
return (0);
} else {
sp->state |= PLSTATE_INIT;
return (1);
}
}
/*
* Setup state for decoding a strip.
*/
static int
PixarLogPreDecode(TIFF* tif, uint16 s)
{
static const char module[] = "PixarLogPreDecode";
PixarLogState* sp = DecoderState(tif);
(void) s;
assert(sp != NULL);
sp->stream.next_in = tif->tif_rawdata;
assert(sizeof(sp->stream.avail_in)==4); /* if this assert gets raised,
we need to simplify this code to reflect a ZLib that is likely updated
to deal with 8byte memory sizes, though this code will respond
appropriately even before we simplify it */
sp->stream.avail_in = (uInt) tif->tif_rawcc;
if ((tmsize_t)sp->stream.avail_in != tif->tif_rawcc)
{
TIFFErrorExt(tif->tif_clientdata, module, "ZLib cannot deal with buffers this size");
return (0);
}
return (inflateReset(&sp->stream) == Z_OK);
}
static int
PixarLogDecode(TIFF* tif, uint8* op, tmsize_t occ, uint16 s)
{
static const char module[] = "PixarLogDecode";
TIFFDirectory *td = &tif->tif_dir;
PixarLogState* sp = DecoderState(tif);
tmsize_t i;
tmsize_t nsamples;
int llen;
uint16 *up;
switch (sp->user_datafmt) {
case PIXARLOGDATAFMT_FLOAT:
nsamples = occ / sizeof(float); /* XXX float == 32 bits */
break;
case PIXARLOGDATAFMT_16BIT:
case PIXARLOGDATAFMT_12BITPICIO:
case PIXARLOGDATAFMT_11BITLOG:
nsamples = occ / sizeof(uint16); /* XXX uint16 == 16 bits */
break;
case PIXARLOGDATAFMT_8BIT:
case PIXARLOGDATAFMT_8BITABGR:
nsamples = occ;
break;
default:
TIFFErrorExt(tif->tif_clientdata, module,
"%d bit input not supported in PixarLog",
td->td_bitspersample);
return 0;
}
llen = sp->stride * td->td_imagewidth;
(void) s;
assert(sp != NULL);
sp->stream.next_out = (unsigned char *) sp->tbuf;
assert(sizeof(sp->stream.avail_out)==4); /* if this assert gets raised,
we need to simplify this code to reflect a ZLib that is likely updated
to deal with 8byte memory sizes, though this code will respond
appropriately even before we simplify it */
sp->stream.avail_out = (uInt) (nsamples * sizeof(uint16));
if (sp->stream.avail_out != nsamples * sizeof(uint16))
{
TIFFErrorExt(tif->tif_clientdata, module, "ZLib cannot deal with buffers this size");
return (0);
}
/* Check that we will not fill more than what was allocated */
if ((tmsize_t)sp->stream.avail_out > sp->tbuf_size)
{
TIFFErrorExt(tif->tif_clientdata, module, "sp->stream.avail_out > sp->tbuf_size");
return (0);
}
do {
int state = inflate(&sp->stream, Z_PARTIAL_FLUSH);
if (state == Z_STREAM_END) {
break; /* XXX */
}
if (state == Z_DATA_ERROR) {
TIFFErrorExt(tif->tif_clientdata, module,
"Decoding error at scanline %lu, %s",
(unsigned long) tif->tif_row, sp->stream.msg ? sp->stream.msg : "(null)");
if (inflateSync(&sp->stream) != Z_OK)
return (0);
continue;
}
if (state != Z_OK) {
TIFFErrorExt(tif->tif_clientdata, module, "ZLib error: %s",
sp->stream.msg ? sp->stream.msg : "(null)");
return (0);
}
} while (sp->stream.avail_out > 0);
/* hopefully, we got all the bytes we needed */
if (sp->stream.avail_out != 0) {
TIFFErrorExt(tif->tif_clientdata, module,
"Not enough data at scanline %lu (short " TIFF_UINT64_FORMAT " bytes)",
(unsigned long) tif->tif_row, (TIFF_UINT64_T) sp->stream.avail_out);
return (0);
}
up = sp->tbuf;
/* Swap bytes in the data if from a different endian machine. */
if (tif->tif_flags & TIFF_SWAB)
TIFFSwabArrayOfShort(up, nsamples);
/*
* if llen is not an exact multiple of nsamples, the decode operation
* may overflow the output buffer, so truncate it enough to prevent
* that but still salvage as much data as possible.
*/
if (nsamples % llen) {
TIFFWarningExt(tif->tif_clientdata, module,
"stride %lu is not a multiple of sample count, "
"%lu, data truncated.", (unsigned long) llen, (unsigned long) nsamples);
nsamples -= nsamples % llen;
}
for (i = 0; i < nsamples; i += llen, up += llen) {
switch (sp->user_datafmt) {
case PIXARLOGDATAFMT_FLOAT:
horizontalAccumulateF(up, llen, sp->stride,
(float *)op, sp->ToLinearF);
op += llen * sizeof(float);
break;
case PIXARLOGDATAFMT_16BIT:
horizontalAccumulate16(up, llen, sp->stride,
(uint16 *)op, sp->ToLinear16);
op += llen * sizeof(uint16);
break;
case PIXARLOGDATAFMT_12BITPICIO:
horizontalAccumulate12(up, llen, sp->stride,
(int16 *)op, sp->ToLinearF);
op += llen * sizeof(int16);
break;
case PIXARLOGDATAFMT_11BITLOG:
horizontalAccumulate11(up, llen, sp->stride,
(uint16 *)op);
op += llen * sizeof(uint16);
break;
case PIXARLOGDATAFMT_8BIT:
horizontalAccumulate8(up, llen, sp->stride,
(unsigned char *)op, sp->ToLinear8);
op += llen * sizeof(unsigned char);
break;
case PIXARLOGDATAFMT_8BITABGR:
horizontalAccumulate8abgr(up, llen, sp->stride,
(unsigned char *)op, sp->ToLinear8);
op += llen * sizeof(unsigned char);
break;
default:
TIFFErrorExt(tif->tif_clientdata, module,
"Unsupported bits/sample: %d",
td->td_bitspersample);
return (0);
}
}
return (1);
}
static int
PixarLogSetupEncode(TIFF* tif)
{
static const char module[] = "PixarLogSetupEncode";
TIFFDirectory *td = &tif->tif_dir;
PixarLogState* sp = EncoderState(tif);
tmsize_t tbuf_size;
assert(sp != NULL);
/* for some reason, we can't do this in TIFFInitPixarLog */
sp->stride = (td->td_planarconfig == PLANARCONFIG_CONTIG ?
td->td_samplesperpixel : 1);
tbuf_size = multiply_ms(multiply_ms(multiply_ms(sp->stride, td->td_imagewidth),
td->td_rowsperstrip), sizeof(uint16));
if (tbuf_size == 0)
return (0); /* TODO: this is an error return without error report through TIFFErrorExt */
sp->tbuf = (uint16 *) _TIFFmalloc(tbuf_size);
if (sp->tbuf == NULL)
return (0);
if (sp->user_datafmt == PIXARLOGDATAFMT_UNKNOWN)
sp->user_datafmt = PixarLogGuessDataFmt(td);
if (sp->user_datafmt == PIXARLOGDATAFMT_UNKNOWN) {
TIFFErrorExt(tif->tif_clientdata, module, "PixarLog compression can't handle %d bit linear encodings", td->td_bitspersample);
return (0);
}
if (deflateInit(&sp->stream, sp->quality) != Z_OK) {
TIFFErrorExt(tif->tif_clientdata, module, "%s", sp->stream.msg ? sp->stream.msg : "(null)");
return (0);
} else {
sp->state |= PLSTATE_INIT;
return (1);
}
}
/*
* Reset encoding state at the start of a strip.
*/
static int
PixarLogPreEncode(TIFF* tif, uint16 s)
{
static const char module[] = "PixarLogPreEncode";
PixarLogState *sp = EncoderState(tif);
(void) s;
assert(sp != NULL);
sp->stream.next_out = tif->tif_rawdata;
assert(sizeof(sp->stream.avail_out)==4); /* if this assert gets raised,
we need to simplify this code to reflect a ZLib that is likely updated
to deal with 8byte memory sizes, though this code will respond
appropriately even before we simplify it */
sp->stream.avail_out = (uInt)tif->tif_rawdatasize;
if ((tmsize_t)sp->stream.avail_out != tif->tif_rawdatasize)
{
TIFFErrorExt(tif->tif_clientdata, module, "ZLib cannot deal with buffers this size");
return (0);
}
return (deflateReset(&sp->stream) == Z_OK);
}
static void
horizontalDifferenceF(float *ip, int n, int stride, uint16 *wp, uint16 *FromLT2)
{
int32 r1, g1, b1, a1, r2, g2, b2, a2, mask;
float fltsize = Fltsize;
#define CLAMP(v) ( (v<(float)0.) ? 0 \
: (v<(float)2.) ? FromLT2[(int)(v*fltsize)] \
: (v>(float)24.2) ? 2047 \
: LogK1*log(v*LogK2) + 0.5 )
mask = CODE_MASK;
if (n >= stride) {
if (stride == 3) {
r2 = wp[0] = (uint16) CLAMP(ip[0]);
g2 = wp[1] = (uint16) CLAMP(ip[1]);
b2 = wp[2] = (uint16) CLAMP(ip[2]);
n -= 3;
while (n > 0) {
n -= 3;
wp += 3;
ip += 3;
r1 = (int32) CLAMP(ip[0]); wp[0] = (uint16)((r1-r2) & mask); r2 = r1;
g1 = (int32) CLAMP(ip[1]); wp[1] = (uint16)((g1-g2) & mask); g2 = g1;
b1 = (int32) CLAMP(ip[2]); wp[2] = (uint16)((b1-b2) & mask); b2 = b1;
}
} else if (stride == 4) {
r2 = wp[0] = (uint16) CLAMP(ip[0]);
g2 = wp[1] = (uint16) CLAMP(ip[1]);
b2 = wp[2] = (uint16) CLAMP(ip[2]);
a2 = wp[3] = (uint16) CLAMP(ip[3]);
n -= 4;
while (n > 0) {
n -= 4;
wp += 4;
ip += 4;
r1 = (int32) CLAMP(ip[0]); wp[0] = (uint16)((r1-r2) & mask); r2 = r1;
g1 = (int32) CLAMP(ip[1]); wp[1] = (uint16)((g1-g2) & mask); g2 = g1;
b1 = (int32) CLAMP(ip[2]); wp[2] = (uint16)((b1-b2) & mask); b2 = b1;
a1 = (int32) CLAMP(ip[3]); wp[3] = (uint16)((a1-a2) & mask); a2 = a1;
}
} else {
REPEAT(stride, wp[0] = (uint16) CLAMP(ip[0]); wp++; ip++)
n -= stride;
while (n > 0) {
REPEAT(stride,
wp[0] = (uint16)(((int32)CLAMP(ip[0])-(int32)CLAMP(ip[-stride])) & mask);
wp++; ip++)
n -= stride;
}
}
}
}
static void
horizontalDifference16(unsigned short *ip, int n, int stride,
unsigned short *wp, uint16 *From14)
{
register int r1, g1, b1, a1, r2, g2, b2, a2, mask;
/* assumption is unsigned pixel values */
#undef CLAMP
#define CLAMP(v) From14[(v) >> 2]
mask = CODE_MASK;
if (n >= stride) {
if (stride == 3) {
r2 = wp[0] = CLAMP(ip[0]); g2 = wp[1] = CLAMP(ip[1]);
b2 = wp[2] = CLAMP(ip[2]);
n -= 3;
while (n > 0) {
n -= 3;
wp += 3;
ip += 3;
r1 = CLAMP(ip[0]); wp[0] = (uint16)((r1-r2) & mask); r2 = r1;
g1 = CLAMP(ip[1]); wp[1] = (uint16)((g1-g2) & mask); g2 = g1;
b1 = CLAMP(ip[2]); wp[2] = (uint16)((b1-b2) & mask); b2 = b1;
}
} else if (stride == 4) {
r2 = wp[0] = CLAMP(ip[0]); g2 = wp[1] = CLAMP(ip[1]);
b2 = wp[2] = CLAMP(ip[2]); a2 = wp[3] = CLAMP(ip[3]);
n -= 4;
while (n > 0) {
n -= 4;
wp += 4;
ip += 4;
r1 = CLAMP(ip[0]); wp[0] = (uint16)((r1-r2) & mask); r2 = r1;
g1 = CLAMP(ip[1]); wp[1] = (uint16)((g1-g2) & mask); g2 = g1;
b1 = CLAMP(ip[2]); wp[2] = (uint16)((b1-b2) & mask); b2 = b1;
a1 = CLAMP(ip[3]); wp[3] = (uint16)((a1-a2) & mask); a2 = a1;
}
} else {
REPEAT(stride, wp[0] = CLAMP(ip[0]); wp++; ip++)
n -= stride;
while (n > 0) {
REPEAT(stride,
wp[0] = (uint16)((CLAMP(ip[0])-CLAMP(ip[-stride])) & mask);
wp++; ip++)
n -= stride;
}
}
}
}
static void
horizontalDifference8(unsigned char *ip, int n, int stride,
unsigned short *wp, uint16 *From8)
{
register int r1, g1, b1, a1, r2, g2, b2, a2, mask;
#undef CLAMP
#define CLAMP(v) (From8[(v)])
mask = CODE_MASK;
if (n >= stride) {
if (stride == 3) {
r2 = wp[0] = CLAMP(ip[0]); g2 = wp[1] = CLAMP(ip[1]);
b2 = wp[2] = CLAMP(ip[2]);
n -= 3;
while (n > 0) {
n -= 3;
r1 = CLAMP(ip[3]); wp[3] = (uint16)((r1-r2) & mask); r2 = r1;
g1 = CLAMP(ip[4]); wp[4] = (uint16)((g1-g2) & mask); g2 = g1;
b1 = CLAMP(ip[5]); wp[5] = (uint16)((b1-b2) & mask); b2 = b1;
wp += 3;
ip += 3;
}
} else if (stride == 4) {
r2 = wp[0] = CLAMP(ip[0]); g2 = wp[1] = CLAMP(ip[1]);
b2 = wp[2] = CLAMP(ip[2]); a2 = wp[3] = CLAMP(ip[3]);
n -= 4;
while (n > 0) {
n -= 4;
r1 = CLAMP(ip[4]); wp[4] = (uint16)((r1-r2) & mask); r2 = r1;
g1 = CLAMP(ip[5]); wp[5] = (uint16)((g1-g2) & mask); g2 = g1;
b1 = CLAMP(ip[6]); wp[6] = (uint16)((b1-b2) & mask); b2 = b1;
a1 = CLAMP(ip[7]); wp[7] = (uint16)((a1-a2) & mask); a2 = a1;
wp += 4;
ip += 4;
}
} else {
REPEAT(stride, wp[0] = CLAMP(ip[0]); wp++; ip++)
n -= stride;
while (n > 0) {
REPEAT(stride,
wp[0] = (uint16)((CLAMP(ip[0])-CLAMP(ip[-stride])) & mask);
wp++; ip++)
n -= stride;
}
}
}
}
/*
* Encode a chunk of pixels.
*/
static int
PixarLogEncode(TIFF* tif, uint8* bp, tmsize_t cc, uint16 s)
{
static const char module[] = "PixarLogEncode";
TIFFDirectory *td = &tif->tif_dir;
PixarLogState *sp = EncoderState(tif);
tmsize_t i;
tmsize_t n;
int llen;
unsigned short * up;
(void) s;
switch (sp->user_datafmt) {
case PIXARLOGDATAFMT_FLOAT:
n = cc / sizeof(float); /* XXX float == 32 bits */
break;
case PIXARLOGDATAFMT_16BIT:
case PIXARLOGDATAFMT_12BITPICIO:
case PIXARLOGDATAFMT_11BITLOG:
n = cc / sizeof(uint16); /* XXX uint16 == 16 bits */
break;
case PIXARLOGDATAFMT_8BIT:
case PIXARLOGDATAFMT_8BITABGR:
n = cc;
break;
default:
TIFFErrorExt(tif->tif_clientdata, module,
"%d bit input not supported in PixarLog",
td->td_bitspersample);
return 0;
}
llen = sp->stride * td->td_imagewidth;
/* Check against the number of elements (of size uint16) of sp->tbuf */
if( n > (tmsize_t)(td->td_rowsperstrip * llen) )
{
TIFFErrorExt(tif->tif_clientdata, module,
"Too many input bytes provided");
return 0;
}
for (i = 0, up = sp->tbuf; i < n; i += llen, up += llen) {
switch (sp->user_datafmt) {
case PIXARLOGDATAFMT_FLOAT:
horizontalDifferenceF((float *)bp, llen,
sp->stride, up, sp->FromLT2);
bp += llen * sizeof(float);
break;
case PIXARLOGDATAFMT_16BIT:
horizontalDifference16((uint16 *)bp, llen,
sp->stride, up, sp->From14);
bp += llen * sizeof(uint16);
break;
case PIXARLOGDATAFMT_8BIT:
horizontalDifference8((unsigned char *)bp, llen,
sp->stride, up, sp->From8);
bp += llen * sizeof(unsigned char);
break;
default:
TIFFErrorExt(tif->tif_clientdata, module,
"%d bit input not supported in PixarLog",
td->td_bitspersample);
return 0;
}
}
sp->stream.next_in = (unsigned char *) sp->tbuf;
assert(sizeof(sp->stream.avail_in)==4); /* if this assert gets raised,
we need to simplify this code to reflect a ZLib that is likely updated
to deal with 8byte memory sizes, though this code will respond
appropriately even before we simplify it */
sp->stream.avail_in = (uInt) (n * sizeof(uint16));
if ((sp->stream.avail_in / sizeof(uint16)) != (uInt) n)
{
TIFFErrorExt(tif->tif_clientdata, module,
"ZLib cannot deal with buffers this size");
return (0);
}
do {
if (deflate(&sp->stream, Z_NO_FLUSH) != Z_OK) {
TIFFErrorExt(tif->tif_clientdata, module, "Encoder error: %s",
sp->stream.msg ? sp->stream.msg : "(null)");
return (0);
}
if (sp->stream.avail_out == 0) {
tif->tif_rawcc = tif->tif_rawdatasize;
TIFFFlushData1(tif);
sp->stream.next_out = tif->tif_rawdata;
sp->stream.avail_out = (uInt) tif->tif_rawdatasize; /* this is a safe typecast, as check is made already in PixarLogPreEncode */
}
} while (sp->stream.avail_in > 0);
return (1);
}
/*
* Finish off an encoded strip by flushing the last
* string and tacking on an End Of Information code.
*/
static int
PixarLogPostEncode(TIFF* tif)
{
static const char module[] = "PixarLogPostEncode";
PixarLogState *sp = EncoderState(tif);
int state;
sp->stream.avail_in = 0;
do {
state = deflate(&sp->stream, Z_FINISH);
switch (state) {
case Z_STREAM_END:
case Z_OK:
if ((tmsize_t)sp->stream.avail_out != tif->tif_rawdatasize) {
tif->tif_rawcc =
tif->tif_rawdatasize - sp->stream.avail_out;
TIFFFlushData1(tif);
sp->stream.next_out = tif->tif_rawdata;
sp->stream.avail_out = (uInt) tif->tif_rawdatasize; /* this is a safe typecast, as check is made already in PixarLogPreEncode */
}
break;
default:
TIFFErrorExt(tif->tif_clientdata, module, "ZLib error: %s",
sp->stream.msg ? sp->stream.msg : "(null)");
return (0);
}
} while (state != Z_STREAM_END);
return (1);
}
static void
PixarLogClose(TIFF* tif)
{
TIFFDirectory *td = &tif->tif_dir;
/* In a really sneaky (and really incorrect, and untruthful, and
* troublesome, and error-prone) maneuver that completely goes against
* the spirit of TIFF, and breaks TIFF, on close, we covertly
* modify both bitspersample and sampleformat in the directory to
* indicate 8-bit linear. This way, the decode "just works" even for
* readers that don't know about PixarLog, or how to set
* the PIXARLOGDATFMT pseudo-tag.
*/
td->td_bitspersample = 8;
td->td_sampleformat = SAMPLEFORMAT_UINT;
}
static void
PixarLogCleanup(TIFF* tif)
{
PixarLogState* sp = (PixarLogState*) tif->tif_data;
assert(sp != 0);
(void)TIFFPredictorCleanup(tif);
tif->tif_tagmethods.vgetfield = sp->vgetparent;
tif->tif_tagmethods.vsetfield = sp->vsetparent;
if (sp->FromLT2) _TIFFfree(sp->FromLT2);
if (sp->From14) _TIFFfree(sp->From14);
if (sp->From8) _TIFFfree(sp->From8);
if (sp->ToLinearF) _TIFFfree(sp->ToLinearF);
if (sp->ToLinear16) _TIFFfree(sp->ToLinear16);
if (sp->ToLinear8) _TIFFfree(sp->ToLinear8);
if (sp->state&PLSTATE_INIT) {
if (tif->tif_mode == O_RDONLY)
inflateEnd(&sp->stream);
else
deflateEnd(&sp->stream);
}
if (sp->tbuf)
_TIFFfree(sp->tbuf);
_TIFFfree(sp);
tif->tif_data = NULL;
_TIFFSetDefaultCompressionState(tif);
}
static int
PixarLogVSetField(TIFF* tif, uint32 tag, va_list ap)
{
static const char module[] = "PixarLogVSetField";
PixarLogState *sp = (PixarLogState *)tif->tif_data;
int result;
switch (tag) {
case TIFFTAG_PIXARLOGQUALITY:
sp->quality = (int) va_arg(ap, int);
if (tif->tif_mode != O_RDONLY && (sp->state&PLSTATE_INIT)) {
if (deflateParams(&sp->stream,
sp->quality, Z_DEFAULT_STRATEGY) != Z_OK) {
TIFFErrorExt(tif->tif_clientdata, module, "ZLib error: %s",
sp->stream.msg ? sp->stream.msg : "(null)");
return (0);
}
}
return (1);
case TIFFTAG_PIXARLOGDATAFMT:
sp->user_datafmt = (int) va_arg(ap, int);
/* Tweak the TIFF header so that the rest of libtiff knows what
* size of data will be passed between app and library, and
* assume that the app knows what it is doing and is not
* confused by these header manipulations...
*/
switch (sp->user_datafmt) {
case PIXARLOGDATAFMT_8BIT:
case PIXARLOGDATAFMT_8BITABGR:
TIFFSetField(tif, TIFFTAG_BITSPERSAMPLE, 8);
TIFFSetField(tif, TIFFTAG_SAMPLEFORMAT, SAMPLEFORMAT_UINT);
break;
case PIXARLOGDATAFMT_11BITLOG:
TIFFSetField(tif, TIFFTAG_BITSPERSAMPLE, 16);
TIFFSetField(tif, TIFFTAG_SAMPLEFORMAT, SAMPLEFORMAT_UINT);
break;
case PIXARLOGDATAFMT_12BITPICIO:
TIFFSetField(tif, TIFFTAG_BITSPERSAMPLE, 16);
TIFFSetField(tif, TIFFTAG_SAMPLEFORMAT, SAMPLEFORMAT_INT);
break;
case PIXARLOGDATAFMT_16BIT:
TIFFSetField(tif, TIFFTAG_BITSPERSAMPLE, 16);
TIFFSetField(tif, TIFFTAG_SAMPLEFORMAT, SAMPLEFORMAT_UINT);
break;
case PIXARLOGDATAFMT_FLOAT:
TIFFSetField(tif, TIFFTAG_BITSPERSAMPLE, 32);
TIFFSetField(tif, TIFFTAG_SAMPLEFORMAT, SAMPLEFORMAT_IEEEFP);
break;
}
/*
* Must recalculate sizes should bits/sample change.
*/
tif->tif_tilesize = isTiled(tif) ? TIFFTileSize(tif) : (tmsize_t)(-1);
tif->tif_scanlinesize = TIFFScanlineSize(tif);
result = 1; /* NB: pseudo tag */
break;
default:
result = (*sp->vsetparent)(tif, tag, ap);
}
return (result);
}
static int
PixarLogVGetField(TIFF* tif, uint32 tag, va_list ap)
{
PixarLogState *sp = (PixarLogState *)tif->tif_data;
switch (tag) {
case TIFFTAG_PIXARLOGQUALITY:
*va_arg(ap, int*) = sp->quality;
break;
case TIFFTAG_PIXARLOGDATAFMT:
*va_arg(ap, int*) = sp->user_datafmt;
break;
default:
return (*sp->vgetparent)(tif, tag, ap);
}
return (1);
}
static const TIFFField pixarlogFields[] = {
{TIFFTAG_PIXARLOGDATAFMT, 0, 0, TIFF_ANY, 0, TIFF_SETGET_INT, TIFF_SETGET_UNDEFINED, FIELD_PSEUDO, FALSE, FALSE, "", NULL},
{TIFFTAG_PIXARLOGQUALITY, 0, 0, TIFF_ANY, 0, TIFF_SETGET_INT, TIFF_SETGET_UNDEFINED, FIELD_PSEUDO, FALSE, FALSE, "", NULL}
};
int
TIFFInitPixarLog(TIFF* tif, int scheme)
{
static const char module[] = "TIFFInitPixarLog";
PixarLogState* sp;
assert(scheme == COMPRESSION_PIXARLOG);
/*
* Merge codec-specific tag information.
*/
if (!_TIFFMergeFields(tif, pixarlogFields,
TIFFArrayCount(pixarlogFields))) {
TIFFErrorExt(tif->tif_clientdata, module,
"Merging PixarLog codec-specific tags failed");
return 0;
}
/*
* Allocate state block so tag methods have storage to record values.
*/
tif->tif_data = (uint8*) _TIFFmalloc(sizeof (PixarLogState));
if (tif->tif_data == NULL)
goto bad;
sp = (PixarLogState*) tif->tif_data;
_TIFFmemset(sp, 0, sizeof (*sp));
sp->stream.data_type = Z_BINARY;
sp->user_datafmt = PIXARLOGDATAFMT_UNKNOWN;
/*
* Install codec methods.
*/
tif->tif_fixuptags = PixarLogFixupTags;
tif->tif_setupdecode = PixarLogSetupDecode;
tif->tif_predecode = PixarLogPreDecode;
tif->tif_decoderow = PixarLogDecode;
tif->tif_decodestrip = PixarLogDecode;
tif->tif_decodetile = PixarLogDecode;
tif->tif_setupencode = PixarLogSetupEncode;
tif->tif_preencode = PixarLogPreEncode;
tif->tif_postencode = PixarLogPostEncode;
tif->tif_encoderow = PixarLogEncode;
tif->tif_encodestrip = PixarLogEncode;
tif->tif_encodetile = PixarLogEncode;
tif->tif_close = PixarLogClose;
tif->tif_cleanup = PixarLogCleanup;
/* Override SetField so we can handle our private pseudo-tag */
sp->vgetparent = tif->tif_tagmethods.vgetfield;
tif->tif_tagmethods.vgetfield = PixarLogVGetField; /* hook for codec tags */
sp->vsetparent = tif->tif_tagmethods.vsetfield;
tif->tif_tagmethods.vsetfield = PixarLogVSetField; /* hook for codec tags */
/* Default values for codec-specific fields */
sp->quality = Z_DEFAULT_COMPRESSION; /* default comp. level */
sp->state = 0;
/* we don't wish to use the predictor,
* the default is none, which predictor value 1
*/
(void) TIFFPredictorInit(tif);
/*
* build the companding tables
*/
PixarLogMakeTables(sp);
return (1);
bad:
TIFFErrorExt(tif->tif_clientdata, module,
"No space for PixarLog state block");
return (0);
}
#endif /* PIXARLOG_SUPPORT */
/* 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-125/c/bad_4856_2 |
crossvul-cpp_data_good_977_0 | /*
* Copyright © 2001-2011 Stéphane Raimbault <stephane.raimbault@gmail.com>
*
* SPDX-License-Identifier: LGPL-2.1+
*
* This library implements the Modbus protocol.
* http://libmodbus.org/
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdarg.h>
#include <errno.h>
#include <limits.h>
#include <time.h>
#ifndef _MSC_VER
#include <unistd.h>
#endif
#include <config.h>
#include "modbus.h"
#include "modbus-private.h"
/* Internal use */
#define MSG_LENGTH_UNDEFINED -1
/* Exported version */
const unsigned int libmodbus_version_major = LIBMODBUS_VERSION_MAJOR;
const unsigned int libmodbus_version_minor = LIBMODBUS_VERSION_MINOR;
const unsigned int libmodbus_version_micro = LIBMODBUS_VERSION_MICRO;
/* Max between RTU and TCP max adu length (so TCP) */
#define MAX_MESSAGE_LENGTH 260
/* 3 steps are used to parse the query */
typedef enum {
_STEP_FUNCTION,
_STEP_META,
_STEP_DATA
} _step_t;
const char *modbus_strerror(int errnum) {
switch (errnum) {
case EMBXILFUN:
return "Illegal function";
case EMBXILADD:
return "Illegal data address";
case EMBXILVAL:
return "Illegal data value";
case EMBXSFAIL:
return "Slave device or server failure";
case EMBXACK:
return "Acknowledge";
case EMBXSBUSY:
return "Slave device or server is busy";
case EMBXNACK:
return "Negative acknowledge";
case EMBXMEMPAR:
return "Memory parity error";
case EMBXGPATH:
return "Gateway path unavailable";
case EMBXGTAR:
return "Target device failed to respond";
case EMBBADCRC:
return "Invalid CRC";
case EMBBADDATA:
return "Invalid data";
case EMBBADEXC:
return "Invalid exception code";
case EMBMDATA:
return "Too many data";
case EMBBADSLAVE:
return "Response not from requested slave";
default:
return strerror(errnum);
}
}
void _error_print(modbus_t *ctx, const char *context)
{
if (ctx->debug) {
fprintf(stderr, "ERROR %s", modbus_strerror(errno));
if (context != NULL) {
fprintf(stderr, ": %s\n", context);
} else {
fprintf(stderr, "\n");
}
}
}
static void _sleep_response_timeout(modbus_t *ctx)
{
/* Response timeout is always positive */
#ifdef _WIN32
/* usleep doesn't exist on Windows */
Sleep((ctx->response_timeout.tv_sec * 1000) +
(ctx->response_timeout.tv_usec / 1000));
#else
/* usleep source code */
struct timespec request, remaining;
request.tv_sec = ctx->response_timeout.tv_sec;
request.tv_nsec = ((long int)ctx->response_timeout.tv_usec) * 1000;
while (nanosleep(&request, &remaining) == -1 && errno == EINTR) {
request = remaining;
}
#endif
}
int modbus_flush(modbus_t *ctx)
{
int rc;
if (ctx == NULL) {
errno = EINVAL;
return -1;
}
rc = ctx->backend->flush(ctx);
if (rc != -1 && ctx->debug) {
/* Not all backends are able to return the number of bytes flushed */
printf("Bytes flushed (%d)\n", rc);
}
return rc;
}
/* Computes the length of the expected response */
static unsigned int compute_response_length_from_request(modbus_t *ctx, uint8_t *req)
{
int length;
const int offset = ctx->backend->header_length;
switch (req[offset]) {
case MODBUS_FC_READ_COILS:
case MODBUS_FC_READ_DISCRETE_INPUTS: {
/* Header + nb values (code from write_bits) */
int nb = (req[offset + 3] << 8) | req[offset + 4];
length = 2 + (nb / 8) + ((nb % 8) ? 1 : 0);
}
break;
case MODBUS_FC_WRITE_AND_READ_REGISTERS:
case MODBUS_FC_READ_HOLDING_REGISTERS:
case MODBUS_FC_READ_INPUT_REGISTERS:
/* Header + 2 * nb values */
length = 2 + 2 * (req[offset + 3] << 8 | req[offset + 4]);
break;
case MODBUS_FC_READ_EXCEPTION_STATUS:
length = 3;
break;
case MODBUS_FC_REPORT_SLAVE_ID:
/* The response is device specific (the header provides the
length) */
return MSG_LENGTH_UNDEFINED;
case MODBUS_FC_MASK_WRITE_REGISTER:
length = 7;
break;
default:
length = 5;
}
return offset + length + ctx->backend->checksum_length;
}
/* Sends a request/response */
static int send_msg(modbus_t *ctx, uint8_t *msg, int msg_length)
{
int rc;
int i;
msg_length = ctx->backend->send_msg_pre(msg, msg_length);
if (ctx->debug) {
for (i = 0; i < msg_length; i++)
printf("[%.2X]", msg[i]);
printf("\n");
}
/* In recovery mode, the write command will be issued until to be
successful! Disabled by default. */
do {
rc = ctx->backend->send(ctx, msg, msg_length);
if (rc == -1) {
_error_print(ctx, NULL);
if (ctx->error_recovery & MODBUS_ERROR_RECOVERY_LINK) {
int saved_errno = errno;
if ((errno == EBADF || errno == ECONNRESET || errno == EPIPE)) {
modbus_close(ctx);
_sleep_response_timeout(ctx);
modbus_connect(ctx);
} else {
_sleep_response_timeout(ctx);
modbus_flush(ctx);
}
errno = saved_errno;
}
}
} while ((ctx->error_recovery & MODBUS_ERROR_RECOVERY_LINK) &&
rc == -1);
if (rc > 0 && rc != msg_length) {
errno = EMBBADDATA;
return -1;
}
return rc;
}
int modbus_send_raw_request(modbus_t *ctx, uint8_t *raw_req, int raw_req_length)
{
sft_t sft;
uint8_t req[MAX_MESSAGE_LENGTH];
int req_length;
if (ctx == NULL) {
errno = EINVAL;
return -1;
}
if (raw_req_length < 2 || raw_req_length > (MODBUS_MAX_PDU_LENGTH + 1)) {
/* The raw request must contain function and slave at least and
must not be longer than the maximum pdu length plus the slave
address. */
errno = EINVAL;
return -1;
}
sft.slave = raw_req[0];
sft.function = raw_req[1];
/* The t_id is left to zero */
sft.t_id = 0;
/* This response function only set the header so it's convenient here */
req_length = ctx->backend->build_response_basis(&sft, req);
if (raw_req_length > 2) {
/* Copy data after function code */
memcpy(req + req_length, raw_req + 2, raw_req_length - 2);
req_length += raw_req_length - 2;
}
return send_msg(ctx, req, req_length);
}
/*
* ---------- Request Indication ----------
* | Client | ---------------------->| Server |
* ---------- Confirmation Response ----------
*/
/* Computes the length to read after the function received */
static uint8_t compute_meta_length_after_function(int function,
msg_type_t msg_type)
{
int length;
if (msg_type == MSG_INDICATION) {
if (function <= MODBUS_FC_WRITE_SINGLE_REGISTER) {
length = 4;
} else if (function == MODBUS_FC_WRITE_MULTIPLE_COILS ||
function == MODBUS_FC_WRITE_MULTIPLE_REGISTERS) {
length = 5;
} else if (function == MODBUS_FC_MASK_WRITE_REGISTER) {
length = 6;
} else if (function == MODBUS_FC_WRITE_AND_READ_REGISTERS) {
length = 9;
} else {
/* MODBUS_FC_READ_EXCEPTION_STATUS, MODBUS_FC_REPORT_SLAVE_ID */
length = 0;
}
} else {
/* MSG_CONFIRMATION */
switch (function) {
case MODBUS_FC_WRITE_SINGLE_COIL:
case MODBUS_FC_WRITE_SINGLE_REGISTER:
case MODBUS_FC_WRITE_MULTIPLE_COILS:
case MODBUS_FC_WRITE_MULTIPLE_REGISTERS:
length = 4;
break;
case MODBUS_FC_MASK_WRITE_REGISTER:
length = 6;
break;
default:
length = 1;
}
}
return length;
}
/* Computes the length to read after the meta information (address, count, etc) */
static int compute_data_length_after_meta(modbus_t *ctx, uint8_t *msg,
msg_type_t msg_type)
{
int function = msg[ctx->backend->header_length];
int length;
if (msg_type == MSG_INDICATION) {
switch (function) {
case MODBUS_FC_WRITE_MULTIPLE_COILS:
case MODBUS_FC_WRITE_MULTIPLE_REGISTERS:
length = msg[ctx->backend->header_length + 5];
break;
case MODBUS_FC_WRITE_AND_READ_REGISTERS:
length = msg[ctx->backend->header_length + 9];
break;
default:
length = 0;
}
} else {
/* MSG_CONFIRMATION */
if (function <= MODBUS_FC_READ_INPUT_REGISTERS ||
function == MODBUS_FC_REPORT_SLAVE_ID ||
function == MODBUS_FC_WRITE_AND_READ_REGISTERS) {
length = msg[ctx->backend->header_length + 1];
} else {
length = 0;
}
}
length += ctx->backend->checksum_length;
return length;
}
/* Waits a response from a modbus server or a request from a modbus client.
This function blocks if there is no replies (3 timeouts).
The function shall return the number of received characters and the received
message in an array of uint8_t if successful. Otherwise it shall return -1
and errno is set to one of the values defined below:
- ECONNRESET
- EMBBADDATA
- EMBUNKEXC
- ETIMEDOUT
- read() or recv() error codes
*/
int _modbus_receive_msg(modbus_t *ctx, uint8_t *msg, msg_type_t msg_type)
{
int rc;
fd_set rset;
struct timeval tv;
struct timeval *p_tv;
int length_to_read;
int msg_length = 0;
_step_t step;
if (ctx->debug) {
if (msg_type == MSG_INDICATION) {
printf("Waiting for an indication...\n");
} else {
printf("Waiting for a confirmation...\n");
}
}
/* Add a file descriptor to the set */
FD_ZERO(&rset);
FD_SET(ctx->s, &rset);
/* We need to analyse the message step by step. At the first step, we want
* to reach the function code because all packets contain this
* information. */
step = _STEP_FUNCTION;
length_to_read = ctx->backend->header_length + 1;
if (msg_type == MSG_INDICATION) {
/* Wait for a message, we don't know when the message will be
* received */
if (ctx->indication_timeout.tv_sec == 0 && ctx->indication_timeout.tv_usec == 0) {
/* By default, the indication timeout isn't set */
p_tv = NULL;
} else {
/* Wait for an indication (name of a received request by a server, see schema) */
tv.tv_sec = ctx->indication_timeout.tv_sec;
tv.tv_usec = ctx->indication_timeout.tv_usec;
p_tv = &tv;
}
} else {
tv.tv_sec = ctx->response_timeout.tv_sec;
tv.tv_usec = ctx->response_timeout.tv_usec;
p_tv = &tv;
}
while (length_to_read != 0) {
rc = ctx->backend->select(ctx, &rset, p_tv, length_to_read);
if (rc == -1) {
_error_print(ctx, "select");
if (ctx->error_recovery & MODBUS_ERROR_RECOVERY_LINK) {
int saved_errno = errno;
if (errno == ETIMEDOUT) {
_sleep_response_timeout(ctx);
modbus_flush(ctx);
} else if (errno == EBADF) {
modbus_close(ctx);
modbus_connect(ctx);
}
errno = saved_errno;
}
return -1;
}
rc = ctx->backend->recv(ctx, msg + msg_length, length_to_read);
if (rc == 0) {
errno = ECONNRESET;
rc = -1;
}
if (rc == -1) {
_error_print(ctx, "read");
if ((ctx->error_recovery & MODBUS_ERROR_RECOVERY_LINK) &&
(errno == ECONNRESET || errno == ECONNREFUSED ||
errno == EBADF)) {
int saved_errno = errno;
modbus_close(ctx);
modbus_connect(ctx);
/* Could be removed by previous calls */
errno = saved_errno;
}
return -1;
}
/* Display the hex code of each character received */
if (ctx->debug) {
int i;
for (i=0; i < rc; i++)
printf("<%.2X>", msg[msg_length + i]);
}
/* Sums bytes received */
msg_length += rc;
/* Computes remaining bytes */
length_to_read -= rc;
if (length_to_read == 0) {
switch (step) {
case _STEP_FUNCTION:
/* Function code position */
length_to_read = compute_meta_length_after_function(
msg[ctx->backend->header_length],
msg_type);
if (length_to_read != 0) {
step = _STEP_META;
break;
} /* else switches straight to the next step */
case _STEP_META:
length_to_read = compute_data_length_after_meta(
ctx, msg, msg_type);
if ((msg_length + length_to_read) > (int)ctx->backend->max_adu_length) {
errno = EMBBADDATA;
_error_print(ctx, "too many data");
return -1;
}
step = _STEP_DATA;
break;
default:
break;
}
}
if (length_to_read > 0 &&
(ctx->byte_timeout.tv_sec > 0 || ctx->byte_timeout.tv_usec > 0)) {
/* If there is no character in the buffer, the allowed timeout
interval between two consecutive bytes is defined by
byte_timeout */
tv.tv_sec = ctx->byte_timeout.tv_sec;
tv.tv_usec = ctx->byte_timeout.tv_usec;
p_tv = &tv;
}
/* else timeout isn't set again, the full response must be read before
expiration of response timeout (for CONFIRMATION only) */
}
if (ctx->debug)
printf("\n");
return ctx->backend->check_integrity(ctx, msg, msg_length);
}
/* Receive the request from a modbus master */
int modbus_receive(modbus_t *ctx, uint8_t *req)
{
if (ctx == NULL) {
errno = EINVAL;
return -1;
}
return ctx->backend->receive(ctx, req);
}
/* Receives the confirmation.
The function shall store the read response in rsp and return the number of
values (bits or words). Otherwise, its shall return -1 and errno is set.
The function doesn't check the confirmation is the expected response to the
initial request.
*/
int modbus_receive_confirmation(modbus_t *ctx, uint8_t *rsp)
{
if (ctx == NULL) {
errno = EINVAL;
return -1;
}
return _modbus_receive_msg(ctx, rsp, MSG_CONFIRMATION);
}
static int check_confirmation(modbus_t *ctx, uint8_t *req,
uint8_t *rsp, int rsp_length)
{
int rc;
int rsp_length_computed;
const int offset = ctx->backend->header_length;
const int function = rsp[offset];
if (ctx->backend->pre_check_confirmation) {
rc = ctx->backend->pre_check_confirmation(ctx, req, rsp, rsp_length);
if (rc == -1) {
if (ctx->error_recovery & MODBUS_ERROR_RECOVERY_PROTOCOL) {
_sleep_response_timeout(ctx);
modbus_flush(ctx);
}
return -1;
}
}
rsp_length_computed = compute_response_length_from_request(ctx, req);
/* Exception code */
if (function >= 0x80) {
if (rsp_length == (offset + 2 + (int)ctx->backend->checksum_length) &&
req[offset] == (rsp[offset] - 0x80)) {
/* Valid exception code received */
int exception_code = rsp[offset + 1];
if (exception_code < MODBUS_EXCEPTION_MAX) {
errno = MODBUS_ENOBASE + exception_code;
} else {
errno = EMBBADEXC;
}
_error_print(ctx, NULL);
return -1;
} else {
errno = EMBBADEXC;
_error_print(ctx, NULL);
return -1;
}
}
/* Check length */
if ((rsp_length == rsp_length_computed ||
rsp_length_computed == MSG_LENGTH_UNDEFINED) &&
function < 0x80) {
int req_nb_value;
int rsp_nb_value;
/* Check function code */
if (function != req[offset]) {
if (ctx->debug) {
fprintf(stderr,
"Received function not corresponding to the request (0x%X != 0x%X)\n",
function, req[offset]);
}
if (ctx->error_recovery & MODBUS_ERROR_RECOVERY_PROTOCOL) {
_sleep_response_timeout(ctx);
modbus_flush(ctx);
}
errno = EMBBADDATA;
return -1;
}
/* Check the number of values is corresponding to the request */
switch (function) {
case MODBUS_FC_READ_COILS:
case MODBUS_FC_READ_DISCRETE_INPUTS:
/* Read functions, 8 values in a byte (nb
* of values in the request and byte count in
* the response. */
req_nb_value = (req[offset + 3] << 8) + req[offset + 4];
req_nb_value = (req_nb_value / 8) + ((req_nb_value % 8) ? 1 : 0);
rsp_nb_value = rsp[offset + 1];
break;
case MODBUS_FC_WRITE_AND_READ_REGISTERS:
case MODBUS_FC_READ_HOLDING_REGISTERS:
case MODBUS_FC_READ_INPUT_REGISTERS:
/* Read functions 1 value = 2 bytes */
req_nb_value = (req[offset + 3] << 8) + req[offset + 4];
rsp_nb_value = (rsp[offset + 1] / 2);
break;
case MODBUS_FC_WRITE_MULTIPLE_COILS:
case MODBUS_FC_WRITE_MULTIPLE_REGISTERS:
/* N Write functions */
req_nb_value = (req[offset + 3] << 8) + req[offset + 4];
rsp_nb_value = (rsp[offset + 3] << 8) | rsp[offset + 4];
break;
case MODBUS_FC_REPORT_SLAVE_ID:
/* Report slave ID (bytes received) */
req_nb_value = rsp_nb_value = rsp[offset + 1];
break;
default:
/* 1 Write functions & others */
req_nb_value = rsp_nb_value = 1;
}
if (req_nb_value == rsp_nb_value) {
rc = rsp_nb_value;
} else {
if (ctx->debug) {
fprintf(stderr,
"Quantity not corresponding to the request (%d != %d)\n",
rsp_nb_value, req_nb_value);
}
if (ctx->error_recovery & MODBUS_ERROR_RECOVERY_PROTOCOL) {
_sleep_response_timeout(ctx);
modbus_flush(ctx);
}
errno = EMBBADDATA;
rc = -1;
}
} else {
if (ctx->debug) {
fprintf(stderr,
"Message length not corresponding to the computed length (%d != %d)\n",
rsp_length, rsp_length_computed);
}
if (ctx->error_recovery & MODBUS_ERROR_RECOVERY_PROTOCOL) {
_sleep_response_timeout(ctx);
modbus_flush(ctx);
}
errno = EMBBADDATA;
rc = -1;
}
return rc;
}
static int response_io_status(uint8_t *tab_io_status,
int address, int nb,
uint8_t *rsp, int offset)
{
int shift = 0;
/* Instead of byte (not allowed in Win32) */
int one_byte = 0;
int i;
for (i = address; i < address + nb; i++) {
one_byte |= tab_io_status[i] << shift;
if (shift == 7) {
/* Byte is full */
rsp[offset++] = one_byte;
one_byte = shift = 0;
} else {
shift++;
}
}
if (shift != 0)
rsp[offset++] = one_byte;
return offset;
}
/* Build the exception response */
static int response_exception(modbus_t *ctx, sft_t *sft,
int exception_code, uint8_t *rsp,
unsigned int to_flush,
const char* template, ...)
{
int rsp_length;
/* Print debug message */
if (ctx->debug) {
va_list ap;
va_start(ap, template);
vfprintf(stderr, template, ap);
va_end(ap);
}
/* Flush if required */
if (to_flush) {
_sleep_response_timeout(ctx);
modbus_flush(ctx);
}
/* Build exception response */
sft->function = sft->function + 0x80;
rsp_length = ctx->backend->build_response_basis(sft, rsp);
rsp[rsp_length++] = exception_code;
return rsp_length;
}
/* Send a response to the received request.
Analyses the request and constructs a response.
If an error occurs, this function construct the response
accordingly.
*/
int modbus_reply(modbus_t *ctx, const uint8_t *req,
int req_length, modbus_mapping_t *mb_mapping)
{
int offset;
int slave;
int function;
uint16_t address;
uint8_t rsp[MAX_MESSAGE_LENGTH];
int rsp_length = 0;
sft_t sft;
if (ctx == NULL) {
errno = EINVAL;
return -1;
}
offset = ctx->backend->header_length;
slave = req[offset - 1];
function = req[offset];
address = (req[offset + 1] << 8) + req[offset + 2];
sft.slave = slave;
sft.function = function;
sft.t_id = ctx->backend->prepare_response_tid(req, &req_length);
/* Data are flushed on illegal number of values errors. */
switch (function) {
case MODBUS_FC_READ_COILS:
case MODBUS_FC_READ_DISCRETE_INPUTS: {
unsigned int is_input = (function == MODBUS_FC_READ_DISCRETE_INPUTS);
int start_bits = is_input ? mb_mapping->start_input_bits : mb_mapping->start_bits;
int nb_bits = is_input ? mb_mapping->nb_input_bits : mb_mapping->nb_bits;
uint8_t *tab_bits = is_input ? mb_mapping->tab_input_bits : mb_mapping->tab_bits;
const char * const name = is_input ? "read_input_bits" : "read_bits";
int nb = (req[offset + 3] << 8) + req[offset + 4];
/* The mapping can be shifted to reduce memory consumption and it
doesn't always start at address zero. */
int mapping_address = address - start_bits;
if (nb < 1 || MODBUS_MAX_READ_BITS < nb) {
rsp_length = response_exception(
ctx, &sft, MODBUS_EXCEPTION_ILLEGAL_DATA_VALUE, rsp, TRUE,
"Illegal nb of values %d in %s (max %d)\n",
nb, name, MODBUS_MAX_READ_BITS);
} else if (mapping_address < 0 || (mapping_address + nb) > nb_bits) {
rsp_length = response_exception(
ctx, &sft,
MODBUS_EXCEPTION_ILLEGAL_DATA_ADDRESS, rsp, FALSE,
"Illegal data address 0x%0X in %s\n",
mapping_address < 0 ? address : address + nb, name);
} else {
rsp_length = ctx->backend->build_response_basis(&sft, rsp);
rsp[rsp_length++] = (nb / 8) + ((nb % 8) ? 1 : 0);
rsp_length = response_io_status(tab_bits, mapping_address, nb,
rsp, rsp_length);
}
}
break;
case MODBUS_FC_READ_HOLDING_REGISTERS:
case MODBUS_FC_READ_INPUT_REGISTERS: {
unsigned int is_input = (function == MODBUS_FC_READ_INPUT_REGISTERS);
int start_registers = is_input ? mb_mapping->start_input_registers : mb_mapping->start_registers;
int nb_registers = is_input ? mb_mapping->nb_input_registers : mb_mapping->nb_registers;
uint16_t *tab_registers = is_input ? mb_mapping->tab_input_registers : mb_mapping->tab_registers;
const char * const name = is_input ? "read_input_registers" : "read_registers";
int nb = (req[offset + 3] << 8) + req[offset + 4];
/* The mapping can be shifted to reduce memory consumption and it
doesn't always start at address zero. */
int mapping_address = address - start_registers;
if (nb < 1 || MODBUS_MAX_READ_REGISTERS < nb) {
rsp_length = response_exception(
ctx, &sft, MODBUS_EXCEPTION_ILLEGAL_DATA_VALUE, rsp, TRUE,
"Illegal nb of values %d in %s (max %d)\n",
nb, name, MODBUS_MAX_READ_REGISTERS);
} else if (mapping_address < 0 || (mapping_address + nb) > nb_registers) {
rsp_length = response_exception(
ctx, &sft, MODBUS_EXCEPTION_ILLEGAL_DATA_ADDRESS, rsp, FALSE,
"Illegal data address 0x%0X in %s\n",
mapping_address < 0 ? address : address + nb, name);
} else {
int i;
rsp_length = ctx->backend->build_response_basis(&sft, rsp);
rsp[rsp_length++] = nb << 1;
for (i = mapping_address; i < mapping_address + nb; i++) {
rsp[rsp_length++] = tab_registers[i] >> 8;
rsp[rsp_length++] = tab_registers[i] & 0xFF;
}
}
}
break;
case MODBUS_FC_WRITE_SINGLE_COIL: {
int mapping_address = address - mb_mapping->start_bits;
if (mapping_address < 0 || mapping_address >= mb_mapping->nb_bits) {
rsp_length = response_exception(
ctx, &sft, MODBUS_EXCEPTION_ILLEGAL_DATA_ADDRESS, rsp, FALSE,
"Illegal data address 0x%0X in write_bit\n",
address);
} else {
int data = (req[offset + 3] << 8) + req[offset + 4];
if (data == 0xFF00 || data == 0x0) {
mb_mapping->tab_bits[mapping_address] = data ? ON : OFF;
memcpy(rsp, req, req_length);
rsp_length = req_length;
} else {
rsp_length = response_exception(
ctx, &sft,
MODBUS_EXCEPTION_ILLEGAL_DATA_VALUE, rsp, FALSE,
"Illegal data value 0x%0X in write_bit request at address %0X\n",
data, address);
}
}
}
break;
case MODBUS_FC_WRITE_SINGLE_REGISTER: {
int mapping_address = address - mb_mapping->start_registers;
if (mapping_address < 0 || mapping_address >= mb_mapping->nb_registers) {
rsp_length = response_exception(
ctx, &sft,
MODBUS_EXCEPTION_ILLEGAL_DATA_ADDRESS, rsp, FALSE,
"Illegal data address 0x%0X in write_register\n",
address);
} else {
int data = (req[offset + 3] << 8) + req[offset + 4];
mb_mapping->tab_registers[mapping_address] = data;
memcpy(rsp, req, req_length);
rsp_length = req_length;
}
}
break;
case MODBUS_FC_WRITE_MULTIPLE_COILS: {
int nb = (req[offset + 3] << 8) + req[offset + 4];
int nb_bits = req[offset + 5];
int mapping_address = address - mb_mapping->start_bits;
if (nb < 1 || MODBUS_MAX_WRITE_BITS < nb || nb_bits * 8 < nb) {
/* May be the indication has been truncated on reading because of
* invalid address (eg. nb is 0 but the request contains values to
* write) so it's necessary to flush. */
rsp_length = response_exception(
ctx, &sft, MODBUS_EXCEPTION_ILLEGAL_DATA_VALUE, rsp, TRUE,
"Illegal number of values %d in write_bits (max %d)\n",
nb, MODBUS_MAX_WRITE_BITS);
} else if (mapping_address < 0 ||
(mapping_address + nb) > mb_mapping->nb_bits) {
rsp_length = response_exception(
ctx, &sft,
MODBUS_EXCEPTION_ILLEGAL_DATA_ADDRESS, rsp, FALSE,
"Illegal data address 0x%0X in write_bits\n",
mapping_address < 0 ? address : address + nb);
} else {
/* 6 = byte count */
modbus_set_bits_from_bytes(mb_mapping->tab_bits, mapping_address, nb,
&req[offset + 6]);
rsp_length = ctx->backend->build_response_basis(&sft, rsp);
/* 4 to copy the bit address (2) and the quantity of bits */
memcpy(rsp + rsp_length, req + rsp_length, 4);
rsp_length += 4;
}
}
break;
case MODBUS_FC_WRITE_MULTIPLE_REGISTERS: {
int nb = (req[offset + 3] << 8) + req[offset + 4];
int nb_bytes = req[offset + 5];
int mapping_address = address - mb_mapping->start_registers;
if (nb < 1 || MODBUS_MAX_WRITE_REGISTERS < nb || nb_bytes * 8 < nb) {
rsp_length = response_exception(
ctx, &sft, MODBUS_EXCEPTION_ILLEGAL_DATA_VALUE, rsp, TRUE,
"Illegal number of values %d in write_registers (max %d)\n",
nb, MODBUS_MAX_WRITE_REGISTERS);
} else if (mapping_address < 0 ||
(mapping_address + nb) > mb_mapping->nb_registers) {
rsp_length = response_exception(
ctx, &sft, MODBUS_EXCEPTION_ILLEGAL_DATA_ADDRESS, rsp, FALSE,
"Illegal data address 0x%0X in write_registers\n",
mapping_address < 0 ? address : address + nb);
} else {
int i, j;
for (i = mapping_address, j = 6; i < mapping_address + nb; i++, j += 2) {
/* 6 and 7 = first value */
mb_mapping->tab_registers[i] =
(req[offset + j] << 8) + req[offset + j + 1];
}
rsp_length = ctx->backend->build_response_basis(&sft, rsp);
/* 4 to copy the address (2) and the no. of registers */
memcpy(rsp + rsp_length, req + rsp_length, 4);
rsp_length += 4;
}
}
break;
case MODBUS_FC_REPORT_SLAVE_ID: {
int str_len;
int byte_count_pos;
rsp_length = ctx->backend->build_response_basis(&sft, rsp);
/* Skip byte count for now */
byte_count_pos = rsp_length++;
rsp[rsp_length++] = _REPORT_SLAVE_ID;
/* Run indicator status to ON */
rsp[rsp_length++] = 0xFF;
/* LMB + length of LIBMODBUS_VERSION_STRING */
str_len = 3 + strlen(LIBMODBUS_VERSION_STRING);
memcpy(rsp + rsp_length, "LMB" LIBMODBUS_VERSION_STRING, str_len);
rsp_length += str_len;
rsp[byte_count_pos] = rsp_length - byte_count_pos - 1;
}
break;
case MODBUS_FC_READ_EXCEPTION_STATUS:
if (ctx->debug) {
fprintf(stderr, "FIXME Not implemented\n");
}
errno = ENOPROTOOPT;
return -1;
break;
case MODBUS_FC_MASK_WRITE_REGISTER: {
int mapping_address = address - mb_mapping->start_registers;
if (mapping_address < 0 || mapping_address >= mb_mapping->nb_registers) {
rsp_length = response_exception(
ctx, &sft, MODBUS_EXCEPTION_ILLEGAL_DATA_ADDRESS, rsp, FALSE,
"Illegal data address 0x%0X in write_register\n",
address);
} else {
uint16_t data = mb_mapping->tab_registers[mapping_address];
uint16_t and = (req[offset + 3] << 8) + req[offset + 4];
uint16_t or = (req[offset + 5] << 8) + req[offset + 6];
data = (data & and) | (or & (~and));
mb_mapping->tab_registers[mapping_address] = data;
memcpy(rsp, req, req_length);
rsp_length = req_length;
}
}
break;
case MODBUS_FC_WRITE_AND_READ_REGISTERS: {
int nb = (req[offset + 3] << 8) + req[offset + 4];
uint16_t address_write = (req[offset + 5] << 8) + req[offset + 6];
int nb_write = (req[offset + 7] << 8) + req[offset + 8];
int nb_write_bytes = req[offset + 9];
int mapping_address = address - mb_mapping->start_registers;
int mapping_address_write = address_write - mb_mapping->start_registers;
if (nb_write < 1 || MODBUS_MAX_WR_WRITE_REGISTERS < nb_write ||
nb < 1 || MODBUS_MAX_WR_READ_REGISTERS < nb ||
nb_write_bytes != nb_write * 2) {
rsp_length = response_exception(
ctx, &sft, MODBUS_EXCEPTION_ILLEGAL_DATA_VALUE, rsp, TRUE,
"Illegal nb of values (W%d, R%d) in write_and_read_registers (max W%d, R%d)\n",
nb_write, nb, MODBUS_MAX_WR_WRITE_REGISTERS, MODBUS_MAX_WR_READ_REGISTERS);
} else if (mapping_address < 0 ||
(mapping_address + nb) > mb_mapping->nb_registers ||
mapping_address < 0 ||
(mapping_address_write + nb_write) > mb_mapping->nb_registers) {
rsp_length = response_exception(
ctx, &sft, MODBUS_EXCEPTION_ILLEGAL_DATA_ADDRESS, rsp, FALSE,
"Illegal data read address 0x%0X or write address 0x%0X write_and_read_registers\n",
mapping_address < 0 ? address : address + nb,
mapping_address_write < 0 ? address_write : address_write + nb_write);
} else {
int i, j;
rsp_length = ctx->backend->build_response_basis(&sft, rsp);
rsp[rsp_length++] = nb << 1;
/* Write first.
10 and 11 are the offset of the first values to write */
for (i = mapping_address_write, j = 10;
i < mapping_address_write + nb_write; i++, j += 2) {
mb_mapping->tab_registers[i] =
(req[offset + j] << 8) + req[offset + j + 1];
}
/* and read the data for the response */
for (i = mapping_address; i < mapping_address + nb; i++) {
rsp[rsp_length++] = mb_mapping->tab_registers[i] >> 8;
rsp[rsp_length++] = mb_mapping->tab_registers[i] & 0xFF;
}
}
}
break;
default:
rsp_length = response_exception(
ctx, &sft, MODBUS_EXCEPTION_ILLEGAL_FUNCTION, rsp, TRUE,
"Unknown Modbus function code: 0x%0X\n", function);
break;
}
/* Suppress any responses when the request was a broadcast */
return (ctx->backend->backend_type == _MODBUS_BACKEND_TYPE_RTU &&
slave == MODBUS_BROADCAST_ADDRESS) ? 0 : send_msg(ctx, rsp, rsp_length);
}
int modbus_reply_exception(modbus_t *ctx, const uint8_t *req,
unsigned int exception_code)
{
int offset;
int slave;
int function;
uint8_t rsp[MAX_MESSAGE_LENGTH];
int rsp_length;
int dummy_length = 99;
sft_t sft;
if (ctx == NULL) {
errno = EINVAL;
return -1;
}
offset = ctx->backend->header_length;
slave = req[offset - 1];
function = req[offset];
sft.slave = slave;
sft.function = function + 0x80;
sft.t_id = ctx->backend->prepare_response_tid(req, &dummy_length);
rsp_length = ctx->backend->build_response_basis(&sft, rsp);
/* Positive exception code */
if (exception_code < MODBUS_EXCEPTION_MAX) {
rsp[rsp_length++] = exception_code;
return send_msg(ctx, rsp, rsp_length);
} else {
errno = EINVAL;
return -1;
}
}
/* Reads IO status */
static int read_io_status(modbus_t *ctx, int function,
int addr, int nb, uint8_t *dest)
{
int rc;
int req_length;
uint8_t req[_MIN_REQ_LENGTH];
uint8_t rsp[MAX_MESSAGE_LENGTH];
req_length = ctx->backend->build_request_basis(ctx, function, addr, nb, req);
rc = send_msg(ctx, req, req_length);
if (rc > 0) {
int i, temp, bit;
int pos = 0;
int offset;
int offset_end;
rc = _modbus_receive_msg(ctx, rsp, MSG_CONFIRMATION);
if (rc == -1)
return -1;
rc = check_confirmation(ctx, req, rsp, rc);
if (rc == -1)
return -1;
offset = ctx->backend->header_length + 2;
offset_end = offset + rc;
for (i = offset; i < offset_end; i++) {
/* Shift reg hi_byte to temp */
temp = rsp[i];
for (bit = 0x01; (bit & 0xff) && (pos < nb);) {
dest[pos++] = (temp & bit) ? TRUE : FALSE;
bit = bit << 1;
}
}
}
return rc;
}
/* Reads the boolean status of bits and sets the array elements
in the destination to TRUE or FALSE (single bits). */
int modbus_read_bits(modbus_t *ctx, int addr, int nb, uint8_t *dest)
{
int rc;
if (ctx == NULL) {
errno = EINVAL;
return -1;
}
if (nb > MODBUS_MAX_READ_BITS) {
if (ctx->debug) {
fprintf(stderr,
"ERROR Too many bits requested (%d > %d)\n",
nb, MODBUS_MAX_READ_BITS);
}
errno = EMBMDATA;
return -1;
}
rc = read_io_status(ctx, MODBUS_FC_READ_COILS, addr, nb, dest);
if (rc == -1)
return -1;
else
return nb;
}
/* Same as modbus_read_bits but reads the remote device input table */
int modbus_read_input_bits(modbus_t *ctx, int addr, int nb, uint8_t *dest)
{
int rc;
if (ctx == NULL) {
errno = EINVAL;
return -1;
}
if (nb > MODBUS_MAX_READ_BITS) {
if (ctx->debug) {
fprintf(stderr,
"ERROR Too many discrete inputs requested (%d > %d)\n",
nb, MODBUS_MAX_READ_BITS);
}
errno = EMBMDATA;
return -1;
}
rc = read_io_status(ctx, MODBUS_FC_READ_DISCRETE_INPUTS, addr, nb, dest);
if (rc == -1)
return -1;
else
return nb;
}
/* Reads the data from a remove device and put that data into an array */
static int read_registers(modbus_t *ctx, int function, int addr, int nb,
uint16_t *dest)
{
int rc;
int req_length;
uint8_t req[_MIN_REQ_LENGTH];
uint8_t rsp[MAX_MESSAGE_LENGTH];
if (nb > MODBUS_MAX_READ_REGISTERS) {
if (ctx->debug) {
fprintf(stderr,
"ERROR Too many registers requested (%d > %d)\n",
nb, MODBUS_MAX_READ_REGISTERS);
}
errno = EMBMDATA;
return -1;
}
req_length = ctx->backend->build_request_basis(ctx, function, addr, nb, req);
rc = send_msg(ctx, req, req_length);
if (rc > 0) {
int offset;
int i;
rc = _modbus_receive_msg(ctx, rsp, MSG_CONFIRMATION);
if (rc == -1)
return -1;
rc = check_confirmation(ctx, req, rsp, rc);
if (rc == -1)
return -1;
offset = ctx->backend->header_length;
for (i = 0; i < rc; i++) {
/* shift reg hi_byte to temp OR with lo_byte */
dest[i] = (rsp[offset + 2 + (i << 1)] << 8) |
rsp[offset + 3 + (i << 1)];
}
}
return rc;
}
/* Reads the holding registers of remote device and put the data into an
array */
int modbus_read_registers(modbus_t *ctx, int addr, int nb, uint16_t *dest)
{
int status;
if (ctx == NULL) {
errno = EINVAL;
return -1;
}
if (nb > MODBUS_MAX_READ_REGISTERS) {
if (ctx->debug) {
fprintf(stderr,
"ERROR Too many registers requested (%d > %d)\n",
nb, MODBUS_MAX_READ_REGISTERS);
}
errno = EMBMDATA;
return -1;
}
status = read_registers(ctx, MODBUS_FC_READ_HOLDING_REGISTERS,
addr, nb, dest);
return status;
}
/* Reads the input registers of remote device and put the data into an array */
int modbus_read_input_registers(modbus_t *ctx, int addr, int nb,
uint16_t *dest)
{
int status;
if (ctx == NULL) {
errno = EINVAL;
return -1;
}
if (nb > MODBUS_MAX_READ_REGISTERS) {
fprintf(stderr,
"ERROR Too many input registers requested (%d > %d)\n",
nb, MODBUS_MAX_READ_REGISTERS);
errno = EMBMDATA;
return -1;
}
status = read_registers(ctx, MODBUS_FC_READ_INPUT_REGISTERS,
addr, nb, dest);
return status;
}
/* Write a value to the specified register of the remote device.
Used by write_bit and write_register */
static int write_single(modbus_t *ctx, int function, int addr, int value)
{
int rc;
int req_length;
uint8_t req[_MIN_REQ_LENGTH];
if (ctx == NULL) {
errno = EINVAL;
return -1;
}
req_length = ctx->backend->build_request_basis(ctx, function, addr, value, req);
rc = send_msg(ctx, req, req_length);
if (rc > 0) {
/* Used by write_bit and write_register */
uint8_t rsp[MAX_MESSAGE_LENGTH];
rc = _modbus_receive_msg(ctx, rsp, MSG_CONFIRMATION);
if (rc == -1)
return -1;
rc = check_confirmation(ctx, req, rsp, rc);
}
return rc;
}
/* Turns ON or OFF a single bit of the remote device */
int modbus_write_bit(modbus_t *ctx, int addr, int status)
{
if (ctx == NULL) {
errno = EINVAL;
return -1;
}
return write_single(ctx, MODBUS_FC_WRITE_SINGLE_COIL, addr,
status ? 0xFF00 : 0);
}
/* Writes a value in one register of the remote device */
int modbus_write_register(modbus_t *ctx, int addr, int value)
{
if (ctx == NULL) {
errno = EINVAL;
return -1;
}
return write_single(ctx, MODBUS_FC_WRITE_SINGLE_REGISTER, addr, value);
}
/* Write the bits of the array in the remote device */
int modbus_write_bits(modbus_t *ctx, int addr, int nb, const uint8_t *src)
{
int rc;
int i;
int byte_count;
int req_length;
int bit_check = 0;
int pos = 0;
uint8_t req[MAX_MESSAGE_LENGTH];
if (ctx == NULL) {
errno = EINVAL;
return -1;
}
if (nb > MODBUS_MAX_WRITE_BITS) {
if (ctx->debug) {
fprintf(stderr, "ERROR Writing too many bits (%d > %d)\n",
nb, MODBUS_MAX_WRITE_BITS);
}
errno = EMBMDATA;
return -1;
}
req_length = ctx->backend->build_request_basis(ctx,
MODBUS_FC_WRITE_MULTIPLE_COILS,
addr, nb, req);
byte_count = (nb / 8) + ((nb % 8) ? 1 : 0);
req[req_length++] = byte_count;
for (i = 0; i < byte_count; i++) {
int bit;
bit = 0x01;
req[req_length] = 0;
while ((bit & 0xFF) && (bit_check++ < nb)) {
if (src[pos++])
req[req_length] |= bit;
else
req[req_length] &=~ bit;
bit = bit << 1;
}
req_length++;
}
rc = send_msg(ctx, req, req_length);
if (rc > 0) {
uint8_t rsp[MAX_MESSAGE_LENGTH];
rc = _modbus_receive_msg(ctx, rsp, MSG_CONFIRMATION);
if (rc == -1)
return -1;
rc = check_confirmation(ctx, req, rsp, rc);
}
return rc;
}
/* Write the values from the array to the registers of the remote device */
int modbus_write_registers(modbus_t *ctx, int addr, int nb, const uint16_t *src)
{
int rc;
int i;
int req_length;
int byte_count;
uint8_t req[MAX_MESSAGE_LENGTH];
if (ctx == NULL) {
errno = EINVAL;
return -1;
}
if (nb > MODBUS_MAX_WRITE_REGISTERS) {
if (ctx->debug) {
fprintf(stderr,
"ERROR Trying to write to too many registers (%d > %d)\n",
nb, MODBUS_MAX_WRITE_REGISTERS);
}
errno = EMBMDATA;
return -1;
}
req_length = ctx->backend->build_request_basis(ctx,
MODBUS_FC_WRITE_MULTIPLE_REGISTERS,
addr, nb, req);
byte_count = nb * 2;
req[req_length++] = byte_count;
for (i = 0; i < nb; i++) {
req[req_length++] = src[i] >> 8;
req[req_length++] = src[i] & 0x00FF;
}
rc = send_msg(ctx, req, req_length);
if (rc > 0) {
uint8_t rsp[MAX_MESSAGE_LENGTH];
rc = _modbus_receive_msg(ctx, rsp, MSG_CONFIRMATION);
if (rc == -1)
return -1;
rc = check_confirmation(ctx, req, rsp, rc);
}
return rc;
}
int modbus_mask_write_register(modbus_t *ctx, int addr, uint16_t and_mask, uint16_t or_mask)
{
int rc;
int req_length;
/* The request length can not exceed _MIN_REQ_LENGTH - 2 and 4 bytes to
* store the masks. The ugly substraction is there to remove the 'nb' value
* (2 bytes) which is not used. */
uint8_t req[_MIN_REQ_LENGTH + 2];
req_length = ctx->backend->build_request_basis(ctx,
MODBUS_FC_MASK_WRITE_REGISTER,
addr, 0, req);
/* HACKISH, count is not used */
req_length -= 2;
req[req_length++] = and_mask >> 8;
req[req_length++] = and_mask & 0x00ff;
req[req_length++] = or_mask >> 8;
req[req_length++] = or_mask & 0x00ff;
rc = send_msg(ctx, req, req_length);
if (rc > 0) {
/* Used by write_bit and write_register */
uint8_t rsp[MAX_MESSAGE_LENGTH];
rc = _modbus_receive_msg(ctx, rsp, MSG_CONFIRMATION);
if (rc == -1)
return -1;
rc = check_confirmation(ctx, req, rsp, rc);
}
return rc;
}
/* Write multiple registers from src array to remote device and read multiple
registers from remote device to dest array. */
int modbus_write_and_read_registers(modbus_t *ctx,
int write_addr, int write_nb,
const uint16_t *src,
int read_addr, int read_nb,
uint16_t *dest)
{
int rc;
int req_length;
int i;
int byte_count;
uint8_t req[MAX_MESSAGE_LENGTH];
uint8_t rsp[MAX_MESSAGE_LENGTH];
if (ctx == NULL) {
errno = EINVAL;
return -1;
}
if (write_nb > MODBUS_MAX_WR_WRITE_REGISTERS) {
if (ctx->debug) {
fprintf(stderr,
"ERROR Too many registers to write (%d > %d)\n",
write_nb, MODBUS_MAX_WR_WRITE_REGISTERS);
}
errno = EMBMDATA;
return -1;
}
if (read_nb > MODBUS_MAX_WR_READ_REGISTERS) {
if (ctx->debug) {
fprintf(stderr,
"ERROR Too many registers requested (%d > %d)\n",
read_nb, MODBUS_MAX_WR_READ_REGISTERS);
}
errno = EMBMDATA;
return -1;
}
req_length = ctx->backend->build_request_basis(ctx,
MODBUS_FC_WRITE_AND_READ_REGISTERS,
read_addr, read_nb, req);
req[req_length++] = write_addr >> 8;
req[req_length++] = write_addr & 0x00ff;
req[req_length++] = write_nb >> 8;
req[req_length++] = write_nb & 0x00ff;
byte_count = write_nb * 2;
req[req_length++] = byte_count;
for (i = 0; i < write_nb; i++) {
req[req_length++] = src[i] >> 8;
req[req_length++] = src[i] & 0x00FF;
}
rc = send_msg(ctx, req, req_length);
if (rc > 0) {
int offset;
rc = _modbus_receive_msg(ctx, rsp, MSG_CONFIRMATION);
if (rc == -1)
return -1;
rc = check_confirmation(ctx, req, rsp, rc);
if (rc == -1)
return -1;
offset = ctx->backend->header_length;
for (i = 0; i < rc; i++) {
/* shift reg hi_byte to temp OR with lo_byte */
dest[i] = (rsp[offset + 2 + (i << 1)] << 8) |
rsp[offset + 3 + (i << 1)];
}
}
return rc;
}
/* Send a request to get the slave ID of the device (only available in serial
communication). */
int modbus_report_slave_id(modbus_t *ctx, int max_dest, uint8_t *dest)
{
int rc;
int req_length;
uint8_t req[_MIN_REQ_LENGTH];
if (ctx == NULL || max_dest <= 0) {
errno = EINVAL;
return -1;
}
req_length = ctx->backend->build_request_basis(ctx, MODBUS_FC_REPORT_SLAVE_ID,
0, 0, req);
/* HACKISH, addr and count are not used */
req_length -= 4;
rc = send_msg(ctx, req, req_length);
if (rc > 0) {
int i;
int offset;
uint8_t rsp[MAX_MESSAGE_LENGTH];
rc = _modbus_receive_msg(ctx, rsp, MSG_CONFIRMATION);
if (rc == -1)
return -1;
rc = check_confirmation(ctx, req, rsp, rc);
if (rc == -1)
return -1;
offset = ctx->backend->header_length + 2;
/* Byte count, slave id, run indicator status and
additional data. Truncate copy to max_dest. */
for (i=0; i < rc && i < max_dest; i++) {
dest[i] = rsp[offset + i];
}
}
return rc;
}
void _modbus_init_common(modbus_t *ctx)
{
/* Slave and socket are initialized to -1 */
ctx->slave = -1;
ctx->s = -1;
ctx->debug = FALSE;
ctx->error_recovery = MODBUS_ERROR_RECOVERY_NONE;
ctx->response_timeout.tv_sec = 0;
ctx->response_timeout.tv_usec = _RESPONSE_TIMEOUT;
ctx->byte_timeout.tv_sec = 0;
ctx->byte_timeout.tv_usec = _BYTE_TIMEOUT;
ctx->indication_timeout.tv_sec = 0;
ctx->indication_timeout.tv_usec = 0;
}
/* Define the slave number */
int modbus_set_slave(modbus_t *ctx, int slave)
{
if (ctx == NULL) {
errno = EINVAL;
return -1;
}
return ctx->backend->set_slave(ctx, slave);
}
int modbus_get_slave(modbus_t *ctx)
{
if (ctx == NULL) {
errno = EINVAL;
return -1;
}
return ctx->slave;
}
int modbus_set_error_recovery(modbus_t *ctx,
modbus_error_recovery_mode error_recovery)
{
if (ctx == NULL) {
errno = EINVAL;
return -1;
}
/* The type of modbus_error_recovery_mode is unsigned enum */
ctx->error_recovery = (uint8_t) error_recovery;
return 0;
}
int modbus_set_socket(modbus_t *ctx, int s)
{
if (ctx == NULL) {
errno = EINVAL;
return -1;
}
ctx->s = s;
return 0;
}
int modbus_get_socket(modbus_t *ctx)
{
if (ctx == NULL) {
errno = EINVAL;
return -1;
}
return ctx->s;
}
/* Get the timeout interval used to wait for a response */
int modbus_get_response_timeout(modbus_t *ctx, uint32_t *to_sec, uint32_t *to_usec)
{
if (ctx == NULL) {
errno = EINVAL;
return -1;
}
*to_sec = ctx->response_timeout.tv_sec;
*to_usec = ctx->response_timeout.tv_usec;
return 0;
}
int modbus_set_response_timeout(modbus_t *ctx, uint32_t to_sec, uint32_t to_usec)
{
if (ctx == NULL ||
(to_sec == 0 && to_usec == 0) || to_usec > 999999) {
errno = EINVAL;
return -1;
}
ctx->response_timeout.tv_sec = to_sec;
ctx->response_timeout.tv_usec = to_usec;
return 0;
}
/* Get the timeout interval between two consecutive bytes of a message */
int modbus_get_byte_timeout(modbus_t *ctx, uint32_t *to_sec, uint32_t *to_usec)
{
if (ctx == NULL) {
errno = EINVAL;
return -1;
}
*to_sec = ctx->byte_timeout.tv_sec;
*to_usec = ctx->byte_timeout.tv_usec;
return 0;
}
int modbus_set_byte_timeout(modbus_t *ctx, uint32_t to_sec, uint32_t to_usec)
{
/* Byte timeout can be disabled when both values are zero */
if (ctx == NULL || to_usec > 999999) {
errno = EINVAL;
return -1;
}
ctx->byte_timeout.tv_sec = to_sec;
ctx->byte_timeout.tv_usec = to_usec;
return 0;
}
/* Get the timeout interval used by the server to wait for an indication from a client */
int modbus_get_indication_timeout(modbus_t *ctx, uint32_t *to_sec, uint32_t *to_usec)
{
if (ctx == NULL) {
errno = EINVAL;
return -1;
}
*to_sec = ctx->indication_timeout.tv_sec;
*to_usec = ctx->indication_timeout.tv_usec;
return 0;
}
int modbus_set_indication_timeout(modbus_t *ctx, uint32_t to_sec, uint32_t to_usec)
{
/* Indication timeout can be disabled when both values are zero */
if (ctx == NULL || to_usec > 999999) {
errno = EINVAL;
return -1;
}
ctx->indication_timeout.tv_sec = to_sec;
ctx->indication_timeout.tv_usec = to_usec;
return 0;
}
int modbus_get_header_length(modbus_t *ctx)
{
if (ctx == NULL) {
errno = EINVAL;
return -1;
}
return ctx->backend->header_length;
}
int modbus_connect(modbus_t *ctx)
{
if (ctx == NULL) {
errno = EINVAL;
return -1;
}
return ctx->backend->connect(ctx);
}
void modbus_close(modbus_t *ctx)
{
if (ctx == NULL)
return;
ctx->backend->close(ctx);
}
void modbus_free(modbus_t *ctx)
{
if (ctx == NULL)
return;
ctx->backend->free(ctx);
}
int modbus_set_debug(modbus_t *ctx, int flag)
{
if (ctx == NULL) {
errno = EINVAL;
return -1;
}
ctx->debug = flag;
return 0;
}
/* Allocates 4 arrays to store bits, input bits, registers and inputs
registers. The pointers are stored in modbus_mapping structure.
The modbus_mapping_new_start_address() function shall return the new allocated
structure if successful. Otherwise it shall return NULL and set errno to
ENOMEM. */
modbus_mapping_t* modbus_mapping_new_start_address(
unsigned int start_bits, unsigned int nb_bits,
unsigned int start_input_bits, unsigned int nb_input_bits,
unsigned int start_registers, unsigned int nb_registers,
unsigned int start_input_registers, unsigned int nb_input_registers)
{
modbus_mapping_t *mb_mapping;
mb_mapping = (modbus_mapping_t *)malloc(sizeof(modbus_mapping_t));
if (mb_mapping == NULL) {
return NULL;
}
/* 0X */
mb_mapping->nb_bits = nb_bits;
mb_mapping->start_bits = start_bits;
if (nb_bits == 0) {
mb_mapping->tab_bits = NULL;
} else {
/* Negative number raises a POSIX error */
mb_mapping->tab_bits =
(uint8_t *) malloc(nb_bits * sizeof(uint8_t));
if (mb_mapping->tab_bits == NULL) {
free(mb_mapping);
return NULL;
}
memset(mb_mapping->tab_bits, 0, nb_bits * sizeof(uint8_t));
}
/* 1X */
mb_mapping->nb_input_bits = nb_input_bits;
mb_mapping->start_input_bits = start_input_bits;
if (nb_input_bits == 0) {
mb_mapping->tab_input_bits = NULL;
} else {
mb_mapping->tab_input_bits =
(uint8_t *) malloc(nb_input_bits * sizeof(uint8_t));
if (mb_mapping->tab_input_bits == NULL) {
free(mb_mapping->tab_bits);
free(mb_mapping);
return NULL;
}
memset(mb_mapping->tab_input_bits, 0, nb_input_bits * sizeof(uint8_t));
}
/* 4X */
mb_mapping->nb_registers = nb_registers;
mb_mapping->start_registers = start_registers;
if (nb_registers == 0) {
mb_mapping->tab_registers = NULL;
} else {
mb_mapping->tab_registers =
(uint16_t *) malloc(nb_registers * sizeof(uint16_t));
if (mb_mapping->tab_registers == NULL) {
free(mb_mapping->tab_input_bits);
free(mb_mapping->tab_bits);
free(mb_mapping);
return NULL;
}
memset(mb_mapping->tab_registers, 0, nb_registers * sizeof(uint16_t));
}
/* 3X */
mb_mapping->nb_input_registers = nb_input_registers;
mb_mapping->start_input_registers = start_input_registers;
if (nb_input_registers == 0) {
mb_mapping->tab_input_registers = NULL;
} else {
mb_mapping->tab_input_registers =
(uint16_t *) malloc(nb_input_registers * sizeof(uint16_t));
if (mb_mapping->tab_input_registers == NULL) {
free(mb_mapping->tab_registers);
free(mb_mapping->tab_input_bits);
free(mb_mapping->tab_bits);
free(mb_mapping);
return NULL;
}
memset(mb_mapping->tab_input_registers, 0,
nb_input_registers * sizeof(uint16_t));
}
return mb_mapping;
}
modbus_mapping_t* modbus_mapping_new(int nb_bits, int nb_input_bits,
int nb_registers, int nb_input_registers)
{
return modbus_mapping_new_start_address(
0, nb_bits, 0, nb_input_bits, 0, nb_registers, 0, nb_input_registers);
}
/* Frees the 4 arrays */
void modbus_mapping_free(modbus_mapping_t *mb_mapping)
{
if (mb_mapping == NULL) {
return;
}
free(mb_mapping->tab_input_registers);
free(mb_mapping->tab_registers);
free(mb_mapping->tab_input_bits);
free(mb_mapping->tab_bits);
free(mb_mapping);
}
#ifndef HAVE_STRLCPY
/*
* Function strlcpy was originally developed by
* Todd C. Miller <Todd.Miller@courtesan.com> to simplify writing secure code.
* See ftp://ftp.openbsd.org/pub/OpenBSD/src/lib/libc/string/strlcpy.3
* for more information.
*
* Thank you Ulrich Drepper... not!
*
* Copy src to string dest of size dest_size. At most dest_size-1 characters
* will be copied. Always NUL terminates (unless dest_size == 0). Returns
* strlen(src); if retval >= dest_size, truncation occurred.
*/
size_t strlcpy(char *dest, const char *src, size_t dest_size)
{
register char *d = dest;
register const char *s = src;
register size_t n = dest_size;
/* Copy as many bytes as will fit */
if (n != 0 && --n != 0) {
do {
if ((*d++ = *s++) == 0)
break;
} while (--n != 0);
}
/* Not enough room in dest, add NUL and traverse rest of src */
if (n == 0) {
if (dest_size != 0)
*d = '\0'; /* NUL-terminate dest */
while (*s++)
;
}
return (s - src - 1); /* count does not include NUL */
}
#endif
| ./CrossVul/dataset_final_sorted/CWE-125/c/good_977_0 |
crossvul-cpp_data_good_265_0 | /*
* Copyright (C) 1999 WIDE Project.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the project nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* Extensively modified by Hannes Gredler (hannes@gredler.at) for more
* complete BGP support.
*/
/* \summary: Border Gateway Protocol (BGP) printer */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <netdissect-stdinc.h>
#include <stdio.h>
#include <string.h>
#include "netdissect.h"
#include "addrtoname.h"
#include "extract.h"
#include "af.h"
#include "l2vpn.h"
struct bgp {
uint8_t bgp_marker[16];
uint16_t bgp_len;
uint8_t bgp_type;
};
#define BGP_SIZE 19 /* unaligned */
#define BGP_OPEN 1
#define BGP_UPDATE 2
#define BGP_NOTIFICATION 3
#define BGP_KEEPALIVE 4
#define BGP_ROUTE_REFRESH 5
static const struct tok bgp_msg_values[] = {
{ BGP_OPEN, "Open"},
{ BGP_UPDATE, "Update"},
{ BGP_NOTIFICATION, "Notification"},
{ BGP_KEEPALIVE, "Keepalive"},
{ BGP_ROUTE_REFRESH, "Route Refresh"},
{ 0, NULL}
};
struct bgp_open {
uint8_t bgpo_marker[16];
uint16_t bgpo_len;
uint8_t bgpo_type;
uint8_t bgpo_version;
uint16_t bgpo_myas;
uint16_t bgpo_holdtime;
uint32_t bgpo_id;
uint8_t bgpo_optlen;
/* options should follow */
};
#define BGP_OPEN_SIZE 29 /* unaligned */
struct bgp_opt {
uint8_t bgpopt_type;
uint8_t bgpopt_len;
/* variable length */
};
#define BGP_OPT_SIZE 2 /* some compilers may pad to 4 bytes */
#define BGP_CAP_HEADER_SIZE 2 /* some compilers may pad to 4 bytes */
struct bgp_notification {
uint8_t bgpn_marker[16];
uint16_t bgpn_len;
uint8_t bgpn_type;
uint8_t bgpn_major;
uint8_t bgpn_minor;
};
#define BGP_NOTIFICATION_SIZE 21 /* unaligned */
struct bgp_route_refresh {
uint8_t bgp_marker[16];
uint16_t len;
uint8_t type;
uint8_t afi[2]; /* the compiler messes this structure up */
uint8_t res; /* when doing misaligned sequences of int8 and int16 */
uint8_t safi; /* afi should be int16 - so we have to access it using */
}; /* EXTRACT_16BITS(&bgp_route_refresh->afi) (sigh) */
#define BGP_ROUTE_REFRESH_SIZE 23
#define bgp_attr_lenlen(flags, p) \
(((flags) & 0x10) ? 2 : 1)
#define bgp_attr_len(flags, p) \
(((flags) & 0x10) ? EXTRACT_16BITS(p) : *(p))
#define BGPTYPE_ORIGIN 1
#define BGPTYPE_AS_PATH 2
#define BGPTYPE_NEXT_HOP 3
#define BGPTYPE_MULTI_EXIT_DISC 4
#define BGPTYPE_LOCAL_PREF 5
#define BGPTYPE_ATOMIC_AGGREGATE 6
#define BGPTYPE_AGGREGATOR 7
#define BGPTYPE_COMMUNITIES 8 /* RFC1997 */
#define BGPTYPE_ORIGINATOR_ID 9 /* RFC4456 */
#define BGPTYPE_CLUSTER_LIST 10 /* RFC4456 */
#define BGPTYPE_DPA 11 /* deprecated, draft-ietf-idr-bgp-dpa */
#define BGPTYPE_ADVERTISERS 12 /* deprecated RFC1863 */
#define BGPTYPE_RCID_PATH 13 /* deprecated RFC1863 */
#define BGPTYPE_MP_REACH_NLRI 14 /* RFC4760 */
#define BGPTYPE_MP_UNREACH_NLRI 15 /* RFC4760 */
#define BGPTYPE_EXTD_COMMUNITIES 16 /* RFC4360 */
#define BGPTYPE_AS4_PATH 17 /* RFC6793 */
#define BGPTYPE_AGGREGATOR4 18 /* RFC6793 */
#define BGPTYPE_PMSI_TUNNEL 22 /* RFC6514 */
#define BGPTYPE_TUNNEL_ENCAP 23 /* RFC5512 */
#define BGPTYPE_TRAFFIC_ENG 24 /* RFC5543 */
#define BGPTYPE_IPV6_EXTD_COMMUNITIES 25 /* RFC5701 */
#define BGPTYPE_AIGP 26 /* RFC7311 */
#define BGPTYPE_PE_DISTINGUISHER_LABEL 27 /* RFC6514 */
#define BGPTYPE_ENTROPY_LABEL 28 /* RFC6790 */
#define BGPTYPE_LARGE_COMMUNITY 32 /* draft-ietf-idr-large-community-05 */
#define BGPTYPE_ATTR_SET 128 /* RFC6368 */
#define BGP_MP_NLRI_MINSIZE 3 /* End of RIB Marker detection */
static const struct tok bgp_attr_values[] = {
{ BGPTYPE_ORIGIN, "Origin"},
{ BGPTYPE_AS_PATH, "AS Path"},
{ BGPTYPE_AS4_PATH, "AS4 Path"},
{ BGPTYPE_NEXT_HOP, "Next Hop"},
{ BGPTYPE_MULTI_EXIT_DISC, "Multi Exit Discriminator"},
{ BGPTYPE_LOCAL_PREF, "Local Preference"},
{ BGPTYPE_ATOMIC_AGGREGATE, "Atomic Aggregate"},
{ BGPTYPE_AGGREGATOR, "Aggregator"},
{ BGPTYPE_AGGREGATOR4, "Aggregator4"},
{ BGPTYPE_COMMUNITIES, "Community"},
{ BGPTYPE_ORIGINATOR_ID, "Originator ID"},
{ BGPTYPE_CLUSTER_LIST, "Cluster List"},
{ BGPTYPE_DPA, "DPA"},
{ BGPTYPE_ADVERTISERS, "Advertisers"},
{ BGPTYPE_RCID_PATH, "RCID Path / Cluster ID"},
{ BGPTYPE_MP_REACH_NLRI, "Multi-Protocol Reach NLRI"},
{ BGPTYPE_MP_UNREACH_NLRI, "Multi-Protocol Unreach NLRI"},
{ BGPTYPE_EXTD_COMMUNITIES, "Extended Community"},
{ BGPTYPE_PMSI_TUNNEL, "PMSI Tunnel"},
{ BGPTYPE_TUNNEL_ENCAP, "Tunnel Encapsulation"},
{ BGPTYPE_TRAFFIC_ENG, "Traffic Engineering"},
{ BGPTYPE_IPV6_EXTD_COMMUNITIES, "IPv6 Extended Community"},
{ BGPTYPE_AIGP, "Accumulated IGP Metric"},
{ BGPTYPE_PE_DISTINGUISHER_LABEL, "PE Distinguisher Label"},
{ BGPTYPE_ENTROPY_LABEL, "Entropy Label"},
{ BGPTYPE_LARGE_COMMUNITY, "Large Community"},
{ BGPTYPE_ATTR_SET, "Attribute Set"},
{ 255, "Reserved for development"},
{ 0, NULL}
};
#define BGP_AS_SET 1
#define BGP_AS_SEQUENCE 2
#define BGP_CONFED_AS_SEQUENCE 3 /* draft-ietf-idr-rfc3065bis-01 */
#define BGP_CONFED_AS_SET 4 /* draft-ietf-idr-rfc3065bis-01 */
#define BGP_AS_SEG_TYPE_MIN BGP_AS_SET
#define BGP_AS_SEG_TYPE_MAX BGP_CONFED_AS_SET
static const struct tok bgp_as_path_segment_open_values[] = {
{ BGP_AS_SEQUENCE, ""},
{ BGP_AS_SET, "{ "},
{ BGP_CONFED_AS_SEQUENCE, "( "},
{ BGP_CONFED_AS_SET, "({ "},
{ 0, NULL}
};
static const struct tok bgp_as_path_segment_close_values[] = {
{ BGP_AS_SEQUENCE, ""},
{ BGP_AS_SET, "}"},
{ BGP_CONFED_AS_SEQUENCE, ")"},
{ BGP_CONFED_AS_SET, "})"},
{ 0, NULL}
};
#define BGP_OPT_AUTH 1
#define BGP_OPT_CAP 2
static const struct tok bgp_opt_values[] = {
{ BGP_OPT_AUTH, "Authentication Information"},
{ BGP_OPT_CAP, "Capabilities Advertisement"},
{ 0, NULL}
};
#define BGP_CAPCODE_MP 1 /* RFC2858 */
#define BGP_CAPCODE_RR 2 /* RFC2918 */
#define BGP_CAPCODE_ORF 3 /* RFC5291 */
#define BGP_CAPCODE_MR 4 /* RFC3107 */
#define BGP_CAPCODE_EXT_NH 5 /* RFC5549 */
#define BGP_CAPCODE_RESTART 64 /* RFC4724 */
#define BGP_CAPCODE_AS_NEW 65 /* RFC6793 */
#define BGP_CAPCODE_DYN_CAP 67 /* draft-ietf-idr-dynamic-cap */
#define BGP_CAPCODE_MULTISESS 68 /* draft-ietf-idr-bgp-multisession */
#define BGP_CAPCODE_ADD_PATH 69 /* RFC7911 */
#define BGP_CAPCODE_ENH_RR 70 /* draft-keyur-bgp-enhanced-route-refresh */
#define BGP_CAPCODE_RR_CISCO 128
static const struct tok bgp_capcode_values[] = {
{ BGP_CAPCODE_MP, "Multiprotocol Extensions"},
{ BGP_CAPCODE_RR, "Route Refresh"},
{ BGP_CAPCODE_ORF, "Cooperative Route Filtering"},
{ BGP_CAPCODE_MR, "Multiple Routes to a Destination"},
{ BGP_CAPCODE_EXT_NH, "Extended Next Hop Encoding"},
{ BGP_CAPCODE_RESTART, "Graceful Restart"},
{ BGP_CAPCODE_AS_NEW, "32-Bit AS Number"},
{ BGP_CAPCODE_DYN_CAP, "Dynamic Capability"},
{ BGP_CAPCODE_MULTISESS, "Multisession BGP"},
{ BGP_CAPCODE_ADD_PATH, "Multiple Paths"},
{ BGP_CAPCODE_ENH_RR, "Enhanced Route Refresh"},
{ BGP_CAPCODE_RR_CISCO, "Route Refresh (Cisco)"},
{ 0, NULL}
};
#define BGP_NOTIFY_MAJOR_MSG 1
#define BGP_NOTIFY_MAJOR_OPEN 2
#define BGP_NOTIFY_MAJOR_UPDATE 3
#define BGP_NOTIFY_MAJOR_HOLDTIME 4
#define BGP_NOTIFY_MAJOR_FSM 5
#define BGP_NOTIFY_MAJOR_CEASE 6
#define BGP_NOTIFY_MAJOR_CAP 7
static const struct tok bgp_notify_major_values[] = {
{ BGP_NOTIFY_MAJOR_MSG, "Message Header Error"},
{ BGP_NOTIFY_MAJOR_OPEN, "OPEN Message Error"},
{ BGP_NOTIFY_MAJOR_UPDATE, "UPDATE Message Error"},
{ BGP_NOTIFY_MAJOR_HOLDTIME,"Hold Timer Expired"},
{ BGP_NOTIFY_MAJOR_FSM, "Finite State Machine Error"},
{ BGP_NOTIFY_MAJOR_CEASE, "Cease"},
{ BGP_NOTIFY_MAJOR_CAP, "Capability Message Error"},
{ 0, NULL}
};
/* draft-ietf-idr-cease-subcode-02 */
#define BGP_NOTIFY_MINOR_CEASE_MAXPRFX 1
static const struct tok bgp_notify_minor_cease_values[] = {
{ BGP_NOTIFY_MINOR_CEASE_MAXPRFX, "Maximum Number of Prefixes Reached"},
{ 2, "Administratively Shutdown"},
{ 3, "Peer Unconfigured"},
{ 4, "Administratively Reset"},
{ 5, "Connection Rejected"},
{ 6, "Other Configuration Change"},
{ 7, "Connection Collision Resolution"},
{ 0, NULL}
};
static const struct tok bgp_notify_minor_msg_values[] = {
{ 1, "Connection Not Synchronized"},
{ 2, "Bad Message Length"},
{ 3, "Bad Message Type"},
{ 0, NULL}
};
static const struct tok bgp_notify_minor_open_values[] = {
{ 1, "Unsupported Version Number"},
{ 2, "Bad Peer AS"},
{ 3, "Bad BGP Identifier"},
{ 4, "Unsupported Optional Parameter"},
{ 5, "Authentication Failure"},
{ 6, "Unacceptable Hold Time"},
{ 7, "Capability Message Error"},
{ 0, NULL}
};
static const struct tok bgp_notify_minor_update_values[] = {
{ 1, "Malformed Attribute List"},
{ 2, "Unrecognized Well-known Attribute"},
{ 3, "Missing Well-known Attribute"},
{ 4, "Attribute Flags Error"},
{ 5, "Attribute Length Error"},
{ 6, "Invalid ORIGIN Attribute"},
{ 7, "AS Routing Loop"},
{ 8, "Invalid NEXT_HOP Attribute"},
{ 9, "Optional Attribute Error"},
{ 10, "Invalid Network Field"},
{ 11, "Malformed AS_PATH"},
{ 0, NULL}
};
static const struct tok bgp_notify_minor_fsm_values[] = {
{ 1, "In OpenSent State"},
{ 2, "In OpenConfirm State"},
{ 3, "In Established State"},
{ 0, NULL }
};
static const struct tok bgp_notify_minor_cap_values[] = {
{ 1, "Invalid Action Value" },
{ 2, "Invalid Capability Length" },
{ 3, "Malformed Capability Value" },
{ 4, "Unsupported Capability Code" },
{ 0, NULL }
};
static const struct tok bgp_origin_values[] = {
{ 0, "IGP"},
{ 1, "EGP"},
{ 2, "Incomplete"},
{ 0, NULL}
};
#define BGP_PMSI_TUNNEL_RSVP_P2MP 1
#define BGP_PMSI_TUNNEL_LDP_P2MP 2
#define BGP_PMSI_TUNNEL_PIM_SSM 3
#define BGP_PMSI_TUNNEL_PIM_SM 4
#define BGP_PMSI_TUNNEL_PIM_BIDIR 5
#define BGP_PMSI_TUNNEL_INGRESS 6
#define BGP_PMSI_TUNNEL_LDP_MP2MP 7
static const struct tok bgp_pmsi_tunnel_values[] = {
{ BGP_PMSI_TUNNEL_RSVP_P2MP, "RSVP-TE P2MP LSP"},
{ BGP_PMSI_TUNNEL_LDP_P2MP, "LDP P2MP LSP"},
{ BGP_PMSI_TUNNEL_PIM_SSM, "PIM-SSM Tree"},
{ BGP_PMSI_TUNNEL_PIM_SM, "PIM-SM Tree"},
{ BGP_PMSI_TUNNEL_PIM_BIDIR, "PIM-Bidir Tree"},
{ BGP_PMSI_TUNNEL_INGRESS, "Ingress Replication"},
{ BGP_PMSI_TUNNEL_LDP_MP2MP, "LDP MP2MP LSP"},
{ 0, NULL}
};
static const struct tok bgp_pmsi_flag_values[] = {
{ 0x01, "Leaf Information required"},
{ 0, NULL}
};
#define BGP_AIGP_TLV 1
static const struct tok bgp_aigp_values[] = {
{ BGP_AIGP_TLV, "AIGP"},
{ 0, NULL}
};
/* Subsequent address family identifier, RFC2283 section 7 */
#define SAFNUM_RES 0
#define SAFNUM_UNICAST 1
#define SAFNUM_MULTICAST 2
#define SAFNUM_UNIMULTICAST 3 /* deprecated now */
/* labeled BGP RFC3107 */
#define SAFNUM_LABUNICAST 4
/* RFC6514 */
#define SAFNUM_MULTICAST_VPN 5
/* draft-nalawade-kapoor-tunnel-safi */
#define SAFNUM_TUNNEL 64
/* RFC4761 */
#define SAFNUM_VPLS 65
/* RFC6037 */
#define SAFNUM_MDT 66
/* RFC4364 */
#define SAFNUM_VPNUNICAST 128
/* RFC6513 */
#define SAFNUM_VPNMULTICAST 129
#define SAFNUM_VPNUNIMULTICAST 130 /* deprecated now */
/* RFC4684 */
#define SAFNUM_RT_ROUTING_INFO 132
#define BGP_VPN_RD_LEN 8
static const struct tok bgp_safi_values[] = {
{ SAFNUM_RES, "Reserved"},
{ SAFNUM_UNICAST, "Unicast"},
{ SAFNUM_MULTICAST, "Multicast"},
{ SAFNUM_UNIMULTICAST, "Unicast+Multicast"},
{ SAFNUM_LABUNICAST, "labeled Unicast"},
{ SAFNUM_TUNNEL, "Tunnel"},
{ SAFNUM_VPLS, "VPLS"},
{ SAFNUM_MDT, "MDT"},
{ SAFNUM_VPNUNICAST, "labeled VPN Unicast"},
{ SAFNUM_VPNMULTICAST, "labeled VPN Multicast"},
{ SAFNUM_VPNUNIMULTICAST, "labeled VPN Unicast+Multicast"},
{ SAFNUM_RT_ROUTING_INFO, "Route Target Routing Information"},
{ SAFNUM_MULTICAST_VPN, "Multicast VPN"},
{ 0, NULL }
};
/* well-known community */
#define BGP_COMMUNITY_NO_EXPORT 0xffffff01
#define BGP_COMMUNITY_NO_ADVERT 0xffffff02
#define BGP_COMMUNITY_NO_EXPORT_SUBCONFED 0xffffff03
/* Extended community type - draft-ietf-idr-bgp-ext-communities-05 */
#define BGP_EXT_COM_RT_0 0x0002 /* Route Target,Format AS(2bytes):AN(4bytes) */
#define BGP_EXT_COM_RT_1 0x0102 /* Route Target,Format IP address:AN(2bytes) */
#define BGP_EXT_COM_RT_2 0x0202 /* Route Target,Format AN(4bytes):local(2bytes) */
#define BGP_EXT_COM_RO_0 0x0003 /* Route Origin,Format AS(2bytes):AN(4bytes) */
#define BGP_EXT_COM_RO_1 0x0103 /* Route Origin,Format IP address:AN(2bytes) */
#define BGP_EXT_COM_RO_2 0x0203 /* Route Origin,Format AN(4bytes):local(2bytes) */
#define BGP_EXT_COM_LINKBAND 0x4004 /* Link Bandwidth,Format AS(2B):Bandwidth(4B) */
/* rfc2547 bgp-mpls-vpns */
#define BGP_EXT_COM_VPN_ORIGIN 0x0005 /* OSPF Domain ID / VPN of Origin - draft-rosen-vpns-ospf-bgp-mpls */
#define BGP_EXT_COM_VPN_ORIGIN2 0x0105 /* duplicate - keep for backwards compatability */
#define BGP_EXT_COM_VPN_ORIGIN3 0x0205 /* duplicate - keep for backwards compatability */
#define BGP_EXT_COM_VPN_ORIGIN4 0x8005 /* duplicate - keep for backwards compatability */
#define BGP_EXT_COM_OSPF_RTYPE 0x0306 /* OSPF Route Type,Format Area(4B):RouteType(1B):Options(1B) */
#define BGP_EXT_COM_OSPF_RTYPE2 0x8000 /* duplicate - keep for backwards compatability */
#define BGP_EXT_COM_OSPF_RID 0x0107 /* OSPF Router ID,Format RouterID(4B):Unused(2B) */
#define BGP_EXT_COM_OSPF_RID2 0x8001 /* duplicate - keep for backwards compatability */
#define BGP_EXT_COM_L2INFO 0x800a /* draft-kompella-ppvpn-l2vpn */
#define BGP_EXT_COM_SOURCE_AS 0x0009 /* RFC-ietf-l3vpn-2547bis-mcast-bgp-08.txt */
#define BGP_EXT_COM_VRF_RT_IMP 0x010b /* RFC-ietf-l3vpn-2547bis-mcast-bgp-08.txt */
#define BGP_EXT_COM_L2VPN_RT_0 0x000a /* L2VPN Identifier,Format AS(2bytes):AN(4bytes) */
#define BGP_EXT_COM_L2VPN_RT_1 0xF10a /* L2VPN Identifier,Format IP address:AN(2bytes) */
/* http://www.cisco.com/en/US/tech/tk436/tk428/technologies_tech_note09186a00801eb09a.shtml */
#define BGP_EXT_COM_EIGRP_GEN 0x8800
#define BGP_EXT_COM_EIGRP_METRIC_AS_DELAY 0x8801
#define BGP_EXT_COM_EIGRP_METRIC_REL_NH_BW 0x8802
#define BGP_EXT_COM_EIGRP_METRIC_LOAD_MTU 0x8803
#define BGP_EXT_COM_EIGRP_EXT_REMAS_REMID 0x8804
#define BGP_EXT_COM_EIGRP_EXT_REMPROTO_REMMETRIC 0x8805
static const struct tok bgp_extd_comm_flag_values[] = {
{ 0x8000, "vendor-specific"},
{ 0x4000, "non-transitive"},
{ 0, NULL},
};
static const struct tok bgp_extd_comm_subtype_values[] = {
{ BGP_EXT_COM_RT_0, "target"},
{ BGP_EXT_COM_RT_1, "target"},
{ BGP_EXT_COM_RT_2, "target"},
{ BGP_EXT_COM_RO_0, "origin"},
{ BGP_EXT_COM_RO_1, "origin"},
{ BGP_EXT_COM_RO_2, "origin"},
{ BGP_EXT_COM_LINKBAND, "link-BW"},
{ BGP_EXT_COM_VPN_ORIGIN, "ospf-domain"},
{ BGP_EXT_COM_VPN_ORIGIN2, "ospf-domain"},
{ BGP_EXT_COM_VPN_ORIGIN3, "ospf-domain"},
{ BGP_EXT_COM_VPN_ORIGIN4, "ospf-domain"},
{ BGP_EXT_COM_OSPF_RTYPE, "ospf-route-type"},
{ BGP_EXT_COM_OSPF_RTYPE2, "ospf-route-type"},
{ BGP_EXT_COM_OSPF_RID, "ospf-router-id"},
{ BGP_EXT_COM_OSPF_RID2, "ospf-router-id"},
{ BGP_EXT_COM_L2INFO, "layer2-info"},
{ BGP_EXT_COM_EIGRP_GEN , "eigrp-general-route (flag, tag)" },
{ BGP_EXT_COM_EIGRP_METRIC_AS_DELAY , "eigrp-route-metric (AS, delay)" },
{ BGP_EXT_COM_EIGRP_METRIC_REL_NH_BW , "eigrp-route-metric (reliability, nexthop, bandwidth)" },
{ BGP_EXT_COM_EIGRP_METRIC_LOAD_MTU , "eigrp-route-metric (load, MTU)" },
{ BGP_EXT_COM_EIGRP_EXT_REMAS_REMID , "eigrp-external-route (remote-AS, remote-ID)" },
{ BGP_EXT_COM_EIGRP_EXT_REMPROTO_REMMETRIC , "eigrp-external-route (remote-proto, remote-metric)" },
{ BGP_EXT_COM_SOURCE_AS, "source-AS" },
{ BGP_EXT_COM_VRF_RT_IMP, "vrf-route-import"},
{ BGP_EXT_COM_L2VPN_RT_0, "l2vpn-id"},
{ BGP_EXT_COM_L2VPN_RT_1, "l2vpn-id"},
{ 0, NULL},
};
/* OSPF codes for BGP_EXT_COM_OSPF_RTYPE draft-rosen-vpns-ospf-bgp-mpls */
#define BGP_OSPF_RTYPE_RTR 1 /* OSPF Router LSA */
#define BGP_OSPF_RTYPE_NET 2 /* OSPF Network LSA */
#define BGP_OSPF_RTYPE_SUM 3 /* OSPF Summary LSA */
#define BGP_OSPF_RTYPE_EXT 5 /* OSPF External LSA, note that ASBR doesn't apply to MPLS-VPN */
#define BGP_OSPF_RTYPE_NSSA 7 /* OSPF NSSA External*/
#define BGP_OSPF_RTYPE_SHAM 129 /* OSPF-MPLS-VPN Sham link */
#define BGP_OSPF_RTYPE_METRIC_TYPE 0x1 /* LSB of RTYPE Options Field */
static const struct tok bgp_extd_comm_ospf_rtype_values[] = {
{ BGP_OSPF_RTYPE_RTR, "Router" },
{ BGP_OSPF_RTYPE_NET, "Network" },
{ BGP_OSPF_RTYPE_SUM, "Summary" },
{ BGP_OSPF_RTYPE_EXT, "External" },
{ BGP_OSPF_RTYPE_NSSA,"NSSA External" },
{ BGP_OSPF_RTYPE_SHAM,"MPLS-VPN Sham" },
{ 0, NULL },
};
/* ADD-PATH Send/Receive field values */
static const struct tok bgp_add_path_recvsend[] = {
{ 1, "Receive" },
{ 2, "Send" },
{ 3, "Both" },
{ 0, NULL },
};
static char astostr[20];
/*
* as_printf
*
* Convert an AS number into a string and return string pointer.
*
* Depending on bflag is set or not, AS number is converted into ASDOT notation
* or plain number notation.
*
*/
static char *
as_printf(netdissect_options *ndo,
char *str, int size, u_int asnum)
{
if (!ndo->ndo_bflag || asnum <= 0xFFFF) {
snprintf(str, size, "%u", asnum);
} else {
snprintf(str, size, "%u.%u", asnum >> 16, asnum & 0xFFFF);
}
return str;
}
#define ITEMCHECK(minlen) if (itemlen < minlen) goto badtlv;
int
decode_prefix4(netdissect_options *ndo,
const u_char *pptr, u_int itemlen, char *buf, u_int buflen)
{
struct in_addr addr;
u_int plen, plenbytes;
ND_TCHECK(pptr[0]);
ITEMCHECK(1);
plen = pptr[0];
if (32 < plen)
return -1;
itemlen -= 1;
memset(&addr, 0, sizeof(addr));
plenbytes = (plen + 7) / 8;
ND_TCHECK2(pptr[1], plenbytes);
ITEMCHECK(plenbytes);
memcpy(&addr, &pptr[1], plenbytes);
if (plen % 8) {
((u_char *)&addr)[plenbytes - 1] &=
((0xff00 >> (plen % 8)) & 0xff);
}
snprintf(buf, buflen, "%s/%d", ipaddr_string(ndo, &addr), plen);
return 1 + plenbytes;
trunc:
return -2;
badtlv:
return -3;
}
static int
decode_labeled_prefix4(netdissect_options *ndo,
const u_char *pptr, u_int itemlen, char *buf, u_int buflen)
{
struct in_addr addr;
u_int plen, plenbytes;
/* prefix length and label = 4 bytes */
ND_TCHECK2(pptr[0], 4);
ITEMCHECK(4);
plen = pptr[0]; /* get prefix length */
/* this is one of the weirdnesses of rfc3107
the label length (actually the label + COS bits)
is added to the prefix length;
we also do only read out just one label -
there is no real application for advertisement of
stacked labels in a single BGP message
*/
if (24 > plen)
return -1;
plen-=24; /* adjust prefixlen - labellength */
if (32 < plen)
return -1;
itemlen -= 4;
memset(&addr, 0, sizeof(addr));
plenbytes = (plen + 7) / 8;
ND_TCHECK2(pptr[4], plenbytes);
ITEMCHECK(plenbytes);
memcpy(&addr, &pptr[4], plenbytes);
if (plen % 8) {
((u_char *)&addr)[plenbytes - 1] &=
((0xff00 >> (plen % 8)) & 0xff);
}
/* the label may get offsetted by 4 bits so lets shift it right */
snprintf(buf, buflen, "%s/%d, label:%u %s",
ipaddr_string(ndo, &addr),
plen,
EXTRACT_24BITS(pptr+1)>>4,
((pptr[3]&1)==0) ? "(BOGUS: Bottom of Stack NOT set!)" : "(bottom)" );
return 4 + plenbytes;
trunc:
return -2;
badtlv:
return -3;
}
/*
* bgp_vpn_ip_print
*
* print an ipv4 or ipv6 address into a buffer dependend on address length.
*/
static char *
bgp_vpn_ip_print(netdissect_options *ndo,
const u_char *pptr, u_int addr_length)
{
/* worst case string is s fully formatted v6 address */
static char addr[sizeof("1234:5678:89ab:cdef:1234:5678:89ab:cdef")];
char *pos = addr;
switch(addr_length) {
case (sizeof(struct in_addr) << 3): /* 32 */
ND_TCHECK2(pptr[0], sizeof(struct in_addr));
snprintf(pos, sizeof(addr), "%s", ipaddr_string(ndo, pptr));
break;
case (sizeof(struct in6_addr) << 3): /* 128 */
ND_TCHECK2(pptr[0], sizeof(struct in6_addr));
snprintf(pos, sizeof(addr), "%s", ip6addr_string(ndo, pptr));
break;
default:
snprintf(pos, sizeof(addr), "bogus address length %u", addr_length);
break;
}
pos += strlen(pos);
trunc:
*(pos) = '\0';
return (addr);
}
/*
* bgp_vpn_sg_print
*
* print an multicast s,g entry into a buffer.
* the s,g entry is encoded like this.
*
* +-----------------------------------+
* | Multicast Source Length (1 octet) |
* +-----------------------------------+
* | Multicast Source (Variable) |
* +-----------------------------------+
* | Multicast Group Length (1 octet) |
* +-----------------------------------+
* | Multicast Group (Variable) |
* +-----------------------------------+
*
* return the number of bytes read from the wire.
*/
static int
bgp_vpn_sg_print(netdissect_options *ndo,
const u_char *pptr, char *buf, u_int buflen)
{
uint8_t addr_length;
u_int total_length, offset;
total_length = 0;
/* Source address length, encoded in bits */
ND_TCHECK2(pptr[0], 1);
addr_length = *pptr++;
/* Source address */
ND_TCHECK2(pptr[0], (addr_length >> 3));
total_length += (addr_length >> 3) + 1;
offset = strlen(buf);
if (addr_length) {
snprintf(buf + offset, buflen - offset, ", Source %s",
bgp_vpn_ip_print(ndo, pptr, addr_length));
pptr += (addr_length >> 3);
}
/* Group address length, encoded in bits */
ND_TCHECK2(pptr[0], 1);
addr_length = *pptr++;
/* Group address */
ND_TCHECK2(pptr[0], (addr_length >> 3));
total_length += (addr_length >> 3) + 1;
offset = strlen(buf);
if (addr_length) {
snprintf(buf + offset, buflen - offset, ", Group %s",
bgp_vpn_ip_print(ndo, pptr, addr_length));
pptr += (addr_length >> 3);
}
trunc:
return (total_length);
}
/* RDs and RTs share the same semantics
* we use bgp_vpn_rd_print for
* printing route targets inside a NLRI */
char *
bgp_vpn_rd_print(netdissect_options *ndo,
const u_char *pptr)
{
/* allocate space for the largest possible string */
static char rd[sizeof("xxxxxxxxxx:xxxxx (xxx.xxx.xxx.xxx:xxxxx)")];
char *pos = rd;
/* ok lets load the RD format */
switch (EXTRACT_16BITS(pptr)) {
/* 2-byte-AS:number fmt*/
case 0:
snprintf(pos, sizeof(rd) - (pos - rd), "%u:%u (= %u.%u.%u.%u)",
EXTRACT_16BITS(pptr+2),
EXTRACT_32BITS(pptr+4),
*(pptr+4), *(pptr+5), *(pptr+6), *(pptr+7));
break;
/* IP-address:AS fmt*/
case 1:
snprintf(pos, sizeof(rd) - (pos - rd), "%u.%u.%u.%u:%u",
*(pptr+2), *(pptr+3), *(pptr+4), *(pptr+5), EXTRACT_16BITS(pptr+6));
break;
/* 4-byte-AS:number fmt*/
case 2:
snprintf(pos, sizeof(rd) - (pos - rd), "%s:%u (%u.%u.%u.%u:%u)",
as_printf(ndo, astostr, sizeof(astostr), EXTRACT_32BITS(pptr+2)),
EXTRACT_16BITS(pptr+6), *(pptr+2), *(pptr+3), *(pptr+4),
*(pptr+5), EXTRACT_16BITS(pptr+6));
break;
default:
snprintf(pos, sizeof(rd) - (pos - rd), "unknown RD format");
break;
}
pos += strlen(pos);
*(pos) = '\0';
return (rd);
}
static int
decode_rt_routing_info(netdissect_options *ndo,
const u_char *pptr, char *buf, u_int buflen)
{
uint8_t route_target[8];
u_int plen;
char asbuf[sizeof(astostr)]; /* bgp_vpn_rd_print() overwrites astostr */
/* NLRI "prefix length" from RFC 2858 Section 4. */
ND_TCHECK(pptr[0]);
plen = pptr[0]; /* get prefix length */
/* NLRI "prefix" (ibid), valid lengths are { 0, 32, 33, ..., 96 } bits.
* RFC 4684 Section 4 defines the layout of "origin AS" and "route
* target" fields inside the "prefix" depending on its length.
*/
if (0 == plen) {
/* Without "origin AS", without "route target". */
snprintf(buf, buflen, "default route target");
return 1;
}
if (32 > plen)
return -1;
/* With at least "origin AS", possibly with "route target". */
ND_TCHECK_32BITS(pptr + 1);
as_printf(ndo, asbuf, sizeof(asbuf), EXTRACT_32BITS(pptr + 1));
plen-=32; /* adjust prefix length */
if (64 < plen)
return -1;
/* From now on (plen + 7) / 8 evaluates to { 0, 1, 2, ..., 8 }
* and gives the number of octets in the variable-length "route
* target" field inside this NLRI "prefix". Look for it.
*/
memset(&route_target, 0, sizeof(route_target));
ND_TCHECK2(pptr[5], (plen + 7) / 8);
memcpy(&route_target, &pptr[5], (plen + 7) / 8);
/* Which specification says to do this? */
if (plen % 8) {
((u_char *)&route_target)[(plen + 7) / 8 - 1] &=
((0xff00 >> (plen % 8)) & 0xff);
}
snprintf(buf, buflen, "origin AS: %s, route target %s",
asbuf,
bgp_vpn_rd_print(ndo, (u_char *)&route_target));
return 5 + (plen + 7) / 8;
trunc:
return -2;
}
static int
decode_labeled_vpn_prefix4(netdissect_options *ndo,
const u_char *pptr, char *buf, u_int buflen)
{
struct in_addr addr;
u_int plen;
ND_TCHECK(pptr[0]);
plen = pptr[0]; /* get prefix length */
if ((24+64) > plen)
return -1;
plen-=(24+64); /* adjust prefixlen - labellength - RD len*/
if (32 < plen)
return -1;
memset(&addr, 0, sizeof(addr));
ND_TCHECK2(pptr[12], (plen + 7) / 8);
memcpy(&addr, &pptr[12], (plen + 7) / 8);
if (plen % 8) {
((u_char *)&addr)[(plen + 7) / 8 - 1] &=
((0xff00 >> (plen % 8)) & 0xff);
}
/* the label may get offsetted by 4 bits so lets shift it right */
snprintf(buf, buflen, "RD: %s, %s/%d, label:%u %s",
bgp_vpn_rd_print(ndo, pptr+4),
ipaddr_string(ndo, &addr),
plen,
EXTRACT_24BITS(pptr+1)>>4,
((pptr[3]&1)==0) ? "(BOGUS: Bottom of Stack NOT set!)" : "(bottom)" );
return 12 + (plen + 7) / 8;
trunc:
return -2;
}
/*
* +-------------------------------+
* | |
* | RD:IPv4-address (12 octets) |
* | |
* +-------------------------------+
* | MDT Group-address (4 octets) |
* +-------------------------------+
*/
#define MDT_VPN_NLRI_LEN 16
static int
decode_mdt_vpn_nlri(netdissect_options *ndo,
const u_char *pptr, char *buf, u_int buflen)
{
const u_char *rd;
const u_char *vpn_ip;
ND_TCHECK(pptr[0]);
/* if the NLRI is not predefined length, quit.*/
if (*pptr != MDT_VPN_NLRI_LEN * 8)
return -1;
pptr++;
/* RD */
ND_TCHECK2(pptr[0], 8);
rd = pptr;
pptr+=8;
/* IPv4 address */
ND_TCHECK2(pptr[0], sizeof(struct in_addr));
vpn_ip = pptr;
pptr+=sizeof(struct in_addr);
/* MDT Group Address */
ND_TCHECK2(pptr[0], sizeof(struct in_addr));
snprintf(buf, buflen, "RD: %s, VPN IP Address: %s, MC Group Address: %s",
bgp_vpn_rd_print(ndo, rd), ipaddr_string(ndo, vpn_ip), ipaddr_string(ndo, pptr));
return MDT_VPN_NLRI_LEN + 1;
trunc:
return -2;
}
#define BGP_MULTICAST_VPN_ROUTE_TYPE_INTRA_AS_I_PMSI 1
#define BGP_MULTICAST_VPN_ROUTE_TYPE_INTER_AS_I_PMSI 2
#define BGP_MULTICAST_VPN_ROUTE_TYPE_S_PMSI 3
#define BGP_MULTICAST_VPN_ROUTE_TYPE_INTRA_AS_SEG_LEAF 4
#define BGP_MULTICAST_VPN_ROUTE_TYPE_SOURCE_ACTIVE 5
#define BGP_MULTICAST_VPN_ROUTE_TYPE_SHARED_TREE_JOIN 6
#define BGP_MULTICAST_VPN_ROUTE_TYPE_SOURCE_TREE_JOIN 7
static const struct tok bgp_multicast_vpn_route_type_values[] = {
{ BGP_MULTICAST_VPN_ROUTE_TYPE_INTRA_AS_I_PMSI, "Intra-AS I-PMSI"},
{ BGP_MULTICAST_VPN_ROUTE_TYPE_INTER_AS_I_PMSI, "Inter-AS I-PMSI"},
{ BGP_MULTICAST_VPN_ROUTE_TYPE_S_PMSI, "S-PMSI"},
{ BGP_MULTICAST_VPN_ROUTE_TYPE_INTRA_AS_SEG_LEAF, "Intra-AS Segment-Leaf"},
{ BGP_MULTICAST_VPN_ROUTE_TYPE_SOURCE_ACTIVE, "Source-Active"},
{ BGP_MULTICAST_VPN_ROUTE_TYPE_SHARED_TREE_JOIN, "Shared Tree Join"},
{ BGP_MULTICAST_VPN_ROUTE_TYPE_SOURCE_TREE_JOIN, "Source Tree Join"},
{ 0, NULL}
};
static int
decode_multicast_vpn(netdissect_options *ndo,
const u_char *pptr, char *buf, u_int buflen)
{
uint8_t route_type, route_length, addr_length, sg_length;
u_int offset;
ND_TCHECK2(pptr[0], 2);
route_type = *pptr++;
route_length = *pptr++;
snprintf(buf, buflen, "Route-Type: %s (%u), length: %u",
tok2str(bgp_multicast_vpn_route_type_values,
"Unknown", route_type),
route_type, route_length);
switch(route_type) {
case BGP_MULTICAST_VPN_ROUTE_TYPE_INTRA_AS_I_PMSI:
ND_TCHECK2(pptr[0], BGP_VPN_RD_LEN);
offset = strlen(buf);
snprintf(buf + offset, buflen - offset, ", RD: %s, Originator %s",
bgp_vpn_rd_print(ndo, pptr),
bgp_vpn_ip_print(ndo, pptr + BGP_VPN_RD_LEN,
(route_length - BGP_VPN_RD_LEN) << 3));
break;
case BGP_MULTICAST_VPN_ROUTE_TYPE_INTER_AS_I_PMSI:
ND_TCHECK2(pptr[0], BGP_VPN_RD_LEN + 4);
offset = strlen(buf);
snprintf(buf + offset, buflen - offset, ", RD: %s, Source-AS %s",
bgp_vpn_rd_print(ndo, pptr),
as_printf(ndo, astostr, sizeof(astostr),
EXTRACT_32BITS(pptr + BGP_VPN_RD_LEN)));
break;
case BGP_MULTICAST_VPN_ROUTE_TYPE_S_PMSI:
ND_TCHECK2(pptr[0], BGP_VPN_RD_LEN);
offset = strlen(buf);
snprintf(buf + offset, buflen - offset, ", RD: %s",
bgp_vpn_rd_print(ndo, pptr));
pptr += BGP_VPN_RD_LEN;
sg_length = bgp_vpn_sg_print(ndo, pptr, buf, buflen);
addr_length = route_length - sg_length;
ND_TCHECK2(pptr[0], addr_length);
offset = strlen(buf);
snprintf(buf + offset, buflen - offset, ", Originator %s",
bgp_vpn_ip_print(ndo, pptr, addr_length << 3));
break;
case BGP_MULTICAST_VPN_ROUTE_TYPE_SOURCE_ACTIVE:
ND_TCHECK2(pptr[0], BGP_VPN_RD_LEN);
offset = strlen(buf);
snprintf(buf + offset, buflen - offset, ", RD: %s",
bgp_vpn_rd_print(ndo, pptr));
pptr += BGP_VPN_RD_LEN;
bgp_vpn_sg_print(ndo, pptr, buf, buflen);
break;
case BGP_MULTICAST_VPN_ROUTE_TYPE_SHARED_TREE_JOIN: /* fall through */
case BGP_MULTICAST_VPN_ROUTE_TYPE_SOURCE_TREE_JOIN:
ND_TCHECK2(pptr[0], BGP_VPN_RD_LEN + 4);
offset = strlen(buf);
snprintf(buf + offset, buflen - offset, ", RD: %s, Source-AS %s",
bgp_vpn_rd_print(ndo, pptr),
as_printf(ndo, astostr, sizeof(astostr),
EXTRACT_32BITS(pptr + BGP_VPN_RD_LEN)));
pptr += BGP_VPN_RD_LEN + 4;
bgp_vpn_sg_print(ndo, pptr, buf, buflen);
break;
/*
* no per route-type printing yet.
*/
case BGP_MULTICAST_VPN_ROUTE_TYPE_INTRA_AS_SEG_LEAF:
default:
break;
}
return route_length + 2;
trunc:
return -2;
}
/*
* As I remember, some versions of systems have an snprintf() that
* returns -1 if the buffer would have overflowed. If the return
* value is negative, set buflen to 0, to indicate that we've filled
* the buffer up.
*
* If the return value is greater than buflen, that means that
* the buffer would have overflowed; again, set buflen to 0 in
* that case.
*/
#define UPDATE_BUF_BUFLEN(buf, buflen, stringlen) \
if (stringlen<0) \
buflen=0; \
else if ((u_int)stringlen>buflen) \
buflen=0; \
else { \
buflen-=stringlen; \
buf+=stringlen; \
}
static int
decode_labeled_vpn_l2(netdissect_options *ndo,
const u_char *pptr, char *buf, u_int buflen)
{
int plen,tlen,stringlen,tlv_type,tlv_len,ttlv_len;
ND_TCHECK2(pptr[0], 2);
plen=EXTRACT_16BITS(pptr);
tlen=plen;
pptr+=2;
/* Old and new L2VPN NLRI share AFI/SAFI
* -> Assume a 12 Byte-length NLRI is auto-discovery-only
* and > 17 as old format. Complain for the middle case
*/
if (plen==12) {
/* assume AD-only with RD, BGPNH */
ND_TCHECK2(pptr[0],12);
buf[0]='\0';
stringlen=snprintf(buf, buflen, "RD: %s, BGPNH: %s",
bgp_vpn_rd_print(ndo, pptr),
ipaddr_string(ndo, pptr+8)
);
UPDATE_BUF_BUFLEN(buf, buflen, stringlen);
pptr+=12;
tlen-=12;
return plen;
} else if (plen>17) {
/* assume old format */
/* RD, ID, LBLKOFF, LBLBASE */
ND_TCHECK2(pptr[0],15);
buf[0]='\0';
stringlen=snprintf(buf, buflen, "RD: %s, CE-ID: %u, Label-Block Offset: %u, Label Base %u",
bgp_vpn_rd_print(ndo, pptr),
EXTRACT_16BITS(pptr+8),
EXTRACT_16BITS(pptr+10),
EXTRACT_24BITS(pptr+12)>>4); /* the label is offsetted by 4 bits so lets shift it right */
UPDATE_BUF_BUFLEN(buf, buflen, stringlen);
pptr+=15;
tlen-=15;
/* ok now the variable part - lets read out TLVs*/
while (tlen>0) {
if (tlen < 3)
return -1;
ND_TCHECK2(pptr[0], 3);
tlv_type=*pptr++;
tlv_len=EXTRACT_16BITS(pptr);
ttlv_len=tlv_len;
pptr+=2;
switch(tlv_type) {
case 1:
if (buflen!=0) {
stringlen=snprintf(buf,buflen, "\n\t\tcircuit status vector (%u) length: %u: 0x",
tlv_type,
tlv_len);
UPDATE_BUF_BUFLEN(buf, buflen, stringlen);
}
ttlv_len=ttlv_len/8+1; /* how many bytes do we need to read ? */
while (ttlv_len>0) {
ND_TCHECK(pptr[0]);
if (buflen!=0) {
stringlen=snprintf(buf,buflen, "%02x",*pptr++);
UPDATE_BUF_BUFLEN(buf, buflen, stringlen);
}
ttlv_len--;
}
break;
default:
if (buflen!=0) {
stringlen=snprintf(buf,buflen, "\n\t\tunknown TLV #%u, length: %u",
tlv_type,
tlv_len);
UPDATE_BUF_BUFLEN(buf, buflen, stringlen);
}
break;
}
tlen-=(tlv_len<<3); /* the tlv-length is expressed in bits so lets shift it right */
}
return plen+2;
} else {
/* complain bitterly ? */
/* fall through */
goto trunc;
}
trunc:
return -2;
}
int
decode_prefix6(netdissect_options *ndo,
const u_char *pd, u_int itemlen, char *buf, u_int buflen)
{
struct in6_addr addr;
u_int plen, plenbytes;
ND_TCHECK(pd[0]);
ITEMCHECK(1);
plen = pd[0];
if (128 < plen)
return -1;
itemlen -= 1;
memset(&addr, 0, sizeof(addr));
plenbytes = (plen + 7) / 8;
ND_TCHECK2(pd[1], plenbytes);
ITEMCHECK(plenbytes);
memcpy(&addr, &pd[1], plenbytes);
if (plen % 8) {
addr.s6_addr[plenbytes - 1] &=
((0xff00 >> (plen % 8)) & 0xff);
}
snprintf(buf, buflen, "%s/%d", ip6addr_string(ndo, &addr), plen);
return 1 + plenbytes;
trunc:
return -2;
badtlv:
return -3;
}
static int
decode_labeled_prefix6(netdissect_options *ndo,
const u_char *pptr, u_int itemlen, char *buf, u_int buflen)
{
struct in6_addr addr;
u_int plen, plenbytes;
/* prefix length and label = 4 bytes */
ND_TCHECK2(pptr[0], 4);
ITEMCHECK(4);
plen = pptr[0]; /* get prefix length */
if (24 > plen)
return -1;
plen-=24; /* adjust prefixlen - labellength */
if (128 < plen)
return -1;
itemlen -= 4;
memset(&addr, 0, sizeof(addr));
plenbytes = (plen + 7) / 8;
ND_TCHECK2(pptr[4], plenbytes);
memcpy(&addr, &pptr[4], plenbytes);
if (plen % 8) {
addr.s6_addr[plenbytes - 1] &=
((0xff00 >> (plen % 8)) & 0xff);
}
/* the label may get offsetted by 4 bits so lets shift it right */
snprintf(buf, buflen, "%s/%d, label:%u %s",
ip6addr_string(ndo, &addr),
plen,
EXTRACT_24BITS(pptr+1)>>4,
((pptr[3]&1)==0) ? "(BOGUS: Bottom of Stack NOT set!)" : "(bottom)" );
return 4 + plenbytes;
trunc:
return -2;
badtlv:
return -3;
}
static int
decode_labeled_vpn_prefix6(netdissect_options *ndo,
const u_char *pptr, char *buf, u_int buflen)
{
struct in6_addr addr;
u_int plen;
ND_TCHECK(pptr[0]);
plen = pptr[0]; /* get prefix length */
if ((24+64) > plen)
return -1;
plen-=(24+64); /* adjust prefixlen - labellength - RD len*/
if (128 < plen)
return -1;
memset(&addr, 0, sizeof(addr));
ND_TCHECK2(pptr[12], (plen + 7) / 8);
memcpy(&addr, &pptr[12], (plen + 7) / 8);
if (plen % 8) {
addr.s6_addr[(plen + 7) / 8 - 1] &=
((0xff00 >> (plen % 8)) & 0xff);
}
/* the label may get offsetted by 4 bits so lets shift it right */
snprintf(buf, buflen, "RD: %s, %s/%d, label:%u %s",
bgp_vpn_rd_print(ndo, pptr+4),
ip6addr_string(ndo, &addr),
plen,
EXTRACT_24BITS(pptr+1)>>4,
((pptr[3]&1)==0) ? "(BOGUS: Bottom of Stack NOT set!)" : "(bottom)" );
return 12 + (plen + 7) / 8;
trunc:
return -2;
}
static int
decode_clnp_prefix(netdissect_options *ndo,
const u_char *pptr, char *buf, u_int buflen)
{
uint8_t addr[19];
u_int plen;
ND_TCHECK(pptr[0]);
plen = pptr[0]; /* get prefix length */
if (152 < plen)
return -1;
memset(&addr, 0, sizeof(addr));
ND_TCHECK2(pptr[4], (plen + 7) / 8);
memcpy(&addr, &pptr[4], (plen + 7) / 8);
if (plen % 8) {
addr[(plen + 7) / 8 - 1] &=
((0xff00 >> (plen % 8)) & 0xff);
}
snprintf(buf, buflen, "%s/%d",
isonsap_string(ndo, addr,(plen + 7) / 8),
plen);
return 1 + (plen + 7) / 8;
trunc:
return -2;
}
static int
decode_labeled_vpn_clnp_prefix(netdissect_options *ndo,
const u_char *pptr, char *buf, u_int buflen)
{
uint8_t addr[19];
u_int plen;
ND_TCHECK(pptr[0]);
plen = pptr[0]; /* get prefix length */
if ((24+64) > plen)
return -1;
plen-=(24+64); /* adjust prefixlen - labellength - RD len*/
if (152 < plen)
return -1;
memset(&addr, 0, sizeof(addr));
ND_TCHECK2(pptr[12], (plen + 7) / 8);
memcpy(&addr, &pptr[12], (plen + 7) / 8);
if (plen % 8) {
addr[(plen + 7) / 8 - 1] &=
((0xff00 >> (plen % 8)) & 0xff);
}
/* the label may get offsetted by 4 bits so lets shift it right */
snprintf(buf, buflen, "RD: %s, %s/%d, label:%u %s",
bgp_vpn_rd_print(ndo, pptr+4),
isonsap_string(ndo, addr,(plen + 7) / 8),
plen,
EXTRACT_24BITS(pptr+1)>>4,
((pptr[3]&1)==0) ? "(BOGUS: Bottom of Stack NOT set!)" : "(bottom)" );
return 12 + (plen + 7) / 8;
trunc:
return -2;
}
/*
* bgp_attr_get_as_size
*
* Try to find the size of the ASs encoded in an as-path. It is not obvious, as
* both Old speakers that do not support 4 byte AS, and the new speakers that do
* support, exchange AS-Path with the same path-attribute type value 0x02.
*/
static int
bgp_attr_get_as_size(netdissect_options *ndo,
uint8_t bgpa_type, const u_char *pptr, int len)
{
const u_char *tptr = pptr;
/*
* If the path attribute is the optional AS4 path type, then we already
* know, that ASs must be encoded in 4 byte format.
*/
if (bgpa_type == BGPTYPE_AS4_PATH) {
return 4;
}
/*
* Let us assume that ASs are of 2 bytes in size, and check if the AS-Path
* TLV is good. If not, ask the caller to try with AS encoded as 4 bytes
* each.
*/
while (tptr < pptr + len) {
ND_TCHECK(tptr[0]);
/*
* If we do not find a valid segment type, our guess might be wrong.
*/
if (tptr[0] < BGP_AS_SEG_TYPE_MIN || tptr[0] > BGP_AS_SEG_TYPE_MAX) {
goto trunc;
}
ND_TCHECK(tptr[1]);
tptr += 2 + tptr[1] * 2;
}
/*
* If we correctly reached end of the AS path attribute data content,
* then most likely ASs were indeed encoded as 2 bytes.
*/
if (tptr == pptr + len) {
return 2;
}
trunc:
/*
* We can come here, either we did not have enough data, or if we
* try to decode 4 byte ASs in 2 byte format. Either way, return 4,
* so that calller can try to decode each AS as of 4 bytes. If indeed
* there was not enough data, it will crib and end the parse anyways.
*/
return 4;
}
static int
bgp_attr_print(netdissect_options *ndo,
u_int atype, const u_char *pptr, u_int len)
{
int i;
uint16_t af;
uint8_t safi, snpa, nhlen;
union { /* copy buffer for bandwidth values */
float f;
uint32_t i;
} bw;
int advance;
u_int tlen;
const u_char *tptr;
char buf[MAXHOSTNAMELEN + 100];
int as_size;
tptr = pptr;
tlen=len;
switch (atype) {
case BGPTYPE_ORIGIN:
if (len != 1)
ND_PRINT((ndo, "invalid len"));
else {
ND_TCHECK(*tptr);
ND_PRINT((ndo, "%s", tok2str(bgp_origin_values,
"Unknown Origin Typecode",
tptr[0])));
}
break;
/*
* Process AS4 byte path and AS2 byte path attributes here.
*/
case BGPTYPE_AS4_PATH:
case BGPTYPE_AS_PATH:
if (len % 2) {
ND_PRINT((ndo, "invalid len"));
break;
}
if (!len) {
ND_PRINT((ndo, "empty"));
break;
}
/*
* BGP updates exchanged between New speakers that support 4
* byte AS, ASs are always encoded in 4 bytes. There is no
* definitive way to find this, just by the packet's
* contents. So, check for packet's TLV's sanity assuming
* 2 bytes first, and it does not pass, assume that ASs are
* encoded in 4 bytes format and move on.
*/
as_size = bgp_attr_get_as_size(ndo, atype, pptr, len);
while (tptr < pptr + len) {
ND_TCHECK(tptr[0]);
ND_PRINT((ndo, "%s", tok2str(bgp_as_path_segment_open_values,
"?", tptr[0])));
ND_TCHECK(tptr[1]);
for (i = 0; i < tptr[1] * as_size; i += as_size) {
ND_TCHECK2(tptr[2 + i], as_size);
ND_PRINT((ndo, "%s ",
as_printf(ndo, astostr, sizeof(astostr),
as_size == 2 ?
EXTRACT_16BITS(&tptr[2 + i]) :
EXTRACT_32BITS(&tptr[2 + i]))));
}
ND_TCHECK(tptr[0]);
ND_PRINT((ndo, "%s", tok2str(bgp_as_path_segment_close_values,
"?", tptr[0])));
ND_TCHECK(tptr[1]);
tptr += 2 + tptr[1] * as_size;
}
break;
case BGPTYPE_NEXT_HOP:
if (len != 4)
ND_PRINT((ndo, "invalid len"));
else {
ND_TCHECK2(tptr[0], 4);
ND_PRINT((ndo, "%s", ipaddr_string(ndo, tptr)));
}
break;
case BGPTYPE_MULTI_EXIT_DISC:
case BGPTYPE_LOCAL_PREF:
if (len != 4)
ND_PRINT((ndo, "invalid len"));
else {
ND_TCHECK2(tptr[0], 4);
ND_PRINT((ndo, "%u", EXTRACT_32BITS(tptr)));
}
break;
case BGPTYPE_ATOMIC_AGGREGATE:
if (len != 0)
ND_PRINT((ndo, "invalid len"));
break;
case BGPTYPE_AGGREGATOR:
/*
* Depending on the AS encoded is of 2 bytes or of 4 bytes,
* the length of this PA can be either 6 bytes or 8 bytes.
*/
if (len != 6 && len != 8) {
ND_PRINT((ndo, "invalid len"));
break;
}
ND_TCHECK2(tptr[0], len);
if (len == 6) {
ND_PRINT((ndo, " AS #%s, origin %s",
as_printf(ndo, astostr, sizeof(astostr), EXTRACT_16BITS(tptr)),
ipaddr_string(ndo, tptr + 2)));
} else {
ND_PRINT((ndo, " AS #%s, origin %s",
as_printf(ndo, astostr, sizeof(astostr),
EXTRACT_32BITS(tptr)), ipaddr_string(ndo, tptr + 4)));
}
break;
case BGPTYPE_AGGREGATOR4:
if (len != 8) {
ND_PRINT((ndo, "invalid len"));
break;
}
ND_TCHECK2(tptr[0], 8);
ND_PRINT((ndo, " AS #%s, origin %s",
as_printf(ndo, astostr, sizeof(astostr), EXTRACT_32BITS(tptr)),
ipaddr_string(ndo, tptr + 4)));
break;
case BGPTYPE_COMMUNITIES:
if (len % 4) {
ND_PRINT((ndo, "invalid len"));
break;
}
while (tlen>0) {
uint32_t comm;
ND_TCHECK2(tptr[0], 4);
comm = EXTRACT_32BITS(tptr);
switch (comm) {
case BGP_COMMUNITY_NO_EXPORT:
ND_PRINT((ndo, " NO_EXPORT"));
break;
case BGP_COMMUNITY_NO_ADVERT:
ND_PRINT((ndo, " NO_ADVERTISE"));
break;
case BGP_COMMUNITY_NO_EXPORT_SUBCONFED:
ND_PRINT((ndo, " NO_EXPORT_SUBCONFED"));
break;
default:
ND_PRINT((ndo, "%u:%u%s",
(comm >> 16) & 0xffff,
comm & 0xffff,
(tlen>4) ? ", " : ""));
break;
}
tlen -=4;
tptr +=4;
}
break;
case BGPTYPE_ORIGINATOR_ID:
if (len != 4) {
ND_PRINT((ndo, "invalid len"));
break;
}
ND_TCHECK2(tptr[0], 4);
ND_PRINT((ndo, "%s",ipaddr_string(ndo, tptr)));
break;
case BGPTYPE_CLUSTER_LIST:
if (len % 4) {
ND_PRINT((ndo, "invalid len"));
break;
}
while (tlen>0) {
ND_TCHECK2(tptr[0], 4);
ND_PRINT((ndo, "%s%s",
ipaddr_string(ndo, tptr),
(tlen>4) ? ", " : ""));
tlen -=4;
tptr +=4;
}
break;
case BGPTYPE_MP_REACH_NLRI:
ND_TCHECK2(tptr[0], 3);
af = EXTRACT_16BITS(tptr);
safi = tptr[2];
ND_PRINT((ndo, "\n\t AFI: %s (%u), %sSAFI: %s (%u)",
tok2str(af_values, "Unknown AFI", af),
af,
(safi>128) ? "vendor specific " : "", /* 128 is meanwhile wellknown */
tok2str(bgp_safi_values, "Unknown SAFI", safi),
safi));
switch(af<<8 | safi) {
case (AFNUM_INET<<8 | SAFNUM_UNICAST):
case (AFNUM_INET<<8 | SAFNUM_MULTICAST):
case (AFNUM_INET<<8 | SAFNUM_UNIMULTICAST):
case (AFNUM_INET<<8 | SAFNUM_LABUNICAST):
case (AFNUM_INET<<8 | SAFNUM_RT_ROUTING_INFO):
case (AFNUM_INET<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_INET<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_INET<<8 | SAFNUM_VPNUNIMULTICAST):
case (AFNUM_INET<<8 | SAFNUM_MULTICAST_VPN):
case (AFNUM_INET<<8 | SAFNUM_MDT):
case (AFNUM_INET6<<8 | SAFNUM_UNICAST):
case (AFNUM_INET6<<8 | SAFNUM_MULTICAST):
case (AFNUM_INET6<<8 | SAFNUM_UNIMULTICAST):
case (AFNUM_INET6<<8 | SAFNUM_LABUNICAST):
case (AFNUM_INET6<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_INET6<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_INET6<<8 | SAFNUM_VPNUNIMULTICAST):
case (AFNUM_NSAP<<8 | SAFNUM_UNICAST):
case (AFNUM_NSAP<<8 | SAFNUM_MULTICAST):
case (AFNUM_NSAP<<8 | SAFNUM_UNIMULTICAST):
case (AFNUM_NSAP<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_NSAP<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_NSAP<<8 | SAFNUM_VPNUNIMULTICAST):
case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_L2VPN<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNIMULTICAST):
case (AFNUM_VPLS<<8 | SAFNUM_VPLS):
break;
default:
ND_TCHECK2(tptr[0], tlen);
ND_PRINT((ndo, "\n\t no AFI %u / SAFI %u decoder", af, safi));
if (ndo->ndo_vflag <= 1)
print_unknown_data(ndo, tptr, "\n\t ", tlen);
goto done;
break;
}
tptr +=3;
ND_TCHECK(tptr[0]);
nhlen = tptr[0];
tlen = nhlen;
tptr++;
if (tlen) {
int nnh = 0;
ND_PRINT((ndo, "\n\t nexthop: "));
while (tlen > 0) {
if ( nnh++ > 0 ) {
ND_PRINT((ndo, ", " ));
}
switch(af<<8 | safi) {
case (AFNUM_INET<<8 | SAFNUM_UNICAST):
case (AFNUM_INET<<8 | SAFNUM_MULTICAST):
case (AFNUM_INET<<8 | SAFNUM_UNIMULTICAST):
case (AFNUM_INET<<8 | SAFNUM_LABUNICAST):
case (AFNUM_INET<<8 | SAFNUM_RT_ROUTING_INFO):
case (AFNUM_INET<<8 | SAFNUM_MULTICAST_VPN):
case (AFNUM_INET<<8 | SAFNUM_MDT):
if (tlen < (int)sizeof(struct in_addr)) {
ND_PRINT((ndo, "invalid len"));
tlen = 0;
} else {
ND_TCHECK2(tptr[0], sizeof(struct in_addr));
ND_PRINT((ndo, "%s",ipaddr_string(ndo, tptr)));
tlen -= sizeof(struct in_addr);
tptr += sizeof(struct in_addr);
}
break;
case (AFNUM_INET<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_INET<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_INET<<8 | SAFNUM_VPNUNIMULTICAST):
if (tlen < (int)(sizeof(struct in_addr)+BGP_VPN_RD_LEN)) {
ND_PRINT((ndo, "invalid len"));
tlen = 0;
} else {
ND_TCHECK2(tptr[0], sizeof(struct in_addr)+BGP_VPN_RD_LEN);
ND_PRINT((ndo, "RD: %s, %s",
bgp_vpn_rd_print(ndo, tptr),
ipaddr_string(ndo, tptr+BGP_VPN_RD_LEN)));
tlen -= (sizeof(struct in_addr)+BGP_VPN_RD_LEN);
tptr += (sizeof(struct in_addr)+BGP_VPN_RD_LEN);
}
break;
case (AFNUM_INET6<<8 | SAFNUM_UNICAST):
case (AFNUM_INET6<<8 | SAFNUM_MULTICAST):
case (AFNUM_INET6<<8 | SAFNUM_UNIMULTICAST):
case (AFNUM_INET6<<8 | SAFNUM_LABUNICAST):
if (tlen < (int)sizeof(struct in6_addr)) {
ND_PRINT((ndo, "invalid len"));
tlen = 0;
} else {
ND_TCHECK2(tptr[0], sizeof(struct in6_addr));
ND_PRINT((ndo, "%s", ip6addr_string(ndo, tptr)));
tlen -= sizeof(struct in6_addr);
tptr += sizeof(struct in6_addr);
}
break;
case (AFNUM_INET6<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_INET6<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_INET6<<8 | SAFNUM_VPNUNIMULTICAST):
if (tlen < (int)(sizeof(struct in6_addr)+BGP_VPN_RD_LEN)) {
ND_PRINT((ndo, "invalid len"));
tlen = 0;
} else {
ND_TCHECK2(tptr[0], sizeof(struct in6_addr)+BGP_VPN_RD_LEN);
ND_PRINT((ndo, "RD: %s, %s",
bgp_vpn_rd_print(ndo, tptr),
ip6addr_string(ndo, tptr+BGP_VPN_RD_LEN)));
tlen -= (sizeof(struct in6_addr)+BGP_VPN_RD_LEN);
tptr += (sizeof(struct in6_addr)+BGP_VPN_RD_LEN);
}
break;
case (AFNUM_VPLS<<8 | SAFNUM_VPLS):
case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_L2VPN<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNIMULTICAST):
if (tlen < (int)sizeof(struct in_addr)) {
ND_PRINT((ndo, "invalid len"));
tlen = 0;
} else {
ND_TCHECK2(tptr[0], sizeof(struct in_addr));
ND_PRINT((ndo, "%s", ipaddr_string(ndo, tptr)));
tlen -= (sizeof(struct in_addr));
tptr += (sizeof(struct in_addr));
}
break;
case (AFNUM_NSAP<<8 | SAFNUM_UNICAST):
case (AFNUM_NSAP<<8 | SAFNUM_MULTICAST):
case (AFNUM_NSAP<<8 | SAFNUM_UNIMULTICAST):
ND_TCHECK2(tptr[0], tlen);
ND_PRINT((ndo, "%s", isonsap_string(ndo, tptr, tlen)));
tptr += tlen;
tlen = 0;
break;
case (AFNUM_NSAP<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_NSAP<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_NSAP<<8 | SAFNUM_VPNUNIMULTICAST):
if (tlen < BGP_VPN_RD_LEN+1) {
ND_PRINT((ndo, "invalid len"));
tlen = 0;
} else {
ND_TCHECK2(tptr[0], tlen);
ND_PRINT((ndo, "RD: %s, %s",
bgp_vpn_rd_print(ndo, tptr),
isonsap_string(ndo, tptr+BGP_VPN_RD_LEN,tlen-BGP_VPN_RD_LEN)));
/* rfc986 mapped IPv4 address ? */
if (EXTRACT_32BITS(tptr+BGP_VPN_RD_LEN) == 0x47000601)
ND_PRINT((ndo, " = %s", ipaddr_string(ndo, tptr+BGP_VPN_RD_LEN+4)));
/* rfc1888 mapped IPv6 address ? */
else if (EXTRACT_24BITS(tptr+BGP_VPN_RD_LEN) == 0x350000)
ND_PRINT((ndo, " = %s", ip6addr_string(ndo, tptr+BGP_VPN_RD_LEN+3)));
tptr += tlen;
tlen = 0;
}
break;
default:
ND_TCHECK2(tptr[0], tlen);
ND_PRINT((ndo, "no AFI %u/SAFI %u decoder", af, safi));
if (ndo->ndo_vflag <= 1)
print_unknown_data(ndo, tptr, "\n\t ", tlen);
tptr += tlen;
tlen = 0;
goto done;
break;
}
}
}
ND_PRINT((ndo, ", nh-length: %u", nhlen));
tptr += tlen;
ND_TCHECK(tptr[0]);
snpa = tptr[0];
tptr++;
if (snpa) {
ND_PRINT((ndo, "\n\t %u SNPA", snpa));
for (/*nothing*/; snpa > 0; snpa--) {
ND_TCHECK(tptr[0]);
ND_PRINT((ndo, "\n\t %d bytes", tptr[0]));
tptr += tptr[0] + 1;
}
} else {
ND_PRINT((ndo, ", no SNPA"));
}
while (tptr < pptr + len) {
switch (af<<8 | safi) {
case (AFNUM_INET<<8 | SAFNUM_UNICAST):
case (AFNUM_INET<<8 | SAFNUM_MULTICAST):
case (AFNUM_INET<<8 | SAFNUM_UNIMULTICAST):
advance = decode_prefix4(ndo, tptr, len, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else if (advance == -3)
break; /* bytes left, but not enough */
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET<<8 | SAFNUM_LABUNICAST):
advance = decode_labeled_prefix4(ndo, tptr, len, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else if (advance == -3)
break; /* bytes left, but not enough */
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_INET<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_INET<<8 | SAFNUM_VPNUNIMULTICAST):
advance = decode_labeled_vpn_prefix4(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET<<8 | SAFNUM_RT_ROUTING_INFO):
advance = decode_rt_routing_info(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET<<8 | SAFNUM_MULTICAST_VPN): /* fall through */
case (AFNUM_INET6<<8 | SAFNUM_MULTICAST_VPN):
advance = decode_multicast_vpn(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET<<8 | SAFNUM_MDT):
advance = decode_mdt_vpn_nlri(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET6<<8 | SAFNUM_UNICAST):
case (AFNUM_INET6<<8 | SAFNUM_MULTICAST):
case (AFNUM_INET6<<8 | SAFNUM_UNIMULTICAST):
advance = decode_prefix6(ndo, tptr, len, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else if (advance == -3)
break; /* bytes left, but not enough */
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET6<<8 | SAFNUM_LABUNICAST):
advance = decode_labeled_prefix6(ndo, tptr, len, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else if (advance == -3)
break; /* bytes left, but not enough */
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET6<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_INET6<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_INET6<<8 | SAFNUM_VPNUNIMULTICAST):
advance = decode_labeled_vpn_prefix6(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_VPLS<<8 | SAFNUM_VPLS):
case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_L2VPN<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNIMULTICAST):
advance = decode_labeled_vpn_l2(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_NSAP<<8 | SAFNUM_UNICAST):
case (AFNUM_NSAP<<8 | SAFNUM_MULTICAST):
case (AFNUM_NSAP<<8 | SAFNUM_UNIMULTICAST):
advance = decode_clnp_prefix(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_NSAP<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_NSAP<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_NSAP<<8 | SAFNUM_VPNUNIMULTICAST):
advance = decode_labeled_vpn_clnp_prefix(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
default:
ND_TCHECK2(*tptr,tlen);
ND_PRINT((ndo, "\n\t no AFI %u / SAFI %u decoder", af, safi));
if (ndo->ndo_vflag <= 1)
print_unknown_data(ndo, tptr, "\n\t ", tlen);
advance = 0;
tptr = pptr + len;
break;
}
if (advance < 0)
break;
tptr += advance;
}
done:
break;
case BGPTYPE_MP_UNREACH_NLRI:
ND_TCHECK2(tptr[0], BGP_MP_NLRI_MINSIZE);
af = EXTRACT_16BITS(tptr);
safi = tptr[2];
ND_PRINT((ndo, "\n\t AFI: %s (%u), %sSAFI: %s (%u)",
tok2str(af_values, "Unknown AFI", af),
af,
(safi>128) ? "vendor specific " : "", /* 128 is meanwhile wellknown */
tok2str(bgp_safi_values, "Unknown SAFI", safi),
safi));
if (len == BGP_MP_NLRI_MINSIZE)
ND_PRINT((ndo, "\n\t End-of-Rib Marker (empty NLRI)"));
tptr += 3;
while (tptr < pptr + len) {
switch (af<<8 | safi) {
case (AFNUM_INET<<8 | SAFNUM_UNICAST):
case (AFNUM_INET<<8 | SAFNUM_MULTICAST):
case (AFNUM_INET<<8 | SAFNUM_UNIMULTICAST):
advance = decode_prefix4(ndo, tptr, len, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else if (advance == -3)
break; /* bytes left, but not enough */
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET<<8 | SAFNUM_LABUNICAST):
advance = decode_labeled_prefix4(ndo, tptr, len, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else if (advance == -3)
break; /* bytes left, but not enough */
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_INET<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_INET<<8 | SAFNUM_VPNUNIMULTICAST):
advance = decode_labeled_vpn_prefix4(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET6<<8 | SAFNUM_UNICAST):
case (AFNUM_INET6<<8 | SAFNUM_MULTICAST):
case (AFNUM_INET6<<8 | SAFNUM_UNIMULTICAST):
advance = decode_prefix6(ndo, tptr, len, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else if (advance == -3)
break; /* bytes left, but not enough */
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET6<<8 | SAFNUM_LABUNICAST):
advance = decode_labeled_prefix6(ndo, tptr, len, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else if (advance == -3)
break; /* bytes left, but not enough */
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET6<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_INET6<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_INET6<<8 | SAFNUM_VPNUNIMULTICAST):
advance = decode_labeled_vpn_prefix6(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_VPLS<<8 | SAFNUM_VPLS):
case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_L2VPN<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNIMULTICAST):
advance = decode_labeled_vpn_l2(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_NSAP<<8 | SAFNUM_UNICAST):
case (AFNUM_NSAP<<8 | SAFNUM_MULTICAST):
case (AFNUM_NSAP<<8 | SAFNUM_UNIMULTICAST):
advance = decode_clnp_prefix(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_NSAP<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_NSAP<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_NSAP<<8 | SAFNUM_VPNUNIMULTICAST):
advance = decode_labeled_vpn_clnp_prefix(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET<<8 | SAFNUM_MDT):
advance = decode_mdt_vpn_nlri(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET<<8 | SAFNUM_MULTICAST_VPN): /* fall through */
case (AFNUM_INET6<<8 | SAFNUM_MULTICAST_VPN):
advance = decode_multicast_vpn(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
default:
ND_TCHECK2(*(tptr-3),tlen);
ND_PRINT((ndo, "no AFI %u / SAFI %u decoder", af, safi));
if (ndo->ndo_vflag <= 1)
print_unknown_data(ndo, tptr-3, "\n\t ", tlen);
advance = 0;
tptr = pptr + len;
break;
}
if (advance < 0)
break;
tptr += advance;
}
break;
case BGPTYPE_EXTD_COMMUNITIES:
if (len % 8) {
ND_PRINT((ndo, "invalid len"));
break;
}
while (tlen>0) {
uint16_t extd_comm;
ND_TCHECK2(tptr[0], 2);
extd_comm=EXTRACT_16BITS(tptr);
ND_PRINT((ndo, "\n\t %s (0x%04x), Flags [%s]",
tok2str(bgp_extd_comm_subtype_values,
"unknown extd community typecode",
extd_comm),
extd_comm,
bittok2str(bgp_extd_comm_flag_values, "none", extd_comm)));
ND_TCHECK2(*(tptr+2), 6);
switch(extd_comm) {
case BGP_EXT_COM_RT_0:
case BGP_EXT_COM_RO_0:
case BGP_EXT_COM_L2VPN_RT_0:
ND_PRINT((ndo, ": %u:%u (= %s)",
EXTRACT_16BITS(tptr+2),
EXTRACT_32BITS(tptr+4),
ipaddr_string(ndo, tptr+4)));
break;
case BGP_EXT_COM_RT_1:
case BGP_EXT_COM_RO_1:
case BGP_EXT_COM_L2VPN_RT_1:
case BGP_EXT_COM_VRF_RT_IMP:
ND_PRINT((ndo, ": %s:%u",
ipaddr_string(ndo, tptr+2),
EXTRACT_16BITS(tptr+6)));
break;
case BGP_EXT_COM_RT_2:
case BGP_EXT_COM_RO_2:
ND_PRINT((ndo, ": %s:%u",
as_printf(ndo, astostr, sizeof(astostr),
EXTRACT_32BITS(tptr+2)), EXTRACT_16BITS(tptr+6)));
break;
case BGP_EXT_COM_LINKBAND:
bw.i = EXTRACT_32BITS(tptr+2);
ND_PRINT((ndo, ": bandwidth: %.3f Mbps",
bw.f*8/1000000));
break;
case BGP_EXT_COM_VPN_ORIGIN:
case BGP_EXT_COM_VPN_ORIGIN2:
case BGP_EXT_COM_VPN_ORIGIN3:
case BGP_EXT_COM_VPN_ORIGIN4:
case BGP_EXT_COM_OSPF_RID:
case BGP_EXT_COM_OSPF_RID2:
ND_PRINT((ndo, "%s", ipaddr_string(ndo, tptr+2)));
break;
case BGP_EXT_COM_OSPF_RTYPE:
case BGP_EXT_COM_OSPF_RTYPE2:
ND_PRINT((ndo, ": area:%s, router-type:%s, metric-type:%s%s",
ipaddr_string(ndo, tptr+2),
tok2str(bgp_extd_comm_ospf_rtype_values,
"unknown (0x%02x)",
*(tptr+6)),
(*(tptr+7) & BGP_OSPF_RTYPE_METRIC_TYPE) ? "E2" : "",
((*(tptr+6) == BGP_OSPF_RTYPE_EXT) || (*(tptr+6) == BGP_OSPF_RTYPE_NSSA)) ? "E1" : ""));
break;
case BGP_EXT_COM_L2INFO:
ND_PRINT((ndo, ": %s Control Flags [0x%02x]:MTU %u",
tok2str(l2vpn_encaps_values,
"unknown encaps",
*(tptr+2)),
*(tptr+3),
EXTRACT_16BITS(tptr+4)));
break;
case BGP_EXT_COM_SOURCE_AS:
ND_PRINT((ndo, ": AS %u", EXTRACT_16BITS(tptr+2)));
break;
default:
ND_TCHECK2(*tptr,8);
print_unknown_data(ndo, tptr, "\n\t ", 8);
break;
}
tlen -=8;
tptr +=8;
}
break;
case BGPTYPE_PMSI_TUNNEL:
{
uint8_t tunnel_type, flags;
ND_TCHECK2(tptr[0], 5);
tunnel_type = *(tptr+1);
flags = *tptr;
tlen = len;
ND_PRINT((ndo, "\n\t Tunnel-type %s (%u), Flags [%s], MPLS Label %u",
tok2str(bgp_pmsi_tunnel_values, "Unknown", tunnel_type),
tunnel_type,
bittok2str(bgp_pmsi_flag_values, "none", flags),
EXTRACT_24BITS(tptr+2)>>4));
tptr +=5;
tlen -= 5;
switch (tunnel_type) {
case BGP_PMSI_TUNNEL_PIM_SM: /* fall through */
case BGP_PMSI_TUNNEL_PIM_BIDIR:
ND_TCHECK2(tptr[0], 8);
ND_PRINT((ndo, "\n\t Sender %s, P-Group %s",
ipaddr_string(ndo, tptr),
ipaddr_string(ndo, tptr+4)));
break;
case BGP_PMSI_TUNNEL_PIM_SSM:
ND_TCHECK2(tptr[0], 8);
ND_PRINT((ndo, "\n\t Root-Node %s, P-Group %s",
ipaddr_string(ndo, tptr),
ipaddr_string(ndo, tptr+4)));
break;
case BGP_PMSI_TUNNEL_INGRESS:
ND_TCHECK2(tptr[0], 4);
ND_PRINT((ndo, "\n\t Tunnel-Endpoint %s",
ipaddr_string(ndo, tptr)));
break;
case BGP_PMSI_TUNNEL_LDP_P2MP: /* fall through */
case BGP_PMSI_TUNNEL_LDP_MP2MP:
ND_TCHECK2(tptr[0], 8);
ND_PRINT((ndo, "\n\t Root-Node %s, LSP-ID 0x%08x",
ipaddr_string(ndo, tptr),
EXTRACT_32BITS(tptr+4)));
break;
case BGP_PMSI_TUNNEL_RSVP_P2MP:
ND_TCHECK2(tptr[0], 8);
ND_PRINT((ndo, "\n\t Extended-Tunnel-ID %s, P2MP-ID 0x%08x",
ipaddr_string(ndo, tptr),
EXTRACT_32BITS(tptr+4)));
break;
default:
if (ndo->ndo_vflag <= 1) {
print_unknown_data(ndo, tptr, "\n\t ", tlen);
}
}
break;
}
case BGPTYPE_AIGP:
{
uint8_t type;
uint16_t length;
tlen = len;
while (tlen >= 3) {
ND_TCHECK2(tptr[0], 3);
type = *tptr;
length = EXTRACT_16BITS(tptr+1);
tptr += 3;
tlen -= 3;
ND_PRINT((ndo, "\n\t %s TLV (%u), length %u",
tok2str(bgp_aigp_values, "Unknown", type),
type, length));
if (length < 3)
goto trunc;
length -= 3;
/*
* Check if we can read the TLV data.
*/
ND_TCHECK2(tptr[3], length);
switch (type) {
case BGP_AIGP_TLV:
if (length < 8)
goto trunc;
ND_PRINT((ndo, ", metric %" PRIu64,
EXTRACT_64BITS(tptr)));
break;
default:
if (ndo->ndo_vflag <= 1) {
print_unknown_data(ndo, tptr,"\n\t ", length);
}
}
tptr += length;
tlen -= length;
}
break;
}
case BGPTYPE_ATTR_SET:
ND_TCHECK2(tptr[0], 4);
if (len < 4)
goto trunc;
ND_PRINT((ndo, "\n\t Origin AS: %s",
as_printf(ndo, astostr, sizeof(astostr), EXTRACT_32BITS(tptr))));
tptr+=4;
len -=4;
while (len) {
u_int aflags, alenlen, alen;
ND_TCHECK2(tptr[0], 2);
if (len < 2)
goto trunc;
aflags = *tptr;
atype = *(tptr + 1);
tptr += 2;
len -= 2;
alenlen = bgp_attr_lenlen(aflags, tptr);
ND_TCHECK2(tptr[0], alenlen);
if (len < alenlen)
goto trunc;
alen = bgp_attr_len(aflags, tptr);
tptr += alenlen;
len -= alenlen;
ND_PRINT((ndo, "\n\t %s (%u), length: %u",
tok2str(bgp_attr_values,
"Unknown Attribute", atype),
atype,
alen));
if (aflags) {
ND_PRINT((ndo, ", Flags [%s%s%s%s",
aflags & 0x80 ? "O" : "",
aflags & 0x40 ? "T" : "",
aflags & 0x20 ? "P" : "",
aflags & 0x10 ? "E" : ""));
if (aflags & 0xf)
ND_PRINT((ndo, "+%x", aflags & 0xf));
ND_PRINT((ndo, "]: "));
}
/* FIXME check for recursion */
if (!bgp_attr_print(ndo, atype, tptr, alen))
return 0;
tptr += alen;
len -= alen;
}
break;
case BGPTYPE_LARGE_COMMUNITY:
if (len == 0 || len % 12) {
ND_PRINT((ndo, "invalid len"));
break;
}
ND_PRINT((ndo, "\n\t "));
while (len > 0) {
ND_TCHECK2(*tptr, 12);
ND_PRINT((ndo, "%u:%u:%u%s",
EXTRACT_32BITS(tptr),
EXTRACT_32BITS(tptr + 4),
EXTRACT_32BITS(tptr + 8),
(len > 12) ? ", " : ""));
tptr += 12;
len -= 12;
}
break;
default:
ND_TCHECK2(*pptr,len);
ND_PRINT((ndo, "\n\t no Attribute %u decoder", atype)); /* we have no decoder for the attribute */
if (ndo->ndo_vflag <= 1)
print_unknown_data(ndo, pptr, "\n\t ", len);
break;
}
if (ndo->ndo_vflag > 1 && len) { /* omit zero length attributes*/
ND_TCHECK2(*pptr,len);
print_unknown_data(ndo, pptr, "\n\t ", len);
}
return 1;
trunc:
return 0;
}
static void
bgp_capabilities_print(netdissect_options *ndo,
const u_char *opt, int caps_len)
{
int cap_type, cap_len, tcap_len, cap_offset;
int i = 0;
while (i < caps_len) {
ND_TCHECK2(opt[i], BGP_CAP_HEADER_SIZE);
cap_type=opt[i];
cap_len=opt[i+1];
tcap_len=cap_len;
ND_PRINT((ndo, "\n\t %s (%u), length: %u",
tok2str(bgp_capcode_values, "Unknown",
cap_type),
cap_type,
cap_len));
ND_TCHECK2(opt[i+2], cap_len);
switch (cap_type) {
case BGP_CAPCODE_MP:
/* AFI (16 bits), Reserved (8 bits), SAFI (8 bits) */
ND_TCHECK_8BITS(opt + i + 5);
ND_PRINT((ndo, "\n\t\tAFI %s (%u), SAFI %s (%u)",
tok2str(af_values, "Unknown",
EXTRACT_16BITS(opt+i+2)),
EXTRACT_16BITS(opt+i+2),
tok2str(bgp_safi_values, "Unknown",
opt[i+5]),
opt[i+5]));
break;
case BGP_CAPCODE_RESTART:
/* Restart Flags (4 bits), Restart Time in seconds (12 bits) */
ND_TCHECK_16BITS(opt + i + 2);
ND_PRINT((ndo, "\n\t\tRestart Flags: [%s], Restart Time %us",
((opt[i+2])&0x80) ? "R" : "none",
EXTRACT_16BITS(opt+i+2)&0xfff));
tcap_len-=2;
cap_offset=4;
while(tcap_len>=4) {
ND_PRINT((ndo, "\n\t\t AFI %s (%u), SAFI %s (%u), Forwarding state preserved: %s",
tok2str(af_values,"Unknown",
EXTRACT_16BITS(opt+i+cap_offset)),
EXTRACT_16BITS(opt+i+cap_offset),
tok2str(bgp_safi_values,"Unknown",
opt[i+cap_offset+2]),
opt[i+cap_offset+2],
((opt[i+cap_offset+3])&0x80) ? "yes" : "no" ));
tcap_len-=4;
cap_offset+=4;
}
break;
case BGP_CAPCODE_RR:
case BGP_CAPCODE_RR_CISCO:
break;
case BGP_CAPCODE_AS_NEW:
/*
* Extract the 4 byte AS number encoded.
*/
if (cap_len == 4) {
ND_PRINT((ndo, "\n\t\t 4 Byte AS %s",
as_printf(ndo, astostr, sizeof(astostr),
EXTRACT_32BITS(opt + i + 2))));
}
break;
case BGP_CAPCODE_ADD_PATH:
cap_offset=2;
if (tcap_len == 0) {
ND_PRINT((ndo, " (bogus)")); /* length */
break;
}
while (tcap_len > 0) {
if (tcap_len < 4) {
ND_PRINT((ndo, "\n\t\t(invalid)"));
break;
}
ND_PRINT((ndo, "\n\t\tAFI %s (%u), SAFI %s (%u), Send/Receive: %s",
tok2str(af_values,"Unknown",EXTRACT_16BITS(opt+i+cap_offset)),
EXTRACT_16BITS(opt+i+cap_offset),
tok2str(bgp_safi_values,"Unknown",opt[i+cap_offset+2]),
opt[i+cap_offset+2],
tok2str(bgp_add_path_recvsend,"Bogus (0x%02x)",opt[i+cap_offset+3])
));
tcap_len-=4;
cap_offset+=4;
}
break;
default:
ND_PRINT((ndo, "\n\t\tno decoder for Capability %u",
cap_type));
if (ndo->ndo_vflag <= 1)
print_unknown_data(ndo, &opt[i+2], "\n\t\t", cap_len);
break;
}
if (ndo->ndo_vflag > 1 && cap_len > 0) {
print_unknown_data(ndo, &opt[i+2], "\n\t\t", cap_len);
}
i += BGP_CAP_HEADER_SIZE + cap_len;
}
return;
trunc:
ND_PRINT((ndo, "[|BGP]"));
}
static void
bgp_open_print(netdissect_options *ndo,
const u_char *dat, int length)
{
struct bgp_open bgpo;
struct bgp_opt bgpopt;
const u_char *opt;
int i;
ND_TCHECK2(dat[0], BGP_OPEN_SIZE);
memcpy(&bgpo, dat, BGP_OPEN_SIZE);
ND_PRINT((ndo, "\n\t Version %d, ", bgpo.bgpo_version));
ND_PRINT((ndo, "my AS %s, ",
as_printf(ndo, astostr, sizeof(astostr), ntohs(bgpo.bgpo_myas))));
ND_PRINT((ndo, "Holdtime %us, ", ntohs(bgpo.bgpo_holdtime)));
ND_PRINT((ndo, "ID %s", ipaddr_string(ndo, &bgpo.bgpo_id)));
ND_PRINT((ndo, "\n\t Optional parameters, length: %u", bgpo.bgpo_optlen));
/* some little sanity checking */
if (length < bgpo.bgpo_optlen+BGP_OPEN_SIZE)
return;
/* ugly! */
opt = &((const struct bgp_open *)dat)->bgpo_optlen;
opt++;
i = 0;
while (i < bgpo.bgpo_optlen) {
ND_TCHECK2(opt[i], BGP_OPT_SIZE);
memcpy(&bgpopt, &opt[i], BGP_OPT_SIZE);
if (i + 2 + bgpopt.bgpopt_len > bgpo.bgpo_optlen) {
ND_PRINT((ndo, "\n\t Option %d, length: %u", bgpopt.bgpopt_type, bgpopt.bgpopt_len));
break;
}
ND_PRINT((ndo, "\n\t Option %s (%u), length: %u",
tok2str(bgp_opt_values,"Unknown",
bgpopt.bgpopt_type),
bgpopt.bgpopt_type,
bgpopt.bgpopt_len));
/* now let's decode the options we know*/
switch(bgpopt.bgpopt_type) {
case BGP_OPT_CAP:
bgp_capabilities_print(ndo, &opt[i+BGP_OPT_SIZE],
bgpopt.bgpopt_len);
break;
case BGP_OPT_AUTH:
default:
ND_PRINT((ndo, "\n\t no decoder for option %u",
bgpopt.bgpopt_type));
break;
}
i += BGP_OPT_SIZE + bgpopt.bgpopt_len;
}
return;
trunc:
ND_PRINT((ndo, "[|BGP]"));
}
static void
bgp_update_print(netdissect_options *ndo,
const u_char *dat, int length)
{
struct bgp bgp;
const u_char *p;
int withdrawn_routes_len;
int len;
int i;
ND_TCHECK2(dat[0], BGP_SIZE);
if (length < BGP_SIZE)
goto trunc;
memcpy(&bgp, dat, BGP_SIZE);
p = dat + BGP_SIZE; /*XXX*/
length -= BGP_SIZE;
/* Unfeasible routes */
ND_TCHECK2(p[0], 2);
if (length < 2)
goto trunc;
withdrawn_routes_len = EXTRACT_16BITS(p);
p += 2;
length -= 2;
if (withdrawn_routes_len) {
/*
* Without keeping state from the original NLRI message,
* it's not possible to tell if this a v4 or v6 route,
* so only try to decode it if we're not v6 enabled.
*/
ND_TCHECK2(p[0], withdrawn_routes_len);
if (length < withdrawn_routes_len)
goto trunc;
ND_PRINT((ndo, "\n\t Withdrawn routes: %d bytes", withdrawn_routes_len));
p += withdrawn_routes_len;
length -= withdrawn_routes_len;
}
ND_TCHECK2(p[0], 2);
if (length < 2)
goto trunc;
len = EXTRACT_16BITS(p);
p += 2;
length -= 2;
if (withdrawn_routes_len == 0 && len == 0 && length == 0) {
/* No withdrawn routes, no path attributes, no NLRI */
ND_PRINT((ndo, "\n\t End-of-Rib Marker (empty NLRI)"));
return;
}
if (len) {
/* do something more useful!*/
while (len) {
int aflags, atype, alenlen, alen;
ND_TCHECK2(p[0], 2);
if (len < 2)
goto trunc;
if (length < 2)
goto trunc;
aflags = *p;
atype = *(p + 1);
p += 2;
len -= 2;
length -= 2;
alenlen = bgp_attr_lenlen(aflags, p);
ND_TCHECK2(p[0], alenlen);
if (len < alenlen)
goto trunc;
if (length < alenlen)
goto trunc;
alen = bgp_attr_len(aflags, p);
p += alenlen;
len -= alenlen;
length -= alenlen;
ND_PRINT((ndo, "\n\t %s (%u), length: %u",
tok2str(bgp_attr_values, "Unknown Attribute",
atype),
atype,
alen));
if (aflags) {
ND_PRINT((ndo, ", Flags [%s%s%s%s",
aflags & 0x80 ? "O" : "",
aflags & 0x40 ? "T" : "",
aflags & 0x20 ? "P" : "",
aflags & 0x10 ? "E" : ""));
if (aflags & 0xf)
ND_PRINT((ndo, "+%x", aflags & 0xf));
ND_PRINT((ndo, "]: "));
}
if (len < alen)
goto trunc;
if (length < alen)
goto trunc;
if (!bgp_attr_print(ndo, atype, p, alen))
goto trunc;
p += alen;
len -= alen;
length -= alen;
}
}
if (length) {
/*
* XXX - what if they're using the "Advertisement of
* Multiple Paths in BGP" feature:
*
* https://datatracker.ietf.org/doc/draft-ietf-idr-add-paths/
*
* http://tools.ietf.org/html/draft-ietf-idr-add-paths-06
*/
ND_PRINT((ndo, "\n\t Updated routes:"));
while (length) {
char buf[MAXHOSTNAMELEN + 100];
i = decode_prefix4(ndo, p, length, buf, sizeof(buf));
if (i == -1) {
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
break;
} else if (i == -2)
goto trunc;
else if (i == -3)
goto trunc; /* bytes left, but not enough */
else {
ND_PRINT((ndo, "\n\t %s", buf));
p += i;
length -= i;
}
}
}
return;
trunc:
ND_PRINT((ndo, "[|BGP]"));
}
static void
bgp_notification_print(netdissect_options *ndo,
const u_char *dat, int length)
{
struct bgp_notification bgpn;
const u_char *tptr;
ND_TCHECK2(dat[0], BGP_NOTIFICATION_SIZE);
memcpy(&bgpn, dat, BGP_NOTIFICATION_SIZE);
/* some little sanity checking */
if (length<BGP_NOTIFICATION_SIZE)
return;
ND_PRINT((ndo, ", %s (%u)",
tok2str(bgp_notify_major_values, "Unknown Error",
bgpn.bgpn_major),
bgpn.bgpn_major));
switch (bgpn.bgpn_major) {
case BGP_NOTIFY_MAJOR_MSG:
ND_PRINT((ndo, ", subcode %s (%u)",
tok2str(bgp_notify_minor_msg_values, "Unknown",
bgpn.bgpn_minor),
bgpn.bgpn_minor));
break;
case BGP_NOTIFY_MAJOR_OPEN:
ND_PRINT((ndo, ", subcode %s (%u)",
tok2str(bgp_notify_minor_open_values, "Unknown",
bgpn.bgpn_minor),
bgpn.bgpn_minor));
break;
case BGP_NOTIFY_MAJOR_UPDATE:
ND_PRINT((ndo, ", subcode %s (%u)",
tok2str(bgp_notify_minor_update_values, "Unknown",
bgpn.bgpn_minor),
bgpn.bgpn_minor));
break;
case BGP_NOTIFY_MAJOR_FSM:
ND_PRINT((ndo, " subcode %s (%u)",
tok2str(bgp_notify_minor_fsm_values, "Unknown",
bgpn.bgpn_minor),
bgpn.bgpn_minor));
break;
case BGP_NOTIFY_MAJOR_CAP:
ND_PRINT((ndo, " subcode %s (%u)",
tok2str(bgp_notify_minor_cap_values, "Unknown",
bgpn.bgpn_minor),
bgpn.bgpn_minor));
break;
case BGP_NOTIFY_MAJOR_CEASE:
ND_PRINT((ndo, ", subcode %s (%u)",
tok2str(bgp_notify_minor_cease_values, "Unknown",
bgpn.bgpn_minor),
bgpn.bgpn_minor));
/* draft-ietf-idr-cease-subcode-02 mentions optionally 7 bytes
* for the maxprefix subtype, which may contain AFI, SAFI and MAXPREFIXES
*/
if(bgpn.bgpn_minor == BGP_NOTIFY_MINOR_CEASE_MAXPRFX && length >= BGP_NOTIFICATION_SIZE + 7) {
tptr = dat + BGP_NOTIFICATION_SIZE;
ND_TCHECK2(*tptr, 7);
ND_PRINT((ndo, ", AFI %s (%u), SAFI %s (%u), Max Prefixes: %u",
tok2str(af_values, "Unknown",
EXTRACT_16BITS(tptr)),
EXTRACT_16BITS(tptr),
tok2str(bgp_safi_values, "Unknown", *(tptr+2)),
*(tptr+2),
EXTRACT_32BITS(tptr+3)));
}
break;
default:
break;
}
return;
trunc:
ND_PRINT((ndo, "[|BGP]"));
}
static void
bgp_route_refresh_print(netdissect_options *ndo,
const u_char *pptr, int len)
{
const struct bgp_route_refresh *bgp_route_refresh_header;
ND_TCHECK2(pptr[0], BGP_ROUTE_REFRESH_SIZE);
/* some little sanity checking */
if (len<BGP_ROUTE_REFRESH_SIZE)
return;
bgp_route_refresh_header = (const struct bgp_route_refresh *)pptr;
ND_PRINT((ndo, "\n\t AFI %s (%u), SAFI %s (%u)",
tok2str(af_values,"Unknown",
/* this stinks but the compiler pads the structure
* weird */
EXTRACT_16BITS(&bgp_route_refresh_header->afi)),
EXTRACT_16BITS(&bgp_route_refresh_header->afi),
tok2str(bgp_safi_values,"Unknown",
bgp_route_refresh_header->safi),
bgp_route_refresh_header->safi));
if (ndo->ndo_vflag > 1) {
ND_TCHECK2(*pptr, len);
print_unknown_data(ndo, pptr, "\n\t ", len);
}
return;
trunc:
ND_PRINT((ndo, "[|BGP]"));
}
static int
bgp_header_print(netdissect_options *ndo,
const u_char *dat, int length)
{
struct bgp bgp;
ND_TCHECK2(dat[0], BGP_SIZE);
memcpy(&bgp, dat, BGP_SIZE);
ND_PRINT((ndo, "\n\t%s Message (%u), length: %u",
tok2str(bgp_msg_values, "Unknown", bgp.bgp_type),
bgp.bgp_type,
length));
switch (bgp.bgp_type) {
case BGP_OPEN:
bgp_open_print(ndo, dat, length);
break;
case BGP_UPDATE:
bgp_update_print(ndo, dat, length);
break;
case BGP_NOTIFICATION:
bgp_notification_print(ndo, dat, length);
break;
case BGP_KEEPALIVE:
break;
case BGP_ROUTE_REFRESH:
bgp_route_refresh_print(ndo, dat, length);
break;
default:
/* we have no decoder for the BGP message */
ND_TCHECK2(*dat, length);
ND_PRINT((ndo, "\n\t no Message %u decoder", bgp.bgp_type));
print_unknown_data(ndo, dat, "\n\t ", length);
break;
}
return 1;
trunc:
ND_PRINT((ndo, "[|BGP]"));
return 0;
}
void
bgp_print(netdissect_options *ndo,
const u_char *dat, int length)
{
const u_char *p;
const u_char *ep;
const u_char *start;
const u_char marker[] = {
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
};
struct bgp bgp;
uint16_t hlen;
ep = dat + length;
if (ndo->ndo_snapend < dat + length)
ep = ndo->ndo_snapend;
ND_PRINT((ndo, ": BGP"));
if (ndo->ndo_vflag < 1) /* lets be less chatty */
return;
p = dat;
start = p;
while (p < ep) {
if (!ND_TTEST2(p[0], 1))
break;
if (p[0] != 0xff) {
p++;
continue;
}
if (!ND_TTEST2(p[0], sizeof(marker)))
break;
if (memcmp(p, marker, sizeof(marker)) != 0) {
p++;
continue;
}
/* found BGP header */
ND_TCHECK2(p[0], BGP_SIZE); /*XXX*/
memcpy(&bgp, p, BGP_SIZE);
if (start != p)
ND_PRINT((ndo, " [|BGP]"));
hlen = ntohs(bgp.bgp_len);
if (hlen < BGP_SIZE) {
ND_PRINT((ndo, "\n[|BGP Bogus header length %u < %u]", hlen,
BGP_SIZE));
break;
}
if (ND_TTEST2(p[0], hlen)) {
if (!bgp_header_print(ndo, p, hlen))
return;
p += hlen;
start = p;
} else {
ND_PRINT((ndo, "\n[|BGP %s]",
tok2str(bgp_msg_values,
"Unknown Message Type",
bgp.bgp_type)));
break;
}
}
return;
trunc:
ND_PRINT((ndo, " [|BGP]"));
}
/*
* Local Variables:
* c-style: whitesmith
* c-basic-offset: 4
* End:
*/
| ./CrossVul/dataset_final_sorted/CWE-125/c/good_265_0 |
crossvul-cpp_data_bad_514_1 | /*
* uriparser - RFC 3986 URI parsing library
*
* Copyright (C) 2007, Weijia Song <songweijia@gmail.com>
* Copyright (C) 2007, Sebastian Pipping <sebastian@pipping.org>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above
* copyright notice, this list of conditions and the following
* disclaimer.
*
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* * Neither the name of the <ORGANIZATION> 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.
*/
/**
* @file UriParse.c
* Holds the RFC 3986 %URI parsing implementation.
* NOTE: This source file includes itself twice.
*/
/* What encodings are enabled? */
#include <uriparser/UriDefsConfig.h>
#if (!defined(URI_PASS_ANSI) && !defined(URI_PASS_UNICODE))
/* Include SELF twice */
# ifdef URI_ENABLE_ANSI
# define URI_PASS_ANSI 1
# include "UriParse.c"
# undef URI_PASS_ANSI
# endif
# ifdef URI_ENABLE_UNICODE
# define URI_PASS_UNICODE 1
# include "UriParse.c"
# undef URI_PASS_UNICODE
# endif
#else
# ifdef URI_PASS_ANSI
# include <uriparser/UriDefsAnsi.h>
# else
# include <uriparser/UriDefsUnicode.h>
# include <wchar.h>
# endif
#ifndef URI_DOXYGEN
# include <uriparser/Uri.h>
# include <uriparser/UriIp4.h>
# include "UriCommon.h"
# include "UriMemory.h"
# include "UriParseBase.h"
#endif
#define URI_SET_DIGIT \
_UT('0'): \
case _UT('1'): \
case _UT('2'): \
case _UT('3'): \
case _UT('4'): \
case _UT('5'): \
case _UT('6'): \
case _UT('7'): \
case _UT('8'): \
case _UT('9')
#define URI_SET_HEX_LETTER_UPPER \
_UT('A'): \
case _UT('B'): \
case _UT('C'): \
case _UT('D'): \
case _UT('E'): \
case _UT('F')
#define URI_SET_HEX_LETTER_LOWER \
_UT('a'): \
case _UT('b'): \
case _UT('c'): \
case _UT('d'): \
case _UT('e'): \
case _UT('f')
#define URI_SET_HEXDIG \
URI_SET_DIGIT: \
case URI_SET_HEX_LETTER_UPPER: \
case URI_SET_HEX_LETTER_LOWER
#define URI_SET_ALPHA \
URI_SET_HEX_LETTER_UPPER: \
case URI_SET_HEX_LETTER_LOWER: \
case _UT('g'): \
case _UT('G'): \
case _UT('h'): \
case _UT('H'): \
case _UT('i'): \
case _UT('I'): \
case _UT('j'): \
case _UT('J'): \
case _UT('k'): \
case _UT('K'): \
case _UT('l'): \
case _UT('L'): \
case _UT('m'): \
case _UT('M'): \
case _UT('n'): \
case _UT('N'): \
case _UT('o'): \
case _UT('O'): \
case _UT('p'): \
case _UT('P'): \
case _UT('q'): \
case _UT('Q'): \
case _UT('r'): \
case _UT('R'): \
case _UT('s'): \
case _UT('S'): \
case _UT('t'): \
case _UT('T'): \
case _UT('u'): \
case _UT('U'): \
case _UT('v'): \
case _UT('V'): \
case _UT('w'): \
case _UT('W'): \
case _UT('x'): \
case _UT('X'): \
case _UT('y'): \
case _UT('Y'): \
case _UT('z'): \
case _UT('Z')
static const URI_CHAR * URI_FUNC(ParseAuthority)(URI_TYPE(ParserState) * state, const URI_CHAR * first, const URI_CHAR * afterLast, UriMemoryManager * memory);
static const URI_CHAR * URI_FUNC(ParseAuthorityTwo)(URI_TYPE(ParserState) * state, const URI_CHAR * first, const URI_CHAR * afterLast);
static const URI_CHAR * URI_FUNC(ParseHexZero)(URI_TYPE(ParserState) * state, const URI_CHAR * first, const URI_CHAR * afterLast);
static const URI_CHAR * URI_FUNC(ParseHierPart)(URI_TYPE(ParserState) * state, const URI_CHAR * first, const URI_CHAR * afterLast, UriMemoryManager * memory);
static const URI_CHAR * URI_FUNC(ParseIpFutLoop)(URI_TYPE(ParserState) * state, const URI_CHAR * first, const URI_CHAR * afterLast, UriMemoryManager * memory);
static const URI_CHAR * URI_FUNC(ParseIpFutStopGo)(URI_TYPE(ParserState) * state, const URI_CHAR * first, const URI_CHAR * afterLast, UriMemoryManager * memory);
static const URI_CHAR * URI_FUNC(ParseIpLit2)(URI_TYPE(ParserState) * state, const URI_CHAR * first, const URI_CHAR * afterLast, UriMemoryManager * memory);
static const URI_CHAR * URI_FUNC(ParseIPv6address2)(URI_TYPE(ParserState) * state, const URI_CHAR * first, const URI_CHAR * afterLast, UriMemoryManager * memory);
static const URI_CHAR * URI_FUNC(ParseMustBeSegmentNzNc)(URI_TYPE(ParserState) * state, const URI_CHAR * first, const URI_CHAR * afterLast, UriMemoryManager * memory);
static const URI_CHAR * URI_FUNC(ParseOwnHost)(URI_TYPE(ParserState) * state, const URI_CHAR * first, const URI_CHAR * afterLast, UriMemoryManager * memory);
static const URI_CHAR * URI_FUNC(ParseOwnHost2)(URI_TYPE(ParserState) * state, const URI_CHAR * first, const URI_CHAR * afterLast, UriMemoryManager * memory);
static const URI_CHAR * URI_FUNC(ParseOwnHostUserInfo)(URI_TYPE(ParserState) * state, const URI_CHAR * first, const URI_CHAR * afterLast, UriMemoryManager * memory);
static const URI_CHAR * URI_FUNC(ParseOwnHostUserInfoNz)(URI_TYPE(ParserState) * state, const URI_CHAR * first, const URI_CHAR * afterLast, UriMemoryManager * memory);
static const URI_CHAR * URI_FUNC(ParseOwnPortUserInfo)(URI_TYPE(ParserState) * state, const URI_CHAR * first, const URI_CHAR * afterLast, UriMemoryManager * memory);
static const URI_CHAR * URI_FUNC(ParseOwnUserInfo)(URI_TYPE(ParserState) * state, const URI_CHAR * first, const URI_CHAR * afterLast, UriMemoryManager * memory);
static const URI_CHAR * URI_FUNC(ParsePartHelperTwo)(URI_TYPE(ParserState) * state, const URI_CHAR * first, const URI_CHAR * afterLast, UriMemoryManager * memory);
static const URI_CHAR * URI_FUNC(ParsePathAbsEmpty)(URI_TYPE(ParserState) * state, const URI_CHAR * first, const URI_CHAR * afterLast, UriMemoryManager * memory);
static const URI_CHAR * URI_FUNC(ParsePathAbsNoLeadSlash)(URI_TYPE(ParserState) * state, const URI_CHAR * first, const URI_CHAR * afterLast, UriMemoryManager * memory);
static const URI_CHAR * URI_FUNC(ParsePathRootless)(URI_TYPE(ParserState) * state, const URI_CHAR * first, const URI_CHAR * afterLast, UriMemoryManager * memory);
static const URI_CHAR * URI_FUNC(ParsePchar)(URI_TYPE(ParserState) * state, const URI_CHAR * first, const URI_CHAR * afterLast, UriMemoryManager * memory);
static const URI_CHAR * URI_FUNC(ParsePctEncoded)(URI_TYPE(ParserState) * state, const URI_CHAR * first, const URI_CHAR * afterLast, UriMemoryManager * memory);
static const URI_CHAR * URI_FUNC(ParsePctSubUnres)(URI_TYPE(ParserState) * state, const URI_CHAR * first, const URI_CHAR * afterLast, UriMemoryManager * memory);
static const URI_CHAR * URI_FUNC(ParsePort)(URI_TYPE(ParserState) * state, const URI_CHAR * first, const URI_CHAR * afterLast);
static const URI_CHAR * URI_FUNC(ParseQueryFrag)(URI_TYPE(ParserState) * state, const URI_CHAR * first, const URI_CHAR * afterLast, UriMemoryManager * memory);
static const URI_CHAR * URI_FUNC(ParseSegment)(URI_TYPE(ParserState) * state, const URI_CHAR * first, const URI_CHAR * afterLast, UriMemoryManager * memory);
static const URI_CHAR * URI_FUNC(ParseSegmentNz)(URI_TYPE(ParserState) * state, const URI_CHAR * first, const URI_CHAR * afterLast, UriMemoryManager * memory);
static const URI_CHAR * URI_FUNC(ParseSegmentNzNcOrScheme2)(URI_TYPE(ParserState) * state, const URI_CHAR * first, const URI_CHAR * afterLast, UriMemoryManager * memory);
static const URI_CHAR * URI_FUNC(ParseUriReference)(URI_TYPE(ParserState) * state, const URI_CHAR * first, const URI_CHAR * afterLast, UriMemoryManager * memory);
static const URI_CHAR * URI_FUNC(ParseUriTail)(URI_TYPE(ParserState) * state, const URI_CHAR * first, const URI_CHAR * afterLast, UriMemoryManager * memory);
static const URI_CHAR * URI_FUNC(ParseUriTailTwo)(URI_TYPE(ParserState) * state, const URI_CHAR * first, const URI_CHAR * afterLast, UriMemoryManager * memory);
static const URI_CHAR * URI_FUNC(ParseZeroMoreSlashSegs)(URI_TYPE(ParserState) * state, const URI_CHAR * first, const URI_CHAR * afterLast, UriMemoryManager * memory);
static UriBool URI_FUNC(OnExitOwnHost2)(URI_TYPE(ParserState) * state, const URI_CHAR * first, UriMemoryManager * memory);
static UriBool URI_FUNC(OnExitOwnHostUserInfo)(URI_TYPE(ParserState) * state, const URI_CHAR * first, UriMemoryManager * memory);
static UriBool URI_FUNC(OnExitOwnPortUserInfo)(URI_TYPE(ParserState) * state, const URI_CHAR * first, UriMemoryManager * memory);
static UriBool URI_FUNC(OnExitSegmentNzNcOrScheme2)(URI_TYPE(ParserState) * state, const URI_CHAR * first, UriMemoryManager * memory);
static void URI_FUNC(OnExitPartHelperTwo)(URI_TYPE(ParserState) * state);
static void URI_FUNC(ResetParserStateExceptUri)(URI_TYPE(ParserState) * state);
static UriBool URI_FUNC(PushPathSegment)(URI_TYPE(ParserState) * state,
const URI_CHAR * first, const URI_CHAR * afterLast,
UriMemoryManager * memory);
static void URI_FUNC(StopSyntax)(URI_TYPE(ParserState) * state, const URI_CHAR * errorPos, UriMemoryManager * memory);
static void URI_FUNC(StopMalloc)(URI_TYPE(ParserState) * state, UriMemoryManager * memory);
static int URI_FUNC(ParseUriExMm)(URI_TYPE(ParserState) * state,
const URI_CHAR * first, const URI_CHAR * afterLast,
UriMemoryManager * memory);
static URI_INLINE void URI_FUNC(StopSyntax)(URI_TYPE(ParserState) * state,
const URI_CHAR * errorPos, UriMemoryManager * memory) {
URI_FUNC(FreeUriMembersMm)(state->uri, memory);
state->errorPos = errorPos;
state->errorCode = URI_ERROR_SYNTAX;
}
static URI_INLINE void URI_FUNC(StopMalloc)(URI_TYPE(ParserState) * state, UriMemoryManager * memory) {
URI_FUNC(FreeUriMembersMm)(state->uri, memory);
state->errorPos = NULL;
state->errorCode = URI_ERROR_MALLOC;
}
/*
* [authority]-><[>[ipLit2][authorityTwo]
* [authority]->[ownHostUserInfoNz]
* [authority]-><NULL>
*/
static URI_INLINE const URI_CHAR * URI_FUNC(ParseAuthority)(
URI_TYPE(ParserState) * state, const URI_CHAR * first,
const URI_CHAR * afterLast, UriMemoryManager * memory) {
if (first >= afterLast) {
/* "" regname host */
state->uri->hostText.first = URI_FUNC(SafeToPointTo);
state->uri->hostText.afterLast = URI_FUNC(SafeToPointTo);
return afterLast;
}
switch (*first) {
case _UT('['):
{
const URI_CHAR * const afterIpLit2
= URI_FUNC(ParseIpLit2)(state, first + 1, afterLast, memory);
if (afterIpLit2 == NULL) {
return NULL;
}
state->uri->hostText.first = first + 1; /* HOST BEGIN */
return URI_FUNC(ParseAuthorityTwo)(state, afterIpLit2, afterLast);
}
case _UT('!'):
case _UT('$'):
case _UT('%'):
case _UT('&'):
case _UT('('):
case _UT(')'):
case _UT('-'):
case _UT('*'):
case _UT(','):
case _UT('.'):
case _UT(':'):
case _UT(';'):
case _UT('@'):
case _UT('\''):
case _UT('_'):
case _UT('~'):
case _UT('+'):
case _UT('='):
case URI_SET_DIGIT:
case URI_SET_ALPHA:
state->uri->userInfo.first = first; /* USERINFO BEGIN */
return URI_FUNC(ParseOwnHostUserInfoNz)(state, first, afterLast, memory);
default:
/* "" regname host */
state->uri->hostText.first = URI_FUNC(SafeToPointTo);
state->uri->hostText.afterLast = URI_FUNC(SafeToPointTo);
return first;
}
}
/*
* [authorityTwo]-><:>[port]
* [authorityTwo]-><NULL>
*/
static URI_INLINE const URI_CHAR * URI_FUNC(ParseAuthorityTwo)(URI_TYPE(ParserState) * state, const URI_CHAR * first, const URI_CHAR * afterLast) {
if (first >= afterLast) {
return afterLast;
}
switch (*first) {
case _UT(':'):
{
const URI_CHAR * const afterPort = URI_FUNC(ParsePort)(state, first + 1, afterLast);
if (afterPort == NULL) {
return NULL;
}
state->uri->portText.first = first + 1; /* PORT BEGIN */
state->uri->portText.afterLast = afterPort; /* PORT END */
return afterPort;
}
default:
return first;
}
}
/*
* [hexZero]->[HEXDIG][hexZero]
* [hexZero]-><NULL>
*/
static const URI_CHAR * URI_FUNC(ParseHexZero)(URI_TYPE(ParserState) * state, const URI_CHAR * first, const URI_CHAR * afterLast) {
if (first >= afterLast) {
return afterLast;
}
switch (*first) {
case URI_SET_HEXDIG:
return URI_FUNC(ParseHexZero)(state, first + 1, afterLast);
default:
return first;
}
}
/*
* [hierPart]->[pathRootless]
* [hierPart]-></>[partHelperTwo]
* [hierPart]-><NULL>
*/
static URI_INLINE const URI_CHAR * URI_FUNC(ParseHierPart)(
URI_TYPE(ParserState) * state, const URI_CHAR * first,
const URI_CHAR * afterLast, UriMemoryManager * memory) {
if (first >= afterLast) {
return afterLast;
}
switch (*first) {
case _UT('!'):
case _UT('$'):
case _UT('%'):
case _UT('&'):
case _UT('('):
case _UT(')'):
case _UT('-'):
case _UT('*'):
case _UT(','):
case _UT('.'):
case _UT(':'):
case _UT(';'):
case _UT('@'):
case _UT('\''):
case _UT('_'):
case _UT('~'):
case _UT('+'):
case _UT('='):
case URI_SET_DIGIT:
case URI_SET_ALPHA:
return URI_FUNC(ParsePathRootless)(state, first, afterLast, memory);
case _UT('/'):
return URI_FUNC(ParsePartHelperTwo)(state, first + 1, afterLast, memory);
default:
return first;
}
}
/*
* [ipFutLoop]->[subDelims][ipFutStopGo]
* [ipFutLoop]->[unreserved][ipFutStopGo]
* [ipFutLoop]-><:>[ipFutStopGo]
*/
static const URI_CHAR * URI_FUNC(ParseIpFutLoop)(URI_TYPE(ParserState) * state,
const URI_CHAR * first, const URI_CHAR * afterLast,
UriMemoryManager * memory) {
if (first >= afterLast) {
URI_FUNC(StopSyntax)(state, first, memory);
return NULL;
}
switch (*first) {
case _UT('!'):
case _UT('$'):
case _UT('&'):
case _UT('('):
case _UT(')'):
case _UT('-'):
case _UT('*'):
case _UT(','):
case _UT('.'):
case _UT(':'):
case _UT(';'):
case _UT('\''):
case _UT('_'):
case _UT('~'):
case _UT('+'):
case _UT('='):
case URI_SET_DIGIT:
case URI_SET_ALPHA:
return URI_FUNC(ParseIpFutStopGo)(state, first + 1, afterLast, memory);
default:
URI_FUNC(StopSyntax)(state, first, memory);
return NULL;
}
}
/*
* [ipFutStopGo]->[ipFutLoop]
* [ipFutStopGo]-><NULL>
*/
static const URI_CHAR * URI_FUNC(ParseIpFutStopGo)(
URI_TYPE(ParserState) * state,
const URI_CHAR * first, const URI_CHAR * afterLast,
UriMemoryManager * memory) {
if (first >= afterLast) {
return afterLast;
}
switch (*first) {
case _UT('!'):
case _UT('$'):
case _UT('&'):
case _UT('('):
case _UT(')'):
case _UT('-'):
case _UT('*'):
case _UT(','):
case _UT('.'):
case _UT(':'):
case _UT(';'):
case _UT('\''):
case _UT('_'):
case _UT('~'):
case _UT('+'):
case _UT('='):
case URI_SET_DIGIT:
case URI_SET_ALPHA:
return URI_FUNC(ParseIpFutLoop)(state, first, afterLast, memory);
default:
return first;
}
}
/*
* [ipFuture]-><v>[HEXDIG][hexZero]<.>[ipFutLoop]
*/
static const URI_CHAR * URI_FUNC(ParseIpFuture)(URI_TYPE(ParserState) * state,
const URI_CHAR * first, const URI_CHAR * afterLast,
UriMemoryManager * memory) {
if (first >= afterLast) {
URI_FUNC(StopSyntax)(state, first, memory);
return NULL;
}
/*
First character has already been
checked before entering this rule.
switch (*first) {
case _UT('v'):
*/
if (first + 1 >= afterLast) {
URI_FUNC(StopSyntax)(state, first + 1, memory);
return NULL;
}
switch (first[1]) {
case URI_SET_HEXDIG:
{
const URI_CHAR * afterIpFutLoop;
const URI_CHAR * const afterHexZero
= URI_FUNC(ParseHexZero)(state, first + 2, afterLast);
if (afterHexZero == NULL) {
return NULL;
}
if ((afterHexZero >= afterLast)
|| (*afterHexZero != _UT('.'))) {
URI_FUNC(StopSyntax)(state, afterHexZero, memory);
return NULL;
}
state->uri->hostText.first = first; /* HOST BEGIN */
state->uri->hostData.ipFuture.first = first; /* IPFUTURE BEGIN */
afterIpFutLoop = URI_FUNC(ParseIpFutLoop)(state, afterHexZero + 1, afterLast, memory);
if (afterIpFutLoop == NULL) {
return NULL;
}
state->uri->hostText.afterLast = afterIpFutLoop; /* HOST END */
state->uri->hostData.ipFuture.afterLast = afterIpFutLoop; /* IPFUTURE END */
return afterIpFutLoop;
}
default:
URI_FUNC(StopSyntax)(state, first + 1, memory);
return NULL;
}
/*
default:
URI_FUNC(StopSyntax)(state, first, memory);
return NULL;
}
*/
}
/*
* [ipLit2]->[ipFuture]<]>
* [ipLit2]->[IPv6address2]
*/
static URI_INLINE const URI_CHAR * URI_FUNC(ParseIpLit2)(
URI_TYPE(ParserState) * state, const URI_CHAR * first,
const URI_CHAR * afterLast, UriMemoryManager * memory) {
if (first >= afterLast) {
URI_FUNC(StopSyntax)(state, first, memory);
return NULL;
}
switch (*first) {
case _UT('v'):
{
const URI_CHAR * const afterIpFuture
= URI_FUNC(ParseIpFuture)(state, first, afterLast, memory);
if (afterIpFuture == NULL) {
return NULL;
}
if ((afterIpFuture >= afterLast)
|| (*afterIpFuture != _UT(']'))) {
URI_FUNC(StopSyntax)(state, first, memory);
return NULL;
}
return afterIpFuture + 1;
}
case _UT(':'):
case _UT(']'):
case URI_SET_HEXDIG:
state->uri->hostData.ip6 = memory->malloc(memory, 1 * sizeof(UriIp6)); /* Freed when stopping on parse error */
if (state->uri->hostData.ip6 == NULL) {
URI_FUNC(StopMalloc)(state, memory);
return NULL;
}
return URI_FUNC(ParseIPv6address2)(state, first, afterLast, memory);
default:
URI_FUNC(StopSyntax)(state, first, memory);
return NULL;
}
}
/*
* [IPv6address2]->..<]>
*/
static const URI_CHAR * URI_FUNC(ParseIPv6address2)(
URI_TYPE(ParserState) * state,
const URI_CHAR * first, const URI_CHAR * afterLast,
UriMemoryManager * memory) {
int zipperEver = 0;
int quadsDone = 0;
int digitCount = 0;
unsigned char digitHistory[4];
int ip4OctetsDone = 0;
unsigned char quadsAfterZipper[14];
int quadsAfterZipperCount = 0;
for (;;) {
if (first >= afterLast) {
URI_FUNC(StopSyntax)(state, first, memory);
return NULL;
}
/* Inside IPv4 part? */
if (ip4OctetsDone > 0) {
/* Eat rest of IPv4 address */
for (;;) {
switch (*first) {
case URI_SET_DIGIT:
if (digitCount == 4) {
URI_FUNC(StopSyntax)(state, first, memory);
return NULL;
}
digitHistory[digitCount++] = (unsigned char)(9 + *first - _UT('9'));
break;
case _UT('.'):
if ((ip4OctetsDone == 4) /* NOTE! */
|| (digitCount == 0)
|| (digitCount == 4)) {
/* Invalid digit or octet count */
URI_FUNC(StopSyntax)(state, first, memory);
return NULL;
} else if ((digitCount > 1)
&& (digitHistory[0] == 0)) {
/* Leading zero */
URI_FUNC(StopSyntax)(state, first - digitCount, memory);
return NULL;
} else if ((digitCount > 2)
&& (digitHistory[1] == 0)) {
/* Leading zero */
URI_FUNC(StopSyntax)(state, first - digitCount + 1, memory);
return NULL;
} else if ((digitCount == 3)
&& (100 * digitHistory[0]
+ 10 * digitHistory[1]
+ digitHistory[2] > 255)) {
/* Octet value too large */
if (digitHistory[0] > 2) {
URI_FUNC(StopSyntax)(state, first - 3, memory);
} else if (digitHistory[1] > 5) {
URI_FUNC(StopSyntax)(state, first - 2, memory);
} else {
URI_FUNC(StopSyntax)(state, first - 1, memory);
}
return NULL;
}
/* Copy IPv4 octet */
state->uri->hostData.ip6->data[16 - 4 + ip4OctetsDone] = uriGetOctetValue(digitHistory, digitCount);
digitCount = 0;
ip4OctetsDone++;
break;
case _UT(']'):
if ((ip4OctetsDone != 3) /* NOTE! */
|| (digitCount == 0)
|| (digitCount == 4)) {
/* Invalid digit or octet count */
URI_FUNC(StopSyntax)(state, first, memory);
return NULL;
} else if ((digitCount > 1)
&& (digitHistory[0] == 0)) {
/* Leading zero */
URI_FUNC(StopSyntax)(state, first - digitCount, memory);
return NULL;
} else if ((digitCount > 2)
&& (digitHistory[1] == 0)) {
/* Leading zero */
URI_FUNC(StopSyntax)(state, first - digitCount + 1, memory);
return NULL;
} else if ((digitCount == 3)
&& (100 * digitHistory[0]
+ 10 * digitHistory[1]
+ digitHistory[2] > 255)) {
/* Octet value too large */
if (digitHistory[0] > 2) {
URI_FUNC(StopSyntax)(state, first - 3, memory);
} else if (digitHistory[1] > 5) {
URI_FUNC(StopSyntax)(state, first - 2, memory);
} else {
URI_FUNC(StopSyntax)(state, first - 1, memory);
}
return NULL;
}
state->uri->hostText.afterLast = first; /* HOST END */
/* Copy missing quads right before IPv4 */
memcpy(state->uri->hostData.ip6->data + 16 - 4 - 2 * quadsAfterZipperCount,
quadsAfterZipper, 2 * quadsAfterZipperCount);
/* Copy last IPv4 octet */
state->uri->hostData.ip6->data[16 - 4 + 3] = uriGetOctetValue(digitHistory, digitCount);
return first + 1;
default:
URI_FUNC(StopSyntax)(state, first, memory);
return NULL;
}
first++;
}
} else {
/* Eat while no dot in sight */
int letterAmong = 0;
int walking = 1;
do {
switch (*first) {
case URI_SET_HEX_LETTER_LOWER:
letterAmong = 1;
if (digitCount == 4) {
URI_FUNC(StopSyntax)(state, first, memory);
return NULL;
}
digitHistory[digitCount] = (unsigned char)(15 + *first - _UT('f'));
digitCount++;
break;
case URI_SET_HEX_LETTER_UPPER:
letterAmong = 1;
if (digitCount == 4) {
URI_FUNC(StopSyntax)(state, first, memory);
return NULL;
}
digitHistory[digitCount] = (unsigned char)(15 + *first - _UT('F'));
digitCount++;
break;
case URI_SET_DIGIT:
if (digitCount == 4) {
URI_FUNC(StopSyntax)(state, first, memory);
return NULL;
}
digitHistory[digitCount] = (unsigned char)(9 + *first - _UT('9'));
digitCount++;
break;
case _UT(':'):
{
int setZipper = 0;
if (digitCount > 0) {
if (zipperEver) {
uriWriteQuadToDoubleByte(digitHistory, digitCount, quadsAfterZipper + 2 * quadsAfterZipperCount);
quadsAfterZipperCount++;
} else {
uriWriteQuadToDoubleByte(digitHistory, digitCount, state->uri->hostData.ip6->data + 2 * quadsDone);
}
quadsDone++;
digitCount = 0;
}
letterAmong = 0;
/* Too many quads? */
if (quadsDone >= 8 - zipperEver) {
URI_FUNC(StopSyntax)(state, first, memory);
return NULL;
}
/* "::"? */
if (first + 1 >= afterLast) {
URI_FUNC(StopSyntax)(state, first + 1, memory);
return NULL;
}
if (first[1] == _UT(':')) {
const int resetOffset = 2 * (quadsDone + (digitCount > 0));
first++;
if (zipperEver) {
URI_FUNC(StopSyntax)(state, first, memory);
return NULL; /* "::.+::" */
}
/* Zero everything after zipper */
memset(state->uri->hostData.ip6->data + resetOffset, 0, 16 - resetOffset);
setZipper = 1;
/* ":::+"? */
if (first + 1 >= afterLast) {
URI_FUNC(StopSyntax)(state, first + 1, memory);
return NULL; /* No ']' yet */
}
if (first[1] == _UT(':')) {
URI_FUNC(StopSyntax)(state, first + 1, memory);
return NULL; /* ":::+ "*/
}
}
if (setZipper) {
zipperEver = 1;
}
}
break;
case _UT('.'):
if ((quadsDone > 6) /* NOTE */
|| (!zipperEver && (quadsDone < 6))
|| letterAmong
|| (digitCount == 0)
|| (digitCount == 4)) {
/* Invalid octet before */
URI_FUNC(StopSyntax)(state, first, memory);
return NULL;
} else if ((digitCount > 1)
&& (digitHistory[0] == 0)) {
/* Leading zero */
URI_FUNC(StopSyntax)(state, first - digitCount, memory);
return NULL;
} else if ((digitCount > 2)
&& (digitHistory[1] == 0)) {
/* Leading zero */
URI_FUNC(StopSyntax)(state, first - digitCount + 1, memory);
return NULL;
} else if ((digitCount == 3)
&& (100 * digitHistory[0]
+ 10 * digitHistory[1]
+ digitHistory[2] > 255)) {
/* Octet value too large */
if (digitHistory[0] > 2) {
URI_FUNC(StopSyntax)(state, first - 3, memory);
} else if (digitHistory[1] > 5) {
URI_FUNC(StopSyntax)(state, first - 2, memory);
} else {
URI_FUNC(StopSyntax)(state, first - 1, memory);
}
return NULL;
}
/* Copy first IPv4 octet */
state->uri->hostData.ip6->data[16 - 4] = uriGetOctetValue(digitHistory, digitCount);
digitCount = 0;
/* Switch over to IPv4 loop */
ip4OctetsDone = 1;
walking = 0;
break;
case _UT(']'):
/* Too little quads? */
if (!zipperEver && !((quadsDone == 7) && (digitCount > 0))) {
URI_FUNC(StopSyntax)(state, first, memory);
return NULL;
}
if (digitCount > 0) {
if (zipperEver) {
uriWriteQuadToDoubleByte(digitHistory, digitCount, quadsAfterZipper + 2 * quadsAfterZipperCount);
quadsAfterZipperCount++;
} else {
uriWriteQuadToDoubleByte(digitHistory, digitCount, state->uri->hostData.ip6->data + 2 * quadsDone);
}
/*
quadsDone++;
digitCount = 0;
*/
}
/* Copy missing quads to the end */
memcpy(state->uri->hostData.ip6->data + 16 - 2 * quadsAfterZipperCount,
quadsAfterZipper, 2 * quadsAfterZipperCount);
state->uri->hostText.afterLast = first; /* HOST END */
return first + 1; /* Fine */
default:
URI_FUNC(StopSyntax)(state, first, memory);
return NULL;
}
first++;
if (first >= afterLast) {
URI_FUNC(StopSyntax)(state, first, memory);
return NULL; /* No ']' yet */
}
} while (walking);
}
}
}
/*
* [mustBeSegmentNzNc]->[pctEncoded][mustBeSegmentNzNc]
* [mustBeSegmentNzNc]->[subDelims][mustBeSegmentNzNc]
* [mustBeSegmentNzNc]->[unreserved][mustBeSegmentNzNc]
* [mustBeSegmentNzNc]->[uriTail] // can take <NULL>
* [mustBeSegmentNzNc]-></>[segment][zeroMoreSlashSegs][uriTail]
* [mustBeSegmentNzNc]-><@>[mustBeSegmentNzNc]
*/
static const URI_CHAR * URI_FUNC(ParseMustBeSegmentNzNc)(
URI_TYPE(ParserState) * state, const URI_CHAR * first,
const URI_CHAR * afterLast, UriMemoryManager * memory) {
if (first >= afterLast) {
if (!URI_FUNC(PushPathSegment)(state, state->uri->scheme.first, first, memory)) { /* SEGMENT BOTH */
URI_FUNC(StopMalloc)(state, memory);
return NULL;
}
state->uri->scheme.first = NULL; /* Not a scheme, reset */
return afterLast;
}
switch (*first) {
case _UT('%'):
{
const URI_CHAR * const afterPctEncoded
= URI_FUNC(ParsePctEncoded)(state, first, afterLast, memory);
if (afterPctEncoded == NULL) {
return NULL;
}
return URI_FUNC(ParseMustBeSegmentNzNc)(state, afterPctEncoded, afterLast, memory);
}
case _UT('@'):
case _UT('!'):
case _UT('$'):
case _UT('&'):
case _UT('('):
case _UT(')'):
case _UT('*'):
case _UT(','):
case _UT(';'):
case _UT('\''):
case _UT('+'):
case _UT('='):
case _UT('-'):
case _UT('.'):
case _UT('_'):
case _UT('~'):
case URI_SET_DIGIT:
case URI_SET_ALPHA:
return URI_FUNC(ParseMustBeSegmentNzNc)(state, first + 1, afterLast, memory);
case _UT('/'):
{
const URI_CHAR * afterZeroMoreSlashSegs;
const URI_CHAR * afterSegment;
if (!URI_FUNC(PushPathSegment)(state, state->uri->scheme.first, first, memory)) { /* SEGMENT BOTH */
URI_FUNC(StopMalloc)(state, memory);
return NULL;
}
state->uri->scheme.first = NULL; /* Not a scheme, reset */
afterSegment = URI_FUNC(ParseSegment)(state, first + 1, afterLast, memory);
if (afterSegment == NULL) {
return NULL;
}
if (!URI_FUNC(PushPathSegment)(state, first + 1, afterSegment, memory)) { /* SEGMENT BOTH */
URI_FUNC(StopMalloc)(state, memory);
return NULL;
}
afterZeroMoreSlashSegs
= URI_FUNC(ParseZeroMoreSlashSegs)(state, afterSegment, afterLast, memory);
if (afterZeroMoreSlashSegs == NULL) {
return NULL;
}
return URI_FUNC(ParseUriTail)(state, afterZeroMoreSlashSegs, afterLast, memory);
}
default:
if (!URI_FUNC(PushPathSegment)(state, state->uri->scheme.first, first, memory)) { /* SEGMENT BOTH */
URI_FUNC(StopMalloc)(state, memory);
return NULL;
}
state->uri->scheme.first = NULL; /* Not a scheme, reset */
return URI_FUNC(ParseUriTail)(state, first, afterLast, memory);
}
}
/*
* [ownHost]-><[>[ipLit2][authorityTwo]
* [ownHost]->[ownHost2] // can take <NULL>
*/
static URI_INLINE const URI_CHAR * URI_FUNC(ParseOwnHost)(
URI_TYPE(ParserState) * state, const URI_CHAR * first,
const URI_CHAR * afterLast, UriMemoryManager * memory) {
if (first >= afterLast) {
state->uri->hostText.afterLast = afterLast; /* HOST END */
return afterLast;
}
switch (*first) {
case _UT('['):
{
const URI_CHAR * const afterIpLit2
= URI_FUNC(ParseIpLit2)(state, first + 1, afterLast, memory);
if (afterIpLit2 == NULL) {
return NULL;
}
state->uri->hostText.first = first + 1; /* HOST BEGIN */
return URI_FUNC(ParseAuthorityTwo)(state, afterIpLit2, afterLast);
}
default:
return URI_FUNC(ParseOwnHost2)(state, first, afterLast, memory);
}
}
static URI_INLINE UriBool URI_FUNC(OnExitOwnHost2)(
URI_TYPE(ParserState) * state, const URI_CHAR * first,
UriMemoryManager * memory) {
state->uri->hostText.afterLast = first; /* HOST END */
/* Valid IPv4 or just a regname? */
state->uri->hostData.ip4 = memory->malloc(memory, 1 * sizeof(UriIp4)); /* Freed when stopping on parse error */
if (state->uri->hostData.ip4 == NULL) {
return URI_FALSE; /* Raises malloc error */
}
if (URI_FUNC(ParseIpFourAddress)(state->uri->hostData.ip4->data,
state->uri->hostText.first, state->uri->hostText.afterLast)) {
/* Not IPv4 */
memory->free(memory, state->uri->hostData.ip4);
state->uri->hostData.ip4 = NULL;
}
return URI_TRUE; /* Success */
}
/*
* [ownHost2]->[authorityTwo] // can take <NULL>
* [ownHost2]->[pctSubUnres][ownHost2]
*/
static const URI_CHAR * URI_FUNC(ParseOwnHost2)(
URI_TYPE(ParserState) * state, const URI_CHAR * first,
const URI_CHAR * afterLast, UriMemoryManager * memory) {
if (first >= afterLast) {
if (!URI_FUNC(OnExitOwnHost2)(state, first, memory)) {
URI_FUNC(StopMalloc)(state, memory);
return NULL;
}
return afterLast;
}
switch (*first) {
case _UT('!'):
case _UT('$'):
case _UT('%'):
case _UT('&'):
case _UT('('):
case _UT(')'):
case _UT('-'):
case _UT('*'):
case _UT(','):
case _UT('.'):
case _UT(';'):
case _UT('\''):
case _UT('_'):
case _UT('~'):
case _UT('+'):
case _UT('='):
case URI_SET_DIGIT:
case URI_SET_ALPHA:
{
const URI_CHAR * const afterPctSubUnres
= URI_FUNC(ParsePctSubUnres)(state, first, afterLast, memory);
if (afterPctSubUnres == NULL) {
return NULL;
}
return URI_FUNC(ParseOwnHost2)(state, afterPctSubUnres, afterLast, memory);
}
default:
if (!URI_FUNC(OnExitOwnHost2)(state, first, memory)) {
URI_FUNC(StopMalloc)(state, memory);
return NULL;
}
return URI_FUNC(ParseAuthorityTwo)(state, first, afterLast);
}
}
static URI_INLINE UriBool URI_FUNC(OnExitOwnHostUserInfo)(
URI_TYPE(ParserState) * state, const URI_CHAR * first,
UriMemoryManager * memory) {
state->uri->hostText.first = state->uri->userInfo.first; /* Host instead of userInfo, update */
state->uri->userInfo.first = NULL; /* Not a userInfo, reset */
state->uri->hostText.afterLast = first; /* HOST END */
/* Valid IPv4 or just a regname? */
state->uri->hostData.ip4 = memory->malloc(memory, 1 * sizeof(UriIp4)); /* Freed when stopping on parse error */
if (state->uri->hostData.ip4 == NULL) {
return URI_FALSE; /* Raises malloc error */
}
if (URI_FUNC(ParseIpFourAddress)(state->uri->hostData.ip4->data,
state->uri->hostText.first, state->uri->hostText.afterLast)) {
/* Not IPv4 */
memory->free(memory, state->uri->hostData.ip4);
state->uri->hostData.ip4 = NULL;
}
return URI_TRUE; /* Success */
}
/*
* [ownHostUserInfo]->[ownHostUserInfoNz]
* [ownHostUserInfo]-><NULL>
*/
static URI_INLINE const URI_CHAR * URI_FUNC(ParseOwnHostUserInfo)(
URI_TYPE(ParserState) * state, const URI_CHAR * first,
const URI_CHAR * afterLast, UriMemoryManager * memory) {
if (first >= afterLast) {
if (!URI_FUNC(OnExitOwnHostUserInfo)(state, first, memory)) {
URI_FUNC(StopMalloc)(state, memory);
return NULL;
}
return afterLast;
}
switch (*first) {
case _UT('!'):
case _UT('$'):
case _UT('%'):
case _UT('&'):
case _UT('('):
case _UT(')'):
case _UT('-'):
case _UT('*'):
case _UT(','):
case _UT('.'):
case _UT(':'):
case _UT(';'):
case _UT('@'):
case _UT('\''):
case _UT('_'):
case _UT('~'):
case _UT('+'):
case _UT('='):
case URI_SET_DIGIT:
case URI_SET_ALPHA:
return URI_FUNC(ParseOwnHostUserInfoNz)(state, first, afterLast, memory);
default:
if (!URI_FUNC(OnExitOwnHostUserInfo)(state, first, memory)) {
URI_FUNC(StopMalloc)(state, memory);
return NULL;
}
return first;
}
}
/*
* [ownHostUserInfoNz]->[pctSubUnres][ownHostUserInfo]
* [ownHostUserInfoNz]-><:>[ownPortUserInfo]
* [ownHostUserInfoNz]-><@>[ownHost]
*/
static const URI_CHAR * URI_FUNC(ParseOwnHostUserInfoNz)(
URI_TYPE(ParserState) * state, const URI_CHAR * first,
const URI_CHAR * afterLast, UriMemoryManager * memory) {
if (first >= afterLast) {
URI_FUNC(StopSyntax)(state, first, memory);
return NULL;
}
switch (*first) {
case _UT('!'):
case _UT('$'):
case _UT('%'):
case _UT('&'):
case _UT('('):
case _UT(')'):
case _UT('-'):
case _UT('*'):
case _UT(','):
case _UT('.'):
case _UT(';'):
case _UT('\''):
case _UT('_'):
case _UT('~'):
case _UT('+'):
case _UT('='):
case URI_SET_DIGIT:
case URI_SET_ALPHA:
{
const URI_CHAR * const afterPctSubUnres
= URI_FUNC(ParsePctSubUnres)(state, first, afterLast, memory);
if (afterPctSubUnres == NULL) {
return NULL;
}
return URI_FUNC(ParseOwnHostUserInfo)(state, afterPctSubUnres, afterLast, memory);
}
case _UT(':'):
state->uri->hostText.afterLast = first; /* HOST END */
state->uri->portText.first = first + 1; /* PORT BEGIN */
return URI_FUNC(ParseOwnPortUserInfo)(state, first + 1, afterLast, memory);
case _UT('@'):
state->uri->userInfo.afterLast = first; /* USERINFO END */
state->uri->hostText.first = first + 1; /* HOST BEGIN */
return URI_FUNC(ParseOwnHost)(state, first + 1, afterLast, memory);
default:
URI_FUNC(StopSyntax)(state, first, memory);
return NULL;
}
}
static URI_INLINE UriBool URI_FUNC(OnExitOwnPortUserInfo)(
URI_TYPE(ParserState) * state, const URI_CHAR * first,
UriMemoryManager * memory) {
state->uri->hostText.first = state->uri->userInfo.first; /* Host instead of userInfo, update */
state->uri->userInfo.first = NULL; /* Not a userInfo, reset */
state->uri->portText.afterLast = first; /* PORT END */
/* Valid IPv4 or just a regname? */
state->uri->hostData.ip4 = memory->malloc(memory, 1 * sizeof(UriIp4)); /* Freed when stopping on parse error */
if (state->uri->hostData.ip4 == NULL) {
return URI_FALSE; /* Raises malloc error */
}
if (URI_FUNC(ParseIpFourAddress)(state->uri->hostData.ip4->data,
state->uri->hostText.first, state->uri->hostText.afterLast)) {
/* Not IPv4 */
memory->free(memory, state->uri->hostData.ip4);
state->uri->hostData.ip4 = NULL;
}
return URI_TRUE; /* Success */
}
/*
* [ownPortUserInfo]->[ALPHA][ownUserInfo]
* [ownPortUserInfo]->[DIGIT][ownPortUserInfo]
* [ownPortUserInfo]-><.>[ownUserInfo]
* [ownPortUserInfo]-><_>[ownUserInfo]
* [ownPortUserInfo]-><~>[ownUserInfo]
* [ownPortUserInfo]-><->[ownUserInfo]
* [ownPortUserInfo]->[subDelims][ownUserInfo]
* [ownPortUserInfo]->[pctEncoded][ownUserInfo]
* [ownPortUserInfo]-><:>[ownUserInfo]
* [ownPortUserInfo]-><@>[ownHost]
* [ownPortUserInfo]-><NULL>
*/
static const URI_CHAR * URI_FUNC(ParseOwnPortUserInfo)(
URI_TYPE(ParserState) * state, const URI_CHAR * first,
const URI_CHAR * afterLast, UriMemoryManager * memory) {
if (first >= afterLast) {
if (!URI_FUNC(OnExitOwnPortUserInfo)(state, first, memory)) {
URI_FUNC(StopMalloc)(state, memory);
return NULL;
}
return afterLast;
}
switch (*first) {
/* begin sub-delims */
case _UT('!'):
case _UT('$'):
case _UT('&'):
case _UT('\''):
case _UT('('):
case _UT(')'):
case _UT('*'):
case _UT('+'):
case _UT(','):
case _UT(';'):
case _UT('='):
/* end sub-delims */
/* begin unreserved (except alpha and digit) */
case _UT('-'):
case _UT('.'):
case _UT('_'):
case _UT('~'):
/* end unreserved (except alpha and digit) */
case _UT(':'):
case URI_SET_ALPHA:
state->uri->hostText.afterLast = NULL; /* Not a host, reset */
state->uri->portText.first = NULL; /* Not a port, reset */
return URI_FUNC(ParseOwnUserInfo)(state, first + 1, afterLast, memory);
case URI_SET_DIGIT:
return URI_FUNC(ParseOwnPortUserInfo)(state, first + 1, afterLast, memory);
case _UT('%'):
state->uri->portText.first = NULL; /* Not a port, reset */
{
const URI_CHAR * const afterPct
= URI_FUNC(ParsePctEncoded)(state, first, afterLast, memory);
if (afterPct == NULL) {
return NULL;
}
return URI_FUNC(ParseOwnUserInfo)(state, afterPct, afterLast, memory);
}
case _UT('@'):
state->uri->hostText.afterLast = NULL; /* Not a host, reset */
state->uri->portText.first = NULL; /* Not a port, reset */
state->uri->userInfo.afterLast = first; /* USERINFO END */
state->uri->hostText.first = first + 1; /* HOST BEGIN */
return URI_FUNC(ParseOwnHost)(state, first + 1, afterLast, memory);
default:
if (!URI_FUNC(OnExitOwnPortUserInfo)(state, first, memory)) {
URI_FUNC(StopMalloc)(state, memory);
return NULL;
}
return first;
}
}
/*
* [ownUserInfo]->[pctSubUnres][ownUserInfo]
* [ownUserInfo]-><:>[ownUserInfo]
* [ownUserInfo]-><@>[ownHost]
*/
static const URI_CHAR * URI_FUNC(ParseOwnUserInfo)(
URI_TYPE(ParserState) * state, const URI_CHAR * first,
const URI_CHAR * afterLast, UriMemoryManager * memory) {
if (first >= afterLast) {
URI_FUNC(StopSyntax)(state, first, memory);
return NULL;
}
switch (*first) {
case _UT('!'):
case _UT('$'):
case _UT('%'):
case _UT('&'):
case _UT('('):
case _UT(')'):
case _UT('-'):
case _UT('*'):
case _UT(','):
case _UT('.'):
case _UT(';'):
case _UT('\''):
case _UT('_'):
case _UT('~'):
case _UT('+'):
case _UT('='):
case URI_SET_DIGIT:
case URI_SET_ALPHA:
{
const URI_CHAR * const afterPctSubUnres
= URI_FUNC(ParsePctSubUnres)(state, first, afterLast, memory);
if (afterPctSubUnres == NULL) {
return NULL;
}
return URI_FUNC(ParseOwnUserInfo)(state, afterPctSubUnres, afterLast, memory);
}
case _UT(':'):
return URI_FUNC(ParseOwnUserInfo)(state, first + 1, afterLast, memory);
case _UT('@'):
/* SURE */
state->uri->userInfo.afterLast = first; /* USERINFO END */
state->uri->hostText.first = first + 1; /* HOST BEGIN */
return URI_FUNC(ParseOwnHost)(state, first + 1, afterLast, memory);
default:
URI_FUNC(StopSyntax)(state, first, memory);
return NULL;
}
}
static URI_INLINE void URI_FUNC(OnExitPartHelperTwo)(URI_TYPE(ParserState) * state) {
state->uri->absolutePath = URI_TRUE;
}
/*
* [partHelperTwo]->[pathAbsNoLeadSlash] // can take <NULL>
* [partHelperTwo]-></>[authority][pathAbsEmpty]
*/
static URI_INLINE const URI_CHAR * URI_FUNC(ParsePartHelperTwo)(
URI_TYPE(ParserState) * state, const URI_CHAR * first,
const URI_CHAR * afterLast, UriMemoryManager * memory) {
if (first >= afterLast) {
URI_FUNC(OnExitPartHelperTwo)(state);
return afterLast;
}
switch (*first) {
case _UT('/'):
{
const URI_CHAR * const afterAuthority
= URI_FUNC(ParseAuthority)(state, first + 1, afterLast, memory);
const URI_CHAR * afterPathAbsEmpty;
if (afterAuthority == NULL) {
return NULL;
}
afterPathAbsEmpty = URI_FUNC(ParsePathAbsEmpty)(state, afterAuthority, afterLast, memory);
URI_FUNC(FixEmptyTrailSegment)(state->uri, memory);
return afterPathAbsEmpty;
}
default:
URI_FUNC(OnExitPartHelperTwo)(state);
return URI_FUNC(ParsePathAbsNoLeadSlash)(state, first, afterLast, memory);
}
}
/*
* [pathAbsEmpty]-></>[segment][pathAbsEmpty]
* [pathAbsEmpty]-><NULL>
*/
static const URI_CHAR * URI_FUNC(ParsePathAbsEmpty)(
URI_TYPE(ParserState) * state, const URI_CHAR * first,
const URI_CHAR * afterLast, UriMemoryManager * memory) {
if (first >= afterLast) {
return afterLast;
}
switch (*first) {
case _UT('/'):
{
const URI_CHAR * const afterSegment
= URI_FUNC(ParseSegment)(state, first + 1, afterLast, memory);
if (afterSegment == NULL) {
return NULL;
}
if (!URI_FUNC(PushPathSegment)(state, first + 1, afterSegment, memory)) { /* SEGMENT BOTH */
URI_FUNC(StopMalloc)(state, memory);
return NULL;
}
return URI_FUNC(ParsePathAbsEmpty)(state, afterSegment, afterLast, memory);
}
default:
return first;
}
}
/*
* [pathAbsNoLeadSlash]->[segmentNz][zeroMoreSlashSegs]
* [pathAbsNoLeadSlash]-><NULL>
*/
static URI_INLINE const URI_CHAR * URI_FUNC(ParsePathAbsNoLeadSlash)(
URI_TYPE(ParserState) * state, const URI_CHAR * first,
const URI_CHAR * afterLast, UriMemoryManager * memory) {
if (first >= afterLast) {
return afterLast;
}
switch (*first) {
case _UT('!'):
case _UT('$'):
case _UT('%'):
case _UT('&'):
case _UT('('):
case _UT(')'):
case _UT('-'):
case _UT('*'):
case _UT(','):
case _UT('.'):
case _UT(':'):
case _UT(';'):
case _UT('@'):
case _UT('\''):
case _UT('_'):
case _UT('~'):
case _UT('+'):
case _UT('='):
case URI_SET_DIGIT:
case URI_SET_ALPHA:
{
const URI_CHAR * const afterSegmentNz
= URI_FUNC(ParseSegmentNz)(state, first, afterLast, memory);
if (afterSegmentNz == NULL) {
return NULL;
}
if (!URI_FUNC(PushPathSegment)(state, first, afterSegmentNz, memory)) { /* SEGMENT BOTH */
URI_FUNC(StopMalloc)(state, memory);
return NULL;
}
return URI_FUNC(ParseZeroMoreSlashSegs)(state, afterSegmentNz, afterLast, memory);
}
default:
return first;
}
}
/*
* [pathRootless]->[segmentNz][zeroMoreSlashSegs]
*/
static URI_INLINE const URI_CHAR * URI_FUNC(ParsePathRootless)(
URI_TYPE(ParserState) * state, const URI_CHAR * first,
const URI_CHAR * afterLast, UriMemoryManager * memory) {
const URI_CHAR * const afterSegmentNz
= URI_FUNC(ParseSegmentNz)(state, first, afterLast, memory);
if (afterSegmentNz == NULL) {
return NULL;
} else {
if (!URI_FUNC(PushPathSegment)(state, first, afterSegmentNz, memory)) { /* SEGMENT BOTH */
URI_FUNC(StopMalloc)(state, memory);
return NULL;
}
}
return URI_FUNC(ParseZeroMoreSlashSegs)(state, afterSegmentNz, afterLast, memory);
}
/*
* [pchar]->[pctEncoded]
* [pchar]->[subDelims]
* [pchar]->[unreserved]
* [pchar]-><:>
* [pchar]-><@>
*/
static const URI_CHAR * URI_FUNC(ParsePchar)(URI_TYPE(ParserState) * state,
const URI_CHAR * first, const URI_CHAR * afterLast,
UriMemoryManager * memory) {
if (first >= afterLast) {
URI_FUNC(StopSyntax)(state, first, memory);
return NULL;
}
switch (*first) {
case _UT('%'):
return URI_FUNC(ParsePctEncoded)(state, first, afterLast, memory);
case _UT(':'):
case _UT('@'):
case _UT('!'):
case _UT('$'):
case _UT('&'):
case _UT('('):
case _UT(')'):
case _UT('*'):
case _UT(','):
case _UT(';'):
case _UT('\''):
case _UT('+'):
case _UT('='):
case _UT('-'):
case _UT('.'):
case _UT('_'):
case _UT('~'):
case URI_SET_DIGIT:
case URI_SET_ALPHA:
return first + 1;
default:
URI_FUNC(StopSyntax)(state, first, memory);
return NULL;
}
}
/*
* [pctEncoded]-><%>[HEXDIG][HEXDIG]
*/
static const URI_CHAR * URI_FUNC(ParsePctEncoded)(
URI_TYPE(ParserState) * state,
const URI_CHAR * first, const URI_CHAR * afterLast,
UriMemoryManager * memory) {
if (first >= afterLast) {
URI_FUNC(StopSyntax)(state, first, memory);
return NULL;
}
/*
First character has already been
checked before entering this rule.
switch (*first) {
case _UT('%'):
*/
if (first + 1 >= afterLast) {
URI_FUNC(StopSyntax)(state, first + 1, memory);
return NULL;
}
switch (first[1]) {
case URI_SET_HEXDIG:
if (first + 2 >= afterLast) {
URI_FUNC(StopSyntax)(state, first + 2, memory);
return NULL;
}
switch (first[2]) {
case URI_SET_HEXDIG:
return first + 3;
default:
URI_FUNC(StopSyntax)(state, first + 2, memory);
return NULL;
}
default:
URI_FUNC(StopSyntax)(state, first + 1, memory);
return NULL;
}
/*
default:
URI_FUNC(StopSyntax)(state, first, memory);
return NULL;
}
*/
}
/*
* [pctSubUnres]->[pctEncoded]
* [pctSubUnres]->[subDelims]
* [pctSubUnres]->[unreserved]
*/
static const URI_CHAR * URI_FUNC(ParsePctSubUnres)(
URI_TYPE(ParserState) * state,
const URI_CHAR * first, const URI_CHAR * afterLast,
UriMemoryManager * memory) {
if (first >= afterLast) {
URI_FUNC(StopSyntax)(state, first, memory);
return NULL;
}
switch (*first) {
case _UT('%'):
return URI_FUNC(ParsePctEncoded)(state, first, afterLast, memory);
case _UT('!'):
case _UT('$'):
case _UT('&'):
case _UT('('):
case _UT(')'):
case _UT('*'):
case _UT(','):
case _UT(';'):
case _UT('\''):
case _UT('+'):
case _UT('='):
case _UT('-'):
case _UT('.'):
case _UT('_'):
case _UT('~'):
case URI_SET_DIGIT:
case URI_SET_ALPHA:
return first + 1;
default:
URI_FUNC(StopSyntax)(state, first, memory);
return NULL;
}
}
/*
* [port]->[DIGIT][port]
* [port]-><NULL>
*/
static const URI_CHAR * URI_FUNC(ParsePort)(URI_TYPE(ParserState) * state, const URI_CHAR * first, const URI_CHAR * afterLast) {
if (first >= afterLast) {
return afterLast;
}
switch (*first) {
case URI_SET_DIGIT:
return URI_FUNC(ParsePort)(state, first + 1, afterLast);
default:
return first;
}
}
/*
* [queryFrag]->[pchar][queryFrag]
* [queryFrag]-></>[queryFrag]
* [queryFrag]-><?>[queryFrag]
* [queryFrag]-><NULL>
*/
static const URI_CHAR * URI_FUNC(ParseQueryFrag)(URI_TYPE(ParserState) * state,
const URI_CHAR * first, const URI_CHAR * afterLast,
UriMemoryManager * memory) {
if (first >= afterLast) {
return afterLast;
}
switch (*first) {
case _UT('!'):
case _UT('$'):
case _UT('%'):
case _UT('&'):
case _UT('('):
case _UT(')'):
case _UT('-'):
case _UT('*'):
case _UT(','):
case _UT('.'):
case _UT(':'):
case _UT(';'):
case _UT('@'):
case _UT('\''):
case _UT('_'):
case _UT('~'):
case _UT('+'):
case _UT('='):
case URI_SET_DIGIT:
case URI_SET_ALPHA:
{
const URI_CHAR * const afterPchar
= URI_FUNC(ParsePchar)(state, first, afterLast, memory);
if (afterPchar == NULL) {
return NULL;
}
return URI_FUNC(ParseQueryFrag)(state, afterPchar, afterLast, memory);
}
case _UT('/'):
case _UT('?'):
return URI_FUNC(ParseQueryFrag)(state, first + 1, afterLast, memory);
default:
return first;
}
}
/*
* [segment]->[pchar][segment]
* [segment]-><NULL>
*/
static const URI_CHAR * URI_FUNC(ParseSegment)(URI_TYPE(ParserState) * state,
const URI_CHAR * first, const URI_CHAR * afterLast,
UriMemoryManager * memory) {
if (first >= afterLast) {
return afterLast;
}
switch (*first) {
case _UT('!'):
case _UT('$'):
case _UT('%'):
case _UT('&'):
case _UT('('):
case _UT(')'):
case _UT('-'):
case _UT('*'):
case _UT(','):
case _UT('.'):
case _UT(':'):
case _UT(';'):
case _UT('@'):
case _UT('\''):
case _UT('_'):
case _UT('~'):
case _UT('+'):
case _UT('='):
case URI_SET_DIGIT:
case URI_SET_ALPHA:
{
const URI_CHAR * const afterPchar
= URI_FUNC(ParsePchar)(state, first, afterLast, memory);
if (afterPchar == NULL) {
return NULL;
}
return URI_FUNC(ParseSegment)(state, afterPchar, afterLast, memory);
}
default:
return first;
}
}
/*
* [segmentNz]->[pchar][segment]
*/
static URI_INLINE const URI_CHAR * URI_FUNC(ParseSegmentNz)(
URI_TYPE(ParserState) * state,
const URI_CHAR * first, const URI_CHAR * afterLast,
UriMemoryManager * memory) {
const URI_CHAR * const afterPchar
= URI_FUNC(ParsePchar)(state, first, afterLast, memory);
if (afterPchar == NULL) {
return NULL;
}
return URI_FUNC(ParseSegment)(state, afterPchar, afterLast, memory);
}
static URI_INLINE UriBool URI_FUNC(OnExitSegmentNzNcOrScheme2)(
URI_TYPE(ParserState) * state, const URI_CHAR * first,
UriMemoryManager * memory) {
if (!URI_FUNC(PushPathSegment)(state, state->uri->scheme.first, first, memory)) { /* SEGMENT BOTH */
return URI_FALSE; /* Raises malloc error*/
}
state->uri->scheme.first = NULL; /* Not a scheme, reset */
return URI_TRUE; /* Success */
}
/*
* [segmentNzNcOrScheme2]->[ALPHA][segmentNzNcOrScheme2]
* [segmentNzNcOrScheme2]->[DIGIT][segmentNzNcOrScheme2]
* [segmentNzNcOrScheme2]->[pctEncoded][mustBeSegmentNzNc]
* [segmentNzNcOrScheme2]->[uriTail] // can take <NULL>
* [segmentNzNcOrScheme2]-><!>[mustBeSegmentNzNc]
* [segmentNzNcOrScheme2]-><$>[mustBeSegmentNzNc]
* [segmentNzNcOrScheme2]-><&>[mustBeSegmentNzNc]
* [segmentNzNcOrScheme2]-><(>[mustBeSegmentNzNc]
* [segmentNzNcOrScheme2]-><)>[mustBeSegmentNzNc]
* [segmentNzNcOrScheme2]-><*>[mustBeSegmentNzNc]
* [segmentNzNcOrScheme2]-><,>[mustBeSegmentNzNc]
* [segmentNzNcOrScheme2]-><.>[segmentNzNcOrScheme2]
* [segmentNzNcOrScheme2]-></>[segment][zeroMoreSlashSegs][uriTail]
* [segmentNzNcOrScheme2]-><:>[hierPart][uriTail]
* [segmentNzNcOrScheme2]-><;>[mustBeSegmentNzNc]
* [segmentNzNcOrScheme2]-><@>[mustBeSegmentNzNc]
* [segmentNzNcOrScheme2]-><_>[mustBeSegmentNzNc]
* [segmentNzNcOrScheme2]-><~>[mustBeSegmentNzNc]
* [segmentNzNcOrScheme2]-><+>[segmentNzNcOrScheme2]
* [segmentNzNcOrScheme2]-><=>[mustBeSegmentNzNc]
* [segmentNzNcOrScheme2]-><'>[mustBeSegmentNzNc]
* [segmentNzNcOrScheme2]-><->[segmentNzNcOrScheme2]
*/
static const URI_CHAR * URI_FUNC(ParseSegmentNzNcOrScheme2)(
URI_TYPE(ParserState) * state, const URI_CHAR * first,
const URI_CHAR * afterLast, UriMemoryManager * memory) {
if (first >= afterLast) {
if (!URI_FUNC(OnExitSegmentNzNcOrScheme2)(state, first, memory)) {
URI_FUNC(StopMalloc)(state, memory);
return NULL;
}
return afterLast;
}
switch (*first) {
case _UT('.'):
case _UT('+'):
case _UT('-'):
case URI_SET_ALPHA:
case URI_SET_DIGIT:
return URI_FUNC(ParseSegmentNzNcOrScheme2)(state, first + 1, afterLast, memory);
case _UT('%'):
{
const URI_CHAR * const afterPctEncoded
= URI_FUNC(ParsePctEncoded)(state, first, afterLast, memory);
if (afterPctEncoded == NULL) {
return NULL;
}
return URI_FUNC(ParseMustBeSegmentNzNc)(state, afterPctEncoded, afterLast, memory);
}
case _UT('!'):
case _UT('$'):
case _UT('&'):
case _UT('('):
case _UT(')'):
case _UT('*'):
case _UT(','):
case _UT(';'):
case _UT('@'):
case _UT('_'):
case _UT('~'):
case _UT('='):
case _UT('\''):
return URI_FUNC(ParseMustBeSegmentNzNc)(state, first + 1, afterLast, memory);
case _UT('/'):
{
const URI_CHAR * afterZeroMoreSlashSegs;
const URI_CHAR * const afterSegment
= URI_FUNC(ParseSegment)(state, first + 1, afterLast, memory);
if (afterSegment == NULL) {
return NULL;
}
if (!URI_FUNC(PushPathSegment)(state, state->uri->scheme.first, first, memory)) { /* SEGMENT BOTH */
URI_FUNC(StopMalloc)(state, memory);
return NULL;
}
state->uri->scheme.first = NULL; /* Not a scheme, reset */
if (!URI_FUNC(PushPathSegment)(state, first + 1, afterSegment, memory)) { /* SEGMENT BOTH */
URI_FUNC(StopMalloc)(state, memory);
return NULL;
}
afterZeroMoreSlashSegs
= URI_FUNC(ParseZeroMoreSlashSegs)(state, afterSegment, afterLast, memory);
if (afterZeroMoreSlashSegs == NULL) {
return NULL;
}
return URI_FUNC(ParseUriTail)(state, afterZeroMoreSlashSegs, afterLast, memory);
}
case _UT(':'):
{
const URI_CHAR * const afterHierPart
= URI_FUNC(ParseHierPart)(state, first + 1, afterLast, memory);
state->uri->scheme.afterLast = first; /* SCHEME END */
if (afterHierPart == NULL) {
return NULL;
}
return URI_FUNC(ParseUriTail)(state, afterHierPart, afterLast, memory);
}
default:
if (!URI_FUNC(OnExitSegmentNzNcOrScheme2)(state, first, memory)) {
URI_FUNC(StopMalloc)(state, memory);
return NULL;
}
return URI_FUNC(ParseUriTail)(state, first, afterLast, memory);
}
}
/*
* [uriReference]->[ALPHA][segmentNzNcOrScheme2]
* [uriReference]->[DIGIT][mustBeSegmentNzNc]
* [uriReference]->[pctEncoded][mustBeSegmentNzNc]
* [uriReference]->[subDelims][mustBeSegmentNzNc]
* [uriReference]->[uriTail] // can take <NULL>
* [uriReference]-><.>[mustBeSegmentNzNc]
* [uriReference]-></>[partHelperTwo][uriTail]
* [uriReference]-><@>[mustBeSegmentNzNc]
* [uriReference]-><_>[mustBeSegmentNzNc]
* [uriReference]-><~>[mustBeSegmentNzNc]
* [uriReference]-><->[mustBeSegmentNzNc]
*/
static const URI_CHAR * URI_FUNC(ParseUriReference)(
URI_TYPE(ParserState) * state, const URI_CHAR * first,
const URI_CHAR * afterLast, UriMemoryManager * memory) {
if (first >= afterLast) {
return afterLast;
}
switch (*first) {
case URI_SET_ALPHA:
state->uri->scheme.first = first; /* SCHEME BEGIN */
return URI_FUNC(ParseSegmentNzNcOrScheme2)(state, first + 1, afterLast, memory);
case URI_SET_DIGIT:
case _UT('!'):
case _UT('$'):
case _UT('&'):
case _UT('('):
case _UT(')'):
case _UT('*'):
case _UT(','):
case _UT(';'):
case _UT('\''):
case _UT('+'):
case _UT('='):
case _UT('.'):
case _UT('_'):
case _UT('~'):
case _UT('-'):
case _UT('@'):
state->uri->scheme.first = first; /* SEGMENT BEGIN, ABUSE SCHEME POINTER */
return URI_FUNC(ParseMustBeSegmentNzNc)(state, first + 1, afterLast, memory);
case _UT('%'):
{
const URI_CHAR * const afterPctEncoded
= URI_FUNC(ParsePctEncoded)(state, first, afterLast, memory);
if (afterPctEncoded == NULL) {
return NULL;
}
state->uri->scheme.first = first; /* SEGMENT BEGIN, ABUSE SCHEME POINTER */
return URI_FUNC(ParseMustBeSegmentNzNc)(state, afterPctEncoded, afterLast, memory);
}
case _UT('/'):
{
const URI_CHAR * const afterPartHelperTwo
= URI_FUNC(ParsePartHelperTwo)(state, first + 1, afterLast, memory);
if (afterPartHelperTwo == NULL) {
return NULL;
}
return URI_FUNC(ParseUriTail)(state, afterPartHelperTwo, afterLast, memory);
}
default:
return URI_FUNC(ParseUriTail)(state, first, afterLast, memory);
}
}
/*
* [uriTail]-><#>[queryFrag]
* [uriTail]-><?>[queryFrag][uriTailTwo]
* [uriTail]-><NULL>
*/
static URI_INLINE const URI_CHAR * URI_FUNC(ParseUriTail)(
URI_TYPE(ParserState) * state,
const URI_CHAR * first, const URI_CHAR * afterLast,
UriMemoryManager * memory) {
if (first >= afterLast) {
return afterLast;
}
switch (*first) {
case _UT('#'):
{
const URI_CHAR * const afterQueryFrag = URI_FUNC(ParseQueryFrag)(state, first + 1, afterLast, memory);
if (afterQueryFrag == NULL) {
return NULL;
}
state->uri->fragment.first = first + 1; /* FRAGMENT BEGIN */
state->uri->fragment.afterLast = afterQueryFrag; /* FRAGMENT END */
return afterQueryFrag;
}
case _UT('?'):
{
const URI_CHAR * const afterQueryFrag
= URI_FUNC(ParseQueryFrag)(state, first + 1, afterLast, memory);
if (afterQueryFrag == NULL) {
return NULL;
}
state->uri->query.first = first + 1; /* QUERY BEGIN */
state->uri->query.afterLast = afterQueryFrag; /* QUERY END */
return URI_FUNC(ParseUriTailTwo)(state, afterQueryFrag, afterLast, memory);
}
default:
return first;
}
}
/*
* [uriTailTwo]-><#>[queryFrag]
* [uriTailTwo]-><NULL>
*/
static URI_INLINE const URI_CHAR * URI_FUNC(ParseUriTailTwo)(
URI_TYPE(ParserState) * state,
const URI_CHAR * first, const URI_CHAR * afterLast,
UriMemoryManager * memory) {
if (first >= afterLast) {
return afterLast;
}
switch (*first) {
case _UT('#'):
{
const URI_CHAR * const afterQueryFrag = URI_FUNC(ParseQueryFrag)(state, first + 1, afterLast, memory);
if (afterQueryFrag == NULL) {
return NULL;
}
state->uri->fragment.first = first + 1; /* FRAGMENT BEGIN */
state->uri->fragment.afterLast = afterQueryFrag; /* FRAGMENT END */
return afterQueryFrag;
}
default:
return first;
}
}
/*
* [zeroMoreSlashSegs]-></>[segment][zeroMoreSlashSegs]
* [zeroMoreSlashSegs]-><NULL>
*/
static const URI_CHAR * URI_FUNC(ParseZeroMoreSlashSegs)(
URI_TYPE(ParserState) * state, const URI_CHAR * first,
const URI_CHAR * afterLast, UriMemoryManager * memory) {
if (first >= afterLast) {
return afterLast;
}
switch (*first) {
case _UT('/'):
{
const URI_CHAR * const afterSegment
= URI_FUNC(ParseSegment)(state, first + 1, afterLast, memory);
if (afterSegment == NULL) {
return NULL;
}
if (!URI_FUNC(PushPathSegment)(state, first + 1, afterSegment, memory)) { /* SEGMENT BOTH */
URI_FUNC(StopMalloc)(state, memory);
return NULL;
}
return URI_FUNC(ParseZeroMoreSlashSegs)(state, afterSegment, afterLast, memory);
}
default:
return first;
}
}
static URI_INLINE void URI_FUNC(ResetParserStateExceptUri)(URI_TYPE(ParserState) * state) {
URI_TYPE(Uri) * const uriBackup = state->uri;
memset(state, 0, sizeof(URI_TYPE(ParserState)));
state->uri = uriBackup;
}
static URI_INLINE UriBool URI_FUNC(PushPathSegment)(
URI_TYPE(ParserState) * state, const URI_CHAR * first,
const URI_CHAR * afterLast, UriMemoryManager * memory) {
URI_TYPE(PathSegment) * segment = memory->calloc(memory, 1, sizeof(URI_TYPE(PathSegment)));
if (segment == NULL) {
return URI_FALSE; /* Raises malloc error */
}
if (first == afterLast) {
segment->text.first = URI_FUNC(SafeToPointTo);
segment->text.afterLast = URI_FUNC(SafeToPointTo);
} else {
segment->text.first = first;
segment->text.afterLast = afterLast;
}
/* First segment ever? */
if (state->uri->pathHead == NULL) {
/* First segment ever, set head and tail */
state->uri->pathHead = segment;
state->uri->pathTail = segment;
} else {
/* Append, update tail */
state->uri->pathTail->next = segment;
state->uri->pathTail = segment;
}
return URI_TRUE; /* Success */
}
int URI_FUNC(ParseUriEx)(URI_TYPE(ParserState) * state,
const URI_CHAR * first, const URI_CHAR * afterLast) {
return URI_FUNC(ParseUriExMm)(state, first, afterLast, NULL);
}
static int URI_FUNC(ParseUriExMm)(URI_TYPE(ParserState) * state,
const URI_CHAR * first, const URI_CHAR * afterLast,
UriMemoryManager * memory) {
const URI_CHAR * afterUriReference;
URI_TYPE(Uri) * uri;
/* Check params */
if ((state == NULL) || (first == NULL) || (afterLast == NULL)) {
return URI_ERROR_NULL;
}
URI_CHECK_MEMORY_MANAGER(memory); /* may return */
uri = state->uri;
/* Init parser */
URI_FUNC(ResetParserStateExceptUri)(state);
URI_FUNC(ResetUri)(uri);
/* Parse */
afterUriReference = URI_FUNC(ParseUriReference)(state, first, afterLast, memory);
if (afterUriReference == NULL) {
return state->errorCode;
}
if (afterUriReference != afterLast) {
URI_FUNC(StopSyntax)(state, afterUriReference, memory);
return state->errorCode;
}
return URI_SUCCESS;
}
int URI_FUNC(ParseUri)(URI_TYPE(ParserState) * state, const URI_CHAR * text) {
if ((state == NULL) || (text == NULL)) {
return URI_ERROR_NULL;
}
return URI_FUNC(ParseUriEx)(state, text, text + URI_STRLEN(text));
}
int URI_FUNC(ParseSingleUri)(URI_TYPE(Uri) * uri, const URI_CHAR * text,
const URI_CHAR ** errorPos) {
return URI_FUNC(ParseSingleUriEx)(uri, text, NULL, errorPos);
}
int URI_FUNC(ParseSingleUriEx)(URI_TYPE(Uri) * uri,
const URI_CHAR * first, const URI_CHAR * afterLast,
const URI_CHAR ** errorPos) {
if ((afterLast == NULL) && (first != NULL)) {
afterLast = first + URI_STRLEN(first);
}
return URI_FUNC(ParseSingleUriExMm)(uri, first, afterLast, errorPos, NULL);
}
int URI_FUNC(ParseSingleUriExMm)(URI_TYPE(Uri) * uri,
const URI_CHAR * first, const URI_CHAR * afterLast,
const URI_CHAR ** errorPos, UriMemoryManager * memory) {
URI_TYPE(ParserState) state;
int res;
/* Check params */
if ((uri == NULL) || (first == NULL) || (afterLast == NULL)) {
return URI_ERROR_NULL;
}
URI_CHECK_MEMORY_MANAGER(memory); /* may return */
state.uri = uri;
res = URI_FUNC(ParseUriExMm)(&state, first, afterLast, memory);
if (res != URI_SUCCESS) {
if (errorPos != NULL) {
*errorPos = state.errorPos;
}
URI_FUNC(FreeUriMembersMm)(uri, memory);
}
return res;
}
void URI_FUNC(FreeUriMembers)(URI_TYPE(Uri) * uri) {
URI_FUNC(FreeUriMembersMm)(uri, NULL);
}
int URI_FUNC(FreeUriMembersMm)(URI_TYPE(Uri) * uri, UriMemoryManager * memory) {
if (uri == NULL) {
return URI_ERROR_NULL;
}
URI_CHECK_MEMORY_MANAGER(memory); /* may return */
if (uri->owner) {
/* Scheme */
if (uri->scheme.first != NULL) {
if (uri->scheme.first != uri->scheme.afterLast) {
memory->free(memory, (URI_CHAR *)uri->scheme.first);
}
uri->scheme.first = NULL;
uri->scheme.afterLast = NULL;
}
/* User info */
if (uri->userInfo.first != NULL) {
if (uri->userInfo.first != uri->userInfo.afterLast) {
memory->free(memory, (URI_CHAR *)uri->userInfo.first);
}
uri->userInfo.first = NULL;
uri->userInfo.afterLast = NULL;
}
/* Host data - IPvFuture */
if (uri->hostData.ipFuture.first != NULL) {
if (uri->hostData.ipFuture.first != uri->hostData.ipFuture.afterLast) {
memory->free(memory, (URI_CHAR *)uri->hostData.ipFuture.first);
}
uri->hostData.ipFuture.first = NULL;
uri->hostData.ipFuture.afterLast = NULL;
uri->hostText.first = NULL;
uri->hostText.afterLast = NULL;
}
/* Host text (if regname, after IPvFuture!) */
if ((uri->hostText.first != NULL)
&& (uri->hostData.ip4 == NULL)
&& (uri->hostData.ip6 == NULL)) {
/* Real regname */
if (uri->hostText.first != uri->hostText.afterLast) {
memory->free(memory, (URI_CHAR *)uri->hostText.first);
}
uri->hostText.first = NULL;
uri->hostText.afterLast = NULL;
}
}
/* Host data - IPv4 */
if (uri->hostData.ip4 != NULL) {
memory->free(memory, uri->hostData.ip4);
uri->hostData.ip4 = NULL;
}
/* Host data - IPv6 */
if (uri->hostData.ip6 != NULL) {
memory->free(memory, uri->hostData.ip6);
uri->hostData.ip6 = NULL;
}
/* Port text */
if (uri->owner && (uri->portText.first != NULL)) {
if (uri->portText.first != uri->portText.afterLast) {
memory->free(memory, (URI_CHAR *)uri->portText.first);
}
uri->portText.first = NULL;
uri->portText.afterLast = NULL;
}
/* Path */
if (uri->pathHead != NULL) {
URI_TYPE(PathSegment) * segWalk = uri->pathHead;
while (segWalk != NULL) {
URI_TYPE(PathSegment) * const next = segWalk->next;
if (uri->owner && (segWalk->text.first != NULL)
&& (segWalk->text.first < segWalk->text.afterLast)) {
memory->free(memory, (URI_CHAR *)segWalk->text.first);
}
memory->free(memory, segWalk);
segWalk = next;
}
uri->pathHead = NULL;
uri->pathTail = NULL;
}
if (uri->owner) {
/* Query */
if (uri->query.first != NULL) {
if (uri->query.first != uri->query.afterLast) {
memory->free(memory, (URI_CHAR *)uri->query.first);
}
uri->query.first = NULL;
uri->query.afterLast = NULL;
}
/* Fragment */
if (uri->fragment.first != NULL) {
if (uri->fragment.first != uri->fragment.afterLast) {
memory->free(memory, (URI_CHAR *)uri->fragment.first);
}
uri->fragment.first = NULL;
uri->fragment.afterLast = NULL;
}
}
return URI_SUCCESS;
}
UriBool URI_FUNC(_TESTING_ONLY_ParseIpSix)(const URI_CHAR * text) {
UriMemoryManager * const memory = &defaultMemoryManager;
URI_TYPE(Uri) uri;
URI_TYPE(ParserState) parser;
const URI_CHAR * const afterIpSix = text + URI_STRLEN(text);
const URI_CHAR * res;
URI_FUNC(ResetUri)(&uri);
parser.uri = &uri;
URI_FUNC(ResetParserStateExceptUri)(&parser);
parser.uri->hostData.ip6 = memory->malloc(memory, 1 * sizeof(UriIp6));
res = URI_FUNC(ParseIPv6address2)(&parser, text, afterIpSix, memory);
URI_FUNC(FreeUriMembersMm)(&uri, memory);
return res == afterIpSix ? URI_TRUE : URI_FALSE;
}
UriBool URI_FUNC(_TESTING_ONLY_ParseIpFour)(const URI_CHAR * text) {
unsigned char octets[4];
int res = URI_FUNC(ParseIpFourAddress)(octets, text, text + URI_STRLEN(text));
return (res == URI_SUCCESS) ? URI_TRUE : URI_FALSE;
}
#undef URI_SET_DIGIT
#undef URI_SET_HEX_LETTER_UPPER
#undef URI_SET_HEX_LETTER_LOWER
#undef URI_SET_HEXDIG
#undef URI_SET_ALPHA
#endif
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_514_1 |
crossvul-cpp_data_bad_2693_0 | /*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that: (1) source code
* distributions retain the above copyright notice and this paragraph
* in its entirety, and (2) distributions including binary code include
* the above copyright notice and this paragraph in its entirety in
* the documentation or other materials provided with the distribution.
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND
* WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, WITHOUT
* LIMITATION, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE.
*
* Original code by Andy Heffernan (ahh@juniper.net)
*/
/* \summary: Pragmatic General Multicast (PGM) printer */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <netdissect-stdinc.h>
#include "netdissect.h"
#include "extract.h"
#include "addrtoname.h"
#include "addrtostr.h"
#include "ip.h"
#include "ip6.h"
#include "ipproto.h"
#include "af.h"
/*
* PGM header (RFC 3208)
*/
struct pgm_header {
uint16_t pgm_sport;
uint16_t pgm_dport;
uint8_t pgm_type;
uint8_t pgm_options;
uint16_t pgm_sum;
uint8_t pgm_gsid[6];
uint16_t pgm_length;
};
struct pgm_spm {
uint32_t pgms_seq;
uint32_t pgms_trailseq;
uint32_t pgms_leadseq;
uint16_t pgms_nla_afi;
uint16_t pgms_reserved;
/* ... uint8_t pgms_nla[0]; */
/* ... options */
};
struct pgm_nak {
uint32_t pgmn_seq;
uint16_t pgmn_source_afi;
uint16_t pgmn_reserved;
/* ... uint8_t pgmn_source[0]; */
/* ... uint16_t pgmn_group_afi */
/* ... uint16_t pgmn_reserved2; */
/* ... uint8_t pgmn_group[0]; */
/* ... options */
};
struct pgm_ack {
uint32_t pgma_rx_max_seq;
uint32_t pgma_bitmap;
/* ... options */
};
struct pgm_poll {
uint32_t pgmp_seq;
uint16_t pgmp_round;
uint16_t pgmp_reserved;
/* ... options */
};
struct pgm_polr {
uint32_t pgmp_seq;
uint16_t pgmp_round;
uint16_t pgmp_subtype;
uint16_t pgmp_nla_afi;
uint16_t pgmp_reserved;
/* ... uint8_t pgmp_nla[0]; */
/* ... options */
};
struct pgm_data {
uint32_t pgmd_seq;
uint32_t pgmd_trailseq;
/* ... options */
};
typedef enum _pgm_type {
PGM_SPM = 0, /* source path message */
PGM_POLL = 1, /* POLL Request */
PGM_POLR = 2, /* POLL Response */
PGM_ODATA = 4, /* original data */
PGM_RDATA = 5, /* repair data */
PGM_NAK = 8, /* NAK */
PGM_NULLNAK = 9, /* Null NAK */
PGM_NCF = 10, /* NAK Confirmation */
PGM_ACK = 11, /* ACK for congestion control */
PGM_SPMR = 12, /* SPM request */
PGM_MAX = 255
} pgm_type;
#define PGM_OPT_BIT_PRESENT 0x01
#define PGM_OPT_BIT_NETWORK 0x02
#define PGM_OPT_BIT_VAR_PKTLEN 0x40
#define PGM_OPT_BIT_PARITY 0x80
#define PGM_OPT_LENGTH 0x00
#define PGM_OPT_FRAGMENT 0x01
#define PGM_OPT_NAK_LIST 0x02
#define PGM_OPT_JOIN 0x03
#define PGM_OPT_NAK_BO_IVL 0x04
#define PGM_OPT_NAK_BO_RNG 0x05
#define PGM_OPT_REDIRECT 0x07
#define PGM_OPT_PARITY_PRM 0x08
#define PGM_OPT_PARITY_GRP 0x09
#define PGM_OPT_CURR_TGSIZE 0x0A
#define PGM_OPT_NBR_UNREACH 0x0B
#define PGM_OPT_PATH_NLA 0x0C
#define PGM_OPT_SYN 0x0D
#define PGM_OPT_FIN 0x0E
#define PGM_OPT_RST 0x0F
#define PGM_OPT_CR 0x10
#define PGM_OPT_CRQST 0x11
#define PGM_OPT_PGMCC_DATA 0x12
#define PGM_OPT_PGMCC_FEEDBACK 0x13
#define PGM_OPT_MASK 0x7f
#define PGM_OPT_END 0x80 /* end of options marker */
#define PGM_MIN_OPT_LEN 4
void
pgm_print(netdissect_options *ndo,
register const u_char *bp, register u_int length,
register const u_char *bp2)
{
register const struct pgm_header *pgm;
register const struct ip *ip;
register char ch;
uint16_t sport, dport;
u_int nla_afnum;
char nla_buf[INET6_ADDRSTRLEN];
register const struct ip6_hdr *ip6;
uint8_t opt_type, opt_len;
uint32_t seq, opts_len, len, offset;
pgm = (const struct pgm_header *)bp;
ip = (const struct ip *)bp2;
if (IP_V(ip) == 6)
ip6 = (const struct ip6_hdr *)bp2;
else
ip6 = NULL;
ch = '\0';
if (!ND_TTEST(pgm->pgm_dport)) {
if (ip6) {
ND_PRINT((ndo, "%s > %s: [|pgm]",
ip6addr_string(ndo, &ip6->ip6_src),
ip6addr_string(ndo, &ip6->ip6_dst)));
return;
} else {
ND_PRINT((ndo, "%s > %s: [|pgm]",
ipaddr_string(ndo, &ip->ip_src),
ipaddr_string(ndo, &ip->ip_dst)));
return;
}
}
sport = EXTRACT_16BITS(&pgm->pgm_sport);
dport = EXTRACT_16BITS(&pgm->pgm_dport);
if (ip6) {
if (ip6->ip6_nxt == IPPROTO_PGM) {
ND_PRINT((ndo, "%s.%s > %s.%s: ",
ip6addr_string(ndo, &ip6->ip6_src),
tcpport_string(ndo, sport),
ip6addr_string(ndo, &ip6->ip6_dst),
tcpport_string(ndo, dport)));
} else {
ND_PRINT((ndo, "%s > %s: ",
tcpport_string(ndo, sport), tcpport_string(ndo, dport)));
}
} else {
if (ip->ip_p == IPPROTO_PGM) {
ND_PRINT((ndo, "%s.%s > %s.%s: ",
ipaddr_string(ndo, &ip->ip_src),
tcpport_string(ndo, sport),
ipaddr_string(ndo, &ip->ip_dst),
tcpport_string(ndo, dport)));
} else {
ND_PRINT((ndo, "%s > %s: ",
tcpport_string(ndo, sport), tcpport_string(ndo, dport)));
}
}
ND_TCHECK(*pgm);
ND_PRINT((ndo, "PGM, length %u", EXTRACT_16BITS(&pgm->pgm_length)));
if (!ndo->ndo_vflag)
return;
ND_PRINT((ndo, " 0x%02x%02x%02x%02x%02x%02x ",
pgm->pgm_gsid[0],
pgm->pgm_gsid[1],
pgm->pgm_gsid[2],
pgm->pgm_gsid[3],
pgm->pgm_gsid[4],
pgm->pgm_gsid[5]));
switch (pgm->pgm_type) {
case PGM_SPM: {
const struct pgm_spm *spm;
spm = (const struct pgm_spm *)(pgm + 1);
ND_TCHECK(*spm);
bp = (const u_char *) (spm + 1);
switch (EXTRACT_16BITS(&spm->pgms_nla_afi)) {
case AFNUM_INET:
ND_TCHECK2(*bp, sizeof(struct in_addr));
addrtostr(bp, nla_buf, sizeof(nla_buf));
bp += sizeof(struct in_addr);
break;
case AFNUM_INET6:
ND_TCHECK2(*bp, sizeof(struct in6_addr));
addrtostr6(bp, nla_buf, sizeof(nla_buf));
bp += sizeof(struct in6_addr);
break;
default:
goto trunc;
break;
}
ND_PRINT((ndo, "SPM seq %u trail %u lead %u nla %s",
EXTRACT_32BITS(&spm->pgms_seq),
EXTRACT_32BITS(&spm->pgms_trailseq),
EXTRACT_32BITS(&spm->pgms_leadseq),
nla_buf));
break;
}
case PGM_POLL: {
const struct pgm_poll *poll_msg;
poll_msg = (const struct pgm_poll *)(pgm + 1);
ND_TCHECK(*poll_msg);
ND_PRINT((ndo, "POLL seq %u round %u",
EXTRACT_32BITS(&poll_msg->pgmp_seq),
EXTRACT_16BITS(&poll_msg->pgmp_round)));
bp = (const u_char *) (poll_msg + 1);
break;
}
case PGM_POLR: {
const struct pgm_polr *polr;
uint32_t ivl, rnd, mask;
polr = (const struct pgm_polr *)(pgm + 1);
ND_TCHECK(*polr);
bp = (const u_char *) (polr + 1);
switch (EXTRACT_16BITS(&polr->pgmp_nla_afi)) {
case AFNUM_INET:
ND_TCHECK2(*bp, sizeof(struct in_addr));
addrtostr(bp, nla_buf, sizeof(nla_buf));
bp += sizeof(struct in_addr);
break;
case AFNUM_INET6:
ND_TCHECK2(*bp, sizeof(struct in6_addr));
addrtostr6(bp, nla_buf, sizeof(nla_buf));
bp += sizeof(struct in6_addr);
break;
default:
goto trunc;
break;
}
ND_TCHECK2(*bp, sizeof(uint32_t));
ivl = EXTRACT_32BITS(bp);
bp += sizeof(uint32_t);
ND_TCHECK2(*bp, sizeof(uint32_t));
rnd = EXTRACT_32BITS(bp);
bp += sizeof(uint32_t);
ND_TCHECK2(*bp, sizeof(uint32_t));
mask = EXTRACT_32BITS(bp);
bp += sizeof(uint32_t);
ND_PRINT((ndo, "POLR seq %u round %u nla %s ivl %u rnd 0x%08x "
"mask 0x%08x", EXTRACT_32BITS(&polr->pgmp_seq),
EXTRACT_16BITS(&polr->pgmp_round), nla_buf, ivl, rnd, mask));
break;
}
case PGM_ODATA: {
const struct pgm_data *odata;
odata = (const struct pgm_data *)(pgm + 1);
ND_TCHECK(*odata);
ND_PRINT((ndo, "ODATA trail %u seq %u",
EXTRACT_32BITS(&odata->pgmd_trailseq),
EXTRACT_32BITS(&odata->pgmd_seq)));
bp = (const u_char *) (odata + 1);
break;
}
case PGM_RDATA: {
const struct pgm_data *rdata;
rdata = (const struct pgm_data *)(pgm + 1);
ND_TCHECK(*rdata);
ND_PRINT((ndo, "RDATA trail %u seq %u",
EXTRACT_32BITS(&rdata->pgmd_trailseq),
EXTRACT_32BITS(&rdata->pgmd_seq)));
bp = (const u_char *) (rdata + 1);
break;
}
case PGM_NAK:
case PGM_NULLNAK:
case PGM_NCF: {
const struct pgm_nak *nak;
char source_buf[INET6_ADDRSTRLEN], group_buf[INET6_ADDRSTRLEN];
nak = (const struct pgm_nak *)(pgm + 1);
ND_TCHECK(*nak);
bp = (const u_char *) (nak + 1);
/*
* Skip past the source, saving info along the way
* and stopping if we don't have enough.
*/
switch (EXTRACT_16BITS(&nak->pgmn_source_afi)) {
case AFNUM_INET:
ND_TCHECK2(*bp, sizeof(struct in_addr));
addrtostr(bp, source_buf, sizeof(source_buf));
bp += sizeof(struct in_addr);
break;
case AFNUM_INET6:
ND_TCHECK2(*bp, sizeof(struct in6_addr));
addrtostr6(bp, source_buf, sizeof(source_buf));
bp += sizeof(struct in6_addr);
break;
default:
goto trunc;
break;
}
/*
* Skip past the group, saving info along the way
* and stopping if we don't have enough.
*/
bp += (2 * sizeof(uint16_t));
switch (EXTRACT_16BITS(bp)) {
case AFNUM_INET:
ND_TCHECK2(*bp, sizeof(struct in_addr));
addrtostr(bp, group_buf, sizeof(group_buf));
bp += sizeof(struct in_addr);
break;
case AFNUM_INET6:
ND_TCHECK2(*bp, sizeof(struct in6_addr));
addrtostr6(bp, group_buf, sizeof(group_buf));
bp += sizeof(struct in6_addr);
break;
default:
goto trunc;
break;
}
/*
* Options decoding can go here.
*/
switch (pgm->pgm_type) {
case PGM_NAK:
ND_PRINT((ndo, "NAK "));
break;
case PGM_NULLNAK:
ND_PRINT((ndo, "NNAK "));
break;
case PGM_NCF:
ND_PRINT((ndo, "NCF "));
break;
default:
break;
}
ND_PRINT((ndo, "(%s -> %s), seq %u",
source_buf, group_buf, EXTRACT_32BITS(&nak->pgmn_seq)));
break;
}
case PGM_ACK: {
const struct pgm_ack *ack;
ack = (const struct pgm_ack *)(pgm + 1);
ND_TCHECK(*ack);
ND_PRINT((ndo, "ACK seq %u",
EXTRACT_32BITS(&ack->pgma_rx_max_seq)));
bp = (const u_char *) (ack + 1);
break;
}
case PGM_SPMR:
ND_PRINT((ndo, "SPMR"));
break;
default:
ND_PRINT((ndo, "UNKNOWN type 0x%02x", pgm->pgm_type));
break;
}
if (pgm->pgm_options & PGM_OPT_BIT_PRESENT) {
/*
* make sure there's enough for the first option header
*/
if (!ND_TTEST2(*bp, PGM_MIN_OPT_LEN)) {
ND_PRINT((ndo, "[|OPT]"));
return;
}
/*
* That option header MUST be an OPT_LENGTH option
* (see the first paragraph of section 9.1 in RFC 3208).
*/
opt_type = *bp++;
if ((opt_type & PGM_OPT_MASK) != PGM_OPT_LENGTH) {
ND_PRINT((ndo, "[First option bad, should be PGM_OPT_LENGTH, is %u]", opt_type & PGM_OPT_MASK));
return;
}
opt_len = *bp++;
if (opt_len != 4) {
ND_PRINT((ndo, "[Bad OPT_LENGTH option, length %u != 4]", opt_len));
return;
}
opts_len = EXTRACT_16BITS(bp);
if (opts_len < 4) {
ND_PRINT((ndo, "[Bad total option length %u < 4]", opts_len));
return;
}
bp += sizeof(uint16_t);
ND_PRINT((ndo, " OPTS LEN %d", opts_len));
opts_len -= 4;
while (opts_len) {
if (opts_len < PGM_MIN_OPT_LEN) {
ND_PRINT((ndo, "[Total option length leaves no room for final option]"));
return;
}
opt_type = *bp++;
opt_len = *bp++;
if (opt_len < PGM_MIN_OPT_LEN) {
ND_PRINT((ndo, "[Bad option, length %u < %u]", opt_len,
PGM_MIN_OPT_LEN));
break;
}
if (opts_len < opt_len) {
ND_PRINT((ndo, "[Total option length leaves no room for final option]"));
return;
}
if (!ND_TTEST2(*bp, opt_len - 2)) {
ND_PRINT((ndo, " [|OPT]"));
return;
}
switch (opt_type & PGM_OPT_MASK) {
case PGM_OPT_LENGTH:
if (opt_len != 4) {
ND_PRINT((ndo, "[Bad OPT_LENGTH option, length %u != 4]", opt_len));
return;
}
ND_PRINT((ndo, " OPTS LEN (extra?) %d", EXTRACT_16BITS(bp)));
bp += sizeof(uint16_t);
opts_len -= 4;
break;
case PGM_OPT_FRAGMENT:
if (opt_len != 16) {
ND_PRINT((ndo, "[Bad OPT_FRAGMENT option, length %u != 16]", opt_len));
return;
}
bp += 2;
seq = EXTRACT_32BITS(bp);
bp += sizeof(uint32_t);
offset = EXTRACT_32BITS(bp);
bp += sizeof(uint32_t);
len = EXTRACT_32BITS(bp);
bp += sizeof(uint32_t);
ND_PRINT((ndo, " FRAG seq %u off %u len %u", seq, offset, len));
opts_len -= 16;
break;
case PGM_OPT_NAK_LIST:
bp += 2;
opt_len -= sizeof(uint32_t); /* option header */
ND_PRINT((ndo, " NAK LIST"));
while (opt_len) {
if (opt_len < sizeof(uint32_t)) {
ND_PRINT((ndo, "[Option length not a multiple of 4]"));
return;
}
ND_TCHECK2(*bp, sizeof(uint32_t));
ND_PRINT((ndo, " %u", EXTRACT_32BITS(bp)));
bp += sizeof(uint32_t);
opt_len -= sizeof(uint32_t);
opts_len -= sizeof(uint32_t);
}
break;
case PGM_OPT_JOIN:
if (opt_len != 8) {
ND_PRINT((ndo, "[Bad OPT_JOIN option, length %u != 8]", opt_len));
return;
}
bp += 2;
seq = EXTRACT_32BITS(bp);
bp += sizeof(uint32_t);
ND_PRINT((ndo, " JOIN %u", seq));
opts_len -= 8;
break;
case PGM_OPT_NAK_BO_IVL:
if (opt_len != 12) {
ND_PRINT((ndo, "[Bad OPT_NAK_BO_IVL option, length %u != 12]", opt_len));
return;
}
bp += 2;
offset = EXTRACT_32BITS(bp);
bp += sizeof(uint32_t);
seq = EXTRACT_32BITS(bp);
bp += sizeof(uint32_t);
ND_PRINT((ndo, " BACKOFF ivl %u ivlseq %u", offset, seq));
opts_len -= 12;
break;
case PGM_OPT_NAK_BO_RNG:
if (opt_len != 12) {
ND_PRINT((ndo, "[Bad OPT_NAK_BO_RNG option, length %u != 12]", opt_len));
return;
}
bp += 2;
offset = EXTRACT_32BITS(bp);
bp += sizeof(uint32_t);
seq = EXTRACT_32BITS(bp);
bp += sizeof(uint32_t);
ND_PRINT((ndo, " BACKOFF max %u min %u", offset, seq));
opts_len -= 12;
break;
case PGM_OPT_REDIRECT:
bp += 2;
nla_afnum = EXTRACT_16BITS(bp);
bp += (2 * sizeof(uint16_t));
switch (nla_afnum) {
case AFNUM_INET:
if (opt_len != 4 + sizeof(struct in_addr)) {
ND_PRINT((ndo, "[Bad OPT_REDIRECT option, length %u != 4 + address size]", opt_len));
return;
}
ND_TCHECK2(*bp, sizeof(struct in_addr));
addrtostr(bp, nla_buf, sizeof(nla_buf));
bp += sizeof(struct in_addr);
opts_len -= 4 + sizeof(struct in_addr);
break;
case AFNUM_INET6:
if (opt_len != 4 + sizeof(struct in6_addr)) {
ND_PRINT((ndo, "[Bad OPT_REDIRECT option, length %u != 4 + address size]", opt_len));
return;
}
ND_TCHECK2(*bp, sizeof(struct in6_addr));
addrtostr6(bp, nla_buf, sizeof(nla_buf));
bp += sizeof(struct in6_addr);
opts_len -= 4 + sizeof(struct in6_addr);
break;
default:
goto trunc;
break;
}
ND_PRINT((ndo, " REDIRECT %s", nla_buf));
break;
case PGM_OPT_PARITY_PRM:
if (opt_len != 8) {
ND_PRINT((ndo, "[Bad OPT_PARITY_PRM option, length %u != 8]", opt_len));
return;
}
bp += 2;
len = EXTRACT_32BITS(bp);
bp += sizeof(uint32_t);
ND_PRINT((ndo, " PARITY MAXTGS %u", len));
opts_len -= 8;
break;
case PGM_OPT_PARITY_GRP:
if (opt_len != 8) {
ND_PRINT((ndo, "[Bad OPT_PARITY_GRP option, length %u != 8]", opt_len));
return;
}
bp += 2;
seq = EXTRACT_32BITS(bp);
bp += sizeof(uint32_t);
ND_PRINT((ndo, " PARITY GROUP %u", seq));
opts_len -= 8;
break;
case PGM_OPT_CURR_TGSIZE:
if (opt_len != 8) {
ND_PRINT((ndo, "[Bad OPT_CURR_TGSIZE option, length %u != 8]", opt_len));
return;
}
bp += 2;
len = EXTRACT_32BITS(bp);
bp += sizeof(uint32_t);
ND_PRINT((ndo, " PARITY ATGS %u", len));
opts_len -= 8;
break;
case PGM_OPT_NBR_UNREACH:
if (opt_len != 4) {
ND_PRINT((ndo, "[Bad OPT_NBR_UNREACH option, length %u != 4]", opt_len));
return;
}
bp += 2;
ND_PRINT((ndo, " NBR_UNREACH"));
opts_len -= 4;
break;
case PGM_OPT_PATH_NLA:
ND_PRINT((ndo, " PATH_NLA [%d]", opt_len));
bp += opt_len;
opts_len -= opt_len;
break;
case PGM_OPT_SYN:
if (opt_len != 4) {
ND_PRINT((ndo, "[Bad OPT_SYN option, length %u != 4]", opt_len));
return;
}
bp += 2;
ND_PRINT((ndo, " SYN"));
opts_len -= 4;
break;
case PGM_OPT_FIN:
if (opt_len != 4) {
ND_PRINT((ndo, "[Bad OPT_FIN option, length %u != 4]", opt_len));
return;
}
bp += 2;
ND_PRINT((ndo, " FIN"));
opts_len -= 4;
break;
case PGM_OPT_RST:
if (opt_len != 4) {
ND_PRINT((ndo, "[Bad OPT_RST option, length %u != 4]", opt_len));
return;
}
bp += 2;
ND_PRINT((ndo, " RST"));
opts_len -= 4;
break;
case PGM_OPT_CR:
ND_PRINT((ndo, " CR"));
bp += opt_len;
opts_len -= opt_len;
break;
case PGM_OPT_CRQST:
if (opt_len != 4) {
ND_PRINT((ndo, "[Bad OPT_CRQST option, length %u != 4]", opt_len));
return;
}
bp += 2;
ND_PRINT((ndo, " CRQST"));
opts_len -= 4;
break;
case PGM_OPT_PGMCC_DATA:
bp += 2;
offset = EXTRACT_32BITS(bp);
bp += sizeof(uint32_t);
nla_afnum = EXTRACT_16BITS(bp);
bp += (2 * sizeof(uint16_t));
switch (nla_afnum) {
case AFNUM_INET:
if (opt_len != 12 + sizeof(struct in_addr)) {
ND_PRINT((ndo, "[Bad OPT_PGMCC_DATA option, length %u != 12 + address size]", opt_len));
return;
}
ND_TCHECK2(*bp, sizeof(struct in_addr));
addrtostr(bp, nla_buf, sizeof(nla_buf));
bp += sizeof(struct in_addr);
opts_len -= 12 + sizeof(struct in_addr);
break;
case AFNUM_INET6:
if (opt_len != 12 + sizeof(struct in6_addr)) {
ND_PRINT((ndo, "[Bad OPT_PGMCC_DATA option, length %u != 12 + address size]", opt_len));
return;
}
ND_TCHECK2(*bp, sizeof(struct in6_addr));
addrtostr6(bp, nla_buf, sizeof(nla_buf));
bp += sizeof(struct in6_addr);
opts_len -= 12 + sizeof(struct in6_addr);
break;
default:
goto trunc;
break;
}
ND_PRINT((ndo, " PGMCC DATA %u %s", offset, nla_buf));
break;
case PGM_OPT_PGMCC_FEEDBACK:
bp += 2;
offset = EXTRACT_32BITS(bp);
bp += sizeof(uint32_t);
nla_afnum = EXTRACT_16BITS(bp);
bp += (2 * sizeof(uint16_t));
switch (nla_afnum) {
case AFNUM_INET:
if (opt_len != 12 + sizeof(struct in_addr)) {
ND_PRINT((ndo, "[Bad OPT_PGMCC_DATA option, length %u != 12 + address size]", opt_len));
return;
}
ND_TCHECK2(*bp, sizeof(struct in_addr));
addrtostr(bp, nla_buf, sizeof(nla_buf));
bp += sizeof(struct in_addr);
opts_len -= 12 + sizeof(struct in_addr);
break;
case AFNUM_INET6:
if (opt_len != 12 + sizeof(struct in6_addr)) {
ND_PRINT((ndo, "[Bad OPT_PGMCC_DATA option, length %u != 12 + address size]", opt_len));
return;
}
ND_TCHECK2(*bp, sizeof(struct in6_addr));
addrtostr6(bp, nla_buf, sizeof(nla_buf));
bp += sizeof(struct in6_addr);
opts_len -= 12 + sizeof(struct in6_addr);
break;
default:
goto trunc;
break;
}
ND_PRINT((ndo, " PGMCC FEEDBACK %u %s", offset, nla_buf));
break;
default:
ND_PRINT((ndo, " OPT_%02X [%d] ", opt_type, opt_len));
bp += opt_len;
opts_len -= opt_len;
break;
}
if (opt_type & PGM_OPT_END)
break;
}
}
ND_PRINT((ndo, " [%u]", length));
if (ndo->ndo_packettype == PT_PGM_ZMTP1 &&
(pgm->pgm_type == PGM_ODATA || pgm->pgm_type == PGM_RDATA))
zmtp1_print_datagram(ndo, bp, EXTRACT_16BITS(&pgm->pgm_length));
return;
trunc:
ND_PRINT((ndo, "[|pgm]"));
if (ch != '\0')
ND_PRINT((ndo, ">"));
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_2693_0 |
crossvul-cpp_data_good_2660_0 | /*
* Copyright (c) 2001
* Fortress Technologies, Inc. All rights reserved.
* Charlie Lenahan (clenahan@fortresstech.com)
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that: (1) source code distributions
* retain the above copyright notice and this paragraph in its entirety, (2)
* distributions including binary code include the above copyright notice and
* this paragraph in its entirety in the documentation or other materials
* provided with the distribution, and (3) all advertising materials mentioning
* features or use of this software display the following acknowledgement:
* ``This product includes software developed by the University of California,
* Lawrence Berkeley Laboratory and its contributors.'' Neither the name of
* the University nor the names of its contributors may be used to endorse
* or promote products derived from this software without specific prior
* written permission.
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
/* \summary: IEEE 802.11 printer */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <netdissect-stdinc.h>
#include <string.h>
#include "netdissect.h"
#include "addrtoname.h"
#include "extract.h"
#include "cpack.h"
/* Lengths of 802.11 header components. */
#define IEEE802_11_FC_LEN 2
#define IEEE802_11_DUR_LEN 2
#define IEEE802_11_DA_LEN 6
#define IEEE802_11_SA_LEN 6
#define IEEE802_11_BSSID_LEN 6
#define IEEE802_11_RA_LEN 6
#define IEEE802_11_TA_LEN 6
#define IEEE802_11_ADDR1_LEN 6
#define IEEE802_11_SEQ_LEN 2
#define IEEE802_11_CTL_LEN 2
#define IEEE802_11_CARRIED_FC_LEN 2
#define IEEE802_11_HT_CONTROL_LEN 4
#define IEEE802_11_IV_LEN 3
#define IEEE802_11_KID_LEN 1
/* Frame check sequence length. */
#define IEEE802_11_FCS_LEN 4
/* Lengths of beacon components. */
#define IEEE802_11_TSTAMP_LEN 8
#define IEEE802_11_BCNINT_LEN 2
#define IEEE802_11_CAPINFO_LEN 2
#define IEEE802_11_LISTENINT_LEN 2
#define IEEE802_11_AID_LEN 2
#define IEEE802_11_STATUS_LEN 2
#define IEEE802_11_REASON_LEN 2
/* Length of previous AP in reassocation frame */
#define IEEE802_11_AP_LEN 6
#define T_MGMT 0x0 /* management */
#define T_CTRL 0x1 /* control */
#define T_DATA 0x2 /* data */
#define T_RESV 0x3 /* reserved */
#define ST_ASSOC_REQUEST 0x0
#define ST_ASSOC_RESPONSE 0x1
#define ST_REASSOC_REQUEST 0x2
#define ST_REASSOC_RESPONSE 0x3
#define ST_PROBE_REQUEST 0x4
#define ST_PROBE_RESPONSE 0x5
/* RESERVED 0x6 */
/* RESERVED 0x7 */
#define ST_BEACON 0x8
#define ST_ATIM 0x9
#define ST_DISASSOC 0xA
#define ST_AUTH 0xB
#define ST_DEAUTH 0xC
#define ST_ACTION 0xD
/* RESERVED 0xE */
/* RESERVED 0xF */
static const struct tok st_str[] = {
{ ST_ASSOC_REQUEST, "Assoc Request" },
{ ST_ASSOC_RESPONSE, "Assoc Response" },
{ ST_REASSOC_REQUEST, "ReAssoc Request" },
{ ST_REASSOC_RESPONSE, "ReAssoc Response" },
{ ST_PROBE_REQUEST, "Probe Request" },
{ ST_PROBE_RESPONSE, "Probe Response" },
{ ST_BEACON, "Beacon" },
{ ST_ATIM, "ATIM" },
{ ST_DISASSOC, "Disassociation" },
{ ST_AUTH, "Authentication" },
{ ST_DEAUTH, "DeAuthentication" },
{ ST_ACTION, "Action" },
{ 0, NULL }
};
#define CTRL_CONTROL_WRAPPER 0x7
#define CTRL_BAR 0x8
#define CTRL_BA 0x9
#define CTRL_PS_POLL 0xA
#define CTRL_RTS 0xB
#define CTRL_CTS 0xC
#define CTRL_ACK 0xD
#define CTRL_CF_END 0xE
#define CTRL_END_ACK 0xF
static const struct tok ctrl_str[] = {
{ CTRL_CONTROL_WRAPPER, "Control Wrapper" },
{ CTRL_BAR, "BAR" },
{ CTRL_BA, "BA" },
{ CTRL_PS_POLL, "Power Save-Poll" },
{ CTRL_RTS, "Request-To-Send" },
{ CTRL_CTS, "Clear-To-Send" },
{ CTRL_ACK, "Acknowledgment" },
{ CTRL_CF_END, "CF-End" },
{ CTRL_END_ACK, "CF-End+CF-Ack" },
{ 0, NULL }
};
#define DATA_DATA 0x0
#define DATA_DATA_CF_ACK 0x1
#define DATA_DATA_CF_POLL 0x2
#define DATA_DATA_CF_ACK_POLL 0x3
#define DATA_NODATA 0x4
#define DATA_NODATA_CF_ACK 0x5
#define DATA_NODATA_CF_POLL 0x6
#define DATA_NODATA_CF_ACK_POLL 0x7
#define DATA_QOS_DATA 0x8
#define DATA_QOS_DATA_CF_ACK 0x9
#define DATA_QOS_DATA_CF_POLL 0xA
#define DATA_QOS_DATA_CF_ACK_POLL 0xB
#define DATA_QOS_NODATA 0xC
#define DATA_QOS_CF_POLL_NODATA 0xE
#define DATA_QOS_CF_ACK_POLL_NODATA 0xF
/*
* The subtype field of a data frame is, in effect, composed of 4 flag
* bits - CF-Ack, CF-Poll, Null (means the frame doesn't actually have
* any data), and QoS.
*/
#define DATA_FRAME_IS_CF_ACK(x) ((x) & 0x01)
#define DATA_FRAME_IS_CF_POLL(x) ((x) & 0x02)
#define DATA_FRAME_IS_NULL(x) ((x) & 0x04)
#define DATA_FRAME_IS_QOS(x) ((x) & 0x08)
/*
* Bits in the frame control field.
*/
#define FC_VERSION(fc) ((fc) & 0x3)
#define FC_TYPE(fc) (((fc) >> 2) & 0x3)
#define FC_SUBTYPE(fc) (((fc) >> 4) & 0xF)
#define FC_TO_DS(fc) ((fc) & 0x0100)
#define FC_FROM_DS(fc) ((fc) & 0x0200)
#define FC_MORE_FLAG(fc) ((fc) & 0x0400)
#define FC_RETRY(fc) ((fc) & 0x0800)
#define FC_POWER_MGMT(fc) ((fc) & 0x1000)
#define FC_MORE_DATA(fc) ((fc) & 0x2000)
#define FC_PROTECTED(fc) ((fc) & 0x4000)
#define FC_ORDER(fc) ((fc) & 0x8000)
struct mgmt_header_t {
uint16_t fc;
uint16_t duration;
uint8_t da[IEEE802_11_DA_LEN];
uint8_t sa[IEEE802_11_SA_LEN];
uint8_t bssid[IEEE802_11_BSSID_LEN];
uint16_t seq_ctrl;
};
#define MGMT_HDRLEN (IEEE802_11_FC_LEN+IEEE802_11_DUR_LEN+\
IEEE802_11_DA_LEN+IEEE802_11_SA_LEN+\
IEEE802_11_BSSID_LEN+IEEE802_11_SEQ_LEN)
#define CAPABILITY_ESS(cap) ((cap) & 0x0001)
#define CAPABILITY_IBSS(cap) ((cap) & 0x0002)
#define CAPABILITY_CFP(cap) ((cap) & 0x0004)
#define CAPABILITY_CFP_REQ(cap) ((cap) & 0x0008)
#define CAPABILITY_PRIVACY(cap) ((cap) & 0x0010)
struct ssid_t {
uint8_t element_id;
uint8_t length;
u_char ssid[33]; /* 32 + 1 for null */
};
struct rates_t {
uint8_t element_id;
uint8_t length;
uint8_t rate[16];
};
struct challenge_t {
uint8_t element_id;
uint8_t length;
uint8_t text[254]; /* 1-253 + 1 for null */
};
struct fh_t {
uint8_t element_id;
uint8_t length;
uint16_t dwell_time;
uint8_t hop_set;
uint8_t hop_pattern;
uint8_t hop_index;
};
struct ds_t {
uint8_t element_id;
uint8_t length;
uint8_t channel;
};
struct cf_t {
uint8_t element_id;
uint8_t length;
uint8_t count;
uint8_t period;
uint16_t max_duration;
uint16_t dur_remaing;
};
struct tim_t {
uint8_t element_id;
uint8_t length;
uint8_t count;
uint8_t period;
uint8_t bitmap_control;
uint8_t bitmap[251];
};
#define E_SSID 0
#define E_RATES 1
#define E_FH 2
#define E_DS 3
#define E_CF 4
#define E_TIM 5
#define E_IBSS 6
/* reserved 7 */
/* reserved 8 */
/* reserved 9 */
/* reserved 10 */
/* reserved 11 */
/* reserved 12 */
/* reserved 13 */
/* reserved 14 */
/* reserved 15 */
/* reserved 16 */
#define E_CHALLENGE 16
/* reserved 17 */
/* reserved 18 */
/* reserved 19 */
/* reserved 16 */
/* reserved 16 */
struct mgmt_body_t {
uint8_t timestamp[IEEE802_11_TSTAMP_LEN];
uint16_t beacon_interval;
uint16_t listen_interval;
uint16_t status_code;
uint16_t aid;
u_char ap[IEEE802_11_AP_LEN];
uint16_t reason_code;
uint16_t auth_alg;
uint16_t auth_trans_seq_num;
int challenge_present;
struct challenge_t challenge;
uint16_t capability_info;
int ssid_present;
struct ssid_t ssid;
int rates_present;
struct rates_t rates;
int ds_present;
struct ds_t ds;
int cf_present;
struct cf_t cf;
int fh_present;
struct fh_t fh;
int tim_present;
struct tim_t tim;
};
struct ctrl_control_wrapper_hdr_t {
uint16_t fc;
uint16_t duration;
uint8_t addr1[IEEE802_11_ADDR1_LEN];
uint16_t carried_fc[IEEE802_11_CARRIED_FC_LEN];
uint16_t ht_control[IEEE802_11_HT_CONTROL_LEN];
};
#define CTRL_CONTROL_WRAPPER_HDRLEN (IEEE802_11_FC_LEN+IEEE802_11_DUR_LEN+\
IEEE802_11_ADDR1_LEN+\
IEEE802_11_CARRIED_FC_LEN+\
IEEE802_11_HT_CONTROL_LEN)
struct ctrl_rts_hdr_t {
uint16_t fc;
uint16_t duration;
uint8_t ra[IEEE802_11_RA_LEN];
uint8_t ta[IEEE802_11_TA_LEN];
};
#define CTRL_RTS_HDRLEN (IEEE802_11_FC_LEN+IEEE802_11_DUR_LEN+\
IEEE802_11_RA_LEN+IEEE802_11_TA_LEN)
struct ctrl_cts_hdr_t {
uint16_t fc;
uint16_t duration;
uint8_t ra[IEEE802_11_RA_LEN];
};
#define CTRL_CTS_HDRLEN (IEEE802_11_FC_LEN+IEEE802_11_DUR_LEN+IEEE802_11_RA_LEN)
struct ctrl_ack_hdr_t {
uint16_t fc;
uint16_t duration;
uint8_t ra[IEEE802_11_RA_LEN];
};
#define CTRL_ACK_HDRLEN (IEEE802_11_FC_LEN+IEEE802_11_DUR_LEN+IEEE802_11_RA_LEN)
struct ctrl_ps_poll_hdr_t {
uint16_t fc;
uint16_t aid;
uint8_t bssid[IEEE802_11_BSSID_LEN];
uint8_t ta[IEEE802_11_TA_LEN];
};
#define CTRL_PS_POLL_HDRLEN (IEEE802_11_FC_LEN+IEEE802_11_AID_LEN+\
IEEE802_11_BSSID_LEN+IEEE802_11_TA_LEN)
struct ctrl_end_hdr_t {
uint16_t fc;
uint16_t duration;
uint8_t ra[IEEE802_11_RA_LEN];
uint8_t bssid[IEEE802_11_BSSID_LEN];
};
#define CTRL_END_HDRLEN (IEEE802_11_FC_LEN+IEEE802_11_DUR_LEN+\
IEEE802_11_RA_LEN+IEEE802_11_BSSID_LEN)
struct ctrl_end_ack_hdr_t {
uint16_t fc;
uint16_t duration;
uint8_t ra[IEEE802_11_RA_LEN];
uint8_t bssid[IEEE802_11_BSSID_LEN];
};
#define CTRL_END_ACK_HDRLEN (IEEE802_11_FC_LEN+IEEE802_11_DUR_LEN+\
IEEE802_11_RA_LEN+IEEE802_11_BSSID_LEN)
struct ctrl_ba_hdr_t {
uint16_t fc;
uint16_t duration;
uint8_t ra[IEEE802_11_RA_LEN];
};
#define CTRL_BA_HDRLEN (IEEE802_11_FC_LEN+IEEE802_11_DUR_LEN+IEEE802_11_RA_LEN)
struct ctrl_bar_hdr_t {
uint16_t fc;
uint16_t dur;
uint8_t ra[IEEE802_11_RA_LEN];
uint8_t ta[IEEE802_11_TA_LEN];
uint16_t ctl;
uint16_t seq;
};
#define CTRL_BAR_HDRLEN (IEEE802_11_FC_LEN+IEEE802_11_DUR_LEN+\
IEEE802_11_RA_LEN+IEEE802_11_TA_LEN+\
IEEE802_11_CTL_LEN+IEEE802_11_SEQ_LEN)
struct meshcntl_t {
uint8_t flags;
uint8_t ttl;
uint8_t seq[4];
uint8_t addr4[6];
uint8_t addr5[6];
uint8_t addr6[6];
};
#define IV_IV(iv) ((iv) & 0xFFFFFF)
#define IV_PAD(iv) (((iv) >> 24) & 0x3F)
#define IV_KEYID(iv) (((iv) >> 30) & 0x03)
#define PRINT_SSID(p) \
if (p.ssid_present) { \
ND_PRINT((ndo, " (")); \
fn_print(ndo, p.ssid.ssid, NULL); \
ND_PRINT((ndo, ")")); \
}
#define PRINT_RATE(_sep, _r, _suf) \
ND_PRINT((ndo, "%s%2.1f%s", _sep, (.5 * ((_r) & 0x7f)), _suf))
#define PRINT_RATES(p) \
if (p.rates_present) { \
int z; \
const char *sep = " ["; \
for (z = 0; z < p.rates.length ; z++) { \
PRINT_RATE(sep, p.rates.rate[z], \
(p.rates.rate[z] & 0x80 ? "*" : "")); \
sep = " "; \
} \
if (p.rates.length != 0) \
ND_PRINT((ndo, " Mbit]")); \
}
#define PRINT_DS_CHANNEL(p) \
if (p.ds_present) \
ND_PRINT((ndo, " CH: %u", p.ds.channel)); \
ND_PRINT((ndo, "%s", \
CAPABILITY_PRIVACY(p.capability_info) ? ", PRIVACY" : ""));
#define MAX_MCS_INDEX 76
/*
* Indices are:
*
* the MCS index (0-76);
*
* 0 for 20 MHz, 1 for 40 MHz;
*
* 0 for a long guard interval, 1 for a short guard interval.
*/
static const float ieee80211_float_htrates[MAX_MCS_INDEX+1][2][2] = {
/* MCS 0 */
{ /* 20 Mhz */ { 6.5, /* SGI */ 7.2, },
/* 40 Mhz */ { 13.5, /* SGI */ 15.0, },
},
/* MCS 1 */
{ /* 20 Mhz */ { 13.0, /* SGI */ 14.4, },
/* 40 Mhz */ { 27.0, /* SGI */ 30.0, },
},
/* MCS 2 */
{ /* 20 Mhz */ { 19.5, /* SGI */ 21.7, },
/* 40 Mhz */ { 40.5, /* SGI */ 45.0, },
},
/* MCS 3 */
{ /* 20 Mhz */ { 26.0, /* SGI */ 28.9, },
/* 40 Mhz */ { 54.0, /* SGI */ 60.0, },
},
/* MCS 4 */
{ /* 20 Mhz */ { 39.0, /* SGI */ 43.3, },
/* 40 Mhz */ { 81.0, /* SGI */ 90.0, },
},
/* MCS 5 */
{ /* 20 Mhz */ { 52.0, /* SGI */ 57.8, },
/* 40 Mhz */ { 108.0, /* SGI */ 120.0, },
},
/* MCS 6 */
{ /* 20 Mhz */ { 58.5, /* SGI */ 65.0, },
/* 40 Mhz */ { 121.5, /* SGI */ 135.0, },
},
/* MCS 7 */
{ /* 20 Mhz */ { 65.0, /* SGI */ 72.2, },
/* 40 Mhz */ { 135.0, /* SGI */ 150.0, },
},
/* MCS 8 */
{ /* 20 Mhz */ { 13.0, /* SGI */ 14.4, },
/* 40 Mhz */ { 27.0, /* SGI */ 30.0, },
},
/* MCS 9 */
{ /* 20 Mhz */ { 26.0, /* SGI */ 28.9, },
/* 40 Mhz */ { 54.0, /* SGI */ 60.0, },
},
/* MCS 10 */
{ /* 20 Mhz */ { 39.0, /* SGI */ 43.3, },
/* 40 Mhz */ { 81.0, /* SGI */ 90.0, },
},
/* MCS 11 */
{ /* 20 Mhz */ { 52.0, /* SGI */ 57.8, },
/* 40 Mhz */ { 108.0, /* SGI */ 120.0, },
},
/* MCS 12 */
{ /* 20 Mhz */ { 78.0, /* SGI */ 86.7, },
/* 40 Mhz */ { 162.0, /* SGI */ 180.0, },
},
/* MCS 13 */
{ /* 20 Mhz */ { 104.0, /* SGI */ 115.6, },
/* 40 Mhz */ { 216.0, /* SGI */ 240.0, },
},
/* MCS 14 */
{ /* 20 Mhz */ { 117.0, /* SGI */ 130.0, },
/* 40 Mhz */ { 243.0, /* SGI */ 270.0, },
},
/* MCS 15 */
{ /* 20 Mhz */ { 130.0, /* SGI */ 144.4, },
/* 40 Mhz */ { 270.0, /* SGI */ 300.0, },
},
/* MCS 16 */
{ /* 20 Mhz */ { 19.5, /* SGI */ 21.7, },
/* 40 Mhz */ { 40.5, /* SGI */ 45.0, },
},
/* MCS 17 */
{ /* 20 Mhz */ { 39.0, /* SGI */ 43.3, },
/* 40 Mhz */ { 81.0, /* SGI */ 90.0, },
},
/* MCS 18 */
{ /* 20 Mhz */ { 58.5, /* SGI */ 65.0, },
/* 40 Mhz */ { 121.5, /* SGI */ 135.0, },
},
/* MCS 19 */
{ /* 20 Mhz */ { 78.0, /* SGI */ 86.7, },
/* 40 Mhz */ { 162.0, /* SGI */ 180.0, },
},
/* MCS 20 */
{ /* 20 Mhz */ { 117.0, /* SGI */ 130.0, },
/* 40 Mhz */ { 243.0, /* SGI */ 270.0, },
},
/* MCS 21 */
{ /* 20 Mhz */ { 156.0, /* SGI */ 173.3, },
/* 40 Mhz */ { 324.0, /* SGI */ 360.0, },
},
/* MCS 22 */
{ /* 20 Mhz */ { 175.5, /* SGI */ 195.0, },
/* 40 Mhz */ { 364.5, /* SGI */ 405.0, },
},
/* MCS 23 */
{ /* 20 Mhz */ { 195.0, /* SGI */ 216.7, },
/* 40 Mhz */ { 405.0, /* SGI */ 450.0, },
},
/* MCS 24 */
{ /* 20 Mhz */ { 26.0, /* SGI */ 28.9, },
/* 40 Mhz */ { 54.0, /* SGI */ 60.0, },
},
/* MCS 25 */
{ /* 20 Mhz */ { 52.0, /* SGI */ 57.8, },
/* 40 Mhz */ { 108.0, /* SGI */ 120.0, },
},
/* MCS 26 */
{ /* 20 Mhz */ { 78.0, /* SGI */ 86.7, },
/* 40 Mhz */ { 162.0, /* SGI */ 180.0, },
},
/* MCS 27 */
{ /* 20 Mhz */ { 104.0, /* SGI */ 115.6, },
/* 40 Mhz */ { 216.0, /* SGI */ 240.0, },
},
/* MCS 28 */
{ /* 20 Mhz */ { 156.0, /* SGI */ 173.3, },
/* 40 Mhz */ { 324.0, /* SGI */ 360.0, },
},
/* MCS 29 */
{ /* 20 Mhz */ { 208.0, /* SGI */ 231.1, },
/* 40 Mhz */ { 432.0, /* SGI */ 480.0, },
},
/* MCS 30 */
{ /* 20 Mhz */ { 234.0, /* SGI */ 260.0, },
/* 40 Mhz */ { 486.0, /* SGI */ 540.0, },
},
/* MCS 31 */
{ /* 20 Mhz */ { 260.0, /* SGI */ 288.9, },
/* 40 Mhz */ { 540.0, /* SGI */ 600.0, },
},
/* MCS 32 */
{ /* 20 Mhz */ { 0.0, /* SGI */ 0.0, }, /* not valid */
/* 40 Mhz */ { 6.0, /* SGI */ 6.7, },
},
/* MCS 33 */
{ /* 20 Mhz */ { 39.0, /* SGI */ 43.3, },
/* 40 Mhz */ { 81.0, /* SGI */ 90.0, },
},
/* MCS 34 */
{ /* 20 Mhz */ { 52.0, /* SGI */ 57.8, },
/* 40 Mhz */ { 108.0, /* SGI */ 120.0, },
},
/* MCS 35 */
{ /* 20 Mhz */ { 65.0, /* SGI */ 72.2, },
/* 40 Mhz */ { 135.0, /* SGI */ 150.0, },
},
/* MCS 36 */
{ /* 20 Mhz */ { 58.5, /* SGI */ 65.0, },
/* 40 Mhz */ { 121.5, /* SGI */ 135.0, },
},
/* MCS 37 */
{ /* 20 Mhz */ { 78.0, /* SGI */ 86.7, },
/* 40 Mhz */ { 162.0, /* SGI */ 180.0, },
},
/* MCS 38 */
{ /* 20 Mhz */ { 97.5, /* SGI */ 108.3, },
/* 40 Mhz */ { 202.5, /* SGI */ 225.0, },
},
/* MCS 39 */
{ /* 20 Mhz */ { 52.0, /* SGI */ 57.8, },
/* 40 Mhz */ { 108.0, /* SGI */ 120.0, },
},
/* MCS 40 */
{ /* 20 Mhz */ { 65.0, /* SGI */ 72.2, },
/* 40 Mhz */ { 135.0, /* SGI */ 150.0, },
},
/* MCS 41 */
{ /* 20 Mhz */ { 65.0, /* SGI */ 72.2, },
/* 40 Mhz */ { 135.0, /* SGI */ 150.0, },
},
/* MCS 42 */
{ /* 20 Mhz */ { 78.0, /* SGI */ 86.7, },
/* 40 Mhz */ { 162.0, /* SGI */ 180.0, },
},
/* MCS 43 */
{ /* 20 Mhz */ { 91.0, /* SGI */ 101.1, },
/* 40 Mhz */ { 189.0, /* SGI */ 210.0, },
},
/* MCS 44 */
{ /* 20 Mhz */ { 91.0, /* SGI */ 101.1, },
/* 40 Mhz */ { 189.0, /* SGI */ 210.0, },
},
/* MCS 45 */
{ /* 20 Mhz */ { 104.0, /* SGI */ 115.6, },
/* 40 Mhz */ { 216.0, /* SGI */ 240.0, },
},
/* MCS 46 */
{ /* 20 Mhz */ { 78.0, /* SGI */ 86.7, },
/* 40 Mhz */ { 162.0, /* SGI */ 180.0, },
},
/* MCS 47 */
{ /* 20 Mhz */ { 97.5, /* SGI */ 108.3, },
/* 40 Mhz */ { 202.5, /* SGI */ 225.0, },
},
/* MCS 48 */
{ /* 20 Mhz */ { 97.5, /* SGI */ 108.3, },
/* 40 Mhz */ { 202.5, /* SGI */ 225.0, },
},
/* MCS 49 */
{ /* 20 Mhz */ { 117.0, /* SGI */ 130.0, },
/* 40 Mhz */ { 243.0, /* SGI */ 270.0, },
},
/* MCS 50 */
{ /* 20 Mhz */ { 136.5, /* SGI */ 151.7, },
/* 40 Mhz */ { 283.5, /* SGI */ 315.0, },
},
/* MCS 51 */
{ /* 20 Mhz */ { 136.5, /* SGI */ 151.7, },
/* 40 Mhz */ { 283.5, /* SGI */ 315.0, },
},
/* MCS 52 */
{ /* 20 Mhz */ { 156.0, /* SGI */ 173.3, },
/* 40 Mhz */ { 324.0, /* SGI */ 360.0, },
},
/* MCS 53 */
{ /* 20 Mhz */ { 65.0, /* SGI */ 72.2, },
/* 40 Mhz */ { 135.0, /* SGI */ 150.0, },
},
/* MCS 54 */
{ /* 20 Mhz */ { 78.0, /* SGI */ 86.7, },
/* 40 Mhz */ { 162.0, /* SGI */ 180.0, },
},
/* MCS 55 */
{ /* 20 Mhz */ { 91.0, /* SGI */ 101.1, },
/* 40 Mhz */ { 189.0, /* SGI */ 210.0, },
},
/* MCS 56 */
{ /* 20 Mhz */ { 78.0, /* SGI */ 86.7, },
/* 40 Mhz */ { 162.0, /* SGI */ 180.0, },
},
/* MCS 57 */
{ /* 20 Mhz */ { 91.0, /* SGI */ 101.1, },
/* 40 Mhz */ { 189.0, /* SGI */ 210.0, },
},
/* MCS 58 */
{ /* 20 Mhz */ { 104.0, /* SGI */ 115.6, },
/* 40 Mhz */ { 216.0, /* SGI */ 240.0, },
},
/* MCS 59 */
{ /* 20 Mhz */ { 117.0, /* SGI */ 130.0, },
/* 40 Mhz */ { 243.0, /* SGI */ 270.0, },
},
/* MCS 60 */
{ /* 20 Mhz */ { 104.0, /* SGI */ 115.6, },
/* 40 Mhz */ { 216.0, /* SGI */ 240.0, },
},
/* MCS 61 */
{ /* 20 Mhz */ { 117.0, /* SGI */ 130.0, },
/* 40 Mhz */ { 243.0, /* SGI */ 270.0, },
},
/* MCS 62 */
{ /* 20 Mhz */ { 130.0, /* SGI */ 144.4, },
/* 40 Mhz */ { 270.0, /* SGI */ 300.0, },
},
/* MCS 63 */
{ /* 20 Mhz */ { 130.0, /* SGI */ 144.4, },
/* 40 Mhz */ { 270.0, /* SGI */ 300.0, },
},
/* MCS 64 */
{ /* 20 Mhz */ { 143.0, /* SGI */ 158.9, },
/* 40 Mhz */ { 297.0, /* SGI */ 330.0, },
},
/* MCS 65 */
{ /* 20 Mhz */ { 97.5, /* SGI */ 108.3, },
/* 40 Mhz */ { 202.5, /* SGI */ 225.0, },
},
/* MCS 66 */
{ /* 20 Mhz */ { 117.0, /* SGI */ 130.0, },
/* 40 Mhz */ { 243.0, /* SGI */ 270.0, },
},
/* MCS 67 */
{ /* 20 Mhz */ { 136.5, /* SGI */ 151.7, },
/* 40 Mhz */ { 283.5, /* SGI */ 315.0, },
},
/* MCS 68 */
{ /* 20 Mhz */ { 117.0, /* SGI */ 130.0, },
/* 40 Mhz */ { 243.0, /* SGI */ 270.0, },
},
/* MCS 69 */
{ /* 20 Mhz */ { 136.5, /* SGI */ 151.7, },
/* 40 Mhz */ { 283.5, /* SGI */ 315.0, },
},
/* MCS 70 */
{ /* 20 Mhz */ { 156.0, /* SGI */ 173.3, },
/* 40 Mhz */ { 324.0, /* SGI */ 360.0, },
},
/* MCS 71 */
{ /* 20 Mhz */ { 175.5, /* SGI */ 195.0, },
/* 40 Mhz */ { 364.5, /* SGI */ 405.0, },
},
/* MCS 72 */
{ /* 20 Mhz */ { 156.0, /* SGI */ 173.3, },
/* 40 Mhz */ { 324.0, /* SGI */ 360.0, },
},
/* MCS 73 */
{ /* 20 Mhz */ { 175.5, /* SGI */ 195.0, },
/* 40 Mhz */ { 364.5, /* SGI */ 405.0, },
},
/* MCS 74 */
{ /* 20 Mhz */ { 195.0, /* SGI */ 216.7, },
/* 40 Mhz */ { 405.0, /* SGI */ 450.0, },
},
/* MCS 75 */
{ /* 20 Mhz */ { 195.0, /* SGI */ 216.7, },
/* 40 Mhz */ { 405.0, /* SGI */ 450.0, },
},
/* MCS 76 */
{ /* 20 Mhz */ { 214.5, /* SGI */ 238.3, },
/* 40 Mhz */ { 445.5, /* SGI */ 495.0, },
},
};
static const char *auth_alg_text[]={"Open System","Shared Key","EAP"};
#define NUM_AUTH_ALGS (sizeof auth_alg_text / sizeof auth_alg_text[0])
static const char *status_text[] = {
"Successful", /* 0 */
"Unspecified failure", /* 1 */
"Reserved", /* 2 */
"Reserved", /* 3 */
"Reserved", /* 4 */
"Reserved", /* 5 */
"Reserved", /* 6 */
"Reserved", /* 7 */
"Reserved", /* 8 */
"Reserved", /* 9 */
"Cannot Support all requested capabilities in the Capability "
"Information field", /* 10 */
"Reassociation denied due to inability to confirm that association "
"exists", /* 11 */
"Association denied due to reason outside the scope of the "
"standard", /* 12 */
"Responding station does not support the specified authentication "
"algorithm ", /* 13 */
"Received an Authentication frame with authentication transaction "
"sequence number out of expected sequence", /* 14 */
"Authentication rejected because of challenge failure", /* 15 */
"Authentication rejected due to timeout waiting for next frame in "
"sequence", /* 16 */
"Association denied because AP is unable to handle additional"
"associated stations", /* 17 */
"Association denied due to requesting station not supporting all of "
"the data rates in BSSBasicRateSet parameter", /* 18 */
"Association denied due to requesting station not supporting "
"short preamble operation", /* 19 */
"Association denied due to requesting station not supporting "
"PBCC encoding", /* 20 */
"Association denied due to requesting station not supporting "
"channel agility", /* 21 */
"Association request rejected because Spectrum Management "
"capability is required", /* 22 */
"Association request rejected because the information in the "
"Power Capability element is unacceptable", /* 23 */
"Association request rejected because the information in the "
"Supported Channels element is unacceptable", /* 24 */
"Association denied due to requesting station not supporting "
"short slot operation", /* 25 */
"Association denied due to requesting station not supporting "
"DSSS-OFDM operation", /* 26 */
"Association denied because the requested STA does not support HT "
"features", /* 27 */
"Reserved", /* 28 */
"Association denied because the requested STA does not support "
"the PCO transition time required by the AP", /* 29 */
"Reserved", /* 30 */
"Reserved", /* 31 */
"Unspecified, QoS-related failure", /* 32 */
"Association denied due to QAP having insufficient bandwidth "
"to handle another QSTA", /* 33 */
"Association denied due to excessive frame loss rates and/or "
"poor conditions on current operating channel", /* 34 */
"Association (with QBSS) denied due to requesting station not "
"supporting the QoS facility", /* 35 */
"Association denied due to requesting station not supporting "
"Block Ack", /* 36 */
"The request has been declined", /* 37 */
"The request has not been successful as one or more parameters "
"have invalid values", /* 38 */
"The TS has not been created because the request cannot be honored. "
"Try again with the suggested changes to the TSPEC", /* 39 */
"Invalid Information Element", /* 40 */
"Group Cipher is not valid", /* 41 */
"Pairwise Cipher is not valid", /* 42 */
"AKMP is not valid", /* 43 */
"Unsupported RSN IE version", /* 44 */
"Invalid RSN IE Capabilities", /* 45 */
"Cipher suite is rejected per security policy", /* 46 */
"The TS has not been created. However, the HC may be capable of "
"creating a TS, in response to a request, after the time indicated "
"in the TS Delay element", /* 47 */
"Direct Link is not allowed in the BSS by policy", /* 48 */
"Destination STA is not present within this QBSS.", /* 49 */
"The Destination STA is not a QSTA.", /* 50 */
};
#define NUM_STATUSES (sizeof status_text / sizeof status_text[0])
static const char *reason_text[] = {
"Reserved", /* 0 */
"Unspecified reason", /* 1 */
"Previous authentication no longer valid", /* 2 */
"Deauthenticated because sending station is leaving (or has left) "
"IBSS or ESS", /* 3 */
"Disassociated due to inactivity", /* 4 */
"Disassociated because AP is unable to handle all currently "
" associated stations", /* 5 */
"Class 2 frame received from nonauthenticated station", /* 6 */
"Class 3 frame received from nonassociated station", /* 7 */
"Disassociated because sending station is leaving "
"(or has left) BSS", /* 8 */
"Station requesting (re)association is not authenticated with "
"responding station", /* 9 */
"Disassociated because the information in the Power Capability "
"element is unacceptable", /* 10 */
"Disassociated because the information in the SupportedChannels "
"element is unacceptable", /* 11 */
"Invalid Information Element", /* 12 */
"Reserved", /* 13 */
"Michael MIC failure", /* 14 */
"4-Way Handshake timeout", /* 15 */
"Group key update timeout", /* 16 */
"Information element in 4-Way Handshake different from (Re)Association"
"Request/Probe Response/Beacon", /* 17 */
"Group Cipher is not valid", /* 18 */
"AKMP is not valid", /* 20 */
"Unsupported RSN IE version", /* 21 */
"Invalid RSN IE Capabilities", /* 22 */
"IEEE 802.1X Authentication failed", /* 23 */
"Cipher suite is rejected per security policy", /* 24 */
"Reserved", /* 25 */
"Reserved", /* 26 */
"Reserved", /* 27 */
"Reserved", /* 28 */
"Reserved", /* 29 */
"Reserved", /* 30 */
"TS deleted because QoS AP lacks sufficient bandwidth for this "
"QoS STA due to a change in BSS service characteristics or "
"operational mode (e.g. an HT BSS change from 40 MHz channel "
"to 20 MHz channel)", /* 31 */
"Disassociated for unspecified, QoS-related reason", /* 32 */
"Disassociated because QoS AP lacks sufficient bandwidth for this "
"QoS STA", /* 33 */
"Disassociated because of excessive number of frames that need to be "
"acknowledged, but are not acknowledged for AP transmissions "
"and/or poor channel conditions", /* 34 */
"Disassociated because STA is transmitting outside the limits "
"of its TXOPs", /* 35 */
"Requested from peer STA as the STA is leaving the BSS "
"(or resetting)", /* 36 */
"Requested from peer STA as it does not want to use the "
"mechanism", /* 37 */
"Requested from peer STA as the STA received frames using the "
"mechanism for which a set up is required", /* 38 */
"Requested from peer STA due to time out", /* 39 */
"Reserved", /* 40 */
"Reserved", /* 41 */
"Reserved", /* 42 */
"Reserved", /* 43 */
"Reserved", /* 44 */
"Peer STA does not support the requested cipher suite", /* 45 */
"Association denied due to requesting STA not supporting HT "
"features", /* 46 */
};
#define NUM_REASONS (sizeof reason_text / sizeof reason_text[0])
static int
wep_print(netdissect_options *ndo,
const u_char *p)
{
uint32_t iv;
if (!ND_TTEST2(*p, IEEE802_11_IV_LEN + IEEE802_11_KID_LEN))
return 0;
iv = EXTRACT_LE_32BITS(p);
ND_PRINT((ndo, " IV:%3x Pad %x KeyID %x", IV_IV(iv), IV_PAD(iv),
IV_KEYID(iv)));
return 1;
}
static int
parse_elements(netdissect_options *ndo,
struct mgmt_body_t *pbody, const u_char *p, int offset,
u_int length)
{
u_int elementlen;
struct ssid_t ssid;
struct challenge_t challenge;
struct rates_t rates;
struct ds_t ds;
struct cf_t cf;
struct tim_t tim;
/*
* We haven't seen any elements yet.
*/
pbody->challenge_present = 0;
pbody->ssid_present = 0;
pbody->rates_present = 0;
pbody->ds_present = 0;
pbody->cf_present = 0;
pbody->tim_present = 0;
while (length != 0) {
/* Make sure we at least have the element ID and length. */
if (!ND_TTEST2(*(p + offset), 2))
return 0;
if (length < 2)
return 0;
elementlen = *(p + offset + 1);
/* Make sure we have the entire element. */
if (!ND_TTEST2(*(p + offset + 2), elementlen))
return 0;
if (length < elementlen + 2)
return 0;
switch (*(p + offset)) {
case E_SSID:
memcpy(&ssid, p + offset, 2);
offset += 2;
length -= 2;
if (ssid.length != 0) {
if (ssid.length > sizeof(ssid.ssid) - 1)
return 0;
if (!ND_TTEST2(*(p + offset), ssid.length))
return 0;
if (length < ssid.length)
return 0;
memcpy(&ssid.ssid, p + offset, ssid.length);
offset += ssid.length;
length -= ssid.length;
}
ssid.ssid[ssid.length] = '\0';
/*
* Present and not truncated.
*
* If we haven't already seen an SSID IE,
* copy this one, otherwise ignore this one,
* so we later report the first one we saw.
*/
if (!pbody->ssid_present) {
pbody->ssid = ssid;
pbody->ssid_present = 1;
}
break;
case E_CHALLENGE:
memcpy(&challenge, p + offset, 2);
offset += 2;
length -= 2;
if (challenge.length != 0) {
if (challenge.length >
sizeof(challenge.text) - 1)
return 0;
if (!ND_TTEST2(*(p + offset), challenge.length))
return 0;
if (length < challenge.length)
return 0;
memcpy(&challenge.text, p + offset,
challenge.length);
offset += challenge.length;
length -= challenge.length;
}
challenge.text[challenge.length] = '\0';
/*
* Present and not truncated.
*
* If we haven't already seen a challenge IE,
* copy this one, otherwise ignore this one,
* so we later report the first one we saw.
*/
if (!pbody->challenge_present) {
pbody->challenge = challenge;
pbody->challenge_present = 1;
}
break;
case E_RATES:
memcpy(&rates, p + offset, 2);
offset += 2;
length -= 2;
if (rates.length != 0) {
if (rates.length > sizeof rates.rate)
return 0;
if (!ND_TTEST2(*(p + offset), rates.length))
return 0;
if (length < rates.length)
return 0;
memcpy(&rates.rate, p + offset, rates.length);
offset += rates.length;
length -= rates.length;
}
/*
* Present and not truncated.
*
* If we haven't already seen a rates IE,
* copy this one if it's not zero-length,
* otherwise ignore this one, so we later
* report the first one we saw.
*
* We ignore zero-length rates IEs as some
* devices seem to put a zero-length rates
* IE, followed by an SSID IE, followed by
* a non-zero-length rates IE into frames,
* even though IEEE Std 802.11-2007 doesn't
* seem to indicate that a zero-length rates
* IE is valid.
*/
if (!pbody->rates_present && rates.length != 0) {
pbody->rates = rates;
pbody->rates_present = 1;
}
break;
case E_DS:
memcpy(&ds, p + offset, 2);
offset += 2;
length -= 2;
if (ds.length != 1) {
offset += ds.length;
length -= ds.length;
break;
}
ds.channel = *(p + offset);
offset += 1;
length -= 1;
/*
* Present and not truncated.
*
* If we haven't already seen a DS IE,
* copy this one, otherwise ignore this one,
* so we later report the first one we saw.
*/
if (!pbody->ds_present) {
pbody->ds = ds;
pbody->ds_present = 1;
}
break;
case E_CF:
memcpy(&cf, p + offset, 2);
offset += 2;
length -= 2;
if (cf.length != 6) {
offset += cf.length;
length -= cf.length;
break;
}
memcpy(&cf.count, p + offset, 6);
offset += 6;
length -= 6;
/*
* Present and not truncated.
*
* If we haven't already seen a CF IE,
* copy this one, otherwise ignore this one,
* so we later report the first one we saw.
*/
if (!pbody->cf_present) {
pbody->cf = cf;
pbody->cf_present = 1;
}
break;
case E_TIM:
memcpy(&tim, p + offset, 2);
offset += 2;
length -= 2;
if (tim.length <= 3) {
offset += tim.length;
length -= tim.length;
break;
}
if (tim.length - 3 > (int)sizeof tim.bitmap)
return 0;
memcpy(&tim.count, p + offset, 3);
offset += 3;
length -= 3;
memcpy(tim.bitmap, p + offset + 3, tim.length - 3);
offset += tim.length - 3;
length -= tim.length - 3;
/*
* Present and not truncated.
*
* If we haven't already seen a TIM IE,
* copy this one, otherwise ignore this one,
* so we later report the first one we saw.
*/
if (!pbody->tim_present) {
pbody->tim = tim;
pbody->tim_present = 1;
}
break;
default:
#if 0
ND_PRINT((ndo, "(1) unhandled element_id (%d) ",
*(p + offset)));
#endif
offset += 2 + elementlen;
length -= 2 + elementlen;
break;
}
}
/* No problems found. */
return 1;
}
/*********************************************************************************
* Print Handle functions for the management frame types
*********************************************************************************/
static int
handle_beacon(netdissect_options *ndo,
const u_char *p, u_int length)
{
struct mgmt_body_t pbody;
int offset = 0;
int ret;
memset(&pbody, 0, sizeof(pbody));
if (!ND_TTEST2(*p, IEEE802_11_TSTAMP_LEN + IEEE802_11_BCNINT_LEN +
IEEE802_11_CAPINFO_LEN))
return 0;
if (length < IEEE802_11_TSTAMP_LEN + IEEE802_11_BCNINT_LEN +
IEEE802_11_CAPINFO_LEN)
return 0;
memcpy(&pbody.timestamp, p, IEEE802_11_TSTAMP_LEN);
offset += IEEE802_11_TSTAMP_LEN;
length -= IEEE802_11_TSTAMP_LEN;
pbody.beacon_interval = EXTRACT_LE_16BITS(p+offset);
offset += IEEE802_11_BCNINT_LEN;
length -= IEEE802_11_BCNINT_LEN;
pbody.capability_info = EXTRACT_LE_16BITS(p+offset);
offset += IEEE802_11_CAPINFO_LEN;
length -= IEEE802_11_CAPINFO_LEN;
ret = parse_elements(ndo, &pbody, p, offset, length);
PRINT_SSID(pbody);
PRINT_RATES(pbody);
ND_PRINT((ndo, " %s",
CAPABILITY_ESS(pbody.capability_info) ? "ESS" : "IBSS"));
PRINT_DS_CHANNEL(pbody);
return ret;
}
static int
handle_assoc_request(netdissect_options *ndo,
const u_char *p, u_int length)
{
struct mgmt_body_t pbody;
int offset = 0;
int ret;
memset(&pbody, 0, sizeof(pbody));
if (!ND_TTEST2(*p, IEEE802_11_CAPINFO_LEN + IEEE802_11_LISTENINT_LEN))
return 0;
if (length < IEEE802_11_CAPINFO_LEN + IEEE802_11_LISTENINT_LEN)
return 0;
pbody.capability_info = EXTRACT_LE_16BITS(p);
offset += IEEE802_11_CAPINFO_LEN;
length -= IEEE802_11_CAPINFO_LEN;
pbody.listen_interval = EXTRACT_LE_16BITS(p+offset);
offset += IEEE802_11_LISTENINT_LEN;
length -= IEEE802_11_LISTENINT_LEN;
ret = parse_elements(ndo, &pbody, p, offset, length);
PRINT_SSID(pbody);
PRINT_RATES(pbody);
return ret;
}
static int
handle_assoc_response(netdissect_options *ndo,
const u_char *p, u_int length)
{
struct mgmt_body_t pbody;
int offset = 0;
int ret;
memset(&pbody, 0, sizeof(pbody));
if (!ND_TTEST2(*p, IEEE802_11_CAPINFO_LEN + IEEE802_11_STATUS_LEN +
IEEE802_11_AID_LEN))
return 0;
if (length < IEEE802_11_CAPINFO_LEN + IEEE802_11_STATUS_LEN +
IEEE802_11_AID_LEN)
return 0;
pbody.capability_info = EXTRACT_LE_16BITS(p);
offset += IEEE802_11_CAPINFO_LEN;
length -= IEEE802_11_CAPINFO_LEN;
pbody.status_code = EXTRACT_LE_16BITS(p+offset);
offset += IEEE802_11_STATUS_LEN;
length -= IEEE802_11_STATUS_LEN;
pbody.aid = EXTRACT_LE_16BITS(p+offset);
offset += IEEE802_11_AID_LEN;
length -= IEEE802_11_AID_LEN;
ret = parse_elements(ndo, &pbody, p, offset, length);
ND_PRINT((ndo, " AID(%x) :%s: %s", ((uint16_t)(pbody.aid << 2 )) >> 2 ,
CAPABILITY_PRIVACY(pbody.capability_info) ? " PRIVACY " : "",
(pbody.status_code < NUM_STATUSES
? status_text[pbody.status_code]
: "n/a")));
return ret;
}
static int
handle_reassoc_request(netdissect_options *ndo,
const u_char *p, u_int length)
{
struct mgmt_body_t pbody;
int offset = 0;
int ret;
memset(&pbody, 0, sizeof(pbody));
if (!ND_TTEST2(*p, IEEE802_11_CAPINFO_LEN + IEEE802_11_LISTENINT_LEN +
IEEE802_11_AP_LEN))
return 0;
if (length < IEEE802_11_CAPINFO_LEN + IEEE802_11_LISTENINT_LEN +
IEEE802_11_AP_LEN)
return 0;
pbody.capability_info = EXTRACT_LE_16BITS(p);
offset += IEEE802_11_CAPINFO_LEN;
length -= IEEE802_11_CAPINFO_LEN;
pbody.listen_interval = EXTRACT_LE_16BITS(p+offset);
offset += IEEE802_11_LISTENINT_LEN;
length -= IEEE802_11_LISTENINT_LEN;
memcpy(&pbody.ap, p+offset, IEEE802_11_AP_LEN);
offset += IEEE802_11_AP_LEN;
length -= IEEE802_11_AP_LEN;
ret = parse_elements(ndo, &pbody, p, offset, length);
PRINT_SSID(pbody);
ND_PRINT((ndo, " AP : %s", etheraddr_string(ndo, pbody.ap )));
return ret;
}
static int
handle_reassoc_response(netdissect_options *ndo,
const u_char *p, u_int length)
{
/* Same as a Association Reponse */
return handle_assoc_response(ndo, p, length);
}
static int
handle_probe_request(netdissect_options *ndo,
const u_char *p, u_int length)
{
struct mgmt_body_t pbody;
int offset = 0;
int ret;
memset(&pbody, 0, sizeof(pbody));
ret = parse_elements(ndo, &pbody, p, offset, length);
PRINT_SSID(pbody);
PRINT_RATES(pbody);
return ret;
}
static int
handle_probe_response(netdissect_options *ndo,
const u_char *p, u_int length)
{
struct mgmt_body_t pbody;
int offset = 0;
int ret;
memset(&pbody, 0, sizeof(pbody));
if (!ND_TTEST2(*p, IEEE802_11_TSTAMP_LEN + IEEE802_11_BCNINT_LEN +
IEEE802_11_CAPINFO_LEN))
return 0;
if (length < IEEE802_11_TSTAMP_LEN + IEEE802_11_BCNINT_LEN +
IEEE802_11_CAPINFO_LEN)
return 0;
memcpy(&pbody.timestamp, p, IEEE802_11_TSTAMP_LEN);
offset += IEEE802_11_TSTAMP_LEN;
length -= IEEE802_11_TSTAMP_LEN;
pbody.beacon_interval = EXTRACT_LE_16BITS(p+offset);
offset += IEEE802_11_BCNINT_LEN;
length -= IEEE802_11_BCNINT_LEN;
pbody.capability_info = EXTRACT_LE_16BITS(p+offset);
offset += IEEE802_11_CAPINFO_LEN;
length -= IEEE802_11_CAPINFO_LEN;
ret = parse_elements(ndo, &pbody, p, offset, length);
PRINT_SSID(pbody);
PRINT_RATES(pbody);
PRINT_DS_CHANNEL(pbody);
return ret;
}
static int
handle_atim(void)
{
/* the frame body for ATIM is null. */
return 1;
}
static int
handle_disassoc(netdissect_options *ndo,
const u_char *p, u_int length)
{
struct mgmt_body_t pbody;
memset(&pbody, 0, sizeof(pbody));
if (!ND_TTEST2(*p, IEEE802_11_REASON_LEN))
return 0;
if (length < IEEE802_11_REASON_LEN)
return 0;
pbody.reason_code = EXTRACT_LE_16BITS(p);
ND_PRINT((ndo, ": %s",
(pbody.reason_code < NUM_REASONS)
? reason_text[pbody.reason_code]
: "Reserved"));
return 1;
}
static int
handle_auth(netdissect_options *ndo,
const u_char *p, u_int length)
{
struct mgmt_body_t pbody;
int offset = 0;
int ret;
memset(&pbody, 0, sizeof(pbody));
if (!ND_TTEST2(*p, 6))
return 0;
if (length < 6)
return 0;
pbody.auth_alg = EXTRACT_LE_16BITS(p);
offset += 2;
length -= 2;
pbody.auth_trans_seq_num = EXTRACT_LE_16BITS(p + offset);
offset += 2;
length -= 2;
pbody.status_code = EXTRACT_LE_16BITS(p + offset);
offset += 2;
length -= 2;
ret = parse_elements(ndo, &pbody, p, offset, length);
if ((pbody.auth_alg == 1) &&
((pbody.auth_trans_seq_num == 2) ||
(pbody.auth_trans_seq_num == 3))) {
ND_PRINT((ndo, " (%s)-%x [Challenge Text] %s",
(pbody.auth_alg < NUM_AUTH_ALGS)
? auth_alg_text[pbody.auth_alg]
: "Reserved",
pbody.auth_trans_seq_num,
((pbody.auth_trans_seq_num % 2)
? ((pbody.status_code < NUM_STATUSES)
? status_text[pbody.status_code]
: "n/a") : "")));
return ret;
}
ND_PRINT((ndo, " (%s)-%x: %s",
(pbody.auth_alg < NUM_AUTH_ALGS)
? auth_alg_text[pbody.auth_alg]
: "Reserved",
pbody.auth_trans_seq_num,
(pbody.auth_trans_seq_num % 2)
? ((pbody.status_code < NUM_STATUSES)
? status_text[pbody.status_code]
: "n/a")
: ""));
return ret;
}
static int
handle_deauth(netdissect_options *ndo,
const uint8_t *src, const u_char *p, u_int length)
{
struct mgmt_body_t pbody;
const char *reason = NULL;
memset(&pbody, 0, sizeof(pbody));
if (!ND_TTEST2(*p, IEEE802_11_REASON_LEN))
return 0;
if (length < IEEE802_11_REASON_LEN)
return 0;
pbody.reason_code = EXTRACT_LE_16BITS(p);
reason = (pbody.reason_code < NUM_REASONS)
? reason_text[pbody.reason_code]
: "Reserved";
if (ndo->ndo_eflag) {
ND_PRINT((ndo, ": %s", reason));
} else {
ND_PRINT((ndo, " (%s): %s", etheraddr_string(ndo, src), reason));
}
return 1;
}
#define PRINT_HT_ACTION(v) (\
(v) == 0 ? ND_PRINT((ndo, "TxChWidth")) : \
(v) == 1 ? ND_PRINT((ndo, "MIMOPwrSave")) : \
ND_PRINT((ndo, "Act#%d", (v))) \
)
#define PRINT_BA_ACTION(v) (\
(v) == 0 ? ND_PRINT((ndo, "ADDBA Request")) : \
(v) == 1 ? ND_PRINT((ndo, "ADDBA Response")) : \
(v) == 2 ? ND_PRINT((ndo, "DELBA")) : \
ND_PRINT((ndo, "Act#%d", (v))) \
)
#define PRINT_MESHLINK_ACTION(v) (\
(v) == 0 ? ND_PRINT((ndo, "Request")) : \
(v) == 1 ? ND_PRINT((ndo, "Report")) : \
ND_PRINT((ndo, "Act#%d", (v))) \
)
#define PRINT_MESHPEERING_ACTION(v) (\
(v) == 0 ? ND_PRINT((ndo, "Open")) : \
(v) == 1 ? ND_PRINT((ndo, "Confirm")) : \
(v) == 2 ? ND_PRINT((ndo, "Close")) : \
ND_PRINT((ndo, "Act#%d", (v))) \
)
#define PRINT_MESHPATH_ACTION(v) (\
(v) == 0 ? ND_PRINT((ndo, "Request")) : \
(v) == 1 ? ND_PRINT((ndo, "Report")) : \
(v) == 2 ? ND_PRINT((ndo, "Error")) : \
(v) == 3 ? ND_PRINT((ndo, "RootAnnouncement")) : \
ND_PRINT((ndo, "Act#%d", (v))) \
)
#define PRINT_MESH_ACTION(v) (\
(v) == 0 ? ND_PRINT((ndo, "MeshLink")) : \
(v) == 1 ? ND_PRINT((ndo, "HWMP")) : \
(v) == 2 ? ND_PRINT((ndo, "Gate Announcement")) : \
(v) == 3 ? ND_PRINT((ndo, "Congestion Control")) : \
(v) == 4 ? ND_PRINT((ndo, "MCCA Setup Request")) : \
(v) == 5 ? ND_PRINT((ndo, "MCCA Setup Reply")) : \
(v) == 6 ? ND_PRINT((ndo, "MCCA Advertisement Request")) : \
(v) == 7 ? ND_PRINT((ndo, "MCCA Advertisement")) : \
(v) == 8 ? ND_PRINT((ndo, "MCCA Teardown")) : \
(v) == 9 ? ND_PRINT((ndo, "TBTT Adjustment Request")) : \
(v) == 10 ? ND_PRINT((ndo, "TBTT Adjustment Response")) : \
ND_PRINT((ndo, "Act#%d", (v))) \
)
#define PRINT_MULTIHOP_ACTION(v) (\
(v) == 0 ? ND_PRINT((ndo, "Proxy Update")) : \
(v) == 1 ? ND_PRINT((ndo, "Proxy Update Confirmation")) : \
ND_PRINT((ndo, "Act#%d", (v))) \
)
#define PRINT_SELFPROT_ACTION(v) (\
(v) == 1 ? ND_PRINT((ndo, "Peering Open")) : \
(v) == 2 ? ND_PRINT((ndo, "Peering Confirm")) : \
(v) == 3 ? ND_PRINT((ndo, "Peering Close")) : \
(v) == 4 ? ND_PRINT((ndo, "Group Key Inform")) : \
(v) == 5 ? ND_PRINT((ndo, "Group Key Acknowledge")) : \
ND_PRINT((ndo, "Act#%d", (v))) \
)
static int
handle_action(netdissect_options *ndo,
const uint8_t *src, const u_char *p, u_int length)
{
if (!ND_TTEST2(*p, 2))
return 0;
if (length < 2)
return 0;
if (ndo->ndo_eflag) {
ND_PRINT((ndo, ": "));
} else {
ND_PRINT((ndo, " (%s): ", etheraddr_string(ndo, src)));
}
switch (p[0]) {
case 0: ND_PRINT((ndo, "Spectrum Management Act#%d", p[1])); break;
case 1: ND_PRINT((ndo, "QoS Act#%d", p[1])); break;
case 2: ND_PRINT((ndo, "DLS Act#%d", p[1])); break;
case 3: ND_PRINT((ndo, "BA ")); PRINT_BA_ACTION(p[1]); break;
case 7: ND_PRINT((ndo, "HT ")); PRINT_HT_ACTION(p[1]); break;
case 13: ND_PRINT((ndo, "MeshAction ")); PRINT_MESH_ACTION(p[1]); break;
case 14:
ND_PRINT((ndo, "MultiohopAction "));
PRINT_MULTIHOP_ACTION(p[1]); break;
case 15:
ND_PRINT((ndo, "SelfprotectAction "));
PRINT_SELFPROT_ACTION(p[1]); break;
case 127: ND_PRINT((ndo, "Vendor Act#%d", p[1])); break;
default:
ND_PRINT((ndo, "Reserved(%d) Act#%d", p[0], p[1]));
break;
}
return 1;
}
/*********************************************************************************
* Print Body funcs
*********************************************************************************/
static int
mgmt_body_print(netdissect_options *ndo,
uint16_t fc, const uint8_t *src, const u_char *p, u_int length)
{
ND_PRINT((ndo, "%s", tok2str(st_str, "Unhandled Management subtype(%x)", FC_SUBTYPE(fc))));
/* There may be a problem w/ AP not having this bit set */
if (FC_PROTECTED(fc))
return wep_print(ndo, p);
switch (FC_SUBTYPE(fc)) {
case ST_ASSOC_REQUEST:
return handle_assoc_request(ndo, p, length);
case ST_ASSOC_RESPONSE:
return handle_assoc_response(ndo, p, length);
case ST_REASSOC_REQUEST:
return handle_reassoc_request(ndo, p, length);
case ST_REASSOC_RESPONSE:
return handle_reassoc_response(ndo, p, length);
case ST_PROBE_REQUEST:
return handle_probe_request(ndo, p, length);
case ST_PROBE_RESPONSE:
return handle_probe_response(ndo, p, length);
case ST_BEACON:
return handle_beacon(ndo, p, length);
case ST_ATIM:
return handle_atim();
case ST_DISASSOC:
return handle_disassoc(ndo, p, length);
case ST_AUTH:
return handle_auth(ndo, p, length);
case ST_DEAUTH:
return handle_deauth(ndo, src, p, length);
case ST_ACTION:
return handle_action(ndo, src, p, length);
default:
return 1;
}
}
/*********************************************************************************
* Handles printing all the control frame types
*********************************************************************************/
static int
ctrl_body_print(netdissect_options *ndo,
uint16_t fc, const u_char *p)
{
ND_PRINT((ndo, "%s", tok2str(ctrl_str, "Unknown Ctrl Subtype", FC_SUBTYPE(fc))));
switch (FC_SUBTYPE(fc)) {
case CTRL_CONTROL_WRAPPER:
/* XXX - requires special handling */
break;
case CTRL_BAR:
if (!ND_TTEST2(*p, CTRL_BAR_HDRLEN))
return 0;
if (!ndo->ndo_eflag)
ND_PRINT((ndo, " RA:%s TA:%s CTL(%x) SEQ(%u) ",
etheraddr_string(ndo, ((const struct ctrl_bar_hdr_t *)p)->ra),
etheraddr_string(ndo, ((const struct ctrl_bar_hdr_t *)p)->ta),
EXTRACT_LE_16BITS(&(((const struct ctrl_bar_hdr_t *)p)->ctl)),
EXTRACT_LE_16BITS(&(((const struct ctrl_bar_hdr_t *)p)->seq))));
break;
case CTRL_BA:
if (!ND_TTEST2(*p, CTRL_BA_HDRLEN))
return 0;
if (!ndo->ndo_eflag)
ND_PRINT((ndo, " RA:%s ",
etheraddr_string(ndo, ((const struct ctrl_ba_hdr_t *)p)->ra)));
break;
case CTRL_PS_POLL:
if (!ND_TTEST2(*p, CTRL_PS_POLL_HDRLEN))
return 0;
ND_PRINT((ndo, " AID(%x)",
EXTRACT_LE_16BITS(&(((const struct ctrl_ps_poll_hdr_t *)p)->aid))));
break;
case CTRL_RTS:
if (!ND_TTEST2(*p, CTRL_RTS_HDRLEN))
return 0;
if (!ndo->ndo_eflag)
ND_PRINT((ndo, " TA:%s ",
etheraddr_string(ndo, ((const struct ctrl_rts_hdr_t *)p)->ta)));
break;
case CTRL_CTS:
if (!ND_TTEST2(*p, CTRL_CTS_HDRLEN))
return 0;
if (!ndo->ndo_eflag)
ND_PRINT((ndo, " RA:%s ",
etheraddr_string(ndo, ((const struct ctrl_cts_hdr_t *)p)->ra)));
break;
case CTRL_ACK:
if (!ND_TTEST2(*p, CTRL_ACK_HDRLEN))
return 0;
if (!ndo->ndo_eflag)
ND_PRINT((ndo, " RA:%s ",
etheraddr_string(ndo, ((const struct ctrl_ack_hdr_t *)p)->ra)));
break;
case CTRL_CF_END:
if (!ND_TTEST2(*p, CTRL_END_HDRLEN))
return 0;
if (!ndo->ndo_eflag)
ND_PRINT((ndo, " RA:%s ",
etheraddr_string(ndo, ((const struct ctrl_end_hdr_t *)p)->ra)));
break;
case CTRL_END_ACK:
if (!ND_TTEST2(*p, CTRL_END_ACK_HDRLEN))
return 0;
if (!ndo->ndo_eflag)
ND_PRINT((ndo, " RA:%s ",
etheraddr_string(ndo, ((const struct ctrl_end_ack_hdr_t *)p)->ra)));
break;
}
return 1;
}
/*
* Data Frame - Address field contents
*
* To Ds | From DS | Addr 1 | Addr 2 | Addr 3 | Addr 4
* 0 | 0 | DA | SA | BSSID | n/a
* 0 | 1 | DA | BSSID | SA | n/a
* 1 | 0 | BSSID | SA | DA | n/a
* 1 | 1 | RA | TA | DA | SA
*/
/*
* Function to get source and destination MAC addresses for a data frame.
*/
static void
get_data_src_dst_mac(uint16_t fc, const u_char *p, const uint8_t **srcp,
const uint8_t **dstp)
{
#define ADDR1 (p + 4)
#define ADDR2 (p + 10)
#define ADDR3 (p + 16)
#define ADDR4 (p + 24)
if (!FC_TO_DS(fc)) {
if (!FC_FROM_DS(fc)) {
/* not To DS and not From DS */
*srcp = ADDR2;
*dstp = ADDR1;
} else {
/* not To DS and From DS */
*srcp = ADDR3;
*dstp = ADDR1;
}
} else {
if (!FC_FROM_DS(fc)) {
/* From DS and not To DS */
*srcp = ADDR2;
*dstp = ADDR3;
} else {
/* To DS and From DS */
*srcp = ADDR4;
*dstp = ADDR3;
}
}
#undef ADDR1
#undef ADDR2
#undef ADDR3
#undef ADDR4
}
static void
get_mgmt_src_dst_mac(const u_char *p, const uint8_t **srcp, const uint8_t **dstp)
{
const struct mgmt_header_t *hp = (const struct mgmt_header_t *) p;
if (srcp != NULL)
*srcp = hp->sa;
if (dstp != NULL)
*dstp = hp->da;
}
/*
* Print Header funcs
*/
static void
data_header_print(netdissect_options *ndo, uint16_t fc, const u_char *p)
{
u_int subtype = FC_SUBTYPE(fc);
if (DATA_FRAME_IS_CF_ACK(subtype) || DATA_FRAME_IS_CF_POLL(subtype) ||
DATA_FRAME_IS_QOS(subtype)) {
ND_PRINT((ndo, "CF "));
if (DATA_FRAME_IS_CF_ACK(subtype)) {
if (DATA_FRAME_IS_CF_POLL(subtype))
ND_PRINT((ndo, "Ack/Poll"));
else
ND_PRINT((ndo, "Ack"));
} else {
if (DATA_FRAME_IS_CF_POLL(subtype))
ND_PRINT((ndo, "Poll"));
}
if (DATA_FRAME_IS_QOS(subtype))
ND_PRINT((ndo, "+QoS"));
ND_PRINT((ndo, " "));
}
#define ADDR1 (p + 4)
#define ADDR2 (p + 10)
#define ADDR3 (p + 16)
#define ADDR4 (p + 24)
if (!FC_TO_DS(fc) && !FC_FROM_DS(fc)) {
ND_PRINT((ndo, "DA:%s SA:%s BSSID:%s ",
etheraddr_string(ndo, ADDR1), etheraddr_string(ndo, ADDR2),
etheraddr_string(ndo, ADDR3)));
} else if (!FC_TO_DS(fc) && FC_FROM_DS(fc)) {
ND_PRINT((ndo, "DA:%s BSSID:%s SA:%s ",
etheraddr_string(ndo, ADDR1), etheraddr_string(ndo, ADDR2),
etheraddr_string(ndo, ADDR3)));
} else if (FC_TO_DS(fc) && !FC_FROM_DS(fc)) {
ND_PRINT((ndo, "BSSID:%s SA:%s DA:%s ",
etheraddr_string(ndo, ADDR1), etheraddr_string(ndo, ADDR2),
etheraddr_string(ndo, ADDR3)));
} else if (FC_TO_DS(fc) && FC_FROM_DS(fc)) {
ND_PRINT((ndo, "RA:%s TA:%s DA:%s SA:%s ",
etheraddr_string(ndo, ADDR1), etheraddr_string(ndo, ADDR2),
etheraddr_string(ndo, ADDR3), etheraddr_string(ndo, ADDR4)));
}
#undef ADDR1
#undef ADDR2
#undef ADDR3
#undef ADDR4
}
static void
mgmt_header_print(netdissect_options *ndo, const u_char *p)
{
const struct mgmt_header_t *hp = (const struct mgmt_header_t *) p;
ND_PRINT((ndo, "BSSID:%s DA:%s SA:%s ",
etheraddr_string(ndo, (hp)->bssid), etheraddr_string(ndo, (hp)->da),
etheraddr_string(ndo, (hp)->sa)));
}
static void
ctrl_header_print(netdissect_options *ndo, uint16_t fc, const u_char *p)
{
switch (FC_SUBTYPE(fc)) {
case CTRL_BAR:
ND_PRINT((ndo, " RA:%s TA:%s CTL(%x) SEQ(%u) ",
etheraddr_string(ndo, ((const struct ctrl_bar_hdr_t *)p)->ra),
etheraddr_string(ndo, ((const struct ctrl_bar_hdr_t *)p)->ta),
EXTRACT_LE_16BITS(&(((const struct ctrl_bar_hdr_t *)p)->ctl)),
EXTRACT_LE_16BITS(&(((const struct ctrl_bar_hdr_t *)p)->seq))));
break;
case CTRL_BA:
ND_PRINT((ndo, "RA:%s ",
etheraddr_string(ndo, ((const struct ctrl_ba_hdr_t *)p)->ra)));
break;
case CTRL_PS_POLL:
ND_PRINT((ndo, "BSSID:%s TA:%s ",
etheraddr_string(ndo, ((const struct ctrl_ps_poll_hdr_t *)p)->bssid),
etheraddr_string(ndo, ((const struct ctrl_ps_poll_hdr_t *)p)->ta)));
break;
case CTRL_RTS:
ND_PRINT((ndo, "RA:%s TA:%s ",
etheraddr_string(ndo, ((const struct ctrl_rts_hdr_t *)p)->ra),
etheraddr_string(ndo, ((const struct ctrl_rts_hdr_t *)p)->ta)));
break;
case CTRL_CTS:
ND_PRINT((ndo, "RA:%s ",
etheraddr_string(ndo, ((const struct ctrl_cts_hdr_t *)p)->ra)));
break;
case CTRL_ACK:
ND_PRINT((ndo, "RA:%s ",
etheraddr_string(ndo, ((const struct ctrl_ack_hdr_t *)p)->ra)));
break;
case CTRL_CF_END:
ND_PRINT((ndo, "RA:%s BSSID:%s ",
etheraddr_string(ndo, ((const struct ctrl_end_hdr_t *)p)->ra),
etheraddr_string(ndo, ((const struct ctrl_end_hdr_t *)p)->bssid)));
break;
case CTRL_END_ACK:
ND_PRINT((ndo, "RA:%s BSSID:%s ",
etheraddr_string(ndo, ((const struct ctrl_end_ack_hdr_t *)p)->ra),
etheraddr_string(ndo, ((const struct ctrl_end_ack_hdr_t *)p)->bssid)));
break;
default:
/* We shouldn't get here - we should already have quit */
break;
}
}
static int
extract_header_length(netdissect_options *ndo,
uint16_t fc)
{
int len;
switch (FC_TYPE(fc)) {
case T_MGMT:
return MGMT_HDRLEN;
case T_CTRL:
switch (FC_SUBTYPE(fc)) {
case CTRL_CONTROL_WRAPPER:
return CTRL_CONTROL_WRAPPER_HDRLEN;
case CTRL_BAR:
return CTRL_BAR_HDRLEN;
case CTRL_BA:
return CTRL_BA_HDRLEN;
case CTRL_PS_POLL:
return CTRL_PS_POLL_HDRLEN;
case CTRL_RTS:
return CTRL_RTS_HDRLEN;
case CTRL_CTS:
return CTRL_CTS_HDRLEN;
case CTRL_ACK:
return CTRL_ACK_HDRLEN;
case CTRL_CF_END:
return CTRL_END_HDRLEN;
case CTRL_END_ACK:
return CTRL_END_ACK_HDRLEN;
default:
ND_PRINT((ndo, "unknown 802.11 ctrl frame subtype (%d)", FC_SUBTYPE(fc)));
return 0;
}
case T_DATA:
len = (FC_TO_DS(fc) && FC_FROM_DS(fc)) ? 30 : 24;
if (DATA_FRAME_IS_QOS(FC_SUBTYPE(fc)))
len += 2;
return len;
default:
ND_PRINT((ndo, "unknown 802.11 frame type (%d)", FC_TYPE(fc)));
return 0;
}
}
static int
extract_mesh_header_length(const u_char *p)
{
return (p[0] &~ 3) ? 0 : 6*(1 + (p[0] & 3));
}
/*
* Print the 802.11 MAC header.
*/
static void
ieee_802_11_hdr_print(netdissect_options *ndo,
uint16_t fc, const u_char *p, u_int hdrlen,
u_int meshdrlen)
{
if (ndo->ndo_vflag) {
if (FC_MORE_DATA(fc))
ND_PRINT((ndo, "More Data "));
if (FC_MORE_FLAG(fc))
ND_PRINT((ndo, "More Fragments "));
if (FC_POWER_MGMT(fc))
ND_PRINT((ndo, "Pwr Mgmt "));
if (FC_RETRY(fc))
ND_PRINT((ndo, "Retry "));
if (FC_ORDER(fc))
ND_PRINT((ndo, "Strictly Ordered "));
if (FC_PROTECTED(fc))
ND_PRINT((ndo, "Protected "));
if (FC_TYPE(fc) != T_CTRL || FC_SUBTYPE(fc) != CTRL_PS_POLL)
ND_PRINT((ndo, "%dus ",
EXTRACT_LE_16BITS(
&((const struct mgmt_header_t *)p)->duration)));
}
if (meshdrlen != 0) {
const struct meshcntl_t *mc =
(const struct meshcntl_t *)&p[hdrlen - meshdrlen];
int ae = mc->flags & 3;
ND_PRINT((ndo, "MeshData (AE %d TTL %u seq %u", ae, mc->ttl,
EXTRACT_LE_32BITS(mc->seq)));
if (ae > 0)
ND_PRINT((ndo, " A4:%s", etheraddr_string(ndo, mc->addr4)));
if (ae > 1)
ND_PRINT((ndo, " A5:%s", etheraddr_string(ndo, mc->addr5)));
if (ae > 2)
ND_PRINT((ndo, " A6:%s", etheraddr_string(ndo, mc->addr6)));
ND_PRINT((ndo, ") "));
}
switch (FC_TYPE(fc)) {
case T_MGMT:
mgmt_header_print(ndo, p);
break;
case T_CTRL:
ctrl_header_print(ndo, fc, p);
break;
case T_DATA:
data_header_print(ndo, fc, p);
break;
default:
break;
}
}
#ifndef roundup2
#define roundup2(x, y) (((x)+((y)-1))&(~((y)-1))) /* if y is powers of two */
#endif
static const char tstr[] = "[|802.11]";
static u_int
ieee802_11_print(netdissect_options *ndo,
const u_char *p, u_int length, u_int orig_caplen, int pad,
u_int fcslen)
{
uint16_t fc;
u_int caplen, hdrlen, meshdrlen;
struct lladdr_info src, dst;
int llc_hdrlen;
caplen = orig_caplen;
/* Remove FCS, if present */
if (length < fcslen) {
ND_PRINT((ndo, "%s", tstr));
return caplen;
}
length -= fcslen;
if (caplen > length) {
/* Amount of FCS in actual packet data, if any */
fcslen = caplen - length;
caplen -= fcslen;
ndo->ndo_snapend -= fcslen;
}
if (caplen < IEEE802_11_FC_LEN) {
ND_PRINT((ndo, "%s", tstr));
return orig_caplen;
}
fc = EXTRACT_LE_16BITS(p);
hdrlen = extract_header_length(ndo, fc);
if (hdrlen == 0) {
/* Unknown frame type or control frame subtype; quit. */
return (0);
}
if (pad)
hdrlen = roundup2(hdrlen, 4);
if (ndo->ndo_Hflag && FC_TYPE(fc) == T_DATA &&
DATA_FRAME_IS_QOS(FC_SUBTYPE(fc))) {
meshdrlen = extract_mesh_header_length(p+hdrlen);
hdrlen += meshdrlen;
} else
meshdrlen = 0;
if (caplen < hdrlen) {
ND_PRINT((ndo, "%s", tstr));
return hdrlen;
}
if (ndo->ndo_eflag)
ieee_802_11_hdr_print(ndo, fc, p, hdrlen, meshdrlen);
/*
* Go past the 802.11 header.
*/
length -= hdrlen;
caplen -= hdrlen;
p += hdrlen;
src.addr_string = etheraddr_string;
dst.addr_string = etheraddr_string;
switch (FC_TYPE(fc)) {
case T_MGMT:
get_mgmt_src_dst_mac(p - hdrlen, &src.addr, &dst.addr);
if (!mgmt_body_print(ndo, fc, src.addr, p, length)) {
ND_PRINT((ndo, "%s", tstr));
return hdrlen;
}
break;
case T_CTRL:
if (!ctrl_body_print(ndo, fc, p - hdrlen)) {
ND_PRINT((ndo, "%s", tstr));
return hdrlen;
}
break;
case T_DATA:
if (DATA_FRAME_IS_NULL(FC_SUBTYPE(fc)))
return hdrlen; /* no-data frame */
/* There may be a problem w/ AP not having this bit set */
if (FC_PROTECTED(fc)) {
ND_PRINT((ndo, "Data"));
if (!wep_print(ndo, p)) {
ND_PRINT((ndo, "%s", tstr));
return hdrlen;
}
} else {
get_data_src_dst_mac(fc, p - hdrlen, &src.addr, &dst.addr);
llc_hdrlen = llc_print(ndo, p, length, caplen, &src, &dst);
if (llc_hdrlen < 0) {
/*
* Some kinds of LLC packet we cannot
* handle intelligently
*/
if (!ndo->ndo_suppress_default_print)
ND_DEFAULTPRINT(p, caplen);
llc_hdrlen = -llc_hdrlen;
}
hdrlen += llc_hdrlen;
}
break;
default:
/* We shouldn't get here - we should already have quit */
break;
}
return hdrlen;
}
/*
* This is the top level routine of the printer. 'p' points
* to the 802.11 header of the packet, 'h->ts' is the timestamp,
* 'h->len' is the length of the packet off the wire, and 'h->caplen'
* is the number of bytes actually captured.
*/
u_int
ieee802_11_if_print(netdissect_options *ndo,
const struct pcap_pkthdr *h, const u_char *p)
{
return ieee802_11_print(ndo, p, h->len, h->caplen, 0, 0);
}
/* $FreeBSD: src/sys/net80211/ieee80211_radiotap.h,v 1.5 2005/01/22 20:12:05 sam Exp $ */
/* NetBSD: ieee802_11_radio.h,v 1.2 2006/02/26 03:04:03 dyoung Exp */
/*-
* Copyright (c) 2003, 2004 David Young. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. The name of David Young may not be used to endorse or promote
* products derived from this software without specific prior
* written permission.
*
* THIS SOFTWARE IS PROVIDED BY DAVID 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 DAVID
* YOUNG 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.
*/
/* A generic radio capture format is desirable. It must be
* rigidly defined (e.g., units for fields should be given),
* and easily extensible.
*
* The following is an extensible radio capture format. It is
* based on a bitmap indicating which fields are present.
*
* I am trying to describe precisely what the application programmer
* should expect in the following, and for that reason I tell the
* units and origin of each measurement (where it applies), or else I
* use sufficiently weaselly language ("is a monotonically nondecreasing
* function of...") that I cannot set false expectations for lawyerly
* readers.
*/
/*
* The radio capture header precedes the 802.11 header.
*
* Note well: all radiotap fields are little-endian.
*/
struct ieee80211_radiotap_header {
uint8_t it_version; /* Version 0. Only increases
* for drastic changes,
* introduction of compatible
* new fields does not count.
*/
uint8_t it_pad;
uint16_t it_len; /* length of the whole
* header in bytes, including
* it_version, it_pad,
* it_len, and data fields.
*/
uint32_t it_present; /* A bitmap telling which
* fields are present. Set bit 31
* (0x80000000) to extend the
* bitmap by another 32 bits.
* Additional extensions are made
* by setting bit 31.
*/
};
/* Name Data type Units
* ---- --------- -----
*
* IEEE80211_RADIOTAP_TSFT uint64_t microseconds
*
* Value in microseconds of the MAC's 64-bit 802.11 Time
* Synchronization Function timer when the first bit of the
* MPDU arrived at the MAC. For received frames, only.
*
* IEEE80211_RADIOTAP_CHANNEL 2 x uint16_t MHz, bitmap
*
* Tx/Rx frequency in MHz, followed by flags (see below).
* Note that IEEE80211_RADIOTAP_XCHANNEL must be used to
* represent an HT channel as there is not enough room in
* the flags word.
*
* IEEE80211_RADIOTAP_FHSS uint16_t see below
*
* For frequency-hopping radios, the hop set (first byte)
* and pattern (second byte).
*
* IEEE80211_RADIOTAP_RATE uint8_t 500kb/s or index
*
* Tx/Rx data rate. If bit 0x80 is set then it represents an
* an MCS index and not an IEEE rate.
*
* IEEE80211_RADIOTAP_DBM_ANTSIGNAL int8_t decibels from
* one milliwatt (dBm)
*
* RF signal power at the antenna, decibel difference from
* one milliwatt.
*
* IEEE80211_RADIOTAP_DBM_ANTNOISE int8_t decibels from
* one milliwatt (dBm)
*
* RF noise power at the antenna, decibel difference from one
* milliwatt.
*
* IEEE80211_RADIOTAP_DB_ANTSIGNAL uint8_t decibel (dB)
*
* RF signal power at the antenna, decibel difference from an
* arbitrary, fixed reference.
*
* IEEE80211_RADIOTAP_DB_ANTNOISE uint8_t decibel (dB)
*
* RF noise power at the antenna, decibel difference from an
* arbitrary, fixed reference point.
*
* IEEE80211_RADIOTAP_LOCK_QUALITY uint16_t unitless
*
* Quality of Barker code lock. Unitless. Monotonically
* nondecreasing with "better" lock strength. Called "Signal
* Quality" in datasheets. (Is there a standard way to measure
* this?)
*
* IEEE80211_RADIOTAP_TX_ATTENUATION uint16_t unitless
*
* Transmit power expressed as unitless distance from max
* power set at factory calibration. 0 is max power.
* Monotonically nondecreasing with lower power levels.
*
* IEEE80211_RADIOTAP_DB_TX_ATTENUATION uint16_t decibels (dB)
*
* Transmit power expressed as decibel distance from max power
* set at factory calibration. 0 is max power. Monotonically
* nondecreasing with lower power levels.
*
* IEEE80211_RADIOTAP_DBM_TX_POWER int8_t decibels from
* one milliwatt (dBm)
*
* Transmit power expressed as dBm (decibels from a 1 milliwatt
* reference). This is the absolute power level measured at
* the antenna port.
*
* IEEE80211_RADIOTAP_FLAGS uint8_t bitmap
*
* Properties of transmitted and received frames. See flags
* defined below.
*
* IEEE80211_RADIOTAP_ANTENNA uint8_t antenna index
*
* Unitless indication of the Rx/Tx antenna for this packet.
* The first antenna is antenna 0.
*
* IEEE80211_RADIOTAP_RX_FLAGS uint16_t bitmap
*
* Properties of received frames. See flags defined below.
*
* IEEE80211_RADIOTAP_XCHANNEL uint32_t bitmap
* uint16_t MHz
* uint8_t channel number
* uint8_t .5 dBm
*
* Extended channel specification: flags (see below) followed by
* frequency in MHz, the corresponding IEEE channel number, and
* finally the maximum regulatory transmit power cap in .5 dBm
* units. This property supersedes IEEE80211_RADIOTAP_CHANNEL
* and only one of the two should be present.
*
* IEEE80211_RADIOTAP_MCS uint8_t known
* uint8_t flags
* uint8_t mcs
*
* Bitset indicating which fields have known values, followed
* by bitset of flag values, followed by the MCS rate index as
* in IEEE 802.11n.
*
*
* IEEE80211_RADIOTAP_AMPDU_STATUS u32, u16, u8, u8 unitless
*
* Contains the AMPDU information for the subframe.
*
* IEEE80211_RADIOTAP_VHT u16, u8, u8, u8[4], u8, u8, u16
*
* Contains VHT information about this frame.
*
* IEEE80211_RADIOTAP_VENDOR_NAMESPACE
* uint8_t OUI[3]
* uint8_t subspace
* uint16_t length
*
* The Vendor Namespace Field contains three sub-fields. The first
* sub-field is 3 bytes long. It contains the vendor's IEEE 802
* Organizationally Unique Identifier (OUI). The fourth byte is a
* vendor-specific "namespace selector."
*
*/
enum ieee80211_radiotap_type {
IEEE80211_RADIOTAP_TSFT = 0,
IEEE80211_RADIOTAP_FLAGS = 1,
IEEE80211_RADIOTAP_RATE = 2,
IEEE80211_RADIOTAP_CHANNEL = 3,
IEEE80211_RADIOTAP_FHSS = 4,
IEEE80211_RADIOTAP_DBM_ANTSIGNAL = 5,
IEEE80211_RADIOTAP_DBM_ANTNOISE = 6,
IEEE80211_RADIOTAP_LOCK_QUALITY = 7,
IEEE80211_RADIOTAP_TX_ATTENUATION = 8,
IEEE80211_RADIOTAP_DB_TX_ATTENUATION = 9,
IEEE80211_RADIOTAP_DBM_TX_POWER = 10,
IEEE80211_RADIOTAP_ANTENNA = 11,
IEEE80211_RADIOTAP_DB_ANTSIGNAL = 12,
IEEE80211_RADIOTAP_DB_ANTNOISE = 13,
IEEE80211_RADIOTAP_RX_FLAGS = 14,
/* NB: gap for netbsd definitions */
IEEE80211_RADIOTAP_XCHANNEL = 18,
IEEE80211_RADIOTAP_MCS = 19,
IEEE80211_RADIOTAP_AMPDU_STATUS = 20,
IEEE80211_RADIOTAP_VHT = 21,
IEEE80211_RADIOTAP_NAMESPACE = 29,
IEEE80211_RADIOTAP_VENDOR_NAMESPACE = 30,
IEEE80211_RADIOTAP_EXT = 31
};
/* channel attributes */
#define IEEE80211_CHAN_TURBO 0x00010 /* Turbo channel */
#define IEEE80211_CHAN_CCK 0x00020 /* CCK channel */
#define IEEE80211_CHAN_OFDM 0x00040 /* OFDM channel */
#define IEEE80211_CHAN_2GHZ 0x00080 /* 2 GHz spectrum channel. */
#define IEEE80211_CHAN_5GHZ 0x00100 /* 5 GHz spectrum channel */
#define IEEE80211_CHAN_PASSIVE 0x00200 /* Only passive scan allowed */
#define IEEE80211_CHAN_DYN 0x00400 /* Dynamic CCK-OFDM channel */
#define IEEE80211_CHAN_GFSK 0x00800 /* GFSK channel (FHSS PHY) */
#define IEEE80211_CHAN_GSM 0x01000 /* 900 MHz spectrum channel */
#define IEEE80211_CHAN_STURBO 0x02000 /* 11a static turbo channel only */
#define IEEE80211_CHAN_HALF 0x04000 /* Half rate channel */
#define IEEE80211_CHAN_QUARTER 0x08000 /* Quarter rate channel */
#define IEEE80211_CHAN_HT20 0x10000 /* HT 20 channel */
#define IEEE80211_CHAN_HT40U 0x20000 /* HT 40 channel w/ ext above */
#define IEEE80211_CHAN_HT40D 0x40000 /* HT 40 channel w/ ext below */
/* Useful combinations of channel characteristics, borrowed from Ethereal */
#define IEEE80211_CHAN_A \
(IEEE80211_CHAN_5GHZ | IEEE80211_CHAN_OFDM)
#define IEEE80211_CHAN_B \
(IEEE80211_CHAN_2GHZ | IEEE80211_CHAN_CCK)
#define IEEE80211_CHAN_G \
(IEEE80211_CHAN_2GHZ | IEEE80211_CHAN_DYN)
#define IEEE80211_CHAN_TA \
(IEEE80211_CHAN_5GHZ | IEEE80211_CHAN_OFDM | IEEE80211_CHAN_TURBO)
#define IEEE80211_CHAN_TG \
(IEEE80211_CHAN_2GHZ | IEEE80211_CHAN_DYN | IEEE80211_CHAN_TURBO)
/* For IEEE80211_RADIOTAP_FLAGS */
#define IEEE80211_RADIOTAP_F_CFP 0x01 /* sent/received
* during CFP
*/
#define IEEE80211_RADIOTAP_F_SHORTPRE 0x02 /* sent/received
* with short
* preamble
*/
#define IEEE80211_RADIOTAP_F_WEP 0x04 /* sent/received
* with WEP encryption
*/
#define IEEE80211_RADIOTAP_F_FRAG 0x08 /* sent/received
* with fragmentation
*/
#define IEEE80211_RADIOTAP_F_FCS 0x10 /* frame includes FCS */
#define IEEE80211_RADIOTAP_F_DATAPAD 0x20 /* frame has padding between
* 802.11 header and payload
* (to 32-bit boundary)
*/
#define IEEE80211_RADIOTAP_F_BADFCS 0x40 /* does not pass FCS check */
/* For IEEE80211_RADIOTAP_RX_FLAGS */
#define IEEE80211_RADIOTAP_F_RX_BADFCS 0x0001 /* frame failed crc check */
#define IEEE80211_RADIOTAP_F_RX_PLCP_CRC 0x0002 /* frame failed PLCP CRC check */
/* For IEEE80211_RADIOTAP_MCS known */
#define IEEE80211_RADIOTAP_MCS_BANDWIDTH_KNOWN 0x01
#define IEEE80211_RADIOTAP_MCS_MCS_INDEX_KNOWN 0x02 /* MCS index field */
#define IEEE80211_RADIOTAP_MCS_GUARD_INTERVAL_KNOWN 0x04
#define IEEE80211_RADIOTAP_MCS_HT_FORMAT_KNOWN 0x08
#define IEEE80211_RADIOTAP_MCS_FEC_TYPE_KNOWN 0x10
#define IEEE80211_RADIOTAP_MCS_STBC_KNOWN 0x20
#define IEEE80211_RADIOTAP_MCS_NESS_KNOWN 0x40
#define IEEE80211_RADIOTAP_MCS_NESS_BIT_1 0x80
/* For IEEE80211_RADIOTAP_MCS flags */
#define IEEE80211_RADIOTAP_MCS_BANDWIDTH_MASK 0x03
#define IEEE80211_RADIOTAP_MCS_BANDWIDTH_20 0
#define IEEE80211_RADIOTAP_MCS_BANDWIDTH_40 1
#define IEEE80211_RADIOTAP_MCS_BANDWIDTH_20L 2
#define IEEE80211_RADIOTAP_MCS_BANDWIDTH_20U 3
#define IEEE80211_RADIOTAP_MCS_SHORT_GI 0x04 /* short guard interval */
#define IEEE80211_RADIOTAP_MCS_HT_GREENFIELD 0x08
#define IEEE80211_RADIOTAP_MCS_FEC_LDPC 0x10
#define IEEE80211_RADIOTAP_MCS_STBC_MASK 0x60
#define IEEE80211_RADIOTAP_MCS_STBC_1 1
#define IEEE80211_RADIOTAP_MCS_STBC_2 2
#define IEEE80211_RADIOTAP_MCS_STBC_3 3
#define IEEE80211_RADIOTAP_MCS_STBC_SHIFT 5
#define IEEE80211_RADIOTAP_MCS_NESS_BIT_0 0x80
/* For IEEE80211_RADIOTAP_AMPDU_STATUS */
#define IEEE80211_RADIOTAP_AMPDU_REPORT_ZEROLEN 0x0001
#define IEEE80211_RADIOTAP_AMPDU_IS_ZEROLEN 0x0002
#define IEEE80211_RADIOTAP_AMPDU_LAST_KNOWN 0x0004
#define IEEE80211_RADIOTAP_AMPDU_IS_LAST 0x0008
#define IEEE80211_RADIOTAP_AMPDU_DELIM_CRC_ERR 0x0010
#define IEEE80211_RADIOTAP_AMPDU_DELIM_CRC_KNOWN 0x0020
/* For IEEE80211_RADIOTAP_VHT known */
#define IEEE80211_RADIOTAP_VHT_STBC_KNOWN 0x0001
#define IEEE80211_RADIOTAP_VHT_TXOP_PS_NA_KNOWN 0x0002
#define IEEE80211_RADIOTAP_VHT_GUARD_INTERVAL_KNOWN 0x0004
#define IEEE80211_RADIOTAP_VHT_SGI_NSYM_DIS_KNOWN 0x0008
#define IEEE80211_RADIOTAP_VHT_LDPC_EXTRA_OFDM_SYM_KNOWN 0x0010
#define IEEE80211_RADIOTAP_VHT_BEAMFORMED_KNOWN 0x0020
#define IEEE80211_RADIOTAP_VHT_BANDWIDTH_KNOWN 0x0040
#define IEEE80211_RADIOTAP_VHT_GROUP_ID_KNOWN 0x0080
#define IEEE80211_RADIOTAP_VHT_PARTIAL_AID_KNOWN 0x0100
/* For IEEE80211_RADIOTAP_VHT flags */
#define IEEE80211_RADIOTAP_VHT_STBC 0x01
#define IEEE80211_RADIOTAP_VHT_TXOP_PS_NA 0x02
#define IEEE80211_RADIOTAP_VHT_SHORT_GI 0x04
#define IEEE80211_RADIOTAP_VHT_SGI_NSYM_M10_9 0x08
#define IEEE80211_RADIOTAP_VHT_LDPC_EXTRA_OFDM_SYM 0x10
#define IEEE80211_RADIOTAP_VHT_BEAMFORMED 0x20
#define IEEE80211_RADIOTAP_VHT_BANDWIDTH_MASK 0x1f
#define IEEE80211_RADIOTAP_VHT_NSS_MASK 0x0f
#define IEEE80211_RADIOTAP_VHT_MCS_MASK 0xf0
#define IEEE80211_RADIOTAP_VHT_MCS_SHIFT 4
#define IEEE80211_RADIOTAP_CODING_LDPC_USERn 0x01
#define IEEE80211_CHAN_FHSS \
(IEEE80211_CHAN_2GHZ | IEEE80211_CHAN_GFSK)
#define IEEE80211_CHAN_A \
(IEEE80211_CHAN_5GHZ | IEEE80211_CHAN_OFDM)
#define IEEE80211_CHAN_B \
(IEEE80211_CHAN_2GHZ | IEEE80211_CHAN_CCK)
#define IEEE80211_CHAN_PUREG \
(IEEE80211_CHAN_2GHZ | IEEE80211_CHAN_OFDM)
#define IEEE80211_CHAN_G \
(IEEE80211_CHAN_2GHZ | IEEE80211_CHAN_DYN)
#define IS_CHAN_FHSS(flags) \
((flags & IEEE80211_CHAN_FHSS) == IEEE80211_CHAN_FHSS)
#define IS_CHAN_A(flags) \
((flags & IEEE80211_CHAN_A) == IEEE80211_CHAN_A)
#define IS_CHAN_B(flags) \
((flags & IEEE80211_CHAN_B) == IEEE80211_CHAN_B)
#define IS_CHAN_PUREG(flags) \
((flags & IEEE80211_CHAN_PUREG) == IEEE80211_CHAN_PUREG)
#define IS_CHAN_G(flags) \
((flags & IEEE80211_CHAN_G) == IEEE80211_CHAN_G)
#define IS_CHAN_ANYG(flags) \
(IS_CHAN_PUREG(flags) || IS_CHAN_G(flags))
static void
print_chaninfo(netdissect_options *ndo,
uint16_t freq, int flags, int presentflags)
{
ND_PRINT((ndo, "%u MHz", freq));
if (presentflags & (1 << IEEE80211_RADIOTAP_MCS)) {
/*
* We have the MCS field, so this is 11n, regardless
* of what the channel flags say.
*/
ND_PRINT((ndo, " 11n"));
} else {
if (IS_CHAN_FHSS(flags))
ND_PRINT((ndo, " FHSS"));
if (IS_CHAN_A(flags)) {
if (flags & IEEE80211_CHAN_HALF)
ND_PRINT((ndo, " 11a/10Mhz"));
else if (flags & IEEE80211_CHAN_QUARTER)
ND_PRINT((ndo, " 11a/5Mhz"));
else
ND_PRINT((ndo, " 11a"));
}
if (IS_CHAN_ANYG(flags)) {
if (flags & IEEE80211_CHAN_HALF)
ND_PRINT((ndo, " 11g/10Mhz"));
else if (flags & IEEE80211_CHAN_QUARTER)
ND_PRINT((ndo, " 11g/5Mhz"));
else
ND_PRINT((ndo, " 11g"));
} else if (IS_CHAN_B(flags))
ND_PRINT((ndo, " 11b"));
if (flags & IEEE80211_CHAN_TURBO)
ND_PRINT((ndo, " Turbo"));
}
/*
* These apply to 11n.
*/
if (flags & IEEE80211_CHAN_HT20)
ND_PRINT((ndo, " ht/20"));
else if (flags & IEEE80211_CHAN_HT40D)
ND_PRINT((ndo, " ht/40-"));
else if (flags & IEEE80211_CHAN_HT40U)
ND_PRINT((ndo, " ht/40+"));
ND_PRINT((ndo, " "));
}
static int
print_radiotap_field(netdissect_options *ndo,
struct cpack_state *s, uint32_t bit, uint8_t *flagsp,
uint32_t presentflags)
{
u_int i;
int rc;
switch (bit) {
case IEEE80211_RADIOTAP_TSFT: {
uint64_t tsft;
rc = cpack_uint64(s, &tsft);
if (rc != 0)
goto trunc;
ND_PRINT((ndo, "%" PRIu64 "us tsft ", tsft));
break;
}
case IEEE80211_RADIOTAP_FLAGS: {
uint8_t flagsval;
rc = cpack_uint8(s, &flagsval);
if (rc != 0)
goto trunc;
*flagsp = flagsval;
if (flagsval & IEEE80211_RADIOTAP_F_CFP)
ND_PRINT((ndo, "cfp "));
if (flagsval & IEEE80211_RADIOTAP_F_SHORTPRE)
ND_PRINT((ndo, "short preamble "));
if (flagsval & IEEE80211_RADIOTAP_F_WEP)
ND_PRINT((ndo, "wep "));
if (flagsval & IEEE80211_RADIOTAP_F_FRAG)
ND_PRINT((ndo, "fragmented "));
if (flagsval & IEEE80211_RADIOTAP_F_BADFCS)
ND_PRINT((ndo, "bad-fcs "));
break;
}
case IEEE80211_RADIOTAP_RATE: {
uint8_t rate;
rc = cpack_uint8(s, &rate);
if (rc != 0)
goto trunc;
/*
* XXX On FreeBSD rate & 0x80 means we have an MCS. On
* Linux and AirPcap it does not. (What about
* Mac OS X, NetBSD, OpenBSD, and DragonFly BSD?)
*
* This is an issue either for proprietary extensions
* to 11a or 11g, which do exist, or for 11n
* implementations that stuff a rate value into
* this field, which also appear to exist.
*
* We currently handle that by assuming that
* if the 0x80 bit is set *and* the remaining
* bits have a value between 0 and 15 it's
* an MCS value, otherwise it's a rate. If
* there are cases where systems that use
* "0x80 + MCS index" for MCS indices > 15,
* or stuff a rate value here between 64 and
* 71.5 Mb/s in here, we'll need a preference
* setting. Such rates do exist, e.g. 11n
* MCS 7 at 20 MHz with a long guard interval.
*/
if (rate >= 0x80 && rate <= 0x8f) {
/*
* XXX - we don't know the channel width
* or guard interval length, so we can't
* convert this to a data rate.
*
* If you want us to show a data rate,
* use the MCS field, not the Rate field;
* the MCS field includes not only the
* MCS index, it also includes bandwidth
* and guard interval information.
*
* XXX - can we get the channel width
* from XChannel and the guard interval
* information from Flags, at least on
* FreeBSD?
*/
ND_PRINT((ndo, "MCS %u ", rate & 0x7f));
} else
ND_PRINT((ndo, "%2.1f Mb/s ", .5 * rate));
break;
}
case IEEE80211_RADIOTAP_CHANNEL: {
uint16_t frequency;
uint16_t flags;
rc = cpack_uint16(s, &frequency);
if (rc != 0)
goto trunc;
rc = cpack_uint16(s, &flags);
if (rc != 0)
goto trunc;
/*
* If CHANNEL and XCHANNEL are both present, skip
* CHANNEL.
*/
if (presentflags & (1 << IEEE80211_RADIOTAP_XCHANNEL))
break;
print_chaninfo(ndo, frequency, flags, presentflags);
break;
}
case IEEE80211_RADIOTAP_FHSS: {
uint8_t hopset;
uint8_t hoppat;
rc = cpack_uint8(s, &hopset);
if (rc != 0)
goto trunc;
rc = cpack_uint8(s, &hoppat);
if (rc != 0)
goto trunc;
ND_PRINT((ndo, "fhset %d fhpat %d ", hopset, hoppat));
break;
}
case IEEE80211_RADIOTAP_DBM_ANTSIGNAL: {
int8_t dbm_antsignal;
rc = cpack_int8(s, &dbm_antsignal);
if (rc != 0)
goto trunc;
ND_PRINT((ndo, "%ddBm signal ", dbm_antsignal));
break;
}
case IEEE80211_RADIOTAP_DBM_ANTNOISE: {
int8_t dbm_antnoise;
rc = cpack_int8(s, &dbm_antnoise);
if (rc != 0)
goto trunc;
ND_PRINT((ndo, "%ddBm noise ", dbm_antnoise));
break;
}
case IEEE80211_RADIOTAP_LOCK_QUALITY: {
uint16_t lock_quality;
rc = cpack_uint16(s, &lock_quality);
if (rc != 0)
goto trunc;
ND_PRINT((ndo, "%u sq ", lock_quality));
break;
}
case IEEE80211_RADIOTAP_TX_ATTENUATION: {
uint16_t tx_attenuation;
rc = cpack_uint16(s, &tx_attenuation);
if (rc != 0)
goto trunc;
ND_PRINT((ndo, "%d tx power ", -(int)tx_attenuation));
break;
}
case IEEE80211_RADIOTAP_DB_TX_ATTENUATION: {
uint8_t db_tx_attenuation;
rc = cpack_uint8(s, &db_tx_attenuation);
if (rc != 0)
goto trunc;
ND_PRINT((ndo, "%ddB tx attenuation ", -(int)db_tx_attenuation));
break;
}
case IEEE80211_RADIOTAP_DBM_TX_POWER: {
int8_t dbm_tx_power;
rc = cpack_int8(s, &dbm_tx_power);
if (rc != 0)
goto trunc;
ND_PRINT((ndo, "%ddBm tx power ", dbm_tx_power));
break;
}
case IEEE80211_RADIOTAP_ANTENNA: {
uint8_t antenna;
rc = cpack_uint8(s, &antenna);
if (rc != 0)
goto trunc;
ND_PRINT((ndo, "antenna %u ", antenna));
break;
}
case IEEE80211_RADIOTAP_DB_ANTSIGNAL: {
uint8_t db_antsignal;
rc = cpack_uint8(s, &db_antsignal);
if (rc != 0)
goto trunc;
ND_PRINT((ndo, "%ddB signal ", db_antsignal));
break;
}
case IEEE80211_RADIOTAP_DB_ANTNOISE: {
uint8_t db_antnoise;
rc = cpack_uint8(s, &db_antnoise);
if (rc != 0)
goto trunc;
ND_PRINT((ndo, "%ddB noise ", db_antnoise));
break;
}
case IEEE80211_RADIOTAP_RX_FLAGS: {
uint16_t rx_flags;
rc = cpack_uint16(s, &rx_flags);
if (rc != 0)
goto trunc;
/* Do nothing for now */
break;
}
case IEEE80211_RADIOTAP_XCHANNEL: {
uint32_t flags;
uint16_t frequency;
uint8_t channel;
uint8_t maxpower;
rc = cpack_uint32(s, &flags);
if (rc != 0)
goto trunc;
rc = cpack_uint16(s, &frequency);
if (rc != 0)
goto trunc;
rc = cpack_uint8(s, &channel);
if (rc != 0)
goto trunc;
rc = cpack_uint8(s, &maxpower);
if (rc != 0)
goto trunc;
print_chaninfo(ndo, frequency, flags, presentflags);
break;
}
case IEEE80211_RADIOTAP_MCS: {
uint8_t known;
uint8_t flags;
uint8_t mcs_index;
static const char *ht_bandwidth[4] = {
"20 MHz",
"40 MHz",
"20 MHz (L)",
"20 MHz (U)"
};
float htrate;
rc = cpack_uint8(s, &known);
if (rc != 0)
goto trunc;
rc = cpack_uint8(s, &flags);
if (rc != 0)
goto trunc;
rc = cpack_uint8(s, &mcs_index);
if (rc != 0)
goto trunc;
if (known & IEEE80211_RADIOTAP_MCS_MCS_INDEX_KNOWN) {
/*
* We know the MCS index.
*/
if (mcs_index <= MAX_MCS_INDEX) {
/*
* And it's in-range.
*/
if (known & (IEEE80211_RADIOTAP_MCS_BANDWIDTH_KNOWN|IEEE80211_RADIOTAP_MCS_GUARD_INTERVAL_KNOWN)) {
/*
* And we know both the bandwidth and
* the guard interval, so we can look
* up the rate.
*/
htrate =
ieee80211_float_htrates \
[mcs_index] \
[((flags & IEEE80211_RADIOTAP_MCS_BANDWIDTH_MASK) == IEEE80211_RADIOTAP_MCS_BANDWIDTH_40 ? 1 : 0)] \
[((flags & IEEE80211_RADIOTAP_MCS_SHORT_GI) ? 1 : 0)];
} else {
/*
* We don't know both the bandwidth
* and the guard interval, so we can
* only report the MCS index.
*/
htrate = 0.0;
}
} else {
/*
* The MCS value is out of range.
*/
htrate = 0.0;
}
if (htrate != 0.0) {
/*
* We have the rate.
* Print it.
*/
ND_PRINT((ndo, "%.1f Mb/s MCS %u ", htrate, mcs_index));
} else {
/*
* We at least have the MCS index.
* Print it.
*/
ND_PRINT((ndo, "MCS %u ", mcs_index));
}
}
if (known & IEEE80211_RADIOTAP_MCS_BANDWIDTH_KNOWN) {
ND_PRINT((ndo, "%s ",
ht_bandwidth[flags & IEEE80211_RADIOTAP_MCS_BANDWIDTH_MASK]));
}
if (known & IEEE80211_RADIOTAP_MCS_GUARD_INTERVAL_KNOWN) {
ND_PRINT((ndo, "%s GI ",
(flags & IEEE80211_RADIOTAP_MCS_SHORT_GI) ?
"short" : "long"));
}
if (known & IEEE80211_RADIOTAP_MCS_HT_FORMAT_KNOWN) {
ND_PRINT((ndo, "%s ",
(flags & IEEE80211_RADIOTAP_MCS_HT_GREENFIELD) ?
"greenfield" : "mixed"));
}
if (known & IEEE80211_RADIOTAP_MCS_FEC_TYPE_KNOWN) {
ND_PRINT((ndo, "%s FEC ",
(flags & IEEE80211_RADIOTAP_MCS_FEC_LDPC) ?
"LDPC" : "BCC"));
}
if (known & IEEE80211_RADIOTAP_MCS_STBC_KNOWN) {
ND_PRINT((ndo, "RX-STBC%u ",
(flags & IEEE80211_RADIOTAP_MCS_STBC_MASK) >> IEEE80211_RADIOTAP_MCS_STBC_SHIFT));
}
break;
}
case IEEE80211_RADIOTAP_AMPDU_STATUS: {
uint32_t reference_num;
uint16_t flags;
uint8_t delim_crc;
uint8_t reserved;
rc = cpack_uint32(s, &reference_num);
if (rc != 0)
goto trunc;
rc = cpack_uint16(s, &flags);
if (rc != 0)
goto trunc;
rc = cpack_uint8(s, &delim_crc);
if (rc != 0)
goto trunc;
rc = cpack_uint8(s, &reserved);
if (rc != 0)
goto trunc;
/* Do nothing for now */
break;
}
case IEEE80211_RADIOTAP_VHT: {
uint16_t known;
uint8_t flags;
uint8_t bandwidth;
uint8_t mcs_nss[4];
uint8_t coding;
uint8_t group_id;
uint16_t partial_aid;
static const char *vht_bandwidth[32] = {
"20 MHz",
"40 MHz",
"20 MHz (L)",
"20 MHz (U)",
"80 MHz",
"80 MHz (L)",
"80 MHz (U)",
"80 MHz (LL)",
"80 MHz (LU)",
"80 MHz (UL)",
"80 MHz (UU)",
"160 MHz",
"160 MHz (L)",
"160 MHz (U)",
"160 MHz (LL)",
"160 MHz (LU)",
"160 MHz (UL)",
"160 MHz (UU)",
"160 MHz (LLL)",
"160 MHz (LLU)",
"160 MHz (LUL)",
"160 MHz (UUU)",
"160 MHz (ULL)",
"160 MHz (ULU)",
"160 MHz (UUL)",
"160 MHz (UUU)",
"unknown (26)",
"unknown (27)",
"unknown (28)",
"unknown (29)",
"unknown (30)",
"unknown (31)"
};
rc = cpack_uint16(s, &known);
if (rc != 0)
goto trunc;
rc = cpack_uint8(s, &flags);
if (rc != 0)
goto trunc;
rc = cpack_uint8(s, &bandwidth);
if (rc != 0)
goto trunc;
for (i = 0; i < 4; i++) {
rc = cpack_uint8(s, &mcs_nss[i]);
if (rc != 0)
goto trunc;
}
rc = cpack_uint8(s, &coding);
if (rc != 0)
goto trunc;
rc = cpack_uint8(s, &group_id);
if (rc != 0)
goto trunc;
rc = cpack_uint16(s, &partial_aid);
if (rc != 0)
goto trunc;
for (i = 0; i < 4; i++) {
u_int nss, mcs;
nss = mcs_nss[i] & IEEE80211_RADIOTAP_VHT_NSS_MASK;
mcs = (mcs_nss[i] & IEEE80211_RADIOTAP_VHT_MCS_MASK) >> IEEE80211_RADIOTAP_VHT_MCS_SHIFT;
if (nss == 0)
continue;
ND_PRINT((ndo, "User %u MCS %u ", i, mcs));
ND_PRINT((ndo, "%s FEC ",
(coding & (IEEE80211_RADIOTAP_CODING_LDPC_USERn << i)) ?
"LDPC" : "BCC"));
}
if (known & IEEE80211_RADIOTAP_VHT_BANDWIDTH_KNOWN) {
ND_PRINT((ndo, "%s ",
vht_bandwidth[bandwidth & IEEE80211_RADIOTAP_VHT_BANDWIDTH_MASK]));
}
if (known & IEEE80211_RADIOTAP_VHT_GUARD_INTERVAL_KNOWN) {
ND_PRINT((ndo, "%s GI ",
(flags & IEEE80211_RADIOTAP_VHT_SHORT_GI) ?
"short" : "long"));
}
break;
}
default:
/* this bit indicates a field whose
* size we do not know, so we cannot
* proceed. Just print the bit number.
*/
ND_PRINT((ndo, "[bit %u] ", bit));
return -1;
}
return 0;
trunc:
ND_PRINT((ndo, "%s", tstr));
return rc;
}
static int
print_in_radiotap_namespace(netdissect_options *ndo,
struct cpack_state *s, uint8_t *flags,
uint32_t presentflags, int bit0)
{
#define BITNO_32(x) (((x) >> 16) ? 16 + BITNO_16((x) >> 16) : BITNO_16((x)))
#define BITNO_16(x) (((x) >> 8) ? 8 + BITNO_8((x) >> 8) : BITNO_8((x)))
#define BITNO_8(x) (((x) >> 4) ? 4 + BITNO_4((x) >> 4) : BITNO_4((x)))
#define BITNO_4(x) (((x) >> 2) ? 2 + BITNO_2((x) >> 2) : BITNO_2((x)))
#define BITNO_2(x) (((x) & 2) ? 1 : 0)
uint32_t present, next_present;
int bitno;
enum ieee80211_radiotap_type bit;
int rc;
for (present = presentflags; present; present = next_present) {
/*
* Clear the least significant bit that is set.
*/
next_present = present & (present - 1);
/*
* Get the bit number, within this presence word,
* of the remaining least significant bit that
* is set.
*/
bitno = BITNO_32(present ^ next_present);
/*
* Stop if this is one of the "same meaning
* in all presence flags" bits.
*/
if (bitno >= IEEE80211_RADIOTAP_NAMESPACE)
break;
/*
* Get the radiotap bit number of that bit.
*/
bit = (enum ieee80211_radiotap_type)(bit0 + bitno);
rc = print_radiotap_field(ndo, s, bit, flags, presentflags);
if (rc != 0)
return rc;
}
return 0;
}
static u_int
ieee802_11_radio_print(netdissect_options *ndo,
const u_char *p, u_int length, u_int caplen)
{
#define BIT(n) (1U << n)
#define IS_EXTENDED(__p) \
(EXTRACT_LE_32BITS(__p) & BIT(IEEE80211_RADIOTAP_EXT)) != 0
struct cpack_state cpacker;
const struct ieee80211_radiotap_header *hdr;
uint32_t presentflags;
const uint32_t *presentp, *last_presentp;
int vendor_namespace;
uint8_t vendor_oui[3];
uint8_t vendor_subnamespace;
uint16_t skip_length;
int bit0;
u_int len;
uint8_t flags;
int pad;
u_int fcslen;
if (caplen < sizeof(*hdr)) {
ND_PRINT((ndo, "%s", tstr));
return caplen;
}
hdr = (const struct ieee80211_radiotap_header *)p;
len = EXTRACT_LE_16BITS(&hdr->it_len);
/*
* If we don't have the entire radiotap header, just give up.
*/
if (caplen < len) {
ND_PRINT((ndo, "%s", tstr));
return caplen;
}
cpack_init(&cpacker, (const uint8_t *)hdr, len); /* align against header start */
cpack_advance(&cpacker, sizeof(*hdr)); /* includes the 1st bitmap */
for (last_presentp = &hdr->it_present;
(const u_char*)(last_presentp + 1) <= p + len &&
IS_EXTENDED(last_presentp);
last_presentp++)
cpack_advance(&cpacker, sizeof(hdr->it_present)); /* more bitmaps */
/* are there more bitmap extensions than bytes in header? */
if ((const u_char*)(last_presentp + 1) > p + len) {
ND_PRINT((ndo, "%s", tstr));
return caplen;
}
/*
* Start out at the beginning of the default radiotap namespace.
*/
bit0 = 0;
vendor_namespace = 0;
memset(vendor_oui, 0, 3);
vendor_subnamespace = 0;
skip_length = 0;
/* Assume no flags */
flags = 0;
/* Assume no Atheros padding between 802.11 header and body */
pad = 0;
/* Assume no FCS at end of frame */
fcslen = 0;
for (presentp = &hdr->it_present; presentp <= last_presentp;
presentp++) {
presentflags = EXTRACT_LE_32BITS(presentp);
/*
* If this is a vendor namespace, we don't handle it.
*/
if (vendor_namespace) {
/*
* Skip past the stuff we don't understand.
* If we add support for any vendor namespaces,
* it'd be added here; use vendor_oui and
* vendor_subnamespace to interpret the fields.
*/
if (cpack_advance(&cpacker, skip_length) != 0) {
/*
* Ran out of space in the packet.
*/
break;
}
/*
* We've skipped it all; nothing more to
* skip.
*/
skip_length = 0;
} else {
if (print_in_radiotap_namespace(ndo, &cpacker,
&flags, presentflags, bit0) != 0) {
/*
* Fatal error - can't process anything
* more in the radiotap header.
*/
break;
}
}
/*
* Handle the namespace switch bits; we've already handled
* the extension bit in all but the last word above.
*/
switch (presentflags &
(BIT(IEEE80211_RADIOTAP_NAMESPACE)|BIT(IEEE80211_RADIOTAP_VENDOR_NAMESPACE))) {
case 0:
/*
* We're not changing namespaces.
* advance to the next 32 bits in the current
* namespace.
*/
bit0 += 32;
break;
case BIT(IEEE80211_RADIOTAP_NAMESPACE):
/*
* We're switching to the radiotap namespace.
* Reset the presence-bitmap index to 0, and
* reset the namespace to the default radiotap
* namespace.
*/
bit0 = 0;
vendor_namespace = 0;
memset(vendor_oui, 0, 3);
vendor_subnamespace = 0;
skip_length = 0;
break;
case BIT(IEEE80211_RADIOTAP_VENDOR_NAMESPACE):
/*
* We're switching to a vendor namespace.
* Reset the presence-bitmap index to 0,
* note that we're in a vendor namespace,
* and fetch the fields of the Vendor Namespace
* item.
*/
bit0 = 0;
vendor_namespace = 1;
if ((cpack_align_and_reserve(&cpacker, 2)) == NULL) {
ND_PRINT((ndo, "%s", tstr));
break;
}
if (cpack_uint8(&cpacker, &vendor_oui[0]) != 0) {
ND_PRINT((ndo, "%s", tstr));
break;
}
if (cpack_uint8(&cpacker, &vendor_oui[1]) != 0) {
ND_PRINT((ndo, "%s", tstr));
break;
}
if (cpack_uint8(&cpacker, &vendor_oui[2]) != 0) {
ND_PRINT((ndo, "%s", tstr));
break;
}
if (cpack_uint8(&cpacker, &vendor_subnamespace) != 0) {
ND_PRINT((ndo, "%s", tstr));
break;
}
if (cpack_uint16(&cpacker, &skip_length) != 0) {
ND_PRINT((ndo, "%s", tstr));
break;
}
break;
default:
/*
* Illegal combination. The behavior in this
* case is undefined by the radiotap spec; we
* just ignore both bits.
*/
break;
}
}
if (flags & IEEE80211_RADIOTAP_F_DATAPAD)
pad = 1; /* Atheros padding */
if (flags & IEEE80211_RADIOTAP_F_FCS)
fcslen = 4; /* FCS at end of packet */
return len + ieee802_11_print(ndo, p + len, length - len, caplen - len, pad,
fcslen);
#undef BITNO_32
#undef BITNO_16
#undef BITNO_8
#undef BITNO_4
#undef BITNO_2
#undef BIT
}
static u_int
ieee802_11_avs_radio_print(netdissect_options *ndo,
const u_char *p, u_int length, u_int caplen)
{
uint32_t caphdr_len;
if (caplen < 8) {
ND_PRINT((ndo, "%s", tstr));
return caplen;
}
caphdr_len = EXTRACT_32BITS(p + 4);
if (caphdr_len < 8) {
/*
* Yow! The capture header length is claimed not
* to be large enough to include even the version
* cookie or capture header length!
*/
ND_PRINT((ndo, "%s", tstr));
return caplen;
}
if (caplen < caphdr_len) {
ND_PRINT((ndo, "%s", tstr));
return caplen;
}
return caphdr_len + ieee802_11_print(ndo, p + caphdr_len,
length - caphdr_len, caplen - caphdr_len, 0, 0);
}
#define PRISM_HDR_LEN 144
#define WLANCAP_MAGIC_COOKIE_BASE 0x80211000
#define WLANCAP_MAGIC_COOKIE_V1 0x80211001
#define WLANCAP_MAGIC_COOKIE_V2 0x80211002
/*
* For DLT_PRISM_HEADER; like DLT_IEEE802_11, but with an extra header,
* containing information such as radio information, which we
* currently ignore.
*
* If, however, the packet begins with WLANCAP_MAGIC_COOKIE_V1 or
* WLANCAP_MAGIC_COOKIE_V2, it's really DLT_IEEE802_11_RADIO_AVS
* (currently, on Linux, there's no ARPHRD_ type for
* DLT_IEEE802_11_RADIO_AVS, as there is a ARPHRD_IEEE80211_PRISM
* for DLT_PRISM_HEADER, so ARPHRD_IEEE80211_PRISM is used for
* the AVS header, and the first 4 bytes of the header are used to
* indicate whether it's a Prism header or an AVS header).
*/
u_int
prism_if_print(netdissect_options *ndo,
const struct pcap_pkthdr *h, const u_char *p)
{
u_int caplen = h->caplen;
u_int length = h->len;
uint32_t msgcode;
if (caplen < 4) {
ND_PRINT((ndo, "%s", tstr));
return caplen;
}
msgcode = EXTRACT_32BITS(p);
if (msgcode == WLANCAP_MAGIC_COOKIE_V1 ||
msgcode == WLANCAP_MAGIC_COOKIE_V2)
return ieee802_11_avs_radio_print(ndo, p, length, caplen);
if (caplen < PRISM_HDR_LEN) {
ND_PRINT((ndo, "%s", tstr));
return caplen;
}
return PRISM_HDR_LEN + ieee802_11_print(ndo, p + PRISM_HDR_LEN,
length - PRISM_HDR_LEN, caplen - PRISM_HDR_LEN, 0, 0);
}
/*
* For DLT_IEEE802_11_RADIO; like DLT_IEEE802_11, but with an extra
* header, containing information such as radio information.
*/
u_int
ieee802_11_radio_if_print(netdissect_options *ndo,
const struct pcap_pkthdr *h, const u_char *p)
{
return ieee802_11_radio_print(ndo, p, h->len, h->caplen);
}
/*
* For DLT_IEEE802_11_RADIO_AVS; like DLT_IEEE802_11, but with an
* extra header, containing information such as radio information,
* which we currently ignore.
*/
u_int
ieee802_11_radio_avs_if_print(netdissect_options *ndo,
const struct pcap_pkthdr *h, const u_char *p)
{
return ieee802_11_avs_radio_print(ndo, p, h->len, h->caplen);
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/good_2660_0 |
crossvul-cpp_data_bad_1329_0 | 404: Not Found | ./CrossVul/dataset_final_sorted/CWE-125/c/bad_1329_0 |
crossvul-cpp_data_bad_4493_0 | /*************************************************************************
*
* $Id: trio.c,v 1.131 2010/09/12 11:08:08 breese Exp $
*
* Copyright (C) 1998, 2009 Bjorn Reese and Daniel Stenberg.
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* 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. THE AUTHORS AND
* CONTRIBUTORS ACCEPT NO RESPONSIBILITY IN ANY CONCEIVABLE MANNER.
*
*************************************************************************
*
* A note to trio contributors:
*
* Avoid heap allocation at all costs to ensure that the trio functions
* are async-safe. The exceptions are the printf/fprintf functions, which
* uses fputc, and the asprintf functions and the <alloc> modifier, which
* by design are required to allocate form the heap.
*
************************************************************************/
/*
* TODO:
* - Scan is probably too permissive about its modifiers.
* - C escapes in %#[] ?
* - Multibyte characters (done for format parsing, except scan groups)
* - Complex numbers? (C99 _Complex)
* - Boolean values? (C99 _Bool)
* - C99 NaN(n-char-sequence) missing. The n-char-sequence can be used
* to print the mantissa, e.g. NaN(0xc000000000000000)
* - Should we support the GNU %a alloc modifier? GNU has an ugly hack
* for %a, because C99 used %a for other purposes. If specified as
* %as or %a[ it is interpreted as the alloc modifier, otherwise as
* the C99 hex-float. This means that you cannot scan %as as a hex-float
* immediately followed by an 's'.
* - Scanning of collating symbols.
*/
/*************************************************************************
* Trio include files
*/
#include "triodef.h"
#include "trio.h"
#include "triop.h"
#if defined(TRIO_EMBED_NAN)
#define TRIO_PUBLIC_NAN static
#if TRIO_FEATURE_FLOAT
#define TRIO_FUNC_NAN
#define TRIO_FUNC_NINF
#define TRIO_FUNC_PINF
#define TRIO_FUNC_FPCLASSIFY_AND_SIGNBIT
#define TRIO_FUNC_ISINF
#endif
#endif
#include "trionan.h"
#if defined(TRIO_EMBED_STRING)
#define TRIO_PUBLIC_STRING static
#define TRIO_FUNC_LENGTH
#define TRIO_FUNC_LENGTH_MAX
#define TRIO_FUNC_TO_LONG
#if TRIO_FEATURE_LOCALE
#define TRIO_FUNC_COPY_MAX
#endif
#if TRIO_FEATURE_DYNAMICSTRING
#define TRIO_FUNC_XSTRING_DUPLICATE
#endif
#if TRIO_EXTENSION && TRIO_FEATURE_SCANF
#define TRIO_FUNC_EQUAL_LOCALE
#endif
#if TRIO_FEATURE_ERRNO
#define TRIO_FUNC_ERROR
#endif
#if TRIO_FEATURE_FLOAT && TRIO_FEATURE_SCANF
#define TRIO_FUNC_TO_DOUBLE
#endif
#if TRIO_FEATURE_DYNAMICSTRING
#define TRIO_FUNC_STRING_EXTRACT
#endif
#if TRIO_FEATURE_DYNAMICSTRING
#define TRIO_FUNC_STRING_TERMINATE
#endif
#if TRIO_FEATURE_USER_DEFINED
#define TRIO_FUNC_DUPLICATE
#endif
#if TRIO_FEATURE_DYNAMICSTRING
#define TRIO_FUNC_STRING_DESTROY
#endif
#if TRIO_FEATURE_USER_DEFINED
#define TRIO_FUNC_DESTROY
#endif
#if TRIO_FEATURE_USER_DEFINED || (TRIO_FEATURE_FLOAT && TRIO_FEATURE_SCANF)
#define TRIO_FUNC_EQUAL
#endif
#if TRIO_FEATURE_USER_DEFINED || TRIO_FEATURE_SCANF
#define TRIO_FUNC_EQUAL_CASE
#endif
#if (TRIO_EXTENSION && TRIO_FEATURE_SCANF)
#define TRIO_FUNC_EQUAL_MAX
#endif
#if TRIO_FEATURE_SCANF
#define TRIO_FUNC_TO_UPPER
#endif
#if TRIO_FEATURE_DYNAMICSTRING
#define TRIO_FUNC_XSTRING_APPEND_CHAR
#endif
#endif
#include "triostr.h"
/**************************************************************************
*
* Definitions
*
*************************************************************************/
#include <limits.h>
#if TRIO_FEATURE_FLOAT
#include <math.h>
#include <float.h>
#endif
#if defined(__STDC_ISO_10646__) || defined(MB_LEN_MAX) || defined(USE_MULTIBYTE) || \
TRIO_FEATURE_WIDECHAR
#if (!defined(TRIO_PLATFORM_WINCE) && !defined(ANDROID))
#define TRIO_COMPILER_SUPPORTS_MULTIBYTE
#if !defined(MB_LEN_MAX)
#define MB_LEN_MAX 6
#endif
#endif
#endif
#if (TRIO_COMPILER_VISUALC - 0 >= 1100) || defined(TRIO_COMPILER_BORLAND)
#define TRIO_COMPILER_SUPPORTS_VISUALC_INT
#endif
#if TRIO_FEATURE_FLOAT
#if defined(PREDEF_STANDARD_C99) || defined(PREDEF_STANDARD_UNIX03)
#if !defined(HAVE_FLOORL) && !defined(TRIO_NO_FLOORL)
#define HAVE_FLOORL
#endif
#if !defined(HAVE_CEILL) && !defined(TRIO_NO_CEILL)
#define HAVE_CEILL
#endif
#if !defined(HAVE_POWL) && !defined(TRIO_NO_POWL)
#define HAVE_POWL
#endif
#if !defined(HAVE_FMODL) && !defined(TRIO_NO_FMODL)
#define HAVE_FMODL
#endif
#if !defined(HAVE_LOG10L) && !defined(TRIO_NO_LOG10L)
#define HAVE_LOG10L
#endif
#endif
#if defined(TRIO_COMPILER_VISUALC)
#if defined(floorl)
#define HAVE_FLOORL
#endif
#if defined(ceill)
#define HAVE_CEILL
#endif
#if defined(powl)
#define HAVE_POWL
#endif
#if defined(fmodl)
#define HAVE_FMODL
#endif
#if defined(log10l)
#define HAVE_LOG10L
#endif
#endif
#endif
/*************************************************************************
* Generic definitions
*/
#if !(defined(DEBUG) || defined(NDEBUG))
#define NDEBUG
#endif
#include <assert.h>
#include <ctype.h>
#if defined(PREDEF_STANDARD_C99) && !defined(isascii)
#define isascii(x) ((x)&0x7F)
#endif
#if defined(TRIO_COMPILER_ANCIENT)
#include <varargs.h>
#else
#include <stdarg.h>
#endif
#include <stddef.h>
#if defined(TRIO_PLATFORM_WINCE)
extern int errno;
#else
#include <errno.h>
#endif
#ifndef NULL
#define NULL 0
#endif
#define NIL ((char)0)
#ifndef FALSE
#define FALSE (1 == 0)
#define TRUE (!FALSE)
#endif
#define BOOLEAN_T int
/* mincore() can be used for debugging purposes */
#define VALID(x) (NULL != (x))
#if TRIO_FEATURE_ERRORCODE
/*
* Encode the error code and the position. This is decoded
* with TRIO_ERROR_CODE and TRIO_ERROR_POSITION.
*/
#define TRIO_ERROR_RETURN(x, y) (-((x) + ((y) << 8)))
#else
#define TRIO_ERROR_RETURN(x, y) (-1)
#endif
typedef unsigned long trio_flags_t;
/*************************************************************************
* Platform specific definitions
*/
#if defined(TRIO_PLATFORM_UNIX)
#include <unistd.h>
#include <signal.h>
#include <locale.h>
#if !defined(TRIO_FEATURE_LOCALE)
#define USE_LOCALE
#endif
#endif /* TRIO_PLATFORM_UNIX */
#if defined(TRIO_PLATFORM_VMS)
#include <unistd.h>
#endif
#if defined(TRIO_PLATFORM_WIN32)
#if defined(TRIO_PLATFORM_WINCE)
int read(int handle, char* buffer, unsigned int length);
int write(int handle, const char* buffer, unsigned int length);
#else
#include <io.h>
#define read _read
#define write _write
#endif
#endif /* TRIO_PLATFORM_WIN32 */
#if TRIO_FEATURE_WIDECHAR
#if defined(PREDEF_STANDARD_C94)
#include <wchar.h>
#include <wctype.h>
typedef wchar_t trio_wchar_t;
typedef wint_t trio_wint_t;
#else
typedef char trio_wchar_t;
typedef int trio_wint_t;
#define WCONST(x) L##x
#define WEOF EOF
#define iswalnum(x) isalnum(x)
#define iswalpha(x) isalpha(x)
#define iswcntrl(x) iscntrl(x)
#define iswdigit(x) isdigit(x)
#define iswgraph(x) isgraph(x)
#define iswlower(x) islower(x)
#define iswprint(x) isprint(x)
#define iswpunct(x) ispunct(x)
#define iswspace(x) isspace(x)
#define iswupper(x) isupper(x)
#define iswxdigit(x) isxdigit(x)
#endif
#endif
/*************************************************************************
* Compiler dependent definitions
*/
/* Support for long long */
#ifndef __cplusplus
#if !defined(USE_LONGLONG)
#if defined(TRIO_COMPILER_GCC) && !defined(__STRICT_ANSI__)
#define USE_LONGLONG
#else
#if defined(TRIO_COMPILER_SUNPRO)
#define USE_LONGLONG
#else
#if defined(TRIO_COMPILER_MSVC) && (_MSC_VER >= 1400)
#define USE_LONGLONG
#else
#if defined(_LONG_LONG) || defined(_LONGLONG)
#define USE_LONGLONG
#endif
#endif
#endif
#endif
#endif
#endif
/* The extra long numbers */
#if defined(USE_LONGLONG)
typedef signed long long int trio_longlong_t;
typedef unsigned long long int trio_ulonglong_t;
#else
#if defined(TRIO_COMPILER_SUPPORTS_VISUALC_INT)
typedef signed __int64 trio_longlong_t;
typedef unsigned __int64 trio_ulonglong_t;
#else
typedef TRIO_SIGNED long int trio_longlong_t;
typedef unsigned long int trio_ulonglong_t;
#endif
#endif
/* Maximal and fixed integer types */
#if defined(PREDEF_STANDARD_C99)
#include <stdint.h>
typedef intmax_t trio_intmax_t;
typedef uintmax_t trio_uintmax_t;
typedef int8_t trio_int8_t;
typedef int16_t trio_int16_t;
typedef int32_t trio_int32_t;
typedef int64_t trio_int64_t;
#else
#if defined(PREDEF_STANDARD_UNIX98)
#include <inttypes.h>
typedef intmax_t trio_intmax_t;
typedef uintmax_t trio_uintmax_t;
typedef int8_t trio_int8_t;
typedef int16_t trio_int16_t;
typedef int32_t trio_int32_t;
typedef int64_t trio_int64_t;
#else
#if defined(TRIO_COMPILER_SUPPORTS_VISUALC_INT)
typedef trio_longlong_t trio_intmax_t;
typedef trio_ulonglong_t trio_uintmax_t;
typedef __int8 trio_int8_t;
typedef __int16 trio_int16_t;
typedef __int32 trio_int32_t;
typedef __int64 trio_int64_t;
#else
typedef trio_longlong_t trio_intmax_t;
typedef trio_ulonglong_t trio_uintmax_t;
#if defined(TRIO_INT8_T)
typedef TRIO_INT8_T trio_int8_t;
#else
typedef TRIO_SIGNED char trio_int8_t;
#endif
#if defined(TRIO_INT16_T)
typedef TRIO_INT16_T trio_int16_t;
#else
typedef TRIO_SIGNED short trio_int16_t;
#endif
#if defined(TRIO_INT32_T)
typedef TRIO_INT32_T trio_int32_t;
#else
typedef TRIO_SIGNED int trio_int32_t;
#endif
#if defined(TRIO_INT64_T)
typedef TRIO_INT64_T trio_int64_t;
#else
typedef trio_longlong_t trio_int64_t;
#endif
#endif
#endif
#endif
#if defined(HAVE_FLOORL)
#define trio_floor(x) floorl((x))
#else
#define trio_floor(x) floor((double)(x))
#endif
#if defined(HAVE_CEILL)
#define trio_ceil(x) ceill((x))
#else
#define trio_ceil(x) ceil((double)(x))
#endif
#if defined(HAVE_FMODL)
#define trio_fmod(x, y) fmodl((x), (y))
#else
#define trio_fmod(x, y) fmod((double)(x), (double)(y))
#endif
#if defined(HAVE_POWL)
#define trio_pow(x, y) powl((x), (y))
#else
#define trio_pow(x, y) pow((double)(x), (double)(y))
#endif
#if defined(HAVE_LOG10L)
#define trio_log10(x) log10l((x))
#else
#define trio_log10(x) log10((double)(x))
#endif
#if TRIO_FEATURE_FLOAT
#define TRIO_FABS(x) (((x) < 0.0) ? -(x) : (x))
#endif
/*************************************************************************
* Internal Definitions
*/
#ifdef _WIN32
#pragma warning(push)
#pragma warning(disable : 4244)
#endif
#if TRIO_FEATURE_FLOAT
#if !defined(DECIMAL_DIG)
#define DECIMAL_DIG DBL_DIG
#endif
/* Long double sizes */
#ifdef LDBL_DIG
#define MAX_MANTISSA_DIGITS LDBL_DIG
#define MAX_EXPONENT_DIGITS 4
#define MAX_DOUBLE_DIGITS LDBL_MAX_10_EXP
#else
#define MAX_MANTISSA_DIGITS DECIMAL_DIG
#define MAX_EXPONENT_DIGITS 3
#define MAX_DOUBLE_DIGITS DBL_MAX_10_EXP
#endif
#if defined(TRIO_COMPILER_ANCIENT) || !defined(LDBL_DIG)
#undef LDBL_DIG
#undef LDBL_MANT_DIG
#undef LDBL_EPSILON
#define LDBL_DIG DBL_DIG
#define LDBL_MANT_DIG DBL_MANT_DIG
#define LDBL_EPSILON DBL_EPSILON
#endif
#endif /* TRIO_FEATURE_FLOAT */
/* The maximal number of digits is for base 2 */
#define MAX_CHARS_IN(x) (sizeof(x) * CHAR_BIT)
/* The width of a pointer. The number of bits in a hex digit is 4 */
#define POINTER_WIDTH ((sizeof("0x") - 1) + sizeof(trio_pointer_t) * CHAR_BIT / 4)
#if TRIO_FEATURE_FLOAT
/* Infinite and Not-A-Number for floating-point */
#define INFINITE_LOWER "inf"
#define INFINITE_UPPER "INF"
#define LONG_INFINITE_LOWER "infinite"
#define LONG_INFINITE_UPPER "INFINITE"
#define NAN_LOWER "nan"
#define NAN_UPPER "NAN"
#endif
/* Various constants */
enum
{
TYPE_PRINT = 1,
#if TRIO_FEATURE_SCANF
TYPE_SCAN = 2,
#endif
/* Flags. FLAGS_LAST must be less than ULONG_MAX */
FLAGS_NEW = 0,
FLAGS_STICKY = 1,
FLAGS_SPACE = 2 * FLAGS_STICKY,
FLAGS_SHOWSIGN = 2 * FLAGS_SPACE,
FLAGS_LEFTADJUST = 2 * FLAGS_SHOWSIGN,
FLAGS_ALTERNATIVE = 2 * FLAGS_LEFTADJUST,
FLAGS_SHORT = 2 * FLAGS_ALTERNATIVE,
FLAGS_SHORTSHORT = 2 * FLAGS_SHORT,
FLAGS_LONG = 2 * FLAGS_SHORTSHORT,
FLAGS_QUAD = 2 * FLAGS_LONG,
FLAGS_LONGDOUBLE = 2 * FLAGS_QUAD,
FLAGS_SIZE_T = 2 * FLAGS_LONGDOUBLE,
FLAGS_PTRDIFF_T = 2 * FLAGS_SIZE_T,
FLAGS_INTMAX_T = 2 * FLAGS_PTRDIFF_T,
FLAGS_NILPADDING = 2 * FLAGS_INTMAX_T,
FLAGS_UNSIGNED = 2 * FLAGS_NILPADDING,
FLAGS_UPPER = 2 * FLAGS_UNSIGNED,
FLAGS_WIDTH = 2 * FLAGS_UPPER,
FLAGS_WIDTH_PARAMETER = 2 * FLAGS_WIDTH,
FLAGS_PRECISION = 2 * FLAGS_WIDTH_PARAMETER,
FLAGS_PRECISION_PARAMETER = 2 * FLAGS_PRECISION,
FLAGS_BASE = 2 * FLAGS_PRECISION_PARAMETER,
FLAGS_BASE_PARAMETER = 2 * FLAGS_BASE,
FLAGS_FLOAT_E = 2 * FLAGS_BASE_PARAMETER,
FLAGS_FLOAT_G = 2 * FLAGS_FLOAT_E,
FLAGS_QUOTE = 2 * FLAGS_FLOAT_G,
FLAGS_WIDECHAR = 2 * FLAGS_QUOTE,
FLAGS_IGNORE = 2 * FLAGS_WIDECHAR,
FLAGS_IGNORE_PARAMETER = 2 * FLAGS_IGNORE,
FLAGS_VARSIZE_PARAMETER = 2 * FLAGS_IGNORE_PARAMETER,
FLAGS_FIXED_SIZE = 2 * FLAGS_VARSIZE_PARAMETER,
FLAGS_LAST = FLAGS_FIXED_SIZE,
/* Reused flags */
FLAGS_EXCLUDE = FLAGS_SHORT,
FLAGS_USER_DEFINED = FLAGS_IGNORE,
FLAGS_USER_DEFINED_PARAMETER = FLAGS_IGNORE_PARAMETER,
FLAGS_ROUNDING = FLAGS_INTMAX_T,
/* Compounded flags */
FLAGS_ALL_VARSIZES = FLAGS_LONG | FLAGS_QUAD | FLAGS_INTMAX_T | FLAGS_PTRDIFF_T | FLAGS_SIZE_T,
FLAGS_ALL_SIZES = FLAGS_ALL_VARSIZES | FLAGS_SHORTSHORT | FLAGS_SHORT,
NO_POSITION = -1,
NO_WIDTH = 0,
NO_PRECISION = -1,
NO_SIZE = -1,
/* Do not change these */
NO_BASE = -1,
MIN_BASE = 2,
MAX_BASE = 36,
BASE_BINARY = 2,
BASE_OCTAL = 8,
BASE_DECIMAL = 10,
BASE_HEX = 16,
/* Maximal number of allowed parameters */
MAX_PARAMETERS = 64,
/* Maximal number of characters in class */
MAX_CHARACTER_CLASS = UCHAR_MAX + 1,
#if TRIO_FEATURE_USER_DEFINED
/* Maximal string lengths for user-defined specifiers */
MAX_USER_NAME = 64,
MAX_USER_DATA = 256,
#endif
/* Maximal length of locale separator strings */
MAX_LOCALE_SEPARATOR_LENGTH = MB_LEN_MAX,
/* Maximal number of integers in grouping */
MAX_LOCALE_GROUPS = 64
};
#define NO_GROUPING ((int)CHAR_MAX)
/* Fundamental formatting parameter types */
#define FORMAT_SENTINEL -1 /* marks end of parameters array */
#define FORMAT_UNKNOWN 0
#define FORMAT_INT 1
#define FORMAT_DOUBLE 2
#define FORMAT_CHAR 3
#define FORMAT_STRING 4
#define FORMAT_POINTER 5
#define FORMAT_COUNT 6
#define FORMAT_PARAMETER 7
#define FORMAT_GROUP 8
#define FORMAT_ERRNO 9
#define FORMAT_USER_DEFINED 10
/* Character constants */
#define CHAR_IDENTIFIER '%'
#define CHAR_ALT_IDENTIFIER '$'
#define CHAR_BACKSLASH '\\'
#define CHAR_QUOTE '\"'
#define CHAR_ADJUST ' '
#if TRIO_EXTENSION
/* Character class expressions */
#define CLASS_ALNUM "[:alnum:]"
#define CLASS_ALPHA "[:alpha:]"
#define CLASS_BLANK "[:blank:]"
#define CLASS_CNTRL "[:cntrl:]"
#define CLASS_DIGIT "[:digit:]"
#define CLASS_GRAPH "[:graph:]"
#define CLASS_LOWER "[:lower:]"
#define CLASS_PRINT "[:print:]"
#define CLASS_PUNCT "[:punct:]"
#define CLASS_SPACE "[:space:]"
#define CLASS_UPPER "[:upper:]"
#define CLASS_XDIGIT "[:xdigit:]"
#endif
/*
* SPECIFIERS:
*
*
* a Hex-float
* A Hex-float
* c Character
* C Widechar character (wint_t)
* d Decimal
* e Float
* E Float
* F Float
* F Float
* g Float
* G Float
* i Integer
* m Error message
* n Count
* o Octal
* p Pointer
* s String
* S Widechar string (wchar_t *)
* u Unsigned
* x Hex
* X Hex
* [] Group
* <> User-defined
*
* Reserved:
*
* D Binary Coded Decimal %D(length,precision) (OS/390)
*/
#define SPECIFIER_CHAR 'c'
#define SPECIFIER_STRING 's'
#define SPECIFIER_DECIMAL 'd'
#define SPECIFIER_INTEGER 'i'
#define SPECIFIER_UNSIGNED 'u'
#define SPECIFIER_OCTAL 'o'
#define SPECIFIER_HEX 'x'
#define SPECIFIER_HEX_UPPER 'X'
#if TRIO_FEATURE_FLOAT
#define SPECIFIER_FLOAT_E 'e'
#define SPECIFIER_FLOAT_E_UPPER 'E'
#define SPECIFIER_FLOAT_F 'f'
#define SPECIFIER_FLOAT_F_UPPER 'F'
#define SPECIFIER_FLOAT_G 'g'
#define SPECIFIER_FLOAT_G_UPPER 'G'
#endif
#define SPECIFIER_POINTER 'p'
#if TRIO_FEATURE_SCANF
#define SPECIFIER_GROUP '['
#define SPECIFIER_UNGROUP ']'
#endif
#define SPECIFIER_COUNT 'n'
#if TRIO_UNIX98
#define SPECIFIER_CHAR_UPPER 'C'
#define SPECIFIER_STRING_UPPER 'S'
#endif
#define SPECIFIER_HEXFLOAT 'a'
#define SPECIFIER_HEXFLOAT_UPPER 'A'
#define SPECIFIER_ERRNO 'm'
#if TRIO_FEATURE_BINARY
#define SPECIFIER_BINARY 'b'
#define SPECIFIER_BINARY_UPPER 'B'
#endif
#if TRIO_FEATURE_USER_DEFINED
#define SPECIFIER_USER_DEFINED_BEGIN '<'
#define SPECIFIER_USER_DEFINED_END '>'
#define SPECIFIER_USER_DEFINED_SEPARATOR ':'
#define SPECIFIER_USER_DEFINED_EXTRA '|'
#endif
/*
* QUALIFIERS:
*
*
* Numbers = d,i,o,u,x,X
* Float = a,A,e,E,f,F,g,G
* String = s
* Char = c
*
*
* 9$ Position
* Use the 9th parameter. 9 can be any number between 1 and
* the maximal argument
*
* 9 Width
* Set width to 9. 9 can be any number, but must not be postfixed
* by '$'
*
* h Short
* Numbers:
* (unsigned) short int
*
* hh Short short
* Numbers:
* (unsigned) char
*
* l Long
* Numbers:
* (unsigned) long int
* String:
* as the S specifier
* Char:
* as the C specifier
*
* ll Long Long
* Numbers:
* (unsigned) long long int
*
* L Long Double
* Float
* long double
*
* # Alternative
* Float:
* Decimal-point is always present
* String:
* non-printable characters are handled as \number
*
* Spacing
*
* + Sign
*
* - Alignment
*
* . Precision
*
* * Parameter
* print: use parameter
* scan: no parameter (ignore)
*
* q Quad
*
* Z size_t
*
* w Widechar
*
* ' Thousands/quote
* Numbers:
* Integer part grouped in thousands
* Binary numbers:
* Number grouped in nibbles (4 bits)
* String:
* Quoted string
*
* j intmax_t
* t prtdiff_t
* z size_t
*
* ! Sticky
* @ Parameter (for both print and scan)
*
* I n-bit Integer
* Numbers:
* The following options exists
* I8 = 8-bit integer
* I16 = 16-bit integer
* I32 = 32-bit integer
* I64 = 64-bit integer
*/
#define QUALIFIER_POSITION '$'
#define QUALIFIER_SHORT 'h'
#define QUALIFIER_LONG 'l'
#define QUALIFIER_LONG_UPPER 'L'
#define QUALIFIER_ALTERNATIVE '#'
#define QUALIFIER_SPACE ' '
#define QUALIFIER_PLUS '+'
#define QUALIFIER_MINUS '-'
#define QUALIFIER_DOT '.'
#define QUALIFIER_STAR '*'
#define QUALIFIER_CIRCUMFLEX '^' /* For scanlists */
#define QUALIFIER_SIZE_T 'z'
#define QUALIFIER_PTRDIFF_T 't'
#define QUALIFIER_INTMAX_T 'j'
#define QUALIFIER_QUAD 'q'
#define QUALIFIER_SIZE_T_UPPER 'Z'
#if TRIO_MISC
#define QUALIFIER_WIDECHAR 'w'
#endif
#define QUALIFIER_FIXED_SIZE 'I'
#define QUALIFIER_QUOTE '\''
#define QUALIFIER_STICKY '!'
#define QUALIFIER_VARSIZE '&' /* This should remain undocumented */
#define QUALIFIER_ROUNDING_UPPER 'R'
#if TRIO_EXTENSION
#define QUALIFIER_PARAM '@' /* Experimental */
#define QUALIFIER_COLON ':' /* For scanlists */
#define QUALIFIER_EQUAL '=' /* For scanlists */
#endif
/*************************************************************************
*
* Internal Structures
*
*************************************************************************/
/* Parameters */
typedef struct
{
/* An indication of which entry in the data union is used */
int type;
/* The flags */
trio_flags_t flags;
/* The width qualifier */
int width;
/* The precision qualifier */
int precision;
/* The base qualifier */
int base;
/* Base from specifier */
int baseSpecifier;
/* The size for the variable size qualifier */
int varsize;
/* Offset of the first character of the specifier */
int beginOffset;
/* Offset of the first character after the specifier */
int endOffset;
/* Position in the argument list that this parameter refers to */
int position;
/* The data from the argument list */
union {
char* string;
#if TRIO_FEATURE_WIDECHAR
trio_wchar_t* wstring;
#endif
trio_pointer_t pointer;
union {
trio_intmax_t as_signed;
trio_uintmax_t as_unsigned;
} number;
#if TRIO_FEATURE_FLOAT
double doubleNumber;
double* doublePointer;
trio_long_double_t longdoubleNumber;
trio_long_double_t* longdoublePointer;
#endif
int errorNumber;
} data;
#if TRIO_FEATURE_USER_DEFINED
/* For the user-defined specifier */
union {
char namespace[MAX_USER_NAME];
int handler; /* if flags & FLAGS_USER_DEFINED_PARAMETER */
} user_defined;
char user_data[MAX_USER_DATA];
#endif
} trio_parameter_t;
/* Container for customized functions */
typedef struct
{
union {
trio_outstream_t out;
trio_instream_t in;
} stream;
trio_pointer_t closure;
} trio_custom_t;
/* General trio "class" */
typedef struct _trio_class_t
{
/*
* The function to write characters to a stream.
*/
void(*OutStream) TRIO_PROTO((struct _trio_class_t*, int));
/*
* The function to read characters from a stream.
*/
void(*InStream) TRIO_PROTO((struct _trio_class_t*, int*));
/*
* The function to undo read characters from a stream.
*/
void(*UndoStream) TRIO_PROTO((struct _trio_class_t*));
/*
* The current location in the stream.
*/
trio_pointer_t location;
/*
* The character currently being processed.
*/
int current;
/*
* The number of characters that would have been written/read
* if there had been sufficient space.
*/
int processed;
union {
/*
* The number of characters that are actually written. Processed and
* committed will only differ for the *nprintf functions.
*/
int committed;
/*
* The number of look-ahead characters read.
*/
int cached;
} actually;
/*
* The upper limit of characters that may be written/read.
*/
int max;
/*
* The last output error that was detected.
*/
int error;
} trio_class_t;
/* References (for user-defined callbacks) */
typedef struct _trio_reference_t
{
trio_class_t* data;
trio_parameter_t* parameter;
} trio_reference_t;
#if TRIO_FEATURE_USER_DEFINED
/* Registered entries (for user-defined callbacks) */
typedef struct _trio_userdef_t
{
struct _trio_userdef_t* next;
trio_callback_t callback;
char* name;
} trio_userdef_t;
#endif
/*************************************************************************
*
* Internal Variables
*
*************************************************************************/
/* Unused but kept for reference */
/* static TRIO_CONST char rcsid[] = "@(#)$Id: trio.c,v 1.131 2010/09/12 11:08:08 breese Exp $"; */
#if TRIO_FEATURE_FLOAT
/*
* Need this to workaround a parser bug in HP C/iX compiler that fails
* to resolves macro definitions that includes type 'long double',
* e.g: va_arg(arg_ptr, long double)
*/
#if defined(TRIO_PLATFORM_MPEIX)
static TRIO_CONST trio_long_double_t ___dummy_long_double = 0;
#endif
#endif
static TRIO_CONST char internalNullString[] = "(nil)";
#if defined(USE_LOCALE)
static struct lconv* internalLocaleValues = NULL;
#endif
/*
* UNIX98 says "in a locale where the radix character is not defined,
* the radix character defaults to a period (.)"
*/
#if TRIO_FEATURE_FLOAT || TRIO_FEATURE_LOCALE || defined(USE_LOCALE)
static int internalDecimalPointLength = 1;
static char internalDecimalPoint = '.';
static char internalDecimalPointString[MAX_LOCALE_SEPARATOR_LENGTH + 1] = ".";
#endif
#if TRIO_FEATURE_QUOTE || TRIO_FEATURE_LOCALE || TRIO_EXTENSION
static int internalThousandSeparatorLength = 1;
static char internalThousandSeparator[MAX_LOCALE_SEPARATOR_LENGTH + 1] = ",";
static char internalGrouping[MAX_LOCALE_GROUPS] = { (char)NO_GROUPING };
#endif
static TRIO_CONST char internalDigitsLower[] = "0123456789abcdefghijklmnopqrstuvwxyz";
static TRIO_CONST char internalDigitsUpper[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
#if TRIO_FEATURE_SCANF
static BOOLEAN_T internalDigitsUnconverted = TRUE;
static int internalDigitArray[128];
#if TRIO_EXTENSION
static BOOLEAN_T internalCollationUnconverted = TRUE;
static char internalCollationArray[MAX_CHARACTER_CLASS][MAX_CHARACTER_CLASS];
#endif
#endif
#if TRIO_FEATURE_USER_DEFINED
static TRIO_VOLATILE trio_callback_t internalEnterCriticalRegion = NULL;
static TRIO_VOLATILE trio_callback_t internalLeaveCriticalRegion = NULL;
static trio_userdef_t* internalUserDef = NULL;
#endif
/*************************************************************************
*
* Internal Functions
*
************************************************************************/
#if defined(TRIO_EMBED_NAN)
#include "trionan.c"
#endif
#if defined(TRIO_EMBED_STRING)
#include "triostr.c"
#endif
/*************************************************************************
* TrioInitializeParameter
*
* Description:
* Initialize a trio_parameter_t struct.
*/
TRIO_PRIVATE void TrioInitializeParameter TRIO_ARGS1((parameter), trio_parameter_t* parameter)
{
parameter->type = FORMAT_UNKNOWN;
parameter->flags = 0;
parameter->width = 0;
parameter->precision = 0;
parameter->base = 0;
parameter->baseSpecifier = 0;
parameter->varsize = 0;
parameter->beginOffset = 0;
parameter->endOffset = 0;
parameter->position = 0;
parameter->data.pointer = 0;
#if TRIO_FEATURE_USER_DEFINED
parameter->user_defined.handler = 0;
parameter->user_data[0] = 0;
#endif
}
/*************************************************************************
* TrioCopyParameter
*
* Description:
* Copies one trio_parameter_t struct to another.
*/
TRIO_PRIVATE void TrioCopyParameter TRIO_ARGS2((target, source), trio_parameter_t* target,
TRIO_CONST trio_parameter_t* source)
{
#if TRIO_FEATURE_USER_DEFINED
size_t i;
#endif
target->type = source->type;
target->flags = source->flags;
target->width = source->width;
target->precision = source->precision;
target->base = source->base;
target->baseSpecifier = source->baseSpecifier;
target->varsize = source->varsize;
target->beginOffset = source->beginOffset;
target->endOffset = source->endOffset;
target->position = source->position;
target->data = source->data;
#if TRIO_FEATURE_USER_DEFINED
target->user_defined = source->user_defined;
for (i = 0U; i < sizeof(target->user_data); ++i)
{
if ((target->user_data[i] = source->user_data[i]) == NIL)
break;
}
#endif
}
/*************************************************************************
* TrioIsQualifier
*
* Description:
* Remember to add all new qualifiers to this function.
* QUALIFIER_POSITION must not be added.
*/
TRIO_PRIVATE BOOLEAN_T TrioIsQualifier TRIO_ARGS1((character), TRIO_CONST char character)
{
/* QUALIFIER_POSITION is not included */
switch (character)
{
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case QUALIFIER_PLUS:
case QUALIFIER_MINUS:
case QUALIFIER_SPACE:
case QUALIFIER_DOT:
case QUALIFIER_STAR:
case QUALIFIER_ALTERNATIVE:
case QUALIFIER_SHORT:
case QUALIFIER_LONG:
case QUALIFIER_CIRCUMFLEX:
case QUALIFIER_LONG_UPPER:
case QUALIFIER_SIZE_T:
case QUALIFIER_PTRDIFF_T:
case QUALIFIER_INTMAX_T:
case QUALIFIER_QUAD:
case QUALIFIER_SIZE_T_UPPER:
#if defined(QUALIFIER_WIDECHAR)
case QUALIFIER_WIDECHAR:
#endif
case QUALIFIER_QUOTE:
case QUALIFIER_STICKY:
case QUALIFIER_VARSIZE:
#if defined(QUALIFIER_PARAM)
case QUALIFIER_PARAM:
#endif
case QUALIFIER_FIXED_SIZE:
case QUALIFIER_ROUNDING_UPPER:
return TRUE;
default:
return FALSE;
}
}
/*************************************************************************
* TrioSetLocale
*/
#if defined(USE_LOCALE)
TRIO_PRIVATE void TrioSetLocale(TRIO_NOARGS)
{
internalLocaleValues = (struct lconv*)localeconv();
if (internalLocaleValues)
{
if ((internalLocaleValues->decimal_point) &&
(internalLocaleValues->decimal_point[0] != NIL))
{
internalDecimalPointLength = trio_length(internalLocaleValues->decimal_point);
if (internalDecimalPointLength == 1)
{
internalDecimalPoint = internalLocaleValues->decimal_point[0];
}
else
{
internalDecimalPoint = NIL;
trio_copy_max(internalDecimalPointString, sizeof(internalDecimalPointString),
internalLocaleValues->decimal_point);
}
}
#if TRIO_EXTENSION
if ((internalLocaleValues->thousands_sep) &&
(internalLocaleValues->thousands_sep[0] != NIL))
{
trio_copy_max(internalThousandSeparator, sizeof(internalThousandSeparator),
internalLocaleValues->thousands_sep);
internalThousandSeparatorLength = trio_length(internalThousandSeparator);
}
#endif
#if TRIO_EXTENSION
if ((internalLocaleValues->grouping) && (internalLocaleValues->grouping[0] != NIL))
{
trio_copy_max(internalGrouping, sizeof(internalGrouping),
internalLocaleValues->grouping);
}
#endif
}
}
#endif /* defined(USE_LOCALE) */
#if TRIO_FEATURE_FLOAT && TRIO_FEATURE_QUOTE
TRIO_PRIVATE int TrioCalcThousandSeparatorLength TRIO_ARGS1((digits), int digits)
{
int count = 0;
int step = NO_GROUPING;
char* groupingPointer = internalGrouping;
while (digits > 0)
{
if (*groupingPointer == CHAR_MAX)
{
/* Disable grouping */
break; /* while */
}
else if (*groupingPointer == 0)
{
/* Repeat last group */
if (step == NO_GROUPING)
{
/* Error in locale */
break; /* while */
}
}
else
{
step = *groupingPointer++;
}
if (digits > step)
count += internalThousandSeparatorLength;
digits -= step;
}
return count;
}
#endif /* TRIO_FEATURE_FLOAT && TRIO_FEATURE_QUOTE */
#if TRIO_FEATURE_QUOTE
TRIO_PRIVATE BOOLEAN_T TrioFollowedBySeparator TRIO_ARGS1((position), int position)
{
int step = 0;
char* groupingPointer = internalGrouping;
position--;
if (position == 0)
return FALSE;
while (position > 0)
{
if (*groupingPointer == CHAR_MAX)
{
/* Disable grouping */
break; /* while */
}
else if (*groupingPointer != 0)
{
step = *groupingPointer++;
}
if (step == 0)
break;
position -= step;
}
return (position == 0);
}
#endif /* TRIO_FEATURE_QUOTE */
/*************************************************************************
* TrioGetPosition
*
* Get the %n$ position.
*/
TRIO_PRIVATE int TrioGetPosition TRIO_ARGS2((format, offsetPointer), TRIO_CONST char* format,
int* offsetPointer)
{
#if TRIO_FEATURE_POSITIONAL
char* tmpformat;
int number = 0;
int offset = *offsetPointer;
number = (int)trio_to_long(&format[offset], &tmpformat, BASE_DECIMAL);
offset = (int)(tmpformat - format);
if ((number != 0) && (QUALIFIER_POSITION == format[offset++]))
{
*offsetPointer = offset;
/*
* number is decreased by 1, because n$ starts from 1, whereas
* the array it is indexing starts from 0.
*/
return number - 1;
}
#endif
return NO_POSITION;
}
/*************************************************************************
* TrioFindNamespace
*
* Find registered user-defined specifier.
* The prev argument is used for optimization only.
*/
#if TRIO_FEATURE_USER_DEFINED
TRIO_PRIVATE trio_userdef_t* TrioFindNamespace TRIO_ARGS2((name, prev), TRIO_CONST char* name,
trio_userdef_t** prev)
{
trio_userdef_t* def;
if (internalEnterCriticalRegion)
(void)internalEnterCriticalRegion(NULL);
for (def = internalUserDef; def; def = def->next)
{
/* Case-sensitive string comparison */
if (trio_equal_case(def->name, name))
break;
if (prev)
*prev = def;
}
if (internalLeaveCriticalRegion)
(void)internalLeaveCriticalRegion(NULL);
return def;
}
#endif
/*************************************************************************
* TrioPower
*
* Description:
* Calculate pow(base, exponent), where number and exponent are integers.
*/
#if TRIO_FEATURE_FLOAT
TRIO_PRIVATE trio_long_double_t TrioPower TRIO_ARGS2((number, exponent), int number, int exponent)
{
trio_long_double_t result;
if (number == 10)
{
switch (exponent)
{
/* Speed up calculation of common cases */
case 0:
result = (trio_long_double_t)number * TRIO_SUFFIX_LONG(1E-1);
break;
case 1:
result = (trio_long_double_t)number * TRIO_SUFFIX_LONG(1E+0);
break;
case 2:
result = (trio_long_double_t)number * TRIO_SUFFIX_LONG(1E+1);
break;
case 3:
result = (trio_long_double_t)number * TRIO_SUFFIX_LONG(1E+2);
break;
case 4:
result = (trio_long_double_t)number * TRIO_SUFFIX_LONG(1E+3);
break;
case 5:
result = (trio_long_double_t)number * TRIO_SUFFIX_LONG(1E+4);
break;
case 6:
result = (trio_long_double_t)number * TRIO_SUFFIX_LONG(1E+5);
break;
case 7:
result = (trio_long_double_t)number * TRIO_SUFFIX_LONG(1E+6);
break;
case 8:
result = (trio_long_double_t)number * TRIO_SUFFIX_LONG(1E+7);
break;
case 9:
result = (trio_long_double_t)number * TRIO_SUFFIX_LONG(1E+8);
break;
default:
result = trio_pow((trio_long_double_t)number, (trio_long_double_t)exponent);
break;
}
}
else
{
return trio_pow((trio_long_double_t)number, (trio_long_double_t)exponent);
}
return result;
}
#endif /* TRIO_FEATURE_FLOAT */
/*************************************************************************
* TrioLogarithm
*/
#if TRIO_FEATURE_FLOAT
TRIO_PRIVATE trio_long_double_t TrioLogarithm TRIO_ARGS2((number, base), trio_long_double_t number,
int base)
{
trio_long_double_t result;
if (number <= 0.0)
{
/* xlC crashes on log(0) */
result = (number == 0.0) ? trio_ninf() : trio_nan();
}
else
{
if (base == 10)
{
result = trio_log10(number);
}
else
{
result = trio_log10(number) / trio_log10((double)base);
}
}
return result;
}
#endif /* TRIO_FEATURE_FLOAT */
/*************************************************************************
* TrioLogarithmBase
*/
#if TRIO_FEATURE_FLOAT
TRIO_PRIVATE double TrioLogarithmBase TRIO_ARGS1((base), int base)
{
switch (base)
{
case BASE_BINARY:
return 1.0;
case BASE_OCTAL:
return 3.0;
case BASE_DECIMAL:
return 3.321928094887362345;
case BASE_HEX:
return 4.0;
default:
return TrioLogarithm((double)base, 2);
}
}
#endif /* TRIO_FEATURE_FLOAT */
/*************************************************************************
* TrioParseQualifiers
*
* Description:
* Parse the qualifiers of a potential conversion specifier
*/
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wimplicit-fallthrough"
TRIO_PRIVATE int TrioParseQualifiers TRIO_ARGS4((type, format, offset, parameter), int type,
TRIO_CONST char* format, int offset,
trio_parameter_t* parameter)
{
char ch;
int dots = 0; /* Count number of dots in modifier part */
char* tmpformat;
parameter->beginOffset = offset - 1;
parameter->flags = FLAGS_NEW;
parameter->position = TrioGetPosition(format, &offset);
/* Default values */
parameter->width = NO_WIDTH;
parameter->precision = NO_PRECISION;
parameter->base = NO_BASE;
parameter->varsize = NO_SIZE;
while (TrioIsQualifier(format[offset]))
{
ch = format[offset++];
switch (ch)
{
case QUALIFIER_SPACE:
parameter->flags |= FLAGS_SPACE;
break;
case QUALIFIER_PLUS:
parameter->flags |= FLAGS_SHOWSIGN;
break;
case QUALIFIER_MINUS:
parameter->flags |= FLAGS_LEFTADJUST;
parameter->flags &= ~FLAGS_NILPADDING;
break;
case QUALIFIER_ALTERNATIVE:
parameter->flags |= FLAGS_ALTERNATIVE;
break;
case QUALIFIER_DOT:
if (dots == 0) /* Precision */
{
dots++;
/* Skip if no precision */
if (QUALIFIER_DOT == format[offset])
break;
/* After the first dot we have the precision */
parameter->flags |= FLAGS_PRECISION;
if ((QUALIFIER_STAR == format[offset])
#if defined(QUALIFIER_PARAM)
|| (QUALIFIER_PARAM == format[offset])
#endif
)
{
offset++;
parameter->flags |= FLAGS_PRECISION_PARAMETER;
parameter->precision = TrioGetPosition(format, &offset);
}
else
{
parameter->precision =
trio_to_long(&format[offset], &tmpformat, BASE_DECIMAL);
offset = (int)(tmpformat - format);
}
}
else if (dots == 1) /* Base */
{
dots++;
/* After the second dot we have the base */
parameter->flags |= FLAGS_BASE;
if ((QUALIFIER_STAR == format[offset])
#if defined(QUALIFIER_PARAM)
|| (QUALIFIER_PARAM == format[offset])
#endif
)
{
offset++;
parameter->flags |= FLAGS_BASE_PARAMETER;
parameter->base = TrioGetPosition(format, &offset);
}
else
{
parameter->base = trio_to_long(&format[offset], &tmpformat, BASE_DECIMAL);
if (parameter->base > MAX_BASE)
return TRIO_ERROR_RETURN(TRIO_EINVAL, offset);
offset = (int)(tmpformat - format);
}
}
else
{
return TRIO_ERROR_RETURN(TRIO_EINVAL, offset);
}
break; /* QUALIFIER_DOT */
#if defined(QUALIFIER_PARAM)
case QUALIFIER_PARAM:
parameter->type = TYPE_PRINT;
/* FALLTHROUGH */
#endif
case QUALIFIER_STAR:
/* This has different meanings for print and scan */
if (TYPE_PRINT == type)
{
/* Read with from parameter */
int width = TrioGetPosition(format, &offset);
parameter->flags |= (FLAGS_WIDTH | FLAGS_WIDTH_PARAMETER);
if (NO_POSITION != width)
parameter->width = width;
/* else keep parameter->width = NO_WIDTH which != NO_POSITION */
}
#if TRIO_FEATURE_SCANF
else
{
/* Scan, but do not store result */
parameter->flags |= FLAGS_IGNORE;
}
#endif
break; /* QUALIFIER_STAR */
case '0':
if (!(parameter->flags & FLAGS_LEFTADJUST))
parameter->flags |= FLAGS_NILPADDING;
/* FALLTHROUGH */
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
parameter->flags |= FLAGS_WIDTH;
/*
* &format[offset - 1] is used to "rewind" the read
* character from format
*/
parameter->width = trio_to_long(&format[offset - 1], &tmpformat, BASE_DECIMAL);
offset = (int)(tmpformat - format);
break;
case QUALIFIER_SHORT:
if (parameter->flags & FLAGS_SHORTSHORT)
return TRIO_ERROR_RETURN(TRIO_EINVAL, offset);
else if (parameter->flags & FLAGS_SHORT)
parameter->flags |= FLAGS_SHORTSHORT;
else
parameter->flags |= FLAGS_SHORT;
break;
case QUALIFIER_LONG:
if (parameter->flags & FLAGS_QUAD)
return TRIO_ERROR_RETURN(TRIO_EINVAL, offset);
else if (parameter->flags & FLAGS_LONG)
parameter->flags |= FLAGS_QUAD;
else
parameter->flags |= FLAGS_LONG;
break;
#if TRIO_FEATURE_LONGDOUBLE
case QUALIFIER_LONG_UPPER:
parameter->flags |= FLAGS_LONGDOUBLE;
break;
#endif
#if TRIO_FEATURE_SIZE_T
case QUALIFIER_SIZE_T:
parameter->flags |= FLAGS_SIZE_T;
/* Modify flags for later truncation of number */
if (sizeof(size_t) == sizeof(trio_ulonglong_t))
parameter->flags |= FLAGS_QUAD;
else if (sizeof(size_t) == sizeof(long))
parameter->flags |= FLAGS_LONG;
break;
#endif
#if TRIO_FEATURE_PTRDIFF_T
case QUALIFIER_PTRDIFF_T:
parameter->flags |= FLAGS_PTRDIFF_T;
if (sizeof(ptrdiff_t) == sizeof(trio_ulonglong_t))
parameter->flags |= FLAGS_QUAD;
else if (sizeof(ptrdiff_t) == sizeof(long))
parameter->flags |= FLAGS_LONG;
break;
#endif
#if TRIO_FEATURE_INTMAX_T
case QUALIFIER_INTMAX_T:
parameter->flags |= FLAGS_INTMAX_T;
if (sizeof(trio_intmax_t) == sizeof(trio_ulonglong_t))
parameter->flags |= FLAGS_QUAD;
else if (sizeof(trio_intmax_t) == sizeof(long))
parameter->flags |= FLAGS_LONG;
break;
#endif
#if TRIO_FEATURE_QUAD
case QUALIFIER_QUAD:
parameter->flags |= FLAGS_QUAD;
break;
#endif
#if TRIO_FEATURE_FIXED_SIZE
case QUALIFIER_FIXED_SIZE:
if (parameter->flags & FLAGS_FIXED_SIZE)
return TRIO_ERROR_RETURN(TRIO_EINVAL, offset);
if (parameter->flags &
(FLAGS_ALL_SIZES | FLAGS_LONGDOUBLE | FLAGS_WIDECHAR | FLAGS_VARSIZE_PARAMETER))
return TRIO_ERROR_RETURN(TRIO_EINVAL, offset);
if ((format[offset] == '6') && (format[offset + 1] == '4'))
{
parameter->varsize = sizeof(trio_int64_t);
offset += 2;
}
else if ((format[offset] == '3') && (format[offset + 1] == '2'))
{
parameter->varsize = sizeof(trio_int32_t);
offset += 2;
}
else if ((format[offset] == '1') && (format[offset + 1] == '6'))
{
parameter->varsize = sizeof(trio_int16_t);
offset += 2;
}
else if (format[offset] == '8')
{
parameter->varsize = sizeof(trio_int8_t);
offset++;
}
else
return TRIO_ERROR_RETURN(TRIO_EINVAL, offset);
parameter->flags |= FLAGS_FIXED_SIZE;
break;
#endif /* TRIO_FEATURE_FIXED_SIZE */
#if defined(QUALIFIER_WIDECHAR)
case QUALIFIER_WIDECHAR:
parameter->flags |= FLAGS_WIDECHAR;
break;
#endif
#if TRIO_FEATURE_SIZE_T_UPPER
case QUALIFIER_SIZE_T_UPPER:
break;
#endif
#if TRIO_FEATURE_QUOTE
case QUALIFIER_QUOTE:
parameter->flags |= FLAGS_QUOTE;
break;
#endif
#if TRIO_FEATURE_STICKY
case QUALIFIER_STICKY:
parameter->flags |= FLAGS_STICKY;
break;
#endif
#if TRIO_FEATURE_VARSIZE
case QUALIFIER_VARSIZE:
parameter->flags |= FLAGS_VARSIZE_PARAMETER;
break;
#endif
#if TRIO_FEATURE_ROUNDING
case QUALIFIER_ROUNDING_UPPER:
parameter->flags |= FLAGS_ROUNDING;
break;
#endif
default:
/* Bail out completely to make the error more obvious */
return TRIO_ERROR_RETURN(TRIO_EINVAL, offset);
}
} /* while qualifier */
parameter->endOffset = offset;
return 0;
}
#pragma GCC diagnostic pop
/*************************************************************************
* TrioParseSpecifier
*
* Description:
* Parse the specifier part of a potential conversion specifier
*/
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wimplicit-fallthrough"
TRIO_PRIVATE int TrioParseSpecifier TRIO_ARGS4((type, format, offset, parameter), int type,
TRIO_CONST char* format, int offset,
trio_parameter_t* parameter)
{
parameter->baseSpecifier = NO_BASE;
switch (format[offset++])
{
#if defined(SPECIFIER_CHAR_UPPER)
case SPECIFIER_CHAR_UPPER:
parameter->flags |= FLAGS_WIDECHAR;
/* FALLTHROUGH */
#endif
case SPECIFIER_CHAR:
if (parameter->flags & FLAGS_LONG)
parameter->flags |= FLAGS_WIDECHAR;
else if (parameter->flags & FLAGS_SHORT)
parameter->flags &= ~FLAGS_WIDECHAR;
parameter->type = FORMAT_CHAR;
break;
#if defined(SPECIFIER_STRING_UPPER)
case SPECIFIER_STRING_UPPER:
parameter->flags |= FLAGS_WIDECHAR;
/* FALLTHROUGH */
#endif
case SPECIFIER_STRING:
if (parameter->flags & FLAGS_LONG)
parameter->flags |= FLAGS_WIDECHAR;
else if (parameter->flags & FLAGS_SHORT)
parameter->flags &= ~FLAGS_WIDECHAR;
parameter->type = FORMAT_STRING;
break;
#if defined(SPECIFIER_GROUP)
case SPECIFIER_GROUP:
if (TYPE_SCAN == type)
{
int depth = 1;
parameter->type = FORMAT_GROUP;
if (format[offset] == QUALIFIER_CIRCUMFLEX)
offset++;
if (format[offset] == SPECIFIER_UNGROUP)
offset++;
if (format[offset] == QUALIFIER_MINUS)
offset++;
/* Skip nested brackets */
while (format[offset] != NIL)
{
if (format[offset] == SPECIFIER_GROUP)
{
depth++;
}
else if (format[offset] == SPECIFIER_UNGROUP)
{
if (--depth <= 0)
{
offset++;
break;
}
}
offset++;
}
}
break;
#endif /* defined(SPECIFIER_GROUP) */
case SPECIFIER_INTEGER:
parameter->type = FORMAT_INT;
break;
case SPECIFIER_UNSIGNED:
parameter->flags |= FLAGS_UNSIGNED;
parameter->type = FORMAT_INT;
break;
case SPECIFIER_DECIMAL:
parameter->baseSpecifier = BASE_DECIMAL;
parameter->type = FORMAT_INT;
break;
case SPECIFIER_OCTAL:
parameter->flags |= FLAGS_UNSIGNED;
parameter->baseSpecifier = BASE_OCTAL;
parameter->type = FORMAT_INT;
break;
#if TRIO_FEATURE_BINARY
case SPECIFIER_BINARY_UPPER:
parameter->flags |= FLAGS_UPPER;
/* FALLTHROUGH */
case SPECIFIER_BINARY:
parameter->flags |= FLAGS_NILPADDING;
parameter->baseSpecifier = BASE_BINARY;
parameter->type = FORMAT_INT;
break;
#endif
case SPECIFIER_HEX_UPPER:
parameter->flags |= FLAGS_UPPER;
/* FALLTHROUGH */
case SPECIFIER_HEX:
parameter->flags |= FLAGS_UNSIGNED;
parameter->baseSpecifier = BASE_HEX;
parameter->type = FORMAT_INT;
break;
#if defined(SPECIFIER_FLOAT_E)
#if defined(SPECIFIER_FLOAT_E_UPPER)
case SPECIFIER_FLOAT_E_UPPER:
parameter->flags |= FLAGS_UPPER;
/* FALLTHROUGH */
#endif
case SPECIFIER_FLOAT_E:
parameter->flags |= FLAGS_FLOAT_E;
parameter->type = FORMAT_DOUBLE;
break;
#endif
#if defined(SPECIFIER_FLOAT_G)
#if defined(SPECIFIER_FLOAT_G_UPPER)
case SPECIFIER_FLOAT_G_UPPER:
parameter->flags |= FLAGS_UPPER;
/* FALLTHROUGH */
#endif
case SPECIFIER_FLOAT_G:
parameter->flags |= FLAGS_FLOAT_G;
parameter->type = FORMAT_DOUBLE;
break;
#endif
#if defined(SPECIFIER_FLOAT_F)
#if defined(SPECIFIER_FLOAT_F_UPPER)
case SPECIFIER_FLOAT_F_UPPER:
parameter->flags |= FLAGS_UPPER;
/* FALLTHROUGH */
#endif
case SPECIFIER_FLOAT_F:
parameter->type = FORMAT_DOUBLE;
break;
#endif
#if defined(TRIO_COMPILER_VISUALC)
#pragma warning(push)
#pragma warning(disable : 4127) /* Conditional expression is constant */
#endif
case SPECIFIER_POINTER:
if (sizeof(trio_pointer_t) == sizeof(trio_ulonglong_t))
parameter->flags |= FLAGS_QUAD;
else if (sizeof(trio_pointer_t) == sizeof(long))
parameter->flags |= FLAGS_LONG;
parameter->type = FORMAT_POINTER;
break;
#if defined(TRIO_COMPILER_VISUALC)
#pragma warning(pop)
#endif
case SPECIFIER_COUNT:
parameter->type = FORMAT_COUNT;
break;
#if TRIO_FEATURE_HEXFLOAT
case SPECIFIER_HEXFLOAT_UPPER:
parameter->flags |= FLAGS_UPPER;
/* FALLTHROUGH */
case SPECIFIER_HEXFLOAT:
parameter->baseSpecifier = BASE_HEX;
parameter->type = FORMAT_DOUBLE;
break;
#endif
#if TRIO_FEATURE_ERRNO
case SPECIFIER_ERRNO:
parameter->type = FORMAT_ERRNO;
break;
#endif
#if TRIO_FEATURE_USER_DEFINED
case SPECIFIER_USER_DEFINED_BEGIN:
{
unsigned int max;
int without_namespace = TRUE;
char* tmpformat = (char*)&format[offset];
int ch;
parameter->type = FORMAT_USER_DEFINED;
parameter->user_defined.namespace[0] = NIL;
while ((ch = format[offset]) != NIL)
{
offset++;
if ((ch == SPECIFIER_USER_DEFINED_END) || (ch == SPECIFIER_USER_DEFINED_EXTRA))
{
if (without_namespace)
/* No namespace, handler will be passed as an argument */
parameter->flags |= FLAGS_USER_DEFINED_PARAMETER;
/* Copy the user data */
max = (unsigned int)(&format[offset] - tmpformat);
if (max > MAX_USER_DATA)
max = MAX_USER_DATA;
trio_copy_max(parameter->user_data, max, tmpformat);
/* Skip extra data (which is only there to keep the compiler happy) */
while ((ch != NIL) && (ch != SPECIFIER_USER_DEFINED_END))
ch = format[offset++];
break; /* while */
}
if (ch == SPECIFIER_USER_DEFINED_SEPARATOR)
{
without_namespace = FALSE;
/* Copy the namespace for later looking-up */
max = (int)(&format[offset] - tmpformat);
if (max > MAX_USER_NAME)
max = MAX_USER_NAME;
trio_copy_max(parameter->user_defined.namespace, max, tmpformat);
tmpformat = (char*)&format[offset];
}
}
if (ch != SPECIFIER_USER_DEFINED_END)
return TRIO_ERROR_RETURN(TRIO_EINVAL, offset);
}
break;
#endif /* TRIO_FEATURE_USER_DEFINED */
default:
/* Bail out completely to make the error more obvious */
return TRIO_ERROR_RETURN(TRIO_EINVAL, offset);
}
parameter->endOffset = offset;
return 0;
}
#pragma GCC diagnostic pop
/*************************************************************************
* TrioParse
*
* Description:
* Parse the format string
*/
TRIO_PRIVATE int TrioParse TRIO_ARGS6((type, format, parameters, arglist, argfunc, argarray),
int type, TRIO_CONST char* format,
trio_parameter_t* parameters, va_list arglist,
trio_argfunc_t argfunc, trio_pointer_t* argarray)
{
/* Count the number of times a parameter is referenced */
unsigned short usedEntries[MAX_PARAMETERS];
/* Parameter counters */
int parameterPosition;
int maxParam = -1;
/* Utility variables */
int offset; /* Offset into formatting string */
BOOLEAN_T positional; /* Does the specifier have a positional? */
#if TRIO_FEATURE_STICKY
BOOLEAN_T gotSticky = FALSE; /* Are there any sticky modifiers at all? */
#endif
/*
* indices specifies the order in which the parameters must be
* read from the va_args (this is necessary to handle positionals)
*/
int indices[MAX_PARAMETERS];
int pos = 0;
/* Various variables */
#if defined(TRIO_COMPILER_SUPPORTS_MULTIBYTE)
int charlen;
#endif
int save_errno;
int i = -1;
int num;
trio_parameter_t workParameter;
int status;
/* Both must be set or none must be set */
assert(((argfunc == NULL) && (argarray == NULL)) || ((argfunc != NULL) && (argarray != NULL)));
/*
* The 'parameters' array is not initialized, but we need to
* know which entries we have used.
*/
memset(usedEntries, 0, sizeof(usedEntries));
save_errno = errno;
offset = 0;
parameterPosition = 0;
#if defined(TRIO_COMPILER_SUPPORTS_MULTIBYTE)
(void)mblen(NULL, 0);
#endif
while (format[offset])
{
TrioInitializeParameter(&workParameter);
#if defined(TRIO_COMPILER_SUPPORTS_MULTIBYTE)
if (!isascii(format[offset]))
{
/*
* Multibyte characters cannot be legal specifiers or
* modifiers, so we skip over them.
*/
charlen = mblen(&format[offset], MB_LEN_MAX);
offset += (charlen > 0) ? charlen : 1;
continue; /* while */
}
#endif /* TRIO_COMPILER_SUPPORTS_MULTIBYTE */
switch (format[offset++])
{
case CHAR_IDENTIFIER:
{
if (CHAR_IDENTIFIER == format[offset])
{
/* skip double "%" */
offset++;
continue; /* while */
}
status = TrioParseQualifiers(type, format, offset, &workParameter);
if (status < 0)
return status; /* Return qualifier syntax error */
status = TrioParseSpecifier(type, format, workParameter.endOffset, &workParameter);
if (status < 0)
return status; /* Return specifier syntax error */
}
break;
#if TRIO_EXTENSION
case CHAR_ALT_IDENTIFIER:
{
status = TrioParseQualifiers(type, format, offset, &workParameter);
if (status < 0)
continue; /* False alert, not a user defined specifier */
status = TrioParseSpecifier(type, format, workParameter.endOffset, &workParameter);
if ((status < 0) || (FORMAT_USER_DEFINED != workParameter.type))
continue; /* False alert, not a user defined specifier */
}
break;
#endif
default:
continue; /* while */
}
/* now handle the parsed conversion specification */
positional = (NO_POSITION != workParameter.position);
/*
* Parameters only need the type and value. The value is
* read later.
*/
if (workParameter.flags & FLAGS_WIDTH_PARAMETER)
{
if (workParameter.width == NO_WIDTH)
{
workParameter.width = parameterPosition++;
}
else
{
if (!positional)
workParameter.position = workParameter.width + 1;
}
usedEntries[workParameter.width] += 1;
if (workParameter.width > maxParam)
maxParam = workParameter.width;
parameters[pos].type = FORMAT_PARAMETER;
parameters[pos].flags = 0;
indices[workParameter.width] = pos;
workParameter.width = pos++;
}
if (workParameter.flags & FLAGS_PRECISION_PARAMETER)
{
if (workParameter.precision == NO_PRECISION)
{
workParameter.precision = parameterPosition++;
}
else
{
if (!positional)
workParameter.position = workParameter.precision + 1;
}
usedEntries[workParameter.precision] += 1;
if (workParameter.precision > maxParam)
maxParam = workParameter.precision;
parameters[pos].type = FORMAT_PARAMETER;
parameters[pos].flags = 0;
indices[workParameter.precision] = pos;
workParameter.precision = pos++;
}
if (workParameter.flags & FLAGS_BASE_PARAMETER)
{
if (workParameter.base == NO_BASE)
{
workParameter.base = parameterPosition++;
}
else
{
if (!positional)
workParameter.position = workParameter.base + 1;
}
usedEntries[workParameter.base] += 1;
if (workParameter.base > maxParam)
maxParam = workParameter.base;
parameters[pos].type = FORMAT_PARAMETER;
parameters[pos].flags = 0;
indices[workParameter.base] = pos;
workParameter.base = pos++;
}
#if TRIO_FEATURE_VARSIZE
if (workParameter.flags & FLAGS_VARSIZE_PARAMETER)
{
workParameter.varsize = parameterPosition++;
usedEntries[workParameter.varsize] += 1;
if (workParameter.varsize > maxParam)
maxParam = workParameter.varsize;
parameters[pos].type = FORMAT_PARAMETER;
parameters[pos].flags = 0;
indices[workParameter.varsize] = pos;
workParameter.varsize = pos++;
}
#endif
#if TRIO_FEATURE_USER_DEFINED
if (workParameter.flags & FLAGS_USER_DEFINED_PARAMETER)
{
workParameter.user_defined.handler = parameterPosition++;
usedEntries[workParameter.user_defined.handler] += 1;
if (workParameter.user_defined.handler > maxParam)
maxParam = workParameter.user_defined.handler;
parameters[pos].type = FORMAT_PARAMETER;
parameters[pos].flags = FLAGS_USER_DEFINED;
indices[workParameter.user_defined.handler] = pos;
workParameter.user_defined.handler = pos++;
}
#endif
if (NO_POSITION == workParameter.position)
{
workParameter.position = parameterPosition++;
}
if (workParameter.position > maxParam)
maxParam = workParameter.position;
if (workParameter.position >= MAX_PARAMETERS)
{
/* Bail out completely to make the error more obvious */
return TRIO_ERROR_RETURN(TRIO_ETOOMANY, offset);
}
indices[workParameter.position] = pos;
/* Count the number of times this entry has been used */
usedEntries[workParameter.position] += 1;
/* Find last sticky parameters */
#if TRIO_FEATURE_STICKY
if (workParameter.flags & FLAGS_STICKY)
{
gotSticky = TRUE;
}
else if (gotSticky)
{
for (i = pos - 1; i >= 0; i--)
{
if (parameters[i].type == FORMAT_PARAMETER)
continue;
if ((parameters[i].flags & FLAGS_STICKY) &&
(parameters[i].type == workParameter.type))
{
/* Do not overwrite current qualifiers */
workParameter.flags |= (parameters[i].flags & (unsigned long)~FLAGS_STICKY);
if (workParameter.width == NO_WIDTH)
workParameter.width = parameters[i].width;
if (workParameter.precision == NO_PRECISION)
workParameter.precision = parameters[i].precision;
if (workParameter.base == NO_BASE)
workParameter.base = parameters[i].base;
break;
}
}
}
#endif
if (workParameter.base == NO_BASE)
workParameter.base = BASE_DECIMAL;
offset = workParameter.endOffset;
TrioCopyParameter(¶meters[pos++], &workParameter);
} /* while format characters left */
parameters[pos].type = FORMAT_SENTINEL; /* end parameter array with sentinel */
parameters[pos].beginOffset = offset;
for (num = 0; num <= maxParam; num++)
{
if (usedEntries[num] != 1)
{
if (usedEntries[num] == 0) /* gap detected */
return TRIO_ERROR_RETURN(TRIO_EGAP, num);
else /* double references detected */
return TRIO_ERROR_RETURN(TRIO_EDBLREF, num);
}
i = indices[num];
/*
* FORMAT_PARAMETERS are only present if they must be read,
* so it makes no sense to check the ignore flag (besides,
* the flags variable is not set for that particular type)
*/
if ((parameters[i].type != FORMAT_PARAMETER) && (parameters[i].flags & FLAGS_IGNORE))
continue; /* for all arguments */
/*
* The stack arguments are read according to ANSI C89
* default argument promotions:
*
* char = int
* short = int
* unsigned char = unsigned int
* unsigned short = unsigned int
* float = double
*
* In addition to the ANSI C89 these types are read (the
* default argument promotions of C99 has not been
* considered yet)
*
* long long
* long double
* size_t
* ptrdiff_t
* intmax_t
*/
switch (parameters[i].type)
{
case FORMAT_GROUP:
case FORMAT_STRING:
#if TRIO_FEATURE_WIDECHAR
if (parameters[i].flags & FLAGS_WIDECHAR)
{
parameters[i].data.wstring =
(argfunc == NULL)
? va_arg(arglist, trio_wchar_t*)
: (trio_wchar_t*)(argfunc(argarray, num, TRIO_TYPE_PWCHAR));
}
else
#endif
{
parameters[i].data.string =
(argfunc == NULL) ? va_arg(arglist, char*)
: (char*)(argfunc(argarray, num, TRIO_TYPE_PCHAR));
}
break;
#if TRIO_FEATURE_USER_DEFINED
case FORMAT_USER_DEFINED:
#endif
case FORMAT_POINTER:
case FORMAT_COUNT:
case FORMAT_UNKNOWN:
parameters[i].data.pointer = (argfunc == NULL)
? va_arg(arglist, trio_pointer_t)
: argfunc(argarray, num, TRIO_TYPE_POINTER);
break;
case FORMAT_CHAR:
case FORMAT_INT:
#if TRIO_FEATURE_SCANF
if (TYPE_SCAN == type)
{
if (argfunc == NULL)
parameters[i].data.pointer =
(trio_pointer_t)va_arg(arglist, trio_pointer_t);
else
{
if (parameters[i].type == FORMAT_CHAR)
parameters[i].data.pointer =
(trio_pointer_t)((char*)argfunc(argarray, num, TRIO_TYPE_CHAR));
else if (parameters[i].flags & FLAGS_SHORT)
parameters[i].data.pointer =
(trio_pointer_t)((short*)argfunc(argarray, num, TRIO_TYPE_SHORT));
else
parameters[i].data.pointer =
(trio_pointer_t)((int*)argfunc(argarray, num, TRIO_TYPE_INT));
}
}
else
#endif /* TRIO_FEATURE_SCANF */
{
#if TRIO_FEATURE_VARSIZE || TRIO_FEATURE_FIXED_SIZE
if (parameters[i].flags & (FLAGS_VARSIZE_PARAMETER | FLAGS_FIXED_SIZE))
{
int varsize;
if (parameters[i].flags & FLAGS_VARSIZE_PARAMETER)
{
/*
* Variable sizes are mapped onto the fixed sizes, in
* accordance with integer promotion.
*
* Please note that this may not be portable, as we
* only guess the size, not the layout of the numbers.
* For example, if int is little-endian, and long is
* big-endian, then this will fail.
*/
varsize =
(int)parameters[parameters[i].varsize].data.number.as_unsigned;
}
else
{
/* Used for the I<bits> modifiers */
varsize = parameters[i].varsize;
}
parameters[i].flags &= ~FLAGS_ALL_VARSIZES;
if (varsize <= (int)sizeof(int))
;
else if (varsize <= (int)sizeof(long))
parameters[i].flags |= FLAGS_LONG;
#if TRIO_FEATURE_INTMAX_T
else if (varsize <= (int)sizeof(trio_longlong_t))
parameters[i].flags |= FLAGS_QUAD;
else
parameters[i].flags |= FLAGS_INTMAX_T;
#else
else
parameters[i].flags |= FLAGS_QUAD;
#endif
}
#endif /* TRIO_FEATURE_VARSIZE */
#if TRIO_FEATURE_SIZE_T || TRIO_FEATURE_SIZE_T_UPPER
if (parameters[i].flags & FLAGS_SIZE_T)
parameters[i].data.number.as_unsigned =
(argfunc == NULL)
? (trio_uintmax_t)va_arg(arglist, size_t)
: (trio_uintmax_t)(
*((size_t*)argfunc(argarray, num, TRIO_TYPE_SIZE)));
else
#endif
#if TRIO_FEATURE_PTRDIFF_T
if (parameters[i].flags & FLAGS_PTRDIFF_T)
parameters[i].data.number.as_unsigned =
(argfunc == NULL)
? (trio_uintmax_t)va_arg(arglist, ptrdiff_t)
: (trio_uintmax_t)(
*((ptrdiff_t*)argfunc(argarray, num, TRIO_TYPE_PTRDIFF)));
else
#endif
#if TRIO_FEATURE_INTMAX_T
if (parameters[i].flags & FLAGS_INTMAX_T)
parameters[i].data.number.as_unsigned =
(argfunc == NULL)
? (trio_uintmax_t)va_arg(arglist, trio_intmax_t)
: (trio_uintmax_t)(
*((trio_intmax_t*)argfunc(argarray, num, TRIO_TYPE_UINTMAX)));
else
#endif
if (parameters[i].flags & FLAGS_QUAD)
parameters[i].data.number.as_unsigned =
(argfunc == NULL) ? (trio_uintmax_t)va_arg(arglist, trio_ulonglong_t)
: (trio_uintmax_t)(*((trio_ulonglong_t*)argfunc(
argarray, num, TRIO_TYPE_ULONGLONG)));
else if (parameters[i].flags & FLAGS_LONG)
parameters[i].data.number.as_unsigned =
(argfunc == NULL) ? (trio_uintmax_t)va_arg(arglist, long)
: (trio_uintmax_t)(*(
(long*)argfunc(argarray, num, TRIO_TYPE_LONG)));
else
{
if (argfunc == NULL)
parameters[i].data.number.as_unsigned =
(trio_uintmax_t)va_arg(arglist, int);
else
{
if (parameters[i].type == FORMAT_CHAR)
parameters[i].data.number.as_unsigned = (trio_uintmax_t)(
*((char*)argfunc(argarray, num, TRIO_TYPE_CHAR)));
else if (parameters[i].flags & FLAGS_SHORT)
parameters[i].data.number.as_unsigned = (trio_uintmax_t)(
*((short*)argfunc(argarray, num, TRIO_TYPE_SHORT)));
else
parameters[i].data.number.as_unsigned = (trio_uintmax_t)(
*((int*)argfunc(argarray, num, TRIO_TYPE_INT)));
}
}
}
break;
case FORMAT_PARAMETER:
/*
* The parameter for the user-defined specifier is a pointer,
* whereas the rest (width, precision, base) uses an integer.
*/
if (parameters[i].flags & FLAGS_USER_DEFINED)
parameters[i].data.pointer = (argfunc == NULL)
? va_arg(arglist, trio_pointer_t)
: argfunc(argarray, num, TRIO_TYPE_POINTER);
else
parameters[i].data.number.as_unsigned =
(argfunc == NULL)
? (trio_uintmax_t)va_arg(arglist, int)
: (trio_uintmax_t)(*((int*)argfunc(argarray, num, TRIO_TYPE_INT)));
break;
#if TRIO_FEATURE_FLOAT
case FORMAT_DOUBLE:
#if TRIO_FEATURE_SCANF
if (TYPE_SCAN == type)
{
if (parameters[i].flags & FLAGS_LONGDOUBLE)
parameters[i].data.longdoublePointer =
(argfunc == NULL)
? va_arg(arglist, trio_long_double_t*)
: (trio_long_double_t*)argfunc(argarray, num, TRIO_TYPE_LONGDOUBLE);
else
{
if (parameters[i].flags & FLAGS_LONG)
parameters[i].data.doublePointer =
(argfunc == NULL)
? va_arg(arglist, double*)
: (double*)argfunc(argarray, num, TRIO_TYPE_DOUBLE);
else
parameters[i].data.doublePointer =
(argfunc == NULL)
? (double*)va_arg(arglist, float*)
: (double*)argfunc(argarray, num, TRIO_TYPE_DOUBLE);
}
}
else
#endif /* TRIO_FEATURE_SCANF */
{
if (parameters[i].flags & FLAGS_LONGDOUBLE)
parameters[i].data.longdoubleNumber =
(argfunc == NULL) ? va_arg(arglist, trio_long_double_t)
: (trio_long_double_t)(*((trio_long_double_t*)argfunc(
argarray, num, TRIO_TYPE_LONGDOUBLE)));
else
{
if (argfunc == NULL)
parameters[i].data.longdoubleNumber =
(trio_long_double_t)va_arg(arglist, double);
else
{
if (parameters[i].flags & FLAGS_SHORT)
parameters[i].data.longdoubleNumber = (trio_long_double_t)(
*((float*)argfunc(argarray, num, TRIO_TYPE_FLOAT)));
else
parameters[i].data.longdoubleNumber = (trio_long_double_t)(
*((double*)argfunc(argarray, num, TRIO_TYPE_DOUBLE)));
}
}
}
break;
#endif /* TRIO_FEATURE_FLOAT */
#if TRIO_FEATURE_ERRNO
case FORMAT_ERRNO:
parameters[i].data.errorNumber = save_errno;
break;
#endif
default:
break;
}
} /* for all specifiers */
return num;
}
/*************************************************************************
*
* FORMATTING
*
************************************************************************/
/*************************************************************************
* TrioWriteNumber
*
* Description:
* Output a number.
* The complexity of this function is a result of the complexity
* of the dependencies of the flags.
*/
TRIO_PRIVATE void TrioWriteNumber TRIO_ARGS6((self, number, flags, width, precision, base),
trio_class_t* self, trio_uintmax_t number,
trio_flags_t flags, int width, int precision, int base)
{
BOOLEAN_T isNegative;
BOOLEAN_T isNumberZero;
BOOLEAN_T isPrecisionZero;
BOOLEAN_T ignoreNumber;
char buffer[MAX_CHARS_IN(trio_uintmax_t) * (1 + MAX_LOCALE_SEPARATOR_LENGTH) + 1];
char* bufferend;
char* pointer;
TRIO_CONST char* digits;
int i;
#if TRIO_FEATURE_QUOTE
int length;
char* p;
#endif
int count;
int digitOffset;
assert(VALID(self));
assert(VALID(self->OutStream));
assert(((base >= MIN_BASE) && (base <= MAX_BASE)) || (base == NO_BASE));
digits = (flags & FLAGS_UPPER) ? internalDigitsUpper : internalDigitsLower;
if (base == NO_BASE)
base = BASE_DECIMAL;
isNumberZero = (number == 0);
isPrecisionZero = (precision == 0);
ignoreNumber =
(isNumberZero && isPrecisionZero && !((flags & FLAGS_ALTERNATIVE) && (base == BASE_OCTAL)));
if (flags & FLAGS_UNSIGNED)
{
isNegative = FALSE;
flags &= ~FLAGS_SHOWSIGN;
}
else
{
isNegative = ((trio_intmax_t)number < 0);
if (isNegative)
number = -((trio_intmax_t)number);
}
if (flags & FLAGS_QUAD)
number &= (trio_ulonglong_t)-1;
else if (flags & FLAGS_LONG)
number &= (unsigned long)-1;
else
number &= (unsigned int)-1;
/* Build number */
pointer = bufferend = &buffer[sizeof(buffer) - 1];
*pointer-- = NIL;
for (i = 1; i < (int)sizeof(buffer); i++)
{
digitOffset = number % base;
*pointer-- = digits[digitOffset];
number /= base;
if (number == 0)
break;
#if TRIO_FEATURE_QUOTE
if ((flags & FLAGS_QUOTE) && TrioFollowedBySeparator(i + 1))
{
/*
* We are building the number from the least significant
* to the most significant digit, so we have to copy the
* thousand separator backwards
*/
length = internalThousandSeparatorLength;
if (((int)(pointer - buffer) - length) > 0)
{
p = &internalThousandSeparator[length - 1];
while (length-- > 0)
*pointer-- = *p--;
}
}
#endif
}
if (!ignoreNumber)
{
/* Adjust width */
width -= (bufferend - pointer) - 1;
}
/* Adjust precision */
if (NO_PRECISION != precision)
{
precision -= (bufferend - pointer) - 1;
if (precision < 0)
precision = 0;
flags |= FLAGS_NILPADDING;
}
/* Calculate padding */
count = (!((flags & FLAGS_LEFTADJUST) || (precision == NO_PRECISION))) ? precision : 0;
/* Adjust width further */
if (isNegative || (flags & FLAGS_SHOWSIGN) || (flags & FLAGS_SPACE))
width--;
if ((flags & FLAGS_ALTERNATIVE) && !isNumberZero)
{
switch (base)
{
case BASE_BINARY:
case BASE_HEX:
width -= 2;
break;
case BASE_OCTAL:
if (!(flags & FLAGS_NILPADDING) || (count == 0))
width--;
break;
default:
break;
}
}
/* Output prefixes spaces if needed */
if (!((flags & FLAGS_LEFTADJUST) ||
((flags & FLAGS_NILPADDING) && (precision == NO_PRECISION))))
{
while (width-- > count)
self->OutStream(self, CHAR_ADJUST);
}
/* width has been adjusted for signs and alternatives */
if (isNegative)
self->OutStream(self, '-');
else if (flags & FLAGS_SHOWSIGN)
self->OutStream(self, '+');
else if (flags & FLAGS_SPACE)
self->OutStream(self, ' ');
/* Prefix is not written when the value is zero */
if ((flags & FLAGS_ALTERNATIVE) && !isNumberZero)
{
switch (base)
{
case BASE_BINARY:
self->OutStream(self, '0');
self->OutStream(self, (flags & FLAGS_UPPER) ? 'B' : 'b');
break;
case BASE_OCTAL:
if (!(flags & FLAGS_NILPADDING) || (count == 0))
self->OutStream(self, '0');
break;
case BASE_HEX:
self->OutStream(self, '0');
self->OutStream(self, (flags & FLAGS_UPPER) ? 'X' : 'x');
break;
default:
break;
} /* switch base */
}
/* Output prefixed zero padding if needed */
if (flags & FLAGS_NILPADDING)
{
if (precision == NO_PRECISION)
precision = width;
while (precision-- > 0)
{
self->OutStream(self, '0');
width--;
}
}
if (!ignoreNumber)
{
/* Output the number itself */
while (*(++pointer))
{
self->OutStream(self, *pointer);
}
}
/* Output trailing spaces if needed */
if (flags & FLAGS_LEFTADJUST)
{
while (width-- > 0)
self->OutStream(self, CHAR_ADJUST);
}
}
/*************************************************************************
* TrioWriteStringCharacter
*
* Description:
* Output a single character of a string
*/
TRIO_PRIVATE void TrioWriteStringCharacter TRIO_ARGS3((self, ch, flags), trio_class_t* self, int ch,
trio_flags_t flags)
{
if (flags & FLAGS_ALTERNATIVE)
{
if (!isprint(ch))
{
/*
* Non-printable characters are converted to C escapes or
* \number, if no C escape exists.
*/
self->OutStream(self, CHAR_BACKSLASH);
switch (ch)
{
case '\007':
self->OutStream(self, 'a');
break;
case '\b':
self->OutStream(self, 'b');
break;
case '\f':
self->OutStream(self, 'f');
break;
case '\n':
self->OutStream(self, 'n');
break;
case '\r':
self->OutStream(self, 'r');
break;
case '\t':
self->OutStream(self, 't');
break;
case '\v':
self->OutStream(self, 'v');
break;
case '\\':
self->OutStream(self, '\\');
break;
default:
self->OutStream(self, 'x');
TrioWriteNumber(self, (trio_uintmax_t)ch, FLAGS_UNSIGNED | FLAGS_NILPADDING, 2,
2, BASE_HEX);
break;
}
}
else if (ch == CHAR_BACKSLASH)
{
self->OutStream(self, CHAR_BACKSLASH);
self->OutStream(self, CHAR_BACKSLASH);
}
else
{
self->OutStream(self, ch);
}
}
else
{
self->OutStream(self, ch);
}
}
/*************************************************************************
* TrioWriteString
*
* Description:
* Output a string
*/
TRIO_PRIVATE void TrioWriteString TRIO_ARGS5((self, string, flags, width, precision),
trio_class_t* self, TRIO_CONST char* string,
trio_flags_t flags, int width, int precision)
{
int length;
int ch;
assert(VALID(self));
assert(VALID(self->OutStream));
if (string == NULL)
{
string = internalNullString;
length = sizeof(internalNullString) - 1;
#if TRIO_FEATURE_QUOTE
/* Disable quoting for the null pointer */
flags &= (~FLAGS_QUOTE);
#endif
width = 0;
}
else
{
if (precision == 0)
{
length = trio_length(string);
}
else
{
length = trio_length_max(string, precision);
}
}
if ((NO_PRECISION != precision) && (precision < length))
{
length = precision;
}
width -= length;
#if TRIO_FEATURE_QUOTE
if (flags & FLAGS_QUOTE)
self->OutStream(self, CHAR_QUOTE);
#endif
if (!(flags & FLAGS_LEFTADJUST))
{
while (width-- > 0)
self->OutStream(self, CHAR_ADJUST);
}
while (length-- > 0)
{
/* The ctype parameters must be an unsigned char (or EOF) */
ch = (int)((unsigned char)(*string++));
TrioWriteStringCharacter(self, ch, flags);
}
if (flags & FLAGS_LEFTADJUST)
{
while (width-- > 0)
self->OutStream(self, CHAR_ADJUST);
}
#if TRIO_FEATURE_QUOTE
if (flags & FLAGS_QUOTE)
self->OutStream(self, CHAR_QUOTE);
#endif
}
/*************************************************************************
* TrioWriteWideStringCharacter
*
* Description:
* Output a wide string as a multi-byte sequence
*/
#if TRIO_FEATURE_WIDECHAR
TRIO_PRIVATE int TrioWriteWideStringCharacter TRIO_ARGS4((self, wch, flags, width),
trio_class_t* self, trio_wchar_t wch,
trio_flags_t flags, int width)
{
int size;
int i;
int ch;
char* string;
char buffer[MB_LEN_MAX + 1];
if (width == NO_WIDTH)
width = sizeof(buffer);
size = wctomb(buffer, wch);
if ((size <= 0) || (size > width) || (buffer[0] == NIL))
return 0;
string = buffer;
i = size;
while ((width >= i) && (width-- > 0) && (i-- > 0))
{
/* The ctype parameters must be an unsigned char (or EOF) */
ch = (int)((unsigned char)(*string++));
TrioWriteStringCharacter(self, ch, flags);
}
return size;
}
#endif /* TRIO_FEATURE_WIDECHAR */
/*************************************************************************
* TrioWriteWideString
*
* Description:
* Output a wide character string as a multi-byte string
*/
#if TRIO_FEATURE_WIDECHAR
TRIO_PRIVATE void TrioWriteWideString TRIO_ARGS5((self, wstring, flags, width, precision),
trio_class_t* self,
TRIO_CONST trio_wchar_t* wstring,
trio_flags_t flags, int width, int precision)
{
int length;
int size;
assert(VALID(self));
assert(VALID(self->OutStream));
#if defined(TRIO_COMPILER_SUPPORTS_MULTIBYTE)
/* Required by TrioWriteWideStringCharacter */
(void)mblen(NULL, 0);
#endif
if (wstring == NULL)
{
TrioWriteString(self, NULL, flags, width, precision);
return;
}
if (NO_PRECISION == precision)
{
length = INT_MAX;
}
else
{
length = precision;
width -= length;
}
#if TRIO_FEATURE_QUOTE
if (flags & FLAGS_QUOTE)
self->OutStream(self, CHAR_QUOTE);
#endif
if (!(flags & FLAGS_LEFTADJUST))
{
while (width-- > 0)
self->OutStream(self, CHAR_ADJUST);
}
while (length > 0)
{
size = TrioWriteWideStringCharacter(self, *wstring++, flags, length);
if (size == 0)
break; /* while */
length -= size;
}
if (flags & FLAGS_LEFTADJUST)
{
while (width-- > 0)
self->OutStream(self, CHAR_ADJUST);
}
#if TRIO_FEATURE_QUOTE
if (flags & FLAGS_QUOTE)
self->OutStream(self, CHAR_QUOTE);
#endif
}
#endif /* TRIO_FEATURE_WIDECHAR */
/*************************************************************************
* TrioWriteDouble
*
* http://wwwold.dkuug.dk/JTC1/SC22/WG14/www/docs/dr_211.htm
*
* "5.2.4.2.2 paragraph #4
*
* The accuracy [...] is implementation defined, as is the accuracy
* of the conversion between floating-point internal representations
* and string representations performed by the libray routine in
* <stdio.h>"
*/
/* FIXME: handle all instances of constant long-double number (L)
* and *l() math functions.
*/
#if TRIO_FEATURE_FLOAT
TRIO_PRIVATE void TrioWriteDouble TRIO_ARGS6((self, number, flags, width, precision, base),
trio_class_t* self, trio_long_double_t number,
trio_flags_t flags, int width, int precision, int base)
{
trio_long_double_t integerNumber;
trio_long_double_t fractionNumber;
trio_long_double_t workNumber;
int integerDigits;
int fractionDigits;
int exponentDigits;
int workDigits;
int baseDigits;
int integerThreshold;
int fractionThreshold;
int expectedWidth;
int exponent = 0;
unsigned int uExponent = 0;
int exponentBase;
trio_long_double_t dblBase;
trio_long_double_t dblFractionBase;
trio_long_double_t integerAdjust;
trio_long_double_t fractionAdjust;
trio_long_double_t workFractionNumber;
trio_long_double_t workFractionAdjust;
int fractionDigitsInspect;
BOOLEAN_T isNegative;
BOOLEAN_T isExponentNegative = FALSE;
BOOLEAN_T requireTwoDigitExponent;
BOOLEAN_T isHex;
TRIO_CONST char* digits;
#if TRIO_FEATURE_QUOTE
char* groupingPointer;
#endif
int i;
int offset;
BOOLEAN_T hasOnlyZeroes;
int leadingFractionZeroes = -1;
register int trailingZeroes;
BOOLEAN_T keepTrailingZeroes;
BOOLEAN_T keepDecimalPoint;
trio_long_double_t epsilon;
BOOLEAN_T adjustNumber = FALSE;
assert(VALID(self));
assert(VALID(self->OutStream));
assert(((base >= MIN_BASE) && (base <= MAX_BASE)) || (base == NO_BASE));
/* Determine sign and look for special quantities */
switch (trio_fpclassify_and_signbit(number, &isNegative))
{
case TRIO_FP_NAN:
TrioWriteString(self, (flags & FLAGS_UPPER) ? NAN_UPPER : NAN_LOWER, flags, width,
precision);
return;
case TRIO_FP_INFINITE:
if (isNegative)
{
/* Negative infinity */
TrioWriteString(self,
(flags & FLAGS_UPPER) ? "-" INFINITE_UPPER : "-" INFINITE_LOWER,
flags, width, precision);
return;
}
else
{
/* Positive infinity */
TrioWriteString(self, (flags & FLAGS_UPPER) ? INFINITE_UPPER : INFINITE_LOWER,
flags, width, precision);
return;
}
default:
/* Finitude */
break;
}
/* Normal numbers */
if (flags & FLAGS_LONGDOUBLE)
{
baseDigits =
(base == 10) ? LDBL_DIG : (int)trio_floor(LDBL_MANT_DIG / TrioLogarithmBase(base));
epsilon = LDBL_EPSILON;
}
else if (flags & FLAGS_SHORT)
{
baseDigits = (base == BASE_DECIMAL)
? FLT_DIG
: (int)trio_floor(FLT_MANT_DIG / TrioLogarithmBase(base));
epsilon = FLT_EPSILON;
}
else
{
baseDigits = (base == BASE_DECIMAL)
? DBL_DIG
: (int)trio_floor(DBL_MANT_DIG / TrioLogarithmBase(base));
epsilon = DBL_EPSILON;
}
digits = (flags & FLAGS_UPPER) ? internalDigitsUpper : internalDigitsLower;
isHex = (base == BASE_HEX);
if (base == NO_BASE)
base = BASE_DECIMAL;
dblBase = (trio_long_double_t)base;
keepTrailingZeroes =
!((flags & FLAGS_ROUNDING) || ((flags & FLAGS_FLOAT_G) && !(flags & FLAGS_ALTERNATIVE)));
#if TRIO_FEATURE_ROUNDING
if (flags & FLAGS_ROUNDING)
{
precision = baseDigits;
}
#endif
if (precision == NO_PRECISION)
{
if (isHex)
{
keepTrailingZeroes = FALSE;
precision = FLT_MANT_DIG;
}
else
{
precision = FLT_DIG;
}
}
if (isNegative)
{
number = -number;
}
if (isHex)
{
flags |= FLAGS_FLOAT_E;
}
reprocess:
if (flags & FLAGS_FLOAT_G)
{
if (precision == 0)
precision = 1;
if ((number < TRIO_SUFFIX_LONG(1.0E-4)) ||
(number >= TrioPower(base, (trio_long_double_t)precision)))
{
/* Use scientific notation */
flags |= FLAGS_FLOAT_E;
}
else if (number < 1.0)
{
/*
* Use normal notation. If the integer part of the number is
* zero, then adjust the precision to include leading fractional
* zeros.
*/
workNumber = TrioLogarithm(number, base);
workNumber = TRIO_FABS(workNumber);
if (workNumber - trio_floor(workNumber) < epsilon)
workNumber--;
leadingFractionZeroes = (int)trio_floor(workNumber);
}
}
if (flags & FLAGS_FLOAT_E)
{
/* Scale the number */
workNumber = TrioLogarithm(number, base);
if (trio_isinf(workNumber) == -1)
{
exponent = 0;
/* Undo setting */
if (flags & FLAGS_FLOAT_G)
flags &= ~FLAGS_FLOAT_E;
}
else
{
exponent = (int)trio_floor(workNumber);
workNumber = number;
/*
* The expression A * 10^-B is equivalent to A / 10^B but the former
* usually gives better accuracy.
*/
workNumber *= TrioPower(dblBase, (trio_long_double_t)-exponent);
if (trio_isinf(workNumber))
{
/*
* Scaling is done it two steps to avoid problems with subnormal
* numbers.
*/
workNumber /= TrioPower(dblBase, (trio_long_double_t)(exponent / 2));
workNumber /= TrioPower(dblBase, (trio_long_double_t)(exponent - (exponent / 2)));
}
number = workNumber;
isExponentNegative = (exponent < 0);
uExponent = (isExponentNegative) ? -exponent : exponent;
if (isHex)
uExponent *= 4; /* log16(2) */
#if TRIO_FEATURE_QUOTE
/* No thousand separators */
flags &= ~FLAGS_QUOTE;
#endif
}
}
integerNumber = trio_floor(number);
fractionNumber = number - integerNumber;
/*
* Truncated number.
*
* Precision is number of significant digits for FLOAT_G and number of
* fractional digits for others.
*/
integerDigits = 1;
if (integerNumber > epsilon)
{
integerDigits += (int)TrioLogarithm(integerNumber, base);
}
fractionDigits = precision;
if (flags & FLAGS_FLOAT_G)
{
if (leadingFractionZeroes > 0)
{
fractionDigits += leadingFractionZeroes;
}
if ((integerNumber > epsilon) || (number <= epsilon))
{
fractionDigits -= integerDigits;
}
}
dblFractionBase = TrioPower(base, fractionDigits);
if (integerNumber < 1.0)
{
workNumber = number * dblFractionBase + TRIO_SUFFIX_LONG(0.5);
if (trio_floor(number * dblFractionBase) != trio_floor(workNumber))
{
adjustNumber = TRUE;
/* Remove a leading fraction zero if fraction is rounded up */
if ((int)TrioLogarithm(number * dblFractionBase, base) !=
(int)TrioLogarithm(workNumber, base))
{
--leadingFractionZeroes;
}
}
workNumber /= dblFractionBase;
}
else
{
workNumber = number + TRIO_SUFFIX_LONG(0.5) / dblFractionBase;
adjustNumber = (trio_floor(number) != trio_floor(workNumber));
}
if (adjustNumber)
{
if ((flags & FLAGS_FLOAT_G) && !(flags & FLAGS_FLOAT_E))
{
/* The adjustment may require a change to scientific notation */
if ((workNumber < TRIO_SUFFIX_LONG(1.0E-4)) ||
(workNumber >= TrioPower(base, (trio_long_double_t)precision)))
{
/* Use scientific notation */
flags |= FLAGS_FLOAT_E;
goto reprocess;
}
}
if (flags & FLAGS_FLOAT_E)
{
workDigits = 1 + TrioLogarithm(trio_floor(workNumber), base);
if (integerDigits == workDigits)
{
/* Adjust if the same number of digits are used */
number += TRIO_SUFFIX_LONG(0.5) / dblFractionBase;
integerNumber = trio_floor(number);
fractionNumber = number - integerNumber;
}
else
{
/* Adjust if number was rounded up one digit (ie. 0.99 to 1.00) */
exponent++;
isExponentNegative = (exponent < 0);
uExponent = (isExponentNegative) ? -exponent : exponent;
if (isHex)
uExponent *= 4; /* log16(2) */
workNumber = (number + TRIO_SUFFIX_LONG(0.5) / dblFractionBase) / dblBase;
integerNumber = trio_floor(workNumber);
fractionNumber = workNumber - integerNumber;
}
}
else
{
if (workNumber > 1.0)
{
/* Adjust if number was rounded up one digit (ie. 99 to 100) */
integerNumber = trio_floor(workNumber);
fractionNumber = 0.0;
integerDigits =
(integerNumber > epsilon) ? 1 + (int)TrioLogarithm(integerNumber, base) : 1;
if (flags & FLAGS_FLOAT_G)
{
if (flags & FLAGS_ALTERNATIVE)
{
fractionDigits = precision;
if ((integerNumber > epsilon) || (number <= epsilon))
{
fractionDigits -= integerDigits;
}
}
else
{
fractionDigits = 0;
}
}
}
else
{
integerNumber = trio_floor(workNumber);
fractionNumber = workNumber - integerNumber;
if (flags & FLAGS_FLOAT_G)
{
if (flags & FLAGS_ALTERNATIVE)
{
fractionDigits = precision;
if (leadingFractionZeroes > 0)
{
fractionDigits += leadingFractionZeroes;
}
if ((integerNumber > epsilon) || (number <= epsilon))
{
fractionDigits -= integerDigits;
}
}
}
}
}
}
/* Estimate accuracy */
integerAdjust = fractionAdjust = TRIO_SUFFIX_LONG(0.5);
#if TRIO_FEATURE_ROUNDING
if (flags & FLAGS_ROUNDING)
{
if (integerDigits > baseDigits)
{
integerThreshold = baseDigits;
fractionDigits = 0;
dblFractionBase = 1.0;
fractionThreshold = 0;
precision = 0; /* Disable decimal-point */
integerAdjust = TrioPower(base, integerDigits - integerThreshold - 1);
fractionAdjust = 0.0;
}
else
{
integerThreshold = integerDigits;
fractionThreshold = fractionDigits - integerThreshold;
fractionAdjust = 1.0;
}
}
else
#endif
{
integerThreshold = INT_MAX;
fractionThreshold = INT_MAX;
}
/*
* Calculate expected width.
* sign + integer part + thousands separators + decimal point
* + fraction + exponent
*/
fractionAdjust /= dblFractionBase;
hasOnlyZeroes = (trio_floor((fractionNumber + fractionAdjust) * dblFractionBase) < epsilon);
keepDecimalPoint = ((flags & FLAGS_ALTERNATIVE) ||
!((precision == 0) || (!keepTrailingZeroes && hasOnlyZeroes)));
expectedWidth = integerDigits + fractionDigits;
if (!keepTrailingZeroes)
{
trailingZeroes = 0;
workFractionNumber = fractionNumber;
workFractionAdjust = fractionAdjust;
fractionDigitsInspect = fractionDigits;
if (integerDigits > integerThreshold)
{
fractionDigitsInspect = 0;
}
else if (fractionThreshold <= fractionDigits)
{
fractionDigitsInspect = fractionThreshold + 1;
}
trailingZeroes = fractionDigits - fractionDigitsInspect;
for (i = 0; i < fractionDigitsInspect; i++)
{
workFractionNumber *= dblBase;
workFractionAdjust *= dblBase;
workNumber = trio_floor(workFractionNumber + workFractionAdjust);
workFractionNumber -= workNumber;
offset = (int)trio_fmod(workNumber, dblBase);
if (offset == 0)
{
trailingZeroes++;
}
else
{
trailingZeroes = 0;
}
}
expectedWidth -= trailingZeroes;
}
if (keepDecimalPoint)
{
expectedWidth += internalDecimalPointLength;
}
#if TRIO_FEATURE_QUOTE
if (flags & FLAGS_QUOTE)
{
expectedWidth += TrioCalcThousandSeparatorLength(integerDigits);
}
#endif
if (isNegative || (flags & FLAGS_SHOWSIGN) || (flags & FLAGS_SPACE))
{
expectedWidth += sizeof("-") - 1;
}
exponentDigits = 0;
if (flags & FLAGS_FLOAT_E)
{
exponentDigits =
(uExponent == 0)
? 1
: (int)trio_ceil(TrioLogarithm((double)(uExponent + 1), (isHex) ? 10 : base));
}
requireTwoDigitExponent = ((base == BASE_DECIMAL) && (exponentDigits == 1));
if (exponentDigits > 0)
{
expectedWidth += exponentDigits;
expectedWidth += (requireTwoDigitExponent ? sizeof("E+0") - 1 : sizeof("E+") - 1);
}
if (isHex)
{
expectedWidth += sizeof("0X") - 1;
}
/* Output prefixing */
if (flags & FLAGS_NILPADDING)
{
/* Leading zeros must be after sign */
if (isNegative)
self->OutStream(self, '-');
else if (flags & FLAGS_SHOWSIGN)
self->OutStream(self, '+');
else if (flags & FLAGS_SPACE)
self->OutStream(self, ' ');
if (isHex)
{
self->OutStream(self, '0');
self->OutStream(self, (flags & FLAGS_UPPER) ? 'X' : 'x');
}
if (!(flags & FLAGS_LEFTADJUST))
{
for (i = expectedWidth; i < width; i++)
{
self->OutStream(self, '0');
}
}
}
else
{
/* Leading spaces must be before sign */
if (!(flags & FLAGS_LEFTADJUST))
{
for (i = expectedWidth; i < width; i++)
{
self->OutStream(self, CHAR_ADJUST);
}
}
if (isNegative)
self->OutStream(self, '-');
else if (flags & FLAGS_SHOWSIGN)
self->OutStream(self, '+');
else if (flags & FLAGS_SPACE)
self->OutStream(self, ' ');
if (isHex)
{
self->OutStream(self, '0');
self->OutStream(self, (flags & FLAGS_UPPER) ? 'X' : 'x');
}
}
/* Output the integer part and thousand separators */
for (i = 0; i < integerDigits; i++)
{
workNumber =
trio_floor(((integerNumber + integerAdjust) / TrioPower(base, integerDigits - i - 1)));
if (i > integerThreshold)
{
/* Beyond accuracy */
self->OutStream(self, digits[0]);
}
else
{
self->OutStream(self, digits[(int)trio_fmod(workNumber, dblBase)]);
}
#if TRIO_FEATURE_QUOTE
if (((flags & (FLAGS_FLOAT_E | FLAGS_QUOTE)) == FLAGS_QUOTE) &&
TrioFollowedBySeparator(integerDigits - i))
{
for (groupingPointer = internalThousandSeparator; *groupingPointer != NIL;
groupingPointer++)
{
self->OutStream(self, *groupingPointer);
}
}
#endif
}
/* Insert decimal point and build the fraction part */
trailingZeroes = 0;
if (keepDecimalPoint)
{
if (internalDecimalPoint)
{
self->OutStream(self, internalDecimalPoint);
}
else
{
for (i = 0; i < internalDecimalPointLength; i++)
{
self->OutStream(self, internalDecimalPointString[i]);
}
}
}
for (i = 0; i < fractionDigits; i++)
{
if ((integerDigits > integerThreshold) || (i > fractionThreshold))
{
/* Beyond accuracy */
trailingZeroes++;
}
else
{
fractionNumber *= dblBase;
fractionAdjust *= dblBase;
workNumber = trio_floor(fractionNumber + fractionAdjust);
if (workNumber > fractionNumber)
{
/* fractionNumber should never become negative */
fractionNumber = 0.0;
fractionAdjust = 0.0;
}
else
{
fractionNumber -= workNumber;
}
offset = (int)trio_fmod(workNumber, dblBase);
if (offset == 0)
{
trailingZeroes++;
}
else
{
while (trailingZeroes > 0)
{
/* Not trailing zeroes after all */
self->OutStream(self, digits[0]);
trailingZeroes--;
}
self->OutStream(self, digits[offset]);
}
}
}
if (keepTrailingZeroes)
{
while (trailingZeroes > 0)
{
self->OutStream(self, digits[0]);
trailingZeroes--;
}
}
/* Output exponent */
if (exponentDigits > 0)
{
self->OutStream(self, isHex ? ((flags & FLAGS_UPPER) ? 'P' : 'p')
: ((flags & FLAGS_UPPER) ? 'E' : 'e'));
self->OutStream(self, (isExponentNegative) ? '-' : '+');
/* The exponent must contain at least two digits */
if (requireTwoDigitExponent)
self->OutStream(self, '0');
if (isHex)
base = 10;
exponentBase = (int)TrioPower(base, exponentDigits - 1);
for (i = 0; i < exponentDigits; i++)
{
self->OutStream(self, digits[(uExponent / exponentBase) % base]);
exponentBase /= base;
}
}
/* Output trailing spaces */
if (flags & FLAGS_LEFTADJUST)
{
for (i = expectedWidth; i < width; i++)
{
self->OutStream(self, CHAR_ADJUST);
}
}
}
#endif /* TRIO_FEATURE_FLOAT */
/*************************************************************************
* TrioFormatProcess
*
* Description:
* This is the main engine for formatting output
*/
TRIO_PRIVATE int TrioFormatProcess TRIO_ARGS3((data, format, parameters), trio_class_t* data,
TRIO_CONST char* format, trio_parameter_t* parameters)
{
int i;
#if TRIO_FEATURE_ERRNO
TRIO_CONST char* string;
#endif
trio_pointer_t pointer;
trio_flags_t flags;
int width;
int precision;
int base;
int offset;
offset = 0;
i = 0;
for (;;)
{
/* Skip the parameter entries */
while (parameters[i].type == FORMAT_PARAMETER)
i++;
/* Copy non conversion-specifier part of format string */
while (offset < parameters[i].beginOffset)
{
if (CHAR_IDENTIFIER == format[offset] && CHAR_IDENTIFIER == format[offset + 1])
{
data->OutStream(data, CHAR_IDENTIFIER);
offset += 2;
}
else
{
data->OutStream(data, format[offset++]);
}
}
/* Abort if we reached end of format string */
if (parameters[i].type == FORMAT_SENTINEL)
break;
/* Ouput parameter */
flags = parameters[i].flags;
/* Find width */
width = parameters[i].width;
if (flags & FLAGS_WIDTH_PARAMETER)
{
/* Get width from parameter list */
width = (int)parameters[width].data.number.as_signed;
if (width < 0)
{
/*
* A negative width is the same as the - flag and
* a positive width.
*/
flags |= FLAGS_LEFTADJUST;
flags &= ~FLAGS_NILPADDING;
width = -width;
}
}
/* Find precision */
if (flags & FLAGS_PRECISION)
{
precision = parameters[i].precision;
if (flags & FLAGS_PRECISION_PARAMETER)
{
/* Get precision from parameter list */
precision = (int)parameters[precision].data.number.as_signed;
if (precision < 0)
{
/*
* A negative precision is the same as no
* precision
*/
precision = NO_PRECISION;
}
}
}
else
{
precision = NO_PRECISION;
}
/* Find base */
if (NO_BASE != parameters[i].baseSpecifier)
{
/* Base from specifier has priority */
base = parameters[i].baseSpecifier;
}
else if (flags & FLAGS_BASE_PARAMETER)
{
/* Get base from parameter list */
base = parameters[i].base;
base = (int)parameters[base].data.number.as_signed;
}
else
{
/* Use base from format string */
base = parameters[i].base;
}
switch (parameters[i].type)
{
case FORMAT_CHAR:
#if TRIO_FEATURE_QUOTE
if (flags & FLAGS_QUOTE)
data->OutStream(data, CHAR_QUOTE);
#endif
if (!(flags & FLAGS_LEFTADJUST))
{
while (--width > 0)
data->OutStream(data, CHAR_ADJUST);
}
#if TRIO_FEATURE_WIDECHAR
if (flags & FLAGS_WIDECHAR)
{
TrioWriteWideStringCharacter(
data, (trio_wchar_t)parameters[i].data.number.as_signed, flags, NO_WIDTH);
}
else
#endif
{
TrioWriteStringCharacter(data, (int)parameters[i].data.number.as_signed, flags);
}
if (flags & FLAGS_LEFTADJUST)
{
while (--width > 0)
data->OutStream(data, CHAR_ADJUST);
}
#if TRIO_FEATURE_QUOTE
if (flags & FLAGS_QUOTE)
data->OutStream(data, CHAR_QUOTE);
#endif
break; /* FORMAT_CHAR */
case FORMAT_INT:
TrioWriteNumber(data, parameters[i].data.number.as_unsigned, flags, width,
precision, base);
break; /* FORMAT_INT */
#if TRIO_FEATURE_FLOAT
case FORMAT_DOUBLE:
TrioWriteDouble(data, parameters[i].data.longdoubleNumber, flags, width, precision,
base);
break; /* FORMAT_DOUBLE */
#endif
case FORMAT_STRING:
#if TRIO_FEATURE_WIDECHAR
if (flags & FLAGS_WIDECHAR)
{
TrioWriteWideString(data, parameters[i].data.wstring, flags, width, precision);
}
else
#endif
{
TrioWriteString(data, parameters[i].data.string, flags, width, precision);
}
break; /* FORMAT_STRING */
case FORMAT_POINTER:
{
trio_reference_t reference;
reference.data = data;
reference.parameter = ¶meters[i];
trio_print_pointer(&reference, parameters[i].data.pointer);
}
break; /* FORMAT_POINTER */
case FORMAT_COUNT:
pointer = parameters[i].data.pointer;
if (NULL != pointer)
{
/*
* C99 paragraph 7.19.6.1.8 says "the number of
* characters written to the output stream so far by
* this call", which is data->actually.committed
*/
#if TRIO_FEATURE_SIZE_T || TRIO_FEATURE_SIZE_T_UPPER
if (flags & FLAGS_SIZE_T)
*(size_t*)pointer = (size_t)data->actually.committed;
else
#endif
#if TRIO_FEATURE_PTRDIFF_T
if (flags & FLAGS_PTRDIFF_T)
*(ptrdiff_t*)pointer = (ptrdiff_t)data->actually.committed;
else
#endif
#if TRIO_FEATURE_INTMAX_T
if (flags & FLAGS_INTMAX_T)
*(trio_intmax_t*)pointer = (trio_intmax_t)data->actually.committed;
else
#endif
if (flags & FLAGS_QUAD)
{
*(trio_ulonglong_t*)pointer = (trio_ulonglong_t)data->actually.committed;
}
else if (flags & FLAGS_LONG)
{
*(long int*)pointer = (long int)data->actually.committed;
}
else if (flags & FLAGS_SHORT)
{
*(short int*)pointer = (short int)data->actually.committed;
}
else
{
*(int*)pointer = (int)data->actually.committed;
}
}
break; /* FORMAT_COUNT */
case FORMAT_PARAMETER:
break; /* FORMAT_PARAMETER */
#if TRIO_FEATURE_ERRNO
case FORMAT_ERRNO:
string = trio_error(parameters[i].data.errorNumber);
if (string)
{
TrioWriteString(data, string, flags, width, precision);
}
else
{
data->OutStream(data, '#');
TrioWriteNumber(data, (trio_uintmax_t)parameters[i].data.errorNumber, flags,
width, precision, BASE_DECIMAL);
}
break; /* FORMAT_ERRNO */
#endif /* TRIO_FEATURE_ERRNO */
#if TRIO_FEATURE_USER_DEFINED
case FORMAT_USER_DEFINED:
{
trio_reference_t reference;
trio_userdef_t* def = NULL;
if (parameters[i].flags & FLAGS_USER_DEFINED_PARAMETER)
{
/* Use handle */
if ((i > 0) || (parameters[i - 1].type == FORMAT_PARAMETER))
def = (trio_userdef_t*)parameters[i - 1].data.pointer;
}
else
{
/* Look up namespace */
def = TrioFindNamespace(parameters[i].user_defined.namespace, NULL);
}
if (def)
{
reference.data = data;
reference.parameter = ¶meters[i];
def->callback(&reference);
}
}
break;
#endif /* TRIO_FEATURE_USER_DEFINED */
default:
break;
} /* switch parameter type */
/* Prepare for next */
offset = parameters[i].endOffset;
i++;
}
return data->processed;
}
/*************************************************************************
* TrioFormatRef
*/
#if TRIO_EXTENSION
TRIO_PRIVATE int TrioFormatRef TRIO_ARGS5((reference, format, arglist, argfunc, argarray),
trio_reference_t* reference, TRIO_CONST char* format,
va_list arglist, trio_argfunc_t argfunc,
trio_pointer_t* argarray)
{
int status;
trio_parameter_t parameters[MAX_PARAMETERS];
status = TrioParse(TYPE_PRINT, format, parameters, arglist, argfunc, argarray);
if (status < 0)
return status;
status = TrioFormatProcess(reference->data, format, parameters);
if (reference->data->error != 0)
{
status = reference->data->error;
}
return status;
}
#endif /* TRIO_EXTENSION */
/*************************************************************************
* TrioFormat
*/
TRIO_PRIVATE int TrioFormat TRIO_ARGS7((destination, destinationSize, OutStream, format, arglist,
argfunc, argarray),
trio_pointer_t destination, size_t destinationSize,
void(*OutStream) TRIO_PROTO((trio_class_t*, int)),
TRIO_CONST char* format, va_list arglist,
trio_argfunc_t argfunc, trio_pointer_t* argarray)
{
int status;
trio_class_t data;
trio_parameter_t parameters[MAX_PARAMETERS];
assert(VALID(OutStream));
assert(VALID(format));
memset(&data, 0, sizeof(data));
data.OutStream = OutStream;
data.location = destination;
data.max = destinationSize;
data.error = 0;
#if defined(USE_LOCALE)
if (NULL == internalLocaleValues)
{
TrioSetLocale();
}
#endif
status = TrioParse(TYPE_PRINT, format, parameters, arglist, argfunc, argarray);
if (status < 0)
return status;
status = TrioFormatProcess(&data, format, parameters);
if (data.error != 0)
{
status = data.error;
}
return status;
}
/*************************************************************************
* TrioOutStreamFile
*/
#if TRIO_FEATURE_FILE || TRIO_FEATURE_STDIO
TRIO_PRIVATE void TrioOutStreamFile TRIO_ARGS2((self, output), trio_class_t* self, int output)
{
FILE* file;
assert(VALID(self));
assert(VALID(self->location));
file = (FILE*)self->location;
self->processed++;
if (fputc(output, file) == EOF)
{
self->error = TRIO_ERROR_RETURN(TRIO_EOF, 0);
}
else
{
self->actually.committed++;
}
}
#endif /* TRIO_FEATURE_FILE || TRIO_FEATURE_STDIO */
/*************************************************************************
* TrioOutStreamFileDescriptor
*/
#if TRIO_FEATURE_FD
TRIO_PRIVATE void TrioOutStreamFileDescriptor TRIO_ARGS2((self, output), trio_class_t* self,
int output)
{
int fd;
char ch;
assert(VALID(self));
fd = *((int*)self->location);
ch = (char)output;
self->processed++;
if (write(fd, &ch, sizeof(char)) == -1)
{
self->error = TRIO_ERROR_RETURN(TRIO_ERRNO, 0);
}
else
{
self->actually.committed++;
}
}
#endif /* TRIO_FEATURE_FD */
/*************************************************************************
* TrioOutStreamCustom
*/
#if TRIO_FEATURE_CLOSURE
TRIO_PRIVATE void TrioOutStreamCustom TRIO_ARGS2((self, output), trio_class_t* self, int output)
{
int status;
trio_custom_t* data;
assert(VALID(self));
assert(VALID(self->location));
data = (trio_custom_t*)self->location;
if (data->stream.out)
{
status = (data->stream.out)(data->closure, output);
if (status >= 0)
{
self->actually.committed++;
}
else
{
if (self->error == 0)
{
self->error = TRIO_ERROR_RETURN(TRIO_ECUSTOM, -status);
}
}
}
self->processed++;
}
#endif /* TRIO_FEATURE_CLOSURE */
/*************************************************************************
* TrioOutStreamString
*/
TRIO_PRIVATE void TrioOutStreamString TRIO_ARGS2((self, output), trio_class_t* self, int output)
{
char** buffer;
assert(VALID(self));
assert(VALID(self->location));
buffer = (char**)self->location;
**buffer = (char)output;
(*buffer)++;
self->processed++;
self->actually.committed++;
}
/*************************************************************************
* TrioOutStreamStringMax
*/
TRIO_PRIVATE void TrioOutStreamStringMax TRIO_ARGS2((self, output), trio_class_t* self, int output)
{
char** buffer;
assert(VALID(self));
assert(VALID(self->location));
buffer = (char**)self->location;
if (self->processed < self->max)
{
**buffer = (char)output;
(*buffer)++;
self->actually.committed++;
}
self->processed++;
}
/*************************************************************************
* TrioOutStreamStringDynamic
*/
#if TRIO_FEATURE_DYNAMICSTRING
TRIO_PRIVATE void TrioOutStreamStringDynamic TRIO_ARGS2((self, output), trio_class_t* self,
int output)
{
assert(VALID(self));
assert(VALID(self->location));
if (self->error == 0)
{
trio_xstring_append_char((trio_string_t*)self->location, (char)output);
self->actually.committed++;
}
/* The processed variable must always be increased */
self->processed++;
}
#endif /* TRIO_FEATURE_DYNAMICSTRING */
/*************************************************************************
* TrioArrayGetter
*/
static trio_pointer_t TrioArrayGetter(trio_pointer_t context, int index, int type)
{
/* Utility function for the printfv family */
trio_pointer_t* argarray = (trio_pointer_t*)context;
return argarray[index];
}
/*************************************************************************
*
* Formatted printing functions
*
************************************************************************/
/** @addtogroup Printf
@{
*/
/*************************************************************************
* printf
*/
/**
Print to standard output stream.
@param format Formatting string.
@param ... Arguments.
@return Number of printed characters.
*/
#if TRIO_FEATURE_STDIO
TRIO_PUBLIC int trio_printf TRIO_VARGS2((format, va_alist), TRIO_CONST char* format, TRIO_VA_DECL)
{
int status;
va_list args;
assert(VALID(format));
TRIO_VA_START(args, format);
status = TrioFormat(stdout, 0, TrioOutStreamFile, format, args, NULL, NULL);
TRIO_VA_END(args);
return status;
}
#endif /* TRIO_FEATURE_STDIO */
/**
Print to standard output stream.
@param format Formatting string.
@param args Arguments.
@return Number of printed characters.
*/
#if TRIO_FEATURE_STDIO
TRIO_PUBLIC int trio_vprintf TRIO_ARGS2((format, args), TRIO_CONST char* format, va_list args)
{
assert(VALID(format));
return TrioFormat(stdout, 0, TrioOutStreamFile, format, args, NULL, NULL);
}
#endif /* TRIO_FEATURE_STDIO */
/**
Print to standard output stream.
@param format Formatting string.
@param args Arguments.
@return Number of printed characters.
*/
#if TRIO_FEATURE_STDIO
TRIO_PUBLIC int trio_printfv TRIO_ARGS2((format, args), TRIO_CONST char* format,
trio_pointer_t* args)
{
static va_list unused;
assert(VALID(format));
return TrioFormat(stdout, 0, TrioOutStreamFile, format, unused, TrioArrayGetter, args);
}
#endif /* TRIO_FEATURE_STDIO */
/*************************************************************************
* fprintf
*/
/**
Print to file.
@param file File pointer.
@param format Formatting string.
@param ... Arguments.
@return Number of printed characters.
*/
#if TRIO_FEATURE_FILE
TRIO_PUBLIC int trio_fprintf TRIO_VARGS3((file, format, va_alist), FILE* file,
TRIO_CONST char* format, TRIO_VA_DECL)
{
int status;
va_list args;
assert(VALID(file));
assert(VALID(format));
TRIO_VA_START(args, format);
status = TrioFormat(file, 0, TrioOutStreamFile, format, args, NULL, NULL);
TRIO_VA_END(args);
return status;
}
#endif /* TRIO_FEATURE_FILE */
/**
Print to file.
@param file File pointer.
@param format Formatting string.
@param args Arguments.
@return Number of printed characters.
*/
#if TRIO_FEATURE_FILE
TRIO_PUBLIC int trio_vfprintf TRIO_ARGS3((file, format, args), FILE* file, TRIO_CONST char* format,
va_list args)
{
assert(VALID(file));
assert(VALID(format));
return TrioFormat(file, 0, TrioOutStreamFile, format, args, NULL, NULL);
}
#endif /* TRIO_FEATURE_FILE */
/**
Print to file.
@param file File pointer.
@param format Formatting string.
@param args Arguments.
@return Number of printed characters.
*/
#if TRIO_FEATURE_FILE
TRIO_PUBLIC int trio_fprintfv TRIO_ARGS3((file, format, args), FILE* file, TRIO_CONST char* format,
trio_pointer_t* args)
{
static va_list unused;
assert(VALID(file));
assert(VALID(format));
return TrioFormat(file, 0, TrioOutStreamFile, format, unused, TrioArrayGetter, args);
}
#endif /* TRIO_FEATURE_FILE */
/*************************************************************************
* dprintf
*/
/**
Print to file descriptor.
@param fd File descriptor.
@param format Formatting string.
@param ... Arguments.
@return Number of printed characters.
*/
#if TRIO_FEATURE_FD
TRIO_PUBLIC int trio_dprintf TRIO_VARGS3((fd, format, va_alist), int fd, TRIO_CONST char* format,
TRIO_VA_DECL)
{
int status;
va_list args;
assert(VALID(format));
TRIO_VA_START(args, format);
status = TrioFormat(&fd, 0, TrioOutStreamFileDescriptor, format, args, NULL, NULL);
TRIO_VA_END(args);
return status;
}
#endif /* TRIO_FEATURE_FD */
/**
Print to file descriptor.
@param fd File descriptor.
@param format Formatting string.
@param args Arguments.
@return Number of printed characters.
*/
#if TRIO_FEATURE_FD
TRIO_PUBLIC int trio_vdprintf TRIO_ARGS3((fd, format, args), int fd, TRIO_CONST char* format,
va_list args)
{
assert(VALID(format));
return TrioFormat(&fd, 0, TrioOutStreamFileDescriptor, format, args, NULL, NULL);
}
#endif /* TRIO_FEATURE_FD */
/**
Print to file descriptor.
@param fd File descriptor.
@param format Formatting string.
@param args Arguments.
@return Number of printed characters.
*/
#if TRIO_FEATURE_FD
TRIO_PUBLIC int trio_dprintfv TRIO_ARGS3((fd, format, args), int fd, TRIO_CONST char* format,
trio_pointer_t* args)
{
static va_list unused;
assert(VALID(format));
return TrioFormat(&fd, 0, TrioOutStreamFileDescriptor, format, unused, TrioArrayGetter, args);
}
#endif /* TRIO_FEATURE_FD */
/*************************************************************************
* cprintf
*/
#if TRIO_FEATURE_CLOSURE
TRIO_PUBLIC int trio_cprintf TRIO_VARGS4((stream, closure, format, va_alist),
trio_outstream_t stream, trio_pointer_t closure,
TRIO_CONST char* format, TRIO_VA_DECL)
{
int status;
va_list args;
trio_custom_t data;
assert(VALID(stream));
assert(VALID(format));
TRIO_VA_START(args, format);
data.stream.out = stream;
data.closure = closure;
status = TrioFormat(&data, 0, TrioOutStreamCustom, format, args, NULL, NULL);
TRIO_VA_END(args);
return status;
}
#endif /* TRIO_FEATURE_CLOSURE */
#if TRIO_FEATURE_CLOSURE
TRIO_PUBLIC int trio_vcprintf TRIO_ARGS4((stream, closure, format, args), trio_outstream_t stream,
trio_pointer_t closure, TRIO_CONST char* format,
va_list args)
{
trio_custom_t data;
assert(VALID(stream));
assert(VALID(format));
data.stream.out = stream;
data.closure = closure;
return TrioFormat(&data, 0, TrioOutStreamCustom, format, args, NULL, NULL);
}
#endif /* TRIO_FEATURE_CLOSURE */
#if TRIO_FEATURE_CLOSURE
TRIO_PUBLIC int trio_cprintfv TRIO_ARGS4((stream, closure, format, args), trio_outstream_t stream,
trio_pointer_t closure, TRIO_CONST char* format,
trio_pointer_t* args)
{
static va_list unused;
trio_custom_t data;
assert(VALID(stream));
assert(VALID(format));
data.stream.out = stream;
data.closure = closure;
return TrioFormat(&data, 0, TrioOutStreamCustom, format, unused, TrioArrayGetter, args);
}
#endif /* TRIO_FEATURE_CLOSURE */
#if TRIO_FEATURE_CLOSURE && TRIO_FEATURE_ARGFUNC
TRIO_PUBLIC int trio_cprintff TRIO_ARGS5((stream, closure, format, argfunc, context),
trio_outstream_t stream, trio_pointer_t closure,
TRIO_CONST char* format, trio_argfunc_t argfunc,
trio_pointer_t context)
{
static va_list unused;
trio_custom_t data;
assert(VALID(stream));
assert(VALID(format));
assert(VALID(argfunc));
data.stream.out = stream;
data.closure = closure;
return TrioFormat(&data, 0, TrioOutStreamCustom, format, unused, argfunc,
(trio_pointer_t*)context);
}
#endif /* TRIO_FEATURE_CLOSURE && TRIO_FEATURE_ARGFUNC */
/*************************************************************************
* sprintf
*/
/**
Print to string.
@param buffer Output string.
@param format Formatting string.
@param ... Arguments.
@return Number of printed characters.
*/
TRIO_PUBLIC int trio_sprintf TRIO_VARGS3((buffer, format, va_alist), char* buffer,
TRIO_CONST char* format, TRIO_VA_DECL)
{
int status;
va_list args;
assert(VALID(buffer));
assert(VALID(format));
TRIO_VA_START(args, format);
status = TrioFormat(&buffer, 0, TrioOutStreamString, format, args, NULL, NULL);
*buffer = NIL; /* Terminate with NIL character */
TRIO_VA_END(args);
return status;
}
/**
Print to string.
@param buffer Output string.
@param format Formatting string.
@param args Arguments.
@return Number of printed characters.
*/
TRIO_PUBLIC int trio_vsprintf TRIO_ARGS3((buffer, format, args), char* buffer,
TRIO_CONST char* format, va_list args)
{
int status;
assert(VALID(buffer));
assert(VALID(format));
status = TrioFormat(&buffer, 0, TrioOutStreamString, format, args, NULL, NULL);
*buffer = NIL;
return status;
}
/**
Print to string.
@param buffer Output string.
@param format Formatting string.
@param args Arguments.
@return Number of printed characters.
*/
TRIO_PUBLIC int trio_sprintfv TRIO_ARGS3((buffer, format, args), char* buffer,
TRIO_CONST char* format, trio_pointer_t* args)
{
static va_list unused;
int status;
assert(VALID(buffer));
assert(VALID(format));
status = TrioFormat(&buffer, 0, TrioOutStreamString, format, unused, TrioArrayGetter, args);
*buffer = NIL;
return status;
}
/*************************************************************************
* snprintf
*/
/**
Print at most @p max characters to string.
@param buffer Output string.
@param max Maximum number of characters to print.
@param format Formatting string.
@param ... Arguments.
@return Number of printed characters.
*/
TRIO_PUBLIC int trio_snprintf TRIO_VARGS4((buffer, max, format, va_alist), char* buffer, size_t max,
TRIO_CONST char* format, TRIO_VA_DECL)
{
int status;
va_list args;
assert(VALID(buffer) || (max == 0));
assert(VALID(format));
TRIO_VA_START(args, format);
status = TrioFormat(&buffer, max > 0 ? max - 1 : 0, TrioOutStreamStringMax, format, args, NULL,
NULL);
if (max > 0)
*buffer = NIL;
TRIO_VA_END(args);
return status;
}
/**
Print at most @p max characters to string.
@param buffer Output string.
@param max Maximum number of characters to print.
@param format Formatting string.
@param args Arguments.
@return Number of printed characters.
*/
TRIO_PUBLIC int trio_vsnprintf TRIO_ARGS4((buffer, max, format, args), char* buffer, size_t max,
TRIO_CONST char* format, va_list args)
{
int status;
assert(VALID(buffer) || (max == 0));
assert(VALID(format));
status = TrioFormat(&buffer, max > 0 ? max - 1 : 0, TrioOutStreamStringMax, format, args, NULL,
NULL);
if (max > 0)
*buffer = NIL;
return status;
}
/**
Print at most @p max characters to string.
@param buffer Output string.
@param max Maximum number of characters to print.
@param format Formatting string.
@param args Arguments.
@return Number of printed characters.
*/
TRIO_PUBLIC int trio_snprintfv TRIO_ARGS4((buffer, max, format, args), char* buffer, size_t max,
TRIO_CONST char* format, trio_pointer_t* args)
{
static va_list unused;
int status;
assert(VALID(buffer) || (max == 0));
assert(VALID(format));
status = TrioFormat(&buffer, max > 0 ? max - 1 : 0, TrioOutStreamStringMax, format, unused,
TrioArrayGetter, args);
if (max > 0)
*buffer = NIL;
return status;
}
/*************************************************************************
* snprintfcat
* Appends the new string to the buffer string overwriting the '\0'
* character at the end of buffer.
*/
#if TRIO_EXTENSION
TRIO_PUBLIC int trio_snprintfcat TRIO_VARGS4((buffer, max, format, va_alist), char* buffer,
size_t max, TRIO_CONST char* format, TRIO_VA_DECL)
{
int status;
va_list args;
size_t buf_len;
TRIO_VA_START(args, format);
assert(VALID(buffer));
assert(VALID(format));
buf_len = trio_length(buffer);
buffer = &buffer[buf_len];
status =
TrioFormat(&buffer, max - 1 - buf_len, TrioOutStreamStringMax, format, args, NULL, NULL);
TRIO_VA_END(args);
*buffer = NIL;
return status;
}
#endif
#if TRIO_EXTENSION
TRIO_PUBLIC int trio_vsnprintfcat TRIO_ARGS4((buffer, max, format, args), char* buffer, size_t max,
TRIO_CONST char* format, va_list args)
{
int status;
size_t buf_len;
assert(VALID(buffer));
assert(VALID(format));
buf_len = trio_length(buffer);
buffer = &buffer[buf_len];
status =
TrioFormat(&buffer, max - 1 - buf_len, TrioOutStreamStringMax, format, args, NULL, NULL);
*buffer = NIL;
return status;
}
#endif
/*************************************************************************
* trio_aprintf
*/
#if TRIO_DEPRECATED && TRIO_FEATURE_DYNAMICSTRING
TRIO_PUBLIC char* trio_aprintf TRIO_VARGS2((format, va_alist), TRIO_CONST char* format,
TRIO_VA_DECL)
{
va_list args;
trio_string_t* info;
char* result = NULL;
assert(VALID(format));
info = trio_xstring_duplicate("");
if (info)
{
TRIO_VA_START(args, format);
(void)TrioFormat(info, 0, TrioOutStreamStringDynamic, format, args, NULL, NULL);
TRIO_VA_END(args);
trio_string_terminate(info);
result = trio_string_extract(info);
trio_string_destroy(info);
}
return result;
}
#endif /* TRIO_DEPRECATED && TRIO_FEATURE_DYNAMICSTRING */
#if TRIO_DEPRECATED && TRIO_FEATURE_DYNAMICSTRING
TRIO_PUBLIC char* trio_vaprintf TRIO_ARGS2((format, args), TRIO_CONST char* format, va_list args)
{
trio_string_t* info;
char* result = NULL;
assert(VALID(format));
info = trio_xstring_duplicate("");
if (info)
{
(void)TrioFormat(info, 0, TrioOutStreamStringDynamic, format, args, NULL, NULL);
trio_string_terminate(info);
result = trio_string_extract(info);
trio_string_destroy(info);
}
return result;
}
#endif /* TRIO_DEPRECATED && TRIO_FEATURE_DYNAMICSTRING */
/**
Allocate and print to string.
The memory allocated and returned by @p result must be freed by the
calling application.
@param result Output string.
@param format Formatting string.
@param ... Arguments.
@return Number of printed characters.
*/
#if TRIO_FEATURE_DYNAMICSTRING
TRIO_PUBLIC int trio_asprintf TRIO_VARGS3((result, format, va_alist), char** result,
TRIO_CONST char* format, TRIO_VA_DECL)
{
va_list args;
int status;
trio_string_t* info;
assert(VALID(format));
*result = NULL;
info = trio_xstring_duplicate("");
if (info == NULL)
{
status = TRIO_ERROR_RETURN(TRIO_ENOMEM, 0);
}
else
{
TRIO_VA_START(args, format);
status = TrioFormat(info, 0, TrioOutStreamStringDynamic, format, args, NULL, NULL);
TRIO_VA_END(args);
if (status >= 0)
{
trio_string_terminate(info);
*result = trio_string_extract(info);
}
trio_string_destroy(info);
}
return status;
}
#endif /* TRIO_FEATURE_DYNAMICSTRING */
/**
Allocate and print to string.
The memory allocated and returned by @p result must be freed by the
calling application.
@param result Output string.
@param format Formatting string.
@param args Arguments.
@return Number of printed characters.
*/
#if TRIO_FEATURE_DYNAMICSTRING
TRIO_PUBLIC int trio_vasprintf TRIO_ARGS3((result, format, args), char** result,
TRIO_CONST char* format, va_list args)
{
int status;
trio_string_t* info;
assert(VALID(format));
*result = NULL;
info = trio_xstring_duplicate("");
if (info == NULL)
{
status = TRIO_ERROR_RETURN(TRIO_ENOMEM, 0);
}
else
{
status = TrioFormat(info, 0, TrioOutStreamStringDynamic, format, args, NULL, NULL);
if (status >= 0)
{
trio_string_terminate(info);
*result = trio_string_extract(info);
}
trio_string_destroy(info);
}
return status;
}
#endif /* TRIO_FEATURE_DYNAMICSTRING */
/**
Allocate and print to string.
The memory allocated and returned by @p result must be freed by the
calling application.
@param result Output string.
@param format Formatting string.
@param args Arguments.
@return Number of printed characters.
*/
#if TRIO_FEATURE_DYNAMICSTRING
TRIO_PUBLIC int trio_asprintfv TRIO_ARGS3((result, format, args), char** result,
TRIO_CONST char* format, trio_pointer_t* args)
{
static va_list unused;
int status;
trio_string_t* info;
assert(VALID(format));
*result = NULL;
info = trio_xstring_duplicate("");
if (info == NULL)
{
status = TRIO_ERROR_RETURN(TRIO_ENOMEM, 0);
}
else
{
status =
TrioFormat(info, 0, TrioOutStreamStringDynamic, format, unused, TrioArrayGetter, args);
if (status >= 0)
{
trio_string_terminate(info);
*result = trio_string_extract(info);
}
trio_string_destroy(info);
}
return status;
}
#endif /* TRIO_FEATURE_DYNAMICSTRING */
#if defined(TRIO_DOCUMENTATION)
#include "doc/doc_printf.h"
#endif
/** @} End of Printf documentation module */
/*************************************************************************
*
* CALLBACK
*
************************************************************************/
#if defined(TRIO_DOCUMENTATION)
#include "doc/doc_register.h"
#endif
/**
@addtogroup UserDefined
@{
*/
#if TRIO_FEATURE_USER_DEFINED
/*************************************************************************
* trio_register
*/
/**
Register new user-defined specifier.
@param callback
@param name
@return Handle.
*/
TRIO_PUBLIC trio_pointer_t trio_register TRIO_ARGS2((callback, name), trio_callback_t callback,
TRIO_CONST char* name)
{
trio_userdef_t* def;
trio_userdef_t* prev = NULL;
if (callback == NULL)
return NULL;
if (name)
{
/* Handle built-in namespaces */
if (name[0] == ':')
{
if (trio_equal(name, ":enter"))
{
internalEnterCriticalRegion = callback;
}
else if (trio_equal(name, ":leave"))
{
internalLeaveCriticalRegion = callback;
}
return NULL;
}
/* Bail out if namespace is too long */
if (trio_length(name) >= MAX_USER_NAME)
return NULL;
/* Bail out if namespace already is registered */
def = TrioFindNamespace(name, &prev);
if (def)
return NULL;
}
def = (trio_userdef_t*)TRIO_MALLOC(sizeof(trio_userdef_t));
if (def)
{
if (internalEnterCriticalRegion)
(void)internalEnterCriticalRegion(NULL);
if (name)
{
/* Link into internal list */
if (prev == NULL)
internalUserDef = def;
else
prev->next = def;
}
/* Initialize */
def->callback = callback;
def->name = (name == NULL) ? NULL : trio_duplicate(name);
def->next = NULL;
if (internalLeaveCriticalRegion)
(void)internalLeaveCriticalRegion(NULL);
}
return (trio_pointer_t)def;
}
/**
Unregister an existing user-defined specifier.
@param handle
*/
void trio_unregister TRIO_ARGS1((handle), trio_pointer_t handle)
{
trio_userdef_t* self = (trio_userdef_t*)handle;
trio_userdef_t* def;
trio_userdef_t* prev = NULL;
assert(VALID(self));
if (self->name)
{
def = TrioFindNamespace(self->name, &prev);
if (def)
{
if (internalEnterCriticalRegion)
(void)internalEnterCriticalRegion(NULL);
if (prev == NULL)
internalUserDef = internalUserDef->next;
else
prev->next = def->next;
if (internalLeaveCriticalRegion)
(void)internalLeaveCriticalRegion(NULL);
}
trio_destroy(self->name);
}
TRIO_FREE(self);
}
/*************************************************************************
* trio_get_format [public]
*/
TRIO_CONST char* trio_get_format TRIO_ARGS1((ref), trio_pointer_t ref)
{
#if TRIO_FEATURE_USER_DEFINED
assert(((trio_reference_t*)ref)->parameter->type == FORMAT_USER_DEFINED);
#endif
return (((trio_reference_t*)ref)->parameter->user_data);
}
/*************************************************************************
* trio_get_argument [public]
*/
trio_pointer_t trio_get_argument TRIO_ARGS1((ref), trio_pointer_t ref)
{
#if TRIO_FEATURE_USER_DEFINED
assert(((trio_reference_t*)ref)->parameter->type == FORMAT_USER_DEFINED);
#endif
return ((trio_reference_t*)ref)->parameter->data.pointer;
}
/*************************************************************************
* trio_get_width / trio_set_width [public]
*/
int trio_get_width TRIO_ARGS1((ref), trio_pointer_t ref)
{
return ((trio_reference_t*)ref)->parameter->width;
}
void trio_set_width TRIO_ARGS2((ref, width), trio_pointer_t ref, int width)
{
((trio_reference_t*)ref)->parameter->width = width;
}
/*************************************************************************
* trio_get_precision / trio_set_precision [public]
*/
int trio_get_precision TRIO_ARGS1((ref), trio_pointer_t ref)
{
return (((trio_reference_t*)ref)->parameter->precision);
}
void trio_set_precision TRIO_ARGS2((ref, precision), trio_pointer_t ref, int precision)
{
((trio_reference_t*)ref)->parameter->precision = precision;
}
/*************************************************************************
* trio_get_base / trio_set_base [public]
*/
int trio_get_base TRIO_ARGS1((ref), trio_pointer_t ref)
{
return (((trio_reference_t*)ref)->parameter->base);
}
void trio_set_base TRIO_ARGS2((ref, base), trio_pointer_t ref, int base)
{
((trio_reference_t*)ref)->parameter->base = base;
}
/*************************************************************************
* trio_get_long / trio_set_long [public]
*/
int trio_get_long TRIO_ARGS1((ref), trio_pointer_t ref)
{
return (((trio_reference_t*)ref)->parameter->flags & FLAGS_LONG) ? TRUE : FALSE;
}
void trio_set_long TRIO_ARGS2((ref, is_long), trio_pointer_t ref, int is_long)
{
if (is_long)
((trio_reference_t*)ref)->parameter->flags |= FLAGS_LONG;
else
((trio_reference_t*)ref)->parameter->flags &= ~FLAGS_LONG;
}
/*************************************************************************
* trio_get_longlong / trio_set_longlong [public]
*/
int trio_get_longlong TRIO_ARGS1((ref), trio_pointer_t ref)
{
return (((trio_reference_t*)ref)->parameter->flags & FLAGS_QUAD) ? TRUE : FALSE;
}
void trio_set_longlong TRIO_ARGS2((ref, is_longlong), trio_pointer_t ref, int is_longlong)
{
if (is_longlong)
((trio_reference_t*)ref)->parameter->flags |= FLAGS_QUAD;
else
((trio_reference_t*)ref)->parameter->flags &= ~FLAGS_QUAD;
}
/*************************************************************************
* trio_get_longdouble / trio_set_longdouble [public]
*/
#if TRIO_FEATURE_FLOAT
int trio_get_longdouble TRIO_ARGS1((ref), trio_pointer_t ref)
{
return (((trio_reference_t*)ref)->parameter->flags & FLAGS_LONGDOUBLE) ? TRUE : FALSE;
}
void trio_set_longdouble TRIO_ARGS2((ref, is_longdouble), trio_pointer_t ref, int is_longdouble)
{
if (is_longdouble)
((trio_reference_t*)ref)->parameter->flags |= FLAGS_LONGDOUBLE;
else
((trio_reference_t*)ref)->parameter->flags &= ~FLAGS_LONGDOUBLE;
}
#endif /* TRIO_FEATURE_FLOAT */
/*************************************************************************
* trio_get_short / trio_set_short [public]
*/
int trio_get_short TRIO_ARGS1((ref), trio_pointer_t ref)
{
return (((trio_reference_t*)ref)->parameter->flags & FLAGS_SHORT) ? TRUE : FALSE;
}
void trio_set_short TRIO_ARGS2((ref, is_short), trio_pointer_t ref, int is_short)
{
if (is_short)
((trio_reference_t*)ref)->parameter->flags |= FLAGS_SHORT;
else
((trio_reference_t*)ref)->parameter->flags &= ~FLAGS_SHORT;
}
/*************************************************************************
* trio_get_shortshort / trio_set_shortshort [public]
*/
int trio_get_shortshort TRIO_ARGS1((ref), trio_pointer_t ref)
{
return (((trio_reference_t*)ref)->parameter->flags & FLAGS_SHORTSHORT) ? TRUE : FALSE;
}
void trio_set_shortshort TRIO_ARGS2((ref, is_shortshort), trio_pointer_t ref, int is_shortshort)
{
if (is_shortshort)
((trio_reference_t*)ref)->parameter->flags |= FLAGS_SHORTSHORT;
else
((trio_reference_t*)ref)->parameter->flags &= ~FLAGS_SHORTSHORT;
}
/*************************************************************************
* trio_get_alternative / trio_set_alternative [public]
*/
int trio_get_alternative TRIO_ARGS1((ref), trio_pointer_t ref)
{
return (((trio_reference_t*)ref)->parameter->flags & FLAGS_ALTERNATIVE) ? TRUE : FALSE;
}
void trio_set_alternative TRIO_ARGS2((ref, is_alternative), trio_pointer_t ref, int is_alternative)
{
if (is_alternative)
((trio_reference_t*)ref)->parameter->flags |= FLAGS_ALTERNATIVE;
else
((trio_reference_t*)ref)->parameter->flags &= ~FLAGS_ALTERNATIVE;
}
/*************************************************************************
* trio_get_alignment / trio_set_alignment [public]
*/
int trio_get_alignment TRIO_ARGS1((ref), trio_pointer_t ref)
{
return (((trio_reference_t*)ref)->parameter->flags & FLAGS_LEFTADJUST) ? TRUE : FALSE;
}
void trio_set_alignment TRIO_ARGS2((ref, is_leftaligned), trio_pointer_t ref, int is_leftaligned)
{
if (is_leftaligned)
((trio_reference_t*)ref)->parameter->flags |= FLAGS_LEFTADJUST;
else
((trio_reference_t*)ref)->parameter->flags &= ~FLAGS_LEFTADJUST;
}
/*************************************************************************
* trio_get_spacing /trio_set_spacing [public]
*/
int trio_get_spacing TRIO_ARGS1((ref), trio_pointer_t ref)
{
return (((trio_reference_t*)ref)->parameter->flags & FLAGS_SPACE) ? TRUE : FALSE;
}
void trio_set_spacing TRIO_ARGS2((ref, is_space), trio_pointer_t ref, int is_space)
{
if (is_space)
((trio_reference_t*)ref)->parameter->flags |= FLAGS_SPACE;
else
((trio_reference_t*)ref)->parameter->flags &= ~FLAGS_SPACE;
}
/*************************************************************************
* trio_get_sign / trio_set_sign [public]
*/
int trio_get_sign TRIO_ARGS1((ref), trio_pointer_t ref)
{
return (((trio_reference_t*)ref)->parameter->flags & FLAGS_SHOWSIGN) ? TRUE : FALSE;
}
void trio_set_sign TRIO_ARGS2((ref, is_sign), trio_pointer_t ref, int is_sign)
{
if (is_sign)
((trio_reference_t*)ref)->parameter->flags |= FLAGS_SHOWSIGN;
else
((trio_reference_t*)ref)->parameter->flags &= ~FLAGS_SHOWSIGN;
}
/*************************************************************************
* trio_get_padding / trio_set_padding [public]
*/
int trio_get_padding TRIO_ARGS1((ref), trio_pointer_t ref)
{
return (((trio_reference_t*)ref)->parameter->flags & FLAGS_NILPADDING) ? TRUE : FALSE;
}
void trio_set_padding TRIO_ARGS2((ref, is_padding), trio_pointer_t ref, int is_padding)
{
if (is_padding)
((trio_reference_t*)ref)->parameter->flags |= FLAGS_NILPADDING;
else
((trio_reference_t*)ref)->parameter->flags &= ~FLAGS_NILPADDING;
}
/*************************************************************************
* trio_get_quote / trio_set_quote [public]
*/
#if TRIO_FEATURE_QUOTE
int trio_get_quote TRIO_ARGS1((ref), trio_pointer_t ref)
{
return (((trio_reference_t*)ref)->parameter->flags & FLAGS_QUOTE) ? TRUE : FALSE;
}
void trio_set_quote TRIO_ARGS2((ref, is_quote), trio_pointer_t ref, int is_quote)
{
if (is_quote)
((trio_reference_t*)ref)->parameter->flags |= FLAGS_QUOTE;
else
((trio_reference_t*)ref)->parameter->flags &= ~FLAGS_QUOTE;
}
#endif /* TRIO_FEATURE_QUOTE */
/*************************************************************************
* trio_get_upper / trio_set_upper [public]
*/
int trio_get_upper TRIO_ARGS1((ref), trio_pointer_t ref)
{
return (((trio_reference_t*)ref)->parameter->flags & FLAGS_UPPER) ? TRUE : FALSE;
}
void trio_set_upper TRIO_ARGS2((ref, is_upper), trio_pointer_t ref, int is_upper)
{
if (is_upper)
((trio_reference_t*)ref)->parameter->flags |= FLAGS_UPPER;
else
((trio_reference_t*)ref)->parameter->flags &= ~FLAGS_UPPER;
}
/*************************************************************************
* trio_get_largest / trio_set_largest [public]
*/
#if TRIO_FEATURE_INTMAX_T
int trio_get_largest TRIO_ARGS1((ref), trio_pointer_t ref)
{
return (((trio_reference_t*)ref)->parameter->flags & FLAGS_INTMAX_T) ? TRUE : FALSE;
}
void trio_set_largest TRIO_ARGS2((ref, is_largest), trio_pointer_t ref, int is_largest)
{
if (is_largest)
((trio_reference_t*)ref)->parameter->flags |= FLAGS_INTMAX_T;
else
((trio_reference_t*)ref)->parameter->flags &= ~FLAGS_INTMAX_T;
}
#endif /* TRIO_FEATURE_INTMAX_T */
/*************************************************************************
* trio_get_ptrdiff / trio_set_ptrdiff [public]
*/
#if TRIO_FEATURE_PTRDIFF_T
int trio_get_ptrdiff TRIO_ARGS1((ref), trio_pointer_t ref)
{
return (((trio_reference_t*)ref)->parameter->flags & FLAGS_PTRDIFF_T) ? TRUE : FALSE;
}
void trio_set_ptrdiff TRIO_ARGS2((ref, is_ptrdiff), trio_pointer_t ref, int is_ptrdiff)
{
if (is_ptrdiff)
((trio_reference_t*)ref)->parameter->flags |= FLAGS_PTRDIFF_T;
else
((trio_reference_t*)ref)->parameter->flags &= ~FLAGS_PTRDIFF_T;
}
#endif /* TRIO_FEATURE_PTRDIFF_T */
/*************************************************************************
* trio_get_size / trio_set_size [public]
*/
#if TRIO_FEATURE_SIZE_T
int trio_get_size TRIO_ARGS1((ref), trio_pointer_t ref)
{
return (((trio_reference_t*)ref)->parameter->flags & FLAGS_SIZE_T) ? TRUE : FALSE;
}
void trio_set_size TRIO_ARGS2((ref, is_size), trio_pointer_t ref, int is_size)
{
if (is_size)
((trio_reference_t*)ref)->parameter->flags |= FLAGS_SIZE_T;
else
((trio_reference_t*)ref)->parameter->flags &= ~FLAGS_SIZE_T;
}
#endif /* TRIO_FEATURE_SIZE_T */
/*************************************************************************
* trio_print_int [public]
*/
void trio_print_int TRIO_ARGS2((ref, number), trio_pointer_t ref, int number)
{
trio_reference_t* self = (trio_reference_t*)ref;
TrioWriteNumber(self->data, (trio_uintmax_t)number, self->parameter->flags,
self->parameter->width, self->parameter->precision, self->parameter->base);
}
/*************************************************************************
* trio_print_uint [public]
*/
void trio_print_uint TRIO_ARGS2((ref, number), trio_pointer_t ref, unsigned int number)
{
trio_reference_t* self = (trio_reference_t*)ref;
TrioWriteNumber(self->data, (trio_uintmax_t)number, self->parameter->flags | FLAGS_UNSIGNED,
self->parameter->width, self->parameter->precision, self->parameter->base);
}
/*************************************************************************
* trio_print_double [public]
*/
#if TRIO_FEATURE_FLOAT
void trio_print_double TRIO_ARGS2((ref, number), trio_pointer_t ref, double number)
{
trio_reference_t* self = (trio_reference_t*)ref;
TrioWriteDouble(self->data, number, self->parameter->flags, self->parameter->width,
self->parameter->precision, self->parameter->base);
}
#endif /* TRIO_FEATURE_FLOAT */
/*************************************************************************
* trio_print_string [public]
*/
void trio_print_string TRIO_ARGS2((ref, string), trio_pointer_t ref, TRIO_CONST char* string)
{
trio_reference_t* self = (trio_reference_t*)ref;
TrioWriteString(self->data, string, self->parameter->flags, self->parameter->width,
self->parameter->precision);
}
/*************************************************************************
* trio_print_ref [public]
*/
int trio_print_ref TRIO_VARGS3((ref, format, va_alist), trio_pointer_t ref, TRIO_CONST char* format,
TRIO_VA_DECL)
{
int status;
va_list arglist;
assert(VALID(format));
TRIO_VA_START(arglist, format);
status = TrioFormatRef((trio_reference_t*)ref, format, arglist, NULL, NULL);
TRIO_VA_END(arglist);
return status;
}
/*************************************************************************
* trio_vprint_ref [public]
*/
int trio_vprint_ref TRIO_ARGS3((ref, format, arglist), trio_pointer_t ref, TRIO_CONST char* format,
va_list arglist)
{
assert(VALID(format));
return TrioFormatRef((trio_reference_t*)ref, format, arglist, NULL, NULL);
}
/*************************************************************************
* trio_printv_ref [public]
*/
int trio_printv_ref TRIO_ARGS3((ref, format, argarray), trio_pointer_t ref, TRIO_CONST char* format,
trio_pointer_t* argarray)
{
static va_list unused;
assert(VALID(format));
return TrioFormatRef((trio_reference_t*)ref, format, unused, TrioArrayGetter, argarray);
}
#endif
/*************************************************************************
* trio_print_pointer [public]
*/
void trio_print_pointer TRIO_ARGS2((ref, pointer), trio_pointer_t ref, trio_pointer_t pointer)
{
trio_reference_t* self = (trio_reference_t*)ref;
trio_flags_t flags;
trio_uintmax_t number;
if (NULL == pointer)
{
TRIO_CONST char* string = internalNullString;
while (*string)
self->data->OutStream(self->data, *string++);
}
else
{
/*
* The subtraction of the null pointer is a workaround
* to avoid a compiler warning. The performance overhead
* is negligible (and likely to be removed by an
* optimizing compiler). The (char *) casting is done
* to please ANSI C++.
*/
number = (trio_uintmax_t)((char*)pointer - (char*)0);
/* Shrink to size of pointer */
number &= (trio_uintmax_t)-1;
flags = self->parameter->flags;
flags |= (FLAGS_UNSIGNED | FLAGS_ALTERNATIVE | FLAGS_NILPADDING);
TrioWriteNumber(self->data, number, flags, POINTER_WIDTH, NO_PRECISION, BASE_HEX);
}
}
/** @} End of UserDefined documentation module */
/*************************************************************************
*
* LOCALES
*
************************************************************************/
/*************************************************************************
* trio_locale_set_decimal_point
*
* Decimal point can only be one character. The input argument is a
* string to enable multibyte characters. At most MB_LEN_MAX characters
* will be used.
*/
#if TRIO_FEATURE_LOCALE
TRIO_PUBLIC void trio_locale_set_decimal_point TRIO_ARGS1((decimalPoint), char* decimalPoint)
{
#if defined(USE_LOCALE)
if (NULL == internalLocaleValues)
{
TrioSetLocale();
}
#endif
internalDecimalPointLength = trio_length(decimalPoint);
if (internalDecimalPointLength == 1)
{
internalDecimalPoint = *decimalPoint;
}
else
{
internalDecimalPoint = NIL;
trio_copy_max(internalDecimalPointString, sizeof(internalDecimalPointString), decimalPoint);
}
}
#endif
/*************************************************************************
* trio_locale_set_thousand_separator
*
* See trio_locale_set_decimal_point
*/
#if TRIO_FEATURE_LOCALE || TRIO_EXTENSION
TRIO_PUBLIC void trio_locale_set_thousand_separator TRIO_ARGS1((thousandSeparator),
char* thousandSeparator)
{
#if defined(USE_LOCALE)
if (NULL == internalLocaleValues)
{
TrioSetLocale();
}
#endif
trio_copy_max(internalThousandSeparator, sizeof(internalThousandSeparator), thousandSeparator);
internalThousandSeparatorLength = trio_length(internalThousandSeparator);
}
#endif
/*************************************************************************
* trio_locale_set_grouping
*
* Array of bytes. Reversed order.
*
* CHAR_MAX : No further grouping
* 0 : Repeat last group for the remaining digits (not necessary
* as C strings are zero-terminated)
* n : Set current group to n
*
* Same order as the grouping attribute in LC_NUMERIC.
*/
#if TRIO_FEATURE_LOCALE || TRIO_EXTENSION
TRIO_PUBLIC void trio_locale_set_grouping TRIO_ARGS1((grouping), char* grouping)
{
#if defined(USE_LOCALE)
if (NULL == internalLocaleValues)
{
TrioSetLocale();
}
#endif
trio_copy_max(internalGrouping, sizeof(internalGrouping), grouping);
}
#endif
/*************************************************************************
*
* SCANNING
*
************************************************************************/
#if TRIO_FEATURE_SCANF
/*************************************************************************
* TrioSkipWhitespaces
*/
TRIO_PRIVATE int TrioSkipWhitespaces TRIO_ARGS1((self), trio_class_t* self)
{
int ch;
ch = self->current;
while (isspace(ch))
{
self->InStream(self, &ch);
}
return ch;
}
/*************************************************************************
* TrioGetCollation
*/
#if TRIO_EXTENSION
TRIO_PRIVATE void TrioGetCollation(TRIO_NOARGS)
{
int i;
int j;
int k;
char first[2];
char second[2];
/* This is computationally expensive */
first[1] = NIL;
second[1] = NIL;
for (i = 0; i < MAX_CHARACTER_CLASS; i++)
{
k = 0;
first[0] = (char)i;
for (j = 0; j < MAX_CHARACTER_CLASS; j++)
{
second[0] = (char)j;
if (trio_equal_locale(first, second))
internalCollationArray[i][k++] = (char)j;
}
internalCollationArray[i][k] = NIL;
}
}
#endif
/*************************************************************************
* TrioGetCharacterClass
*
* FIXME:
* multibyte
*/
TRIO_PRIVATE int TrioGetCharacterClass TRIO_ARGS4((format, offsetPointer, flagsPointer,
characterclass),
TRIO_CONST char* format, int* offsetPointer,
trio_flags_t* flagsPointer, int* characterclass)
{
int offset = *offsetPointer;
int i;
char ch;
char range_begin;
char range_end;
*flagsPointer &= ~FLAGS_EXCLUDE;
if (format[offset] == QUALIFIER_CIRCUMFLEX)
{
*flagsPointer |= FLAGS_EXCLUDE;
offset++;
}
/*
* If the ungroup character is at the beginning of the scanlist,
* it will be part of the class, and a second ungroup character
* must follow to end the group.
*/
if (format[offset] == SPECIFIER_UNGROUP)
{
characterclass[(int)SPECIFIER_UNGROUP]++;
offset++;
}
/*
* Minus is used to specify ranges. To include minus in the class,
* it must be at the beginning of the list
*/
if (format[offset] == QUALIFIER_MINUS)
{
characterclass[(int)QUALIFIER_MINUS]++;
offset++;
}
/* Collect characters */
for (ch = format[offset]; (ch != SPECIFIER_UNGROUP) && (ch != NIL); ch = format[++offset])
{
switch (ch)
{
case QUALIFIER_MINUS: /* Scanlist ranges */
/*
* Both C99 and UNIX98 describes ranges as implementation-
* defined.
*
* We support the following behaviour (although this may
* change as we become wiser)
* - only increasing ranges, ie. [a-b] but not [b-a]
* - transitive ranges, ie. [a-b-c] == [a-c]
* - trailing minus, ie. [a-] is interpreted as an 'a'
* and a '-'
* - duplicates (although we can easily convert these
* into errors)
*/
range_begin = format[offset - 1];
range_end = format[++offset];
if (range_end == SPECIFIER_UNGROUP)
{
/* Trailing minus is included */
characterclass[(int)ch]++;
ch = range_end;
break; /* for */
}
if (range_end == NIL)
return TRIO_ERROR_RETURN(TRIO_EINVAL, offset);
if (range_begin > range_end)
return TRIO_ERROR_RETURN(TRIO_ERANGE, offset);
for (i = (int)range_begin; i <= (int)range_end; i++)
characterclass[i]++;
ch = range_end;
break;
#if TRIO_EXTENSION
case SPECIFIER_GROUP:
switch (format[offset + 1])
{
case QUALIFIER_DOT: /* Collating symbol */
/*
* FIXME: This will be easier to implement when multibyte
* characters have been implemented. Until now, we ignore
* this feature.
*/
for (i = offset + 2;; i++)
{
if (format[i] == NIL)
/* Error in syntax */
return -1;
else if (format[i] == QUALIFIER_DOT)
break; /* for */
}
if (format[++i] != SPECIFIER_UNGROUP)
return -1;
offset = i;
break;
case QUALIFIER_EQUAL: /* Equivalence class expressions */
{
unsigned int j;
unsigned int k;
if (internalCollationUnconverted)
{
/* Lazy evaluation of collation array */
TrioGetCollation();
internalCollationUnconverted = FALSE;
}
for (i = offset + 2;; i++)
{
if (format[i] == NIL)
/* Error in syntax */
return -1;
else if (format[i] == QUALIFIER_EQUAL)
break; /* for */
else
{
/* Mark any equivalent character */
k = (unsigned int)format[i];
for (j = 0; internalCollationArray[k][j] != NIL; j++)
characterclass[(int)internalCollationArray[k][j]]++;
}
}
if (format[++i] != SPECIFIER_UNGROUP)
return -1;
offset = i;
}
break;
case QUALIFIER_COLON: /* Character class expressions */
if (trio_equal_max(CLASS_ALNUM, sizeof(CLASS_ALNUM) - 1, &format[offset]))
{
for (i = 0; i < MAX_CHARACTER_CLASS; i++)
if (isalnum(i))
characterclass[i]++;
offset += sizeof(CLASS_ALNUM) - 1;
}
else if (trio_equal_max(CLASS_ALPHA, sizeof(CLASS_ALPHA) - 1,
&format[offset]))
{
for (i = 0; i < MAX_CHARACTER_CLASS; i++)
if (isalpha(i))
characterclass[i]++;
offset += sizeof(CLASS_ALPHA) - 1;
}
else if (trio_equal_max(CLASS_CNTRL, sizeof(CLASS_CNTRL) - 1,
&format[offset]))
{
for (i = 0; i < MAX_CHARACTER_CLASS; i++)
if (iscntrl(i))
characterclass[i]++;
offset += sizeof(CLASS_CNTRL) - 1;
}
else if (trio_equal_max(CLASS_DIGIT, sizeof(CLASS_DIGIT) - 1,
&format[offset]))
{
for (i = 0; i < MAX_CHARACTER_CLASS; i++)
if (isdigit(i))
characterclass[i]++;
offset += sizeof(CLASS_DIGIT) - 1;
}
else if (trio_equal_max(CLASS_GRAPH, sizeof(CLASS_GRAPH) - 1,
&format[offset]))
{
for (i = 0; i < MAX_CHARACTER_CLASS; i++)
if (isgraph(i))
characterclass[i]++;
offset += sizeof(CLASS_GRAPH) - 1;
}
else if (trio_equal_max(CLASS_LOWER, sizeof(CLASS_LOWER) - 1,
&format[offset]))
{
for (i = 0; i < MAX_CHARACTER_CLASS; i++)
if (islower(i))
characterclass[i]++;
offset += sizeof(CLASS_LOWER) - 1;
}
else if (trio_equal_max(CLASS_PRINT, sizeof(CLASS_PRINT) - 1,
&format[offset]))
{
for (i = 0; i < MAX_CHARACTER_CLASS; i++)
if (isprint(i))
characterclass[i]++;
offset += sizeof(CLASS_PRINT) - 1;
}
else if (trio_equal_max(CLASS_PUNCT, sizeof(CLASS_PUNCT) - 1,
&format[offset]))
{
for (i = 0; i < MAX_CHARACTER_CLASS; i++)
if (ispunct(i))
characterclass[i]++;
offset += sizeof(CLASS_PUNCT) - 1;
}
else if (trio_equal_max(CLASS_SPACE, sizeof(CLASS_SPACE) - 1,
&format[offset]))
{
for (i = 0; i < MAX_CHARACTER_CLASS; i++)
if (isspace(i))
characterclass[i]++;
offset += sizeof(CLASS_SPACE) - 1;
}
else if (trio_equal_max(CLASS_UPPER, sizeof(CLASS_UPPER) - 1,
&format[offset]))
{
for (i = 0; i < MAX_CHARACTER_CLASS; i++)
if (isupper(i))
characterclass[i]++;
offset += sizeof(CLASS_UPPER) - 1;
}
else if (trio_equal_max(CLASS_XDIGIT, sizeof(CLASS_XDIGIT) - 1,
&format[offset]))
{
for (i = 0; i < MAX_CHARACTER_CLASS; i++)
if (isxdigit(i))
characterclass[i]++;
offset += sizeof(CLASS_XDIGIT) - 1;
}
else
{
characterclass[(int)ch]++;
}
break;
default:
characterclass[(int)ch]++;
break;
}
break;
#endif /* TRIO_EXTENSION */
default:
characterclass[(int)ch]++;
break;
}
}
return 0;
}
/*************************************************************************
* TrioReadNumber
*
* We implement our own number conversion in preference of strtol and
* strtoul, because we must handle 'long long' and thousand separators.
*/
TRIO_PRIVATE BOOLEAN_T TrioReadNumber TRIO_ARGS5((self, target, flags, width, base),
trio_class_t* self, trio_uintmax_t* target,
trio_flags_t flags, int width, int base)
{
trio_uintmax_t number = 0;
int digit;
int count;
BOOLEAN_T isNegative = FALSE;
BOOLEAN_T gotNumber = FALSE;
int j;
assert(VALID(self));
assert(VALID(self->InStream));
assert((base >= MIN_BASE && base <= MAX_BASE) || (base == NO_BASE));
if (internalDigitsUnconverted)
{
/* Lazy evaluation of digits array */
memset(internalDigitArray, -1, sizeof(internalDigitArray));
for (j = 0; j < (int)sizeof(internalDigitsLower) - 1; j++)
{
internalDigitArray[(int)internalDigitsLower[j]] = j;
internalDigitArray[(int)internalDigitsUpper[j]] = j;
}
internalDigitsUnconverted = FALSE;
}
TrioSkipWhitespaces(self);
/* Leading sign */
if (self->current == '+')
{
self->InStream(self, NULL);
}
else if (self->current == '-')
{
self->InStream(self, NULL);
isNegative = TRUE;
}
count = self->processed;
if (flags & FLAGS_ALTERNATIVE)
{
switch (base)
{
case NO_BASE:
case BASE_OCTAL:
case BASE_HEX:
case BASE_BINARY:
if (self->current == '0')
{
self->InStream(self, NULL);
if (self->current)
{
if ((base == BASE_HEX) && (trio_to_upper(self->current) == 'X'))
{
self->InStream(self, NULL);
}
else if ((base == BASE_BINARY) && (trio_to_upper(self->current) == 'B'))
{
self->InStream(self, NULL);
}
}
}
else
return FALSE;
break;
default:
break;
}
}
while (((width == NO_WIDTH) || (self->processed - count < width)) &&
(!((self->current == EOF) || isspace(self->current))))
{
if (isascii(self->current))
{
digit = internalDigitArray[self->current];
/* Abort if digit is not allowed in the specified base */
if ((digit == -1) || (digit >= base))
break;
}
#if TRIO_FEATURE_QUOTE
else if (flags & FLAGS_QUOTE)
{
/* Compare with thousands separator */
for (j = 0; internalThousandSeparator[j] && self->current; j++)
{
if (internalThousandSeparator[j] != self->current)
break;
self->InStream(self, NULL);
}
if (internalThousandSeparator[j])
break; /* Mismatch */
else
continue; /* Match */
}
#endif
else
break;
number *= base;
number += digit;
gotNumber = TRUE; /* we need at least one digit */
self->InStream(self, NULL);
}
/* Was anything read at all? */
if (!gotNumber)
return FALSE;
if (target)
*target = (isNegative) ? (trio_uintmax_t)(-((trio_intmax_t)number)) : number;
return TRUE;
}
/*************************************************************************
* TrioReadChar
*/
TRIO_PRIVATE int TrioReadChar TRIO_ARGS4((self, target, flags, width), trio_class_t* self,
char* target, trio_flags_t flags, int width)
{
int i;
char ch;
trio_uintmax_t number;
assert(VALID(self));
assert(VALID(self->InStream));
for (i = 0; (self->current != EOF) && (i < width); i++)
{
ch = (char)self->current;
self->InStream(self, NULL);
if ((flags & FLAGS_ALTERNATIVE) && (ch == CHAR_BACKSLASH))
{
switch (self->current)
{
case '\\':
ch = '\\';
break;
case 'a':
ch = '\007';
break;
case 'b':
ch = '\b';
break;
case 'f':
ch = '\f';
break;
case 'n':
ch = '\n';
break;
case 'r':
ch = '\r';
break;
case 't':
ch = '\t';
break;
case 'v':
ch = '\v';
break;
default:
if (isdigit(self->current))
{
/* Read octal number */
if (!TrioReadNumber(self, &number, 0, 3, BASE_OCTAL))
return 0;
ch = (char)number;
}
else if (trio_to_upper(self->current) == 'X')
{
/* Read hexadecimal number */
self->InStream(self, NULL);
if (!TrioReadNumber(self, &number, 0, 2, BASE_HEX))
return 0;
ch = (char)number;
}
else
{
ch = (char)self->current;
}
break;
}
}
if (target)
target[i] = ch;
}
return i + 1;
}
/*************************************************************************
* TrioReadString
*/
TRIO_PRIVATE BOOLEAN_T TrioReadString TRIO_ARGS4((self, target, flags, width), trio_class_t* self,
char* target, trio_flags_t flags, int width)
{
int i;
assert(VALID(self));
assert(VALID(self->InStream));
TrioSkipWhitespaces(self);
/*
* Continue until end of string is reached, a whitespace is encountered,
* or width is exceeded
*/
for (i = 0; ((width == NO_WIDTH) || (i < width)) &&
(!((self->current == EOF) || isspace(self->current)));
i++)
{
if (TrioReadChar(self, (target ? &target[i] : 0), flags, 1) == 0)
break; /* for */
}
if (target)
target[i] = NIL;
return TRUE;
}
/*************************************************************************
* TrioReadWideChar
*/
#if TRIO_FEATURE_WIDECHAR
TRIO_PRIVATE int TrioReadWideChar TRIO_ARGS4((self, target, flags, width), trio_class_t* self,
trio_wchar_t* target, trio_flags_t flags, int width)
{
int i;
int j;
int size;
int amount = 0;
trio_wchar_t wch;
char buffer[MB_LEN_MAX + 1];
assert(VALID(self));
assert(VALID(self->InStream));
for (i = 0; (self->current != EOF) && (i < width); i++)
{
if (isascii(self->current))
{
if (TrioReadChar(self, buffer, flags, 1) == 0)
return 0;
buffer[1] = NIL;
}
else
{
/*
* Collect a multibyte character, by enlarging buffer until
* it contains a fully legal multibyte character, or the
* buffer is full.
*/
j = 0;
do
{
buffer[j++] = (char)self->current;
buffer[j] = NIL;
self->InStream(self, NULL);
} while ((j < (int)sizeof(buffer)) && (mblen(buffer, (size_t)j) != j));
}
if (target)
{
size = mbtowc(&wch, buffer, sizeof(buffer));
if (size > 0)
target[i] = wch;
}
amount += size;
self->InStream(self, NULL);
}
return amount;
}
#endif /* TRIO_FEATURE_WIDECHAR */
/*************************************************************************
* TrioReadWideString
*/
#if TRIO_FEATURE_WIDECHAR
TRIO_PRIVATE BOOLEAN_T TrioReadWideString TRIO_ARGS4((self, target, flags, width),
trio_class_t* self, trio_wchar_t* target,
trio_flags_t flags, int width)
{
int i;
int size;
assert(VALID(self));
assert(VALID(self->InStream));
TrioSkipWhitespaces(self);
#if defined(TRIO_COMPILER_SUPPORTS_MULTIBYTE)
/* Required by TrioReadWideChar */
(void)mblen(NULL, 0);
#endif
/*
* Continue until end of string is reached, a whitespace is encountered,
* or width is exceeded
*/
for (i = 0; ((width == NO_WIDTH) || (i < width)) &&
(!((self->current == EOF) || isspace(self->current)));)
{
size = TrioReadWideChar(self, &target[i], flags, 1);
if (size == 0)
break; /* for */
i += size;
}
if (target)
target[i] = WCONST('\0');
return TRUE;
}
#endif /* TRIO_FEATURE_WIDECHAR */
/*************************************************************************
* TrioReadGroup
*
* Reads non-empty character groups.
*
* FIXME: characterclass does not work with multibyte characters
*/
TRIO_PRIVATE BOOLEAN_T TrioReadGroup TRIO_ARGS5((self, target, characterclass, flags, width),
trio_class_t* self, char* target,
int* characterclass, trio_flags_t flags, int width)
{
int ch;
int i;
assert(VALID(self));
assert(VALID(self->InStream));
ch = self->current;
for (i = 0; ((width == NO_WIDTH) || (i < width)) &&
(!((ch == EOF) || (((flags & FLAGS_EXCLUDE) != 0) ^ (characterclass[ch] == 0))));
i++)
{
if (target)
target[i] = (char)ch;
self->InStream(self, &ch);
}
if (i == 0)
return FALSE;
/* Terminate the string if input saved */
if (target)
target[i] = NIL;
return TRUE;
}
/*************************************************************************
* TrioReadDouble
*
* FIXME:
* add long double
* handle base
*/
#if TRIO_FEATURE_FLOAT
TRIO_PRIVATE BOOLEAN_T TrioReadDouble TRIO_ARGS4((self, target, flags, width), trio_class_t* self,
trio_pointer_t target, trio_flags_t flags,
int width)
{
int ch;
char doubleString[512];
int offset = 0;
int start;
#if TRIO_FEATURE_QUOTE
int j;
#endif
BOOLEAN_T isHex = FALSE;
trio_long_double_t infinity;
doubleString[0] = 0;
if ((width == NO_WIDTH) || (width > (int)sizeof(doubleString) - 1))
width = sizeof(doubleString) - 1;
TrioSkipWhitespaces(self);
/*
* Read entire double number from stream. trio_to_double requires
* a string as input, but InStream can be anything, so we have to
* collect all characters.
*/
ch = self->current;
if ((ch == '+') || (ch == '-'))
{
doubleString[offset++] = (char)ch;
self->InStream(self, &ch);
width--;
}
start = offset;
switch (ch)
{
case 'n':
case 'N':
/* Not-a-number */
if (offset != 0)
break;
/* FALLTHROUGH */
case 'i':
case 'I':
/* Infinity */
while (isalpha(ch) && (offset - start < width))
{
doubleString[offset++] = (char)ch;
self->InStream(self, &ch);
}
doubleString[offset] = NIL;
/* Case insensitive string comparison */
if (trio_equal(&doubleString[start], INFINITE_UPPER) ||
trio_equal(&doubleString[start], LONG_INFINITE_UPPER))
{
infinity = ((start == 1) && (doubleString[0] == '-')) ? trio_ninf() : trio_pinf();
if (!target)
return FALSE;
if (flags & FLAGS_LONGDOUBLE)
{
*((trio_long_double_t*)target) = infinity;
}
else if (flags & FLAGS_LONG)
{
*((double*)target) = infinity;
}
else
{
*((float*)target) = infinity;
}
return TRUE;
}
if (trio_equal(doubleString, NAN_UPPER))
{
if (!target)
return FALSE;
/* NaN must not have a preceeding + nor - */
if (flags & FLAGS_LONGDOUBLE)
{
*((trio_long_double_t*)target) = trio_nan();
}
else if (flags & FLAGS_LONG)
{
*((double*)target) = trio_nan();
}
else
{
*((float*)target) = trio_nan();
}
return TRUE;
}
return FALSE;
case '0':
doubleString[offset++] = (char)ch;
self->InStream(self, &ch);
if (trio_to_upper(ch) == 'X')
{
isHex = TRUE;
doubleString[offset++] = (char)ch;
self->InStream(self, &ch);
}
break;
default:
break;
}
while ((ch != EOF) && (offset - start < width))
{
/* Integer part */
if (isHex ? isxdigit(ch) : isdigit(ch))
{
doubleString[offset++] = (char)ch;
self->InStream(self, &ch);
}
#if TRIO_FEATURE_QUOTE
else if (flags & FLAGS_QUOTE)
{
/* Compare with thousands separator */
for (j = 0; internalThousandSeparator[j] && self->current; j++)
{
if (internalThousandSeparator[j] != self->current)
break;
self->InStream(self, &ch);
}
if (internalThousandSeparator[j])
break; /* Mismatch */
else
continue; /* Match */
}
#endif
else
break; /* while */
}
if (ch == '.')
{
/* Decimal part */
doubleString[offset++] = (char)ch;
self->InStream(self, &ch);
while ((isHex ? isxdigit(ch) : isdigit(ch)) && (offset - start < width))
{
doubleString[offset++] = (char)ch;
self->InStream(self, &ch);
}
}
if (isHex ? (trio_to_upper(ch) == 'P') : (trio_to_upper(ch) == 'E'))
{
/* Exponent */
doubleString[offset++] = (char)ch;
self->InStream(self, &ch);
if ((ch == '+') || (ch == '-'))
{
doubleString[offset++] = (char)ch;
self->InStream(self, &ch);
}
while (isdigit(ch) && (offset - start < width))
{
doubleString[offset++] = (char)ch;
self->InStream(self, &ch);
}
}
if ((offset == start) || (*doubleString == NIL))
return FALSE;
doubleString[offset] = 0;
if (flags & FLAGS_LONGDOUBLE)
{
if (!target)
return FALSE;
*((trio_long_double_t*)target) = trio_to_long_double(doubleString, NULL);
}
else if (flags & FLAGS_LONG)
{
if (!target)
return FALSE;
*((double*)target) = trio_to_double(doubleString, NULL);
}
else
{
if (!target)
return FALSE;
*((float*)target) = trio_to_float(doubleString, NULL);
}
return TRUE;
}
#endif /* TRIO_FEATURE_FLOAT */
/*************************************************************************
* TrioReadPointer
*/
TRIO_PRIVATE BOOLEAN_T TrioReadPointer TRIO_ARGS3((self, target, flags), trio_class_t* self,
trio_pointer_t* target, trio_flags_t flags)
{
trio_uintmax_t number;
char buffer[sizeof(internalNullString)];
flags |= (FLAGS_UNSIGNED | FLAGS_ALTERNATIVE | FLAGS_NILPADDING);
if (TrioReadNumber(self, &number, flags, POINTER_WIDTH, BASE_HEX))
{
if (target)
{
#if defined(TRIO_COMPILER_GCC) || defined(TRIO_COMPILER_MIPSPRO)
/*
* The strange assignment of number is a workaround for a compiler
* warning
*/
*target = &((char*)0)[number];
#else
*target = (trio_pointer_t)number;
#endif
}
return TRUE;
}
else if (TrioReadString(self, (flags & FLAGS_IGNORE) ? NULL : buffer, 0,
sizeof(internalNullString) - 1))
{
if (trio_equal_case(buffer, internalNullString))
{
if (target)
*target = NULL;
return TRUE;
}
}
return FALSE;
}
/*************************************************************************
* TrioScanProcess
*/
TRIO_PRIVATE int TrioScanProcess TRIO_ARGS3((data, format, parameters), trio_class_t* data,
TRIO_CONST char* format, trio_parameter_t* parameters)
{
int status;
int assignment;
int ch;
int offset; /* Offset of format string */
int i; /* Offset of current parameter */
trio_flags_t flags;
int width;
int base;
trio_pointer_t pointer;
/* Return on empty format string */
if (format[0] == NIL)
return 0;
status = 0;
assignment = 0;
i = 0;
offset = 0;
data->InStream(data, &ch);
for (;;)
{
/* Skip the parameter entries */
while (parameters[i].type == FORMAT_PARAMETER)
{
assert(i <= MAX_PARAMETERS);
i++;
}
/* Compare non conversion-specifier part of format string */
while (offset < parameters[i].beginOffset)
{
if ((CHAR_IDENTIFIER == format[offset]) && (CHAR_IDENTIFIER == format[offset + 1]))
{
/* Two % in format matches one % in input stream */
if (CHAR_IDENTIFIER == ch)
{
data->InStream(data, &ch);
offset += 2;
continue; /* while format chars left */
}
else
{
status = TRIO_ERROR_RETURN(TRIO_EINVAL, offset);
goto end;
}
}
else /* Not an % identifier */
{
if (isspace((int)format[offset]))
{
/* Whitespaces may match any amount of whitespaces */
ch = TrioSkipWhitespaces(data);
}
else if (ch == format[offset])
{
data->InStream(data, &ch);
}
else
{
status = assignment;
goto end;
}
offset++;
}
}
if (parameters[i].type == FORMAT_SENTINEL)
break;
if ((EOF == ch) && (parameters[i].type != FORMAT_COUNT))
{
status = (assignment > 0) ? assignment : EOF;
goto end;
}
flags = parameters[i].flags;
/* Find width */
width = parameters[i].width;
if (flags & FLAGS_WIDTH_PARAMETER)
{
/* Get width from parameter list */
width = (int)parameters[width].data.number.as_signed;
}
/* Find base */
if (NO_BASE != parameters[i].baseSpecifier)
{
/* Base from specifier has priority */
base = parameters[i].baseSpecifier;
}
else if (flags & FLAGS_BASE_PARAMETER)
{
/* Get base from parameter list */
base = parameters[i].base;
base = (int)parameters[base].data.number.as_signed;
}
else
{
/* Use base from format string */
base = parameters[i].base;
}
switch (parameters[i].type)
{
case FORMAT_INT:
{
trio_uintmax_t number;
if (0 == base)
base = BASE_DECIMAL;
if (!TrioReadNumber(data, &number, flags, width, base))
{
status = assignment;
goto end;
}
if (!(flags & FLAGS_IGNORE))
{
assignment++;
pointer = parameters[i].data.pointer;
#if TRIO_FEATURE_SIZE_T || TRIO_FEATURE_SIZE_T_UPPER
if (flags & FLAGS_SIZE_T)
*(size_t*)pointer = (size_t)number;
else
#endif
#if TRIO_FEATURE_PTRDIFF_T
if (flags & FLAGS_PTRDIFF_T)
*(ptrdiff_t*)pointer = (ptrdiff_t)number;
else
#endif
#if TRIO_FEATURE_INTMAX_T
if (flags & FLAGS_INTMAX_T)
*(trio_intmax_t*)pointer = (trio_intmax_t)number;
else
#endif
if (flags & FLAGS_QUAD)
*(trio_ulonglong_t*)pointer = (trio_ulonglong_t)number;
else if (flags & FLAGS_LONG)
*(long int*)pointer = (long int)number;
else if (flags & FLAGS_SHORT)
*(short int*)pointer = (short int)number;
else
*(int*)pointer = (int)number;
}
}
break; /* FORMAT_INT */
case FORMAT_STRING:
#if TRIO_FEATURE_WIDECHAR
if (flags & FLAGS_WIDECHAR)
{
if (!TrioReadWideString(
data, (flags & FLAGS_IGNORE) ? NULL : parameters[i].data.wstring, flags,
width))
{
status = assignment;
goto end;
}
}
else
#endif
{
if (!TrioReadString(data,
(flags & FLAGS_IGNORE) ? NULL : parameters[i].data.string,
flags, width))
{
status = assignment;
goto end;
}
}
if (!(flags & FLAGS_IGNORE))
assignment++;
break; /* FORMAT_STRING */
#if TRIO_FEATURE_FLOAT
case FORMAT_DOUBLE:
{
if (flags & FLAGS_IGNORE)
{
pointer = NULL;
}
else
{
pointer = (flags & FLAGS_LONGDOUBLE)
? (trio_pointer_t)parameters[i].data.longdoublePointer
: (trio_pointer_t)parameters[i].data.doublePointer;
}
if (!TrioReadDouble(data, pointer, flags, width))
{
status = assignment;
goto end;
}
if (!(flags & FLAGS_IGNORE))
{
assignment++;
}
break; /* FORMAT_DOUBLE */
}
#endif
case FORMAT_GROUP:
{
int characterclass[MAX_CHARACTER_CLASS + 1];
/* Skip over modifiers */
while (format[offset] != SPECIFIER_GROUP)
{
offset++;
}
/* Skip over group specifier */
offset++;
memset(characterclass, 0, sizeof(characterclass));
status = TrioGetCharacterClass(format, &offset, &flags, characterclass);
if (status < 0)
goto end;
if (!TrioReadGroup(data, (flags & FLAGS_IGNORE) ? NULL : parameters[i].data.string,
characterclass, flags, parameters[i].width))
{
status = assignment;
goto end;
}
if (!(flags & FLAGS_IGNORE))
assignment++;
}
break; /* FORMAT_GROUP */
case FORMAT_COUNT:
pointer = parameters[i].data.pointer;
if (NULL != pointer)
{
int count = data->processed;
if (ch != EOF)
count--; /* a character is read, but is not consumed yet */
#if TRIO_FEATURE_SIZE_T || TRIO_FEATURE_SIZE_T_UPPER
if (flags & FLAGS_SIZE_T)
*(size_t*)pointer = (size_t)count;
else
#endif
#if TRIO_FEATURE_PTRDIFF_T
if (flags & FLAGS_PTRDIFF_T)
*(ptrdiff_t*)pointer = (ptrdiff_t)count;
else
#endif
#if TRIO_FEATURE_INTMAX_T
if (flags & FLAGS_INTMAX_T)
*(trio_intmax_t*)pointer = (trio_intmax_t)count;
else
#endif
if (flags & FLAGS_QUAD)
{
*(trio_ulonglong_t*)pointer = (trio_ulonglong_t)count;
}
else if (flags & FLAGS_LONG)
{
*(long int*)pointer = (long int)count;
}
else if (flags & FLAGS_SHORT)
{
*(short int*)pointer = (short int)count;
}
else
{
*(int*)pointer = (int)count;
}
}
break; /* FORMAT_COUNT */
case FORMAT_CHAR:
#if TRIO_FEATURE_WIDECHAR
if (flags & FLAGS_WIDECHAR)
{
if (TrioReadWideChar(data,
(flags & FLAGS_IGNORE) ? NULL : parameters[i].data.wstring,
flags, (width == NO_WIDTH) ? 1 : width) == 0)
{
status = assignment;
goto end;
}
}
else
#endif
{
if (TrioReadChar(data,
(flags & FLAGS_IGNORE) ? NULL : parameters[i].data.string,
flags, (width == NO_WIDTH) ? 1 : width) == 0)
{
status = assignment;
goto end;
}
}
if (!(flags & FLAGS_IGNORE))
assignment++;
break; /* FORMAT_CHAR */
case FORMAT_POINTER:
if (!TrioReadPointer(
data,
(flags & FLAGS_IGNORE) ? NULL : (trio_pointer_t*)parameters[i].data.pointer,
flags))
{
status = assignment;
goto end;
}
if (!(flags & FLAGS_IGNORE))
assignment++;
break; /* FORMAT_POINTER */
case FORMAT_PARAMETER:
break; /* FORMAT_PARAMETER */
default:
status = TRIO_ERROR_RETURN(TRIO_EINVAL, offset);
goto end;
}
ch = data->current;
offset = parameters[i].endOffset;
i++;
}
status = assignment;
end:
if (data->UndoStream)
data->UndoStream(data);
return status;
}
/*************************************************************************
* TrioScan
*/
TRIO_PRIVATE int TrioScan TRIO_ARGS8(
(source, sourceSize, InStream, UndoStream, format, arglist, argfunc, argarray),
trio_pointer_t source, size_t sourceSize, void(*InStream) TRIO_PROTO((trio_class_t*, int*)),
void(*UndoStream) TRIO_PROTO((trio_class_t*)), TRIO_CONST char* format, va_list arglist,
trio_argfunc_t argfunc, trio_pointer_t* argarray)
{
int status;
trio_parameter_t parameters[MAX_PARAMETERS];
trio_class_t data;
assert(VALID(InStream));
assert(VALID(format));
memset(&data, 0, sizeof(data));
data.InStream = InStream;
data.UndoStream = UndoStream;
data.location = (trio_pointer_t)source;
data.max = sourceSize;
data.error = 0;
#if defined(USE_LOCALE)
if (NULL == internalLocaleValues)
{
TrioSetLocale();
}
#endif
status = TrioParse(TYPE_SCAN, format, parameters, arglist, argfunc, argarray);
if (status < 0)
return status;
status = TrioScanProcess(&data, format, parameters);
if (data.error != 0)
{
status = data.error;
}
return status;
}
/*************************************************************************
* TrioInStreamFile
*/
#if TRIO_FEATURE_FILE || TRIO_FEATURE_STDIO
TRIO_PRIVATE void TrioInStreamFile TRIO_ARGS2((self, intPointer), trio_class_t* self,
int* intPointer)
{
FILE* file = (FILE*)self->location;
assert(VALID(self));
assert(VALID(file));
self->actually.cached = 0;
/* The initial value of self->current is zero */
if (self->current == EOF)
{
self->error =
(ferror(file)) ? TRIO_ERROR_RETURN(TRIO_ERRNO, 0) : TRIO_ERROR_RETURN(TRIO_EOF, 0);
}
else
{
self->processed++;
self->actually.cached++;
}
self->current = fgetc(file);
if (VALID(intPointer))
{
*intPointer = self->current;
}
}
#endif /* TRIO_FEATURE_FILE || TRIO_FEATURE_STDIO */
/*************************************************************************
* TrioUndoStreamFile
*/
#if TRIO_FEATURE_FILE || TRIO_FEATURE_STDIO
TRIO_PRIVATE void TrioUndoStreamFile TRIO_ARGS1((self), trio_class_t* self)
{
FILE* file = (FILE*)self->location;
assert(VALID(self));
assert(VALID(file));
if (self->actually.cached > 0)
{
assert(self->actually.cached == 1);
self->current = ungetc(self->current, file);
self->actually.cached = 0;
}
}
#endif /* TRIO_FEATURE_FILE || TRIO_FEATURE_STDIO */
/*************************************************************************
* TrioInStreamFileDescriptor
*/
#if TRIO_FEATURE_FD
TRIO_PRIVATE void TrioInStreamFileDescriptor TRIO_ARGS2((self, intPointer), trio_class_t* self,
int* intPointer)
{
int fd = *((int*)self->location);
int size;
unsigned char input;
assert(VALID(self));
self->actually.cached = 0;
size = read(fd, &input, sizeof(char));
if (size == -1)
{
self->error = TRIO_ERROR_RETURN(TRIO_ERRNO, 0);
self->current = EOF;
}
else
{
self->current = (size == 0) ? EOF : input;
}
if (self->current != EOF)
{
self->actually.cached++;
self->processed++;
}
if (VALID(intPointer))
{
*intPointer = self->current;
}
}
#endif /* TRIO_FEATURE_FD */
/*************************************************************************
* TrioInStreamCustom
*/
#if TRIO_FEATURE_CLOSURE
TRIO_PRIVATE void TrioInStreamCustom TRIO_ARGS2((self, intPointer), trio_class_t* self,
int* intPointer)
{
trio_custom_t* data;
assert(VALID(self));
assert(VALID(self->location));
self->actually.cached = 0;
data = (trio_custom_t*)self->location;
self->current = (data->stream.in == NULL) ? NIL : (data->stream.in)(data->closure);
if (self->current == NIL)
{
self->current = EOF;
}
else
{
self->processed++;
self->actually.cached++;
}
if (VALID(intPointer))
{
*intPointer = self->current;
}
}
#endif /* TRIO_FEATURE_CLOSURE */
/*************************************************************************
* TrioInStreamString
*/
TRIO_PRIVATE void TrioInStreamString TRIO_ARGS2((self, intPointer), trio_class_t* self,
int* intPointer)
{
unsigned char** buffer;
assert(VALID(self));
assert(VALID(self->location));
self->actually.cached = 0;
buffer = (unsigned char**)self->location;
self->current = (*buffer)[0];
if (self->current == NIL)
{
self->current = EOF;
}
else
{
(*buffer)++;
self->processed++;
self->actually.cached++;
}
if (VALID(intPointer))
{
*intPointer = self->current;
}
}
/*************************************************************************
*
* Formatted scanning functions
*
************************************************************************/
#if defined(TRIO_DOCUMENTATION)
#include "doc/doc_scanf.h"
#endif
/** @addtogroup Scanf
@{
*/
/*************************************************************************
* scanf
*/
/**
Scan characters from standard input stream.
@param format Formatting string.
@param ... Arguments.
@return Number of scanned characters.
*/
#if TRIO_FEATURE_STDIO
TRIO_PUBLIC int trio_scanf TRIO_VARGS2((format, va_alist), TRIO_CONST char* format, TRIO_VA_DECL)
{
int status;
va_list args;
assert(VALID(format));
TRIO_VA_START(args, format);
status = TrioScan((trio_pointer_t)stdin, 0, TrioInStreamFile, TrioUndoStreamFile, format, args,
NULL, NULL);
TRIO_VA_END(args);
return status;
}
#endif /* TRIO_FEATURE_STDIO */
/**
Scan characters from standard input stream.
@param format Formatting string.
@param args Arguments.
@return Number of scanned characters.
*/
#if TRIO_FEATURE_STDIO
TRIO_PUBLIC int trio_vscanf TRIO_ARGS2((format, args), TRIO_CONST char* format, va_list args)
{
assert(VALID(format));
return TrioScan((trio_pointer_t)stdin, 0, TrioInStreamFile, TrioUndoStreamFile, format, args,
NULL, NULL);
}
#endif /* TRIO_FEATURE_STDIO */
/**
Scan characters from standard input stream.
@param format Formatting string.
@param args Arguments.
@return Number of scanned characters.
*/
#if TRIO_FEATURE_STDIO
TRIO_PUBLIC int trio_scanfv TRIO_ARGS2((format, args), TRIO_CONST char* format,
trio_pointer_t* args)
{
static va_list unused;
assert(VALID(format));
return TrioScan((trio_pointer_t)stdin, 0, TrioInStreamFile, TrioUndoStreamFile, format, unused,
TrioArrayGetter, args);
}
#endif /* TRIO_FEATURE_STDIO */
/*************************************************************************
* fscanf
*/
/**
Scan characters from file.
@param file File pointer.
@param format Formatting string.
@param ... Arguments.
@return Number of scanned characters.
*/
#if TRIO_FEATURE_FILE
TRIO_PUBLIC int trio_fscanf TRIO_VARGS3((file, format, va_alist), FILE* file,
TRIO_CONST char* format, TRIO_VA_DECL)
{
int status;
va_list args;
assert(VALID(file));
assert(VALID(format));
TRIO_VA_START(args, format);
status = TrioScan((trio_pointer_t)file, 0, TrioInStreamFile, TrioUndoStreamFile, format, args,
NULL, NULL);
TRIO_VA_END(args);
return status;
}
#endif /* TRIO_FEATURE_FILE */
/**
Scan characters from file.
@param file File pointer.
@param format Formatting string.
@param args Arguments.
@return Number of scanned characters.
*/
#if TRIO_FEATURE_FILE
TRIO_PUBLIC int trio_vfscanf TRIO_ARGS3((file, format, args), FILE* file, TRIO_CONST char* format,
va_list args)
{
assert(VALID(file));
assert(VALID(format));
return TrioScan((trio_pointer_t)file, 0, TrioInStreamFile, TrioUndoStreamFile, format, args,
NULL, NULL);
}
#endif /* TRIO_FEATURE_FILE */
/**
Scan characters from file.
@param file File pointer.
@param format Formatting string.
@param args Arguments.
@return Number of scanned characters.
*/
#if TRIO_FEATURE_FILE
TRIO_PUBLIC int trio_fscanfv TRIO_ARGS3((file, format, args), FILE* file, TRIO_CONST char* format,
trio_pointer_t* args)
{
static va_list unused;
assert(VALID(file));
assert(VALID(format));
return TrioScan((trio_pointer_t)file, 0, TrioInStreamFile, TrioUndoStreamFile, format, unused,
TrioArrayGetter, args);
}
#endif /* TRIO_FEATURE_FILE */
/*************************************************************************
* dscanf
*/
/**
Scan characters from file descriptor.
@param fd File descriptor.
@param format Formatting string.
@param ... Arguments.
@return Number of scanned characters.
*/
#if TRIO_FEATURE_FD
TRIO_PUBLIC int trio_dscanf TRIO_VARGS3((fd, format, va_alist), int fd, TRIO_CONST char* format,
TRIO_VA_DECL)
{
int status;
va_list args;
assert(VALID(format));
TRIO_VA_START(args, format);
status = TrioScan((trio_pointer_t)&fd, 0, TrioInStreamFileDescriptor, NULL, format, args, NULL,
NULL);
TRIO_VA_END(args);
return status;
}
#endif /* TRIO_FEATURE_FD */
/**
Scan characters from file descriptor.
@param fd File descriptor.
@param format Formatting string.
@param args Arguments.
@return Number of scanned characters.
*/
#if TRIO_FEATURE_FD
TRIO_PUBLIC int trio_vdscanf TRIO_ARGS3((fd, format, args), int fd, TRIO_CONST char* format,
va_list args)
{
assert(VALID(format));
return TrioScan((trio_pointer_t)&fd, 0, TrioInStreamFileDescriptor, NULL, format, args, NULL,
NULL);
}
#endif /* TRIO_FEATURE_FD */
/**
Scan characters from file descriptor.
@param fd File descriptor.
@param format Formatting string.
@param args Arguments.
@return Number of scanned characters.
*/
#if TRIO_FEATURE_FD
TRIO_PUBLIC int trio_dscanfv TRIO_ARGS3((fd, format, args), int fd, TRIO_CONST char* format,
trio_pointer_t* args)
{
static va_list unused;
assert(VALID(format));
return TrioScan((trio_pointer_t)&fd, 0, TrioInStreamFileDescriptor, NULL, format, unused,
TrioArrayGetter, args);
}
#endif /* TRIO_FEATURE_FD */
/*************************************************************************
* cscanf
*/
#if TRIO_FEATURE_CLOSURE
TRIO_PUBLIC int trio_cscanf TRIO_VARGS4((stream, closure, format, va_alist), trio_instream_t stream,
trio_pointer_t closure, TRIO_CONST char* format,
TRIO_VA_DECL)
{
int status;
va_list args;
trio_custom_t data;
assert(VALID(stream));
assert(VALID(format));
TRIO_VA_START(args, format);
data.stream.in = stream;
data.closure = closure;
status = TrioScan(&data, 0, TrioInStreamCustom, NULL, format, args, NULL, NULL);
TRIO_VA_END(args);
return status;
}
#endif /* TRIO_FEATURE_CLOSURE */
#if TRIO_FEATURE_CLOSURE
TRIO_PUBLIC int trio_vcscanf TRIO_ARGS4((stream, closure, format, args), trio_instream_t stream,
trio_pointer_t closure, TRIO_CONST char* format,
va_list args)
{
trio_custom_t data;
assert(VALID(stream));
assert(VALID(format));
data.stream.in = stream;
data.closure = closure;
return TrioScan(&data, 0, TrioInStreamCustom, NULL, format, args, NULL, NULL);
}
#endif /* TRIO_FEATURE_CLOSURE */
#if TRIO_FEATURE_CLOSURE
TRIO_PUBLIC int trio_cscanfv TRIO_ARGS4((stream, closure, format, args), trio_instream_t stream,
trio_pointer_t closure, TRIO_CONST char* format,
trio_pointer_t* args)
{
static va_list unused;
trio_custom_t data;
assert(VALID(stream));
assert(VALID(format));
data.stream.in = stream;
data.closure = closure;
return TrioScan(&data, 0, TrioInStreamCustom, NULL, format, unused, TrioArrayGetter, args);
}
#endif /* TRIO_FEATURE_CLOSURE */
#if TRIO_FEATURE_CLOSURE && TRIO_FEATURE_ARGFUNC
TRIO_PUBLIC int trio_cscanff TRIO_ARGS5((stream, closure, format, argfunc, context),
trio_instream_t stream, trio_pointer_t closure,
TRIO_CONST char* format, trio_argfunc_t argfunc,
trio_pointer_t context)
{
static va_list unused;
trio_custom_t data;
assert(VALID(stream));
assert(VALID(format));
assert(VALID(argfunc));
data.stream.in = stream;
data.closure = closure;
return TrioScan(&data, 0, TrioInStreamCustom, NULL, format, unused, argfunc,
(trio_pointer_t*)context);
}
#endif /* TRIO_FEATURE_CLOSURE && TRIO_FEATURE_ARGFUNC */
/*************************************************************************
* sscanf
*/
/**
Scan characters from string.
@param buffer Input string.
@param format Formatting string.
@param ... Arguments.
@return Number of scanned characters.
*/
TRIO_PUBLIC int trio_sscanf TRIO_VARGS3((buffer, format, va_alist), TRIO_CONST char* buffer,
TRIO_CONST char* format, TRIO_VA_DECL)
{
int status;
va_list args;
assert(VALID(buffer));
assert(VALID(format));
TRIO_VA_START(args, format);
status =
TrioScan((trio_pointer_t)&buffer, 0, TrioInStreamString, NULL, format, args, NULL, NULL);
TRIO_VA_END(args);
return status;
}
/**
Scan characters from string.
@param buffer Input string.
@param format Formatting string.
@param args Arguments.
@return Number of scanned characters.
*/
TRIO_PUBLIC int trio_vsscanf TRIO_ARGS3((buffer, format, args), TRIO_CONST char* buffer,
TRIO_CONST char* format, va_list args)
{
assert(VALID(buffer));
assert(VALID(format));
return TrioScan((trio_pointer_t)&buffer, 0, TrioInStreamString, NULL, format, args, NULL, NULL);
}
/**
Scan characters from string.
@param buffer Input string.
@param format Formatting string.
@param args Arguments.
@return Number of scanned characters.
*/
TRIO_PUBLIC int trio_sscanfv TRIO_ARGS3((buffer, format, args), TRIO_CONST char* buffer,
TRIO_CONST char* format, trio_pointer_t* args)
{
static va_list unused;
assert(VALID(buffer));
assert(VALID(format));
return TrioScan((trio_pointer_t)&buffer, 0, TrioInStreamString, NULL, format, unused,
TrioArrayGetter, args);
}
#endif /* TRIO_FEATURE_SCANF */
/** @} End of Scanf documentation module */
/*************************************************************************
* trio_strerror
*/
TRIO_PUBLIC TRIO_CONST char* trio_strerror TRIO_ARGS1((errorcode), int errorcode)
{
#if TRIO_FEATURE_STRERR
/* Textual versions of the error codes */
switch (TRIO_ERROR_CODE(errorcode))
{
case TRIO_EOF:
return "End of file";
case TRIO_EINVAL:
return "Invalid argument";
case TRIO_ETOOMANY:
return "Too many arguments";
case TRIO_EDBLREF:
return "Double reference";
case TRIO_EGAP:
return "Reference gap";
case TRIO_ENOMEM:
return "Out of memory";
case TRIO_ERANGE:
return "Invalid range";
case TRIO_ECUSTOM:
return "Custom error";
default:
return "Unknown";
}
#else
return "Unknown";
#endif
}
#ifdef _WIN32
#pragma warning(pop)
#endif
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_4493_0 |
crossvul-cpp_data_bad_2701_1 | /*
* Copyright (C) 2002 WIDE Project.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the project nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
/* \summary: IPv6 mobility printer */
/* RFC 3775 */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <netdissect-stdinc.h>
#include "netdissect.h"
#include "addrtoname.h"
#include "extract.h"
#include "ip6.h"
static const char tstr[] = "[|MOBILITY]";
/* Mobility header */
struct ip6_mobility {
uint8_t ip6m_pproto; /* following payload protocol (for PG) */
uint8_t ip6m_len; /* length in units of 8 octets */
uint8_t ip6m_type; /* message type */
uint8_t reserved; /* reserved */
uint16_t ip6m_cksum; /* sum of IPv6 pseudo-header and MH */
union {
uint16_t ip6m_un_data16[1]; /* type-specific field */
uint8_t ip6m_un_data8[2]; /* type-specific field */
} ip6m_dataun;
};
#define ip6m_data16 ip6m_dataun.ip6m_un_data16
#define ip6m_data8 ip6m_dataun.ip6m_un_data8
#define IP6M_MINLEN 8
/* http://www.iana.org/assignments/mobility-parameters/mobility-parameters.xhtml */
/* message type */
#define IP6M_BINDING_REQUEST 0 /* Binding Refresh Request */
#define IP6M_HOME_TEST_INIT 1 /* Home Test Init */
#define IP6M_CAREOF_TEST_INIT 2 /* Care-of Test Init */
#define IP6M_HOME_TEST 3 /* Home Test */
#define IP6M_CAREOF_TEST 4 /* Care-of Test */
#define IP6M_BINDING_UPDATE 5 /* Binding Update */
#define IP6M_BINDING_ACK 6 /* Binding Acknowledgement */
#define IP6M_BINDING_ERROR 7 /* Binding Error */
#define IP6M_MAX 7
static const struct tok ip6m_str[] = {
{ IP6M_BINDING_REQUEST, "BRR" },
{ IP6M_HOME_TEST_INIT, "HoTI" },
{ IP6M_CAREOF_TEST_INIT, "CoTI" },
{ IP6M_HOME_TEST, "HoT" },
{ IP6M_CAREOF_TEST, "CoT" },
{ IP6M_BINDING_UPDATE, "BU" },
{ IP6M_BINDING_ACK, "BA" },
{ IP6M_BINDING_ERROR, "BE" },
{ 0, NULL }
};
static const unsigned ip6m_hdrlen[IP6M_MAX + 1] = {
IP6M_MINLEN, /* IP6M_BINDING_REQUEST */
IP6M_MINLEN + 8, /* IP6M_HOME_TEST_INIT */
IP6M_MINLEN + 8, /* IP6M_CAREOF_TEST_INIT */
IP6M_MINLEN + 16, /* IP6M_HOME_TEST */
IP6M_MINLEN + 16, /* IP6M_CAREOF_TEST */
IP6M_MINLEN + 4, /* IP6M_BINDING_UPDATE */
IP6M_MINLEN + 4, /* IP6M_BINDING_ACK */
IP6M_MINLEN + 16, /* IP6M_BINDING_ERROR */
};
/* Mobility Header Options */
#define IP6MOPT_MINLEN 2
#define IP6MOPT_PAD1 0x0 /* Pad1 */
#define IP6MOPT_PADN 0x1 /* PadN */
#define IP6MOPT_REFRESH 0x2 /* Binding Refresh Advice */
#define IP6MOPT_REFRESH_MINLEN 4
#define IP6MOPT_ALTCOA 0x3 /* Alternate Care-of Address */
#define IP6MOPT_ALTCOA_MINLEN 18
#define IP6MOPT_NONCEID 0x4 /* Nonce Indices */
#define IP6MOPT_NONCEID_MINLEN 6
#define IP6MOPT_AUTH 0x5 /* Binding Authorization Data */
#define IP6MOPT_AUTH_MINLEN 12
static int
mobility_opt_print(netdissect_options *ndo,
const u_char *bp, const unsigned len)
{
unsigned i, optlen;
for (i = 0; i < len; i += optlen) {
ND_TCHECK(bp[i]);
if (bp[i] == IP6MOPT_PAD1)
optlen = 1;
else {
if (i + 1 < len) {
ND_TCHECK(bp[i + 1]);
optlen = bp[i + 1] + 2;
}
else
goto trunc;
}
if (i + optlen > len)
goto trunc;
ND_TCHECK(bp[i + optlen]);
switch (bp[i]) {
case IP6MOPT_PAD1:
ND_PRINT((ndo, "(pad1)"));
break;
case IP6MOPT_PADN:
if (len - i < IP6MOPT_MINLEN) {
ND_PRINT((ndo, "(padn: trunc)"));
goto trunc;
}
ND_PRINT((ndo, "(padn)"));
break;
case IP6MOPT_REFRESH:
if (len - i < IP6MOPT_REFRESH_MINLEN) {
ND_PRINT((ndo, "(refresh: trunc)"));
goto trunc;
}
/* units of 4 secs */
ND_TCHECK_16BITS(&bp[i+2]);
ND_PRINT((ndo, "(refresh: %u)",
EXTRACT_16BITS(&bp[i+2]) << 2));
break;
case IP6MOPT_ALTCOA:
if (len - i < IP6MOPT_ALTCOA_MINLEN) {
ND_PRINT((ndo, "(altcoa: trunc)"));
goto trunc;
}
ND_PRINT((ndo, "(alt-CoA: %s)", ip6addr_string(ndo, &bp[i+2])));
break;
case IP6MOPT_NONCEID:
if (len - i < IP6MOPT_NONCEID_MINLEN) {
ND_PRINT((ndo, "(ni: trunc)"));
goto trunc;
}
ND_TCHECK_16BITS(&bp[i+2]);
ND_TCHECK_16BITS(&bp[i+4]);
ND_PRINT((ndo, "(ni: ho=0x%04x co=0x%04x)",
EXTRACT_16BITS(&bp[i+2]),
EXTRACT_16BITS(&bp[i+4])));
break;
case IP6MOPT_AUTH:
if (len - i < IP6MOPT_AUTH_MINLEN) {
ND_PRINT((ndo, "(auth: trunc)"));
goto trunc;
}
ND_PRINT((ndo, "(auth)"));
break;
default:
if (len - i < IP6MOPT_MINLEN) {
ND_PRINT((ndo, "(sopt_type %u: trunc)", bp[i]));
goto trunc;
}
ND_PRINT((ndo, "(type-0x%02x: len=%u)", bp[i], bp[i + 1]));
break;
}
}
return 0;
trunc:
return 1;
}
/*
* Mobility Header
*/
int
mobility_print(netdissect_options *ndo,
const u_char *bp, const u_char *bp2 _U_)
{
const struct ip6_mobility *mh;
const u_char *ep;
unsigned mhlen, hlen;
uint8_t type;
mh = (const struct ip6_mobility *)bp;
/* 'ep' points to the end of available data. */
ep = ndo->ndo_snapend;
if (!ND_TTEST(mh->ip6m_len)) {
/*
* There's not enough captured data to include the
* mobility header length.
*
* Our caller expects us to return the length, however,
* so return a value that will run to the end of the
* captured data.
*
* XXX - "ip6_print()" doesn't do anything with the
* returned length, however, as it breaks out of the
* header-processing loop.
*/
mhlen = ep - bp;
goto trunc;
}
mhlen = (mh->ip6m_len + 1) << 3;
/* XXX ip6m_cksum */
ND_TCHECK(mh->ip6m_type);
type = mh->ip6m_type;
if (type <= IP6M_MAX && mhlen < ip6m_hdrlen[type]) {
ND_PRINT((ndo, "(header length %u is too small for type %u)", mhlen, type));
goto trunc;
}
ND_PRINT((ndo, "mobility: %s", tok2str(ip6m_str, "type-#%u", type)));
switch (type) {
case IP6M_BINDING_REQUEST:
hlen = IP6M_MINLEN;
break;
case IP6M_HOME_TEST_INIT:
case IP6M_CAREOF_TEST_INIT:
hlen = IP6M_MINLEN;
if (ndo->ndo_vflag) {
ND_TCHECK_32BITS(&bp[hlen + 4]);
ND_PRINT((ndo, " %s Init Cookie=%08x:%08x",
type == IP6M_HOME_TEST_INIT ? "Home" : "Care-of",
EXTRACT_32BITS(&bp[hlen]),
EXTRACT_32BITS(&bp[hlen + 4])));
}
hlen += 8;
break;
case IP6M_HOME_TEST:
case IP6M_CAREOF_TEST:
ND_TCHECK(mh->ip6m_data16[0]);
ND_PRINT((ndo, " nonce id=0x%x", EXTRACT_16BITS(&mh->ip6m_data16[0])));
hlen = IP6M_MINLEN;
if (ndo->ndo_vflag) {
ND_TCHECK_32BITS(&bp[hlen + 4]);
ND_PRINT((ndo, " %s Init Cookie=%08x:%08x",
type == IP6M_HOME_TEST ? "Home" : "Care-of",
EXTRACT_32BITS(&bp[hlen]),
EXTRACT_32BITS(&bp[hlen + 4])));
}
hlen += 8;
if (ndo->ndo_vflag) {
ND_TCHECK_32BITS(&bp[hlen + 4]);
ND_PRINT((ndo, " %s Keygen Token=%08x:%08x",
type == IP6M_HOME_TEST ? "Home" : "Care-of",
EXTRACT_32BITS(&bp[hlen]),
EXTRACT_32BITS(&bp[hlen + 4])));
}
hlen += 8;
break;
case IP6M_BINDING_UPDATE:
ND_TCHECK(mh->ip6m_data16[0]);
ND_PRINT((ndo, " seq#=%u", EXTRACT_16BITS(&mh->ip6m_data16[0])));
hlen = IP6M_MINLEN;
ND_TCHECK_16BITS(&bp[hlen]);
if (bp[hlen] & 0xf0) {
ND_PRINT((ndo, " "));
if (bp[hlen] & 0x80)
ND_PRINT((ndo, "A"));
if (bp[hlen] & 0x40)
ND_PRINT((ndo, "H"));
if (bp[hlen] & 0x20)
ND_PRINT((ndo, "L"));
if (bp[hlen] & 0x10)
ND_PRINT((ndo, "K"));
}
/* Reserved (4bits) */
hlen += 1;
/* Reserved (8bits) */
hlen += 1;
ND_TCHECK_16BITS(&bp[hlen]);
/* units of 4 secs */
ND_PRINT((ndo, " lifetime=%u", EXTRACT_16BITS(&bp[hlen]) << 2));
hlen += 2;
break;
case IP6M_BINDING_ACK:
ND_TCHECK(mh->ip6m_data8[0]);
ND_PRINT((ndo, " status=%u", mh->ip6m_data8[0]));
ND_TCHECK(mh->ip6m_data8[1]);
if (mh->ip6m_data8[1] & 0x80)
ND_PRINT((ndo, " K"));
/* Reserved (7bits) */
hlen = IP6M_MINLEN;
ND_TCHECK_16BITS(&bp[hlen]);
ND_PRINT((ndo, " seq#=%u", EXTRACT_16BITS(&bp[hlen])));
hlen += 2;
ND_TCHECK_16BITS(&bp[hlen]);
/* units of 4 secs */
ND_PRINT((ndo, " lifetime=%u", EXTRACT_16BITS(&bp[hlen]) << 2));
hlen += 2;
break;
case IP6M_BINDING_ERROR:
ND_TCHECK(mh->ip6m_data8[0]);
ND_PRINT((ndo, " status=%u", mh->ip6m_data8[0]));
/* Reserved */
hlen = IP6M_MINLEN;
ND_TCHECK2(bp[hlen], 16);
ND_PRINT((ndo, " homeaddr %s", ip6addr_string(ndo, &bp[hlen])));
hlen += 16;
break;
default:
ND_PRINT((ndo, " len=%u", mh->ip6m_len));
return(mhlen);
break;
}
if (ndo->ndo_vflag)
if (mobility_opt_print(ndo, &bp[hlen], mhlen - hlen))
goto trunc;
return(mhlen);
trunc:
ND_PRINT((ndo, "%s", tstr));
return(-1);
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_2701_1 |
crossvul-cpp_data_bad_2748_0 | /*
* Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the project nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
*/
/* \summary: Internet Security Association and Key Management Protocol (ISAKMP) printer */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
/* The functions from print-esp.c used in this file are only defined when both
* OpenSSL and evp.h are detected. Employ the same preprocessor device here.
*/
#ifndef HAVE_OPENSSL_EVP_H
#undef HAVE_LIBCRYPTO
#endif
#include <netdissect-stdinc.h>
#include <string.h>
#include "netdissect.h"
#include "addrtoname.h"
#include "extract.h"
#include "ip.h"
#include "ip6.h"
#include "ipproto.h"
/* refer to RFC 2408 */
typedef u_char cookie_t[8];
typedef u_char msgid_t[4];
#define PORT_ISAKMP 500
/* 3.1 ISAKMP Header Format (IKEv1 and IKEv2)
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
! Initiator !
! Cookie !
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
! Responder !
! Cookie !
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
! Next Payload ! MjVer ! MnVer ! Exchange Type ! Flags !
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
! Message ID !
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
! Length !
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*/
struct isakmp {
cookie_t i_ck; /* Initiator Cookie */
cookie_t r_ck; /* Responder Cookie */
uint8_t np; /* Next Payload Type */
uint8_t vers;
#define ISAKMP_VERS_MAJOR 0xf0
#define ISAKMP_VERS_MAJOR_SHIFT 4
#define ISAKMP_VERS_MINOR 0x0f
#define ISAKMP_VERS_MINOR_SHIFT 0
uint8_t etype; /* Exchange Type */
uint8_t flags; /* Flags */
msgid_t msgid;
uint32_t len; /* Length */
};
/* Next Payload Type */
#define ISAKMP_NPTYPE_NONE 0 /* NONE*/
#define ISAKMP_NPTYPE_SA 1 /* Security Association */
#define ISAKMP_NPTYPE_P 2 /* Proposal */
#define ISAKMP_NPTYPE_T 3 /* Transform */
#define ISAKMP_NPTYPE_KE 4 /* Key Exchange */
#define ISAKMP_NPTYPE_ID 5 /* Identification */
#define ISAKMP_NPTYPE_CERT 6 /* Certificate */
#define ISAKMP_NPTYPE_CR 7 /* Certificate Request */
#define ISAKMP_NPTYPE_HASH 8 /* Hash */
#define ISAKMP_NPTYPE_SIG 9 /* Signature */
#define ISAKMP_NPTYPE_NONCE 10 /* Nonce */
#define ISAKMP_NPTYPE_N 11 /* Notification */
#define ISAKMP_NPTYPE_D 12 /* Delete */
#define ISAKMP_NPTYPE_VID 13 /* Vendor ID */
#define ISAKMP_NPTYPE_v2E 46 /* v2 Encrypted payload */
#define IKEv1_MAJOR_VERSION 1
#define IKEv1_MINOR_VERSION 0
#define IKEv2_MAJOR_VERSION 2
#define IKEv2_MINOR_VERSION 0
/* Flags */
#define ISAKMP_FLAG_E 0x01 /* Encryption Bit */
#define ISAKMP_FLAG_C 0x02 /* Commit Bit */
#define ISAKMP_FLAG_extra 0x04
/* IKEv2 */
#define ISAKMP_FLAG_I (1 << 3) /* (I)nitiator */
#define ISAKMP_FLAG_V (1 << 4) /* (V)ersion */
#define ISAKMP_FLAG_R (1 << 5) /* (R)esponse */
/* 3.2 Payload Generic Header
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
! Next Payload ! RESERVED ! Payload Length !
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*/
struct isakmp_gen {
uint8_t np; /* Next Payload */
uint8_t critical; /* bit 7 - critical, rest is RESERVED */
uint16_t len; /* Payload Length */
};
/* 3.3 Data Attributes
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
!A! Attribute Type ! AF=0 Attribute Length !
!F! ! AF=1 Attribute Value !
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
. AF=0 Attribute Value .
. AF=1 Not Transmitted .
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*/
struct isakmp_data {
uint16_t type; /* defined by DOI-spec, and Attribute Format */
uint16_t lorv; /* if f equal 1, Attribute Length */
/* if f equal 0, Attribute Value */
/* if f equal 1, Attribute Value */
};
/* 3.4 Security Association Payload */
/* MAY NOT be used, because of being defined in ipsec-doi. */
/*
If the current payload is the last in the message,
then the value of the next payload field will be 0.
This field MUST NOT contain the
values for the Proposal or Transform payloads as they are considered
part of the security association negotiation. For example, this
field would contain the value "10" (Nonce payload) in the first
message of a Base Exchange (see Section 4.4) and the value "0" in the
first message of an Identity Protect Exchange (see Section 4.5).
*/
struct ikev1_pl_sa {
struct isakmp_gen h;
uint32_t doi; /* Domain of Interpretation */
uint32_t sit; /* Situation */
};
/* 3.5 Proposal Payload */
/*
The value of the next payload field MUST only contain the value "2"
or "0". If there are additional Proposal payloads in the message,
then this field will be 2. If the current Proposal payload is the
last within the security association proposal, then this field will
be 0.
*/
struct ikev1_pl_p {
struct isakmp_gen h;
uint8_t p_no; /* Proposal # */
uint8_t prot_id; /* Protocol */
uint8_t spi_size; /* SPI Size */
uint8_t num_t; /* Number of Transforms */
/* SPI */
};
/* 3.6 Transform Payload */
/*
The value of the next payload field MUST only contain the value "3"
or "0". If there are additional Transform payloads in the proposal,
then this field will be 3. If the current Transform payload is the
last within the proposal, then this field will be 0.
*/
struct ikev1_pl_t {
struct isakmp_gen h;
uint8_t t_no; /* Transform # */
uint8_t t_id; /* Transform-Id */
uint16_t reserved; /* RESERVED2 */
/* SA Attributes */
};
/* 3.7 Key Exchange Payload */
struct ikev1_pl_ke {
struct isakmp_gen h;
/* Key Exchange Data */
};
/* 3.8 Identification Payload */
/* MUST NOT to be used, because of being defined in ipsec-doi. */
struct ikev1_pl_id {
struct isakmp_gen h;
union {
uint8_t id_type; /* ID Type */
uint32_t doi_data; /* DOI Specific ID Data */
} d;
/* Identification Data */
};
/* 3.9 Certificate Payload */
struct ikev1_pl_cert {
struct isakmp_gen h;
uint8_t encode; /* Cert Encoding */
char cert; /* Certificate Data */
/*
This field indicates the type of
certificate or certificate-related information contained in the
Certificate Data field.
*/
};
/* 3.10 Certificate Request Payload */
struct ikev1_pl_cr {
struct isakmp_gen h;
uint8_t num_cert; /* # Cert. Types */
/*
Certificate Types (variable length)
-- Contains a list of the types of certificates requested,
sorted in order of preference. Each individual certificate
type is 1 octet. This field is NOT requiredo
*/
/* # Certificate Authorities (1 octet) */
/* Certificate Authorities (variable length) */
};
/* 3.11 Hash Payload */
/* may not be used, because of having only data. */
struct ikev1_pl_hash {
struct isakmp_gen h;
/* Hash Data */
};
/* 3.12 Signature Payload */
/* may not be used, because of having only data. */
struct ikev1_pl_sig {
struct isakmp_gen h;
/* Signature Data */
};
/* 3.13 Nonce Payload */
/* may not be used, because of having only data. */
struct ikev1_pl_nonce {
struct isakmp_gen h;
/* Nonce Data */
};
/* 3.14 Notification Payload */
struct ikev1_pl_n {
struct isakmp_gen h;
uint32_t doi; /* Domain of Interpretation */
uint8_t prot_id; /* Protocol-ID */
uint8_t spi_size; /* SPI Size */
uint16_t type; /* Notify Message Type */
/* SPI */
/* Notification Data */
};
/* 3.14.1 Notify Message Types */
/* NOTIFY MESSAGES - ERROR TYPES */
#define ISAKMP_NTYPE_INVALID_PAYLOAD_TYPE 1
#define ISAKMP_NTYPE_DOI_NOT_SUPPORTED 2
#define ISAKMP_NTYPE_SITUATION_NOT_SUPPORTED 3
#define ISAKMP_NTYPE_INVALID_COOKIE 4
#define ISAKMP_NTYPE_INVALID_MAJOR_VERSION 5
#define ISAKMP_NTYPE_INVALID_MINOR_VERSION 6
#define ISAKMP_NTYPE_INVALID_EXCHANGE_TYPE 7
#define ISAKMP_NTYPE_INVALID_FLAGS 8
#define ISAKMP_NTYPE_INVALID_MESSAGE_ID 9
#define ISAKMP_NTYPE_INVALID_PROTOCOL_ID 10
#define ISAKMP_NTYPE_INVALID_SPI 11
#define ISAKMP_NTYPE_INVALID_TRANSFORM_ID 12
#define ISAKMP_NTYPE_ATTRIBUTES_NOT_SUPPORTED 13
#define ISAKMP_NTYPE_NO_PROPOSAL_CHOSEN 14
#define ISAKMP_NTYPE_BAD_PROPOSAL_SYNTAX 15
#define ISAKMP_NTYPE_PAYLOAD_MALFORMED 16
#define ISAKMP_NTYPE_INVALID_KEY_INFORMATION 17
#define ISAKMP_NTYPE_INVALID_ID_INFORMATION 18
#define ISAKMP_NTYPE_INVALID_CERT_ENCODING 19
#define ISAKMP_NTYPE_INVALID_CERTIFICATE 20
#define ISAKMP_NTYPE_BAD_CERT_REQUEST_SYNTAX 21
#define ISAKMP_NTYPE_INVALID_CERT_AUTHORITY 22
#define ISAKMP_NTYPE_INVALID_HASH_INFORMATION 23
#define ISAKMP_NTYPE_AUTHENTICATION_FAILED 24
#define ISAKMP_NTYPE_INVALID_SIGNATURE 25
#define ISAKMP_NTYPE_ADDRESS_NOTIFICATION 26
/* 3.15 Delete Payload */
struct ikev1_pl_d {
struct isakmp_gen h;
uint32_t doi; /* Domain of Interpretation */
uint8_t prot_id; /* Protocol-Id */
uint8_t spi_size; /* SPI Size */
uint16_t num_spi; /* # of SPIs */
/* SPI(es) */
};
struct ikev1_ph1tab {
struct ikev1_ph1 *head;
struct ikev1_ph1 *tail;
int len;
};
struct isakmp_ph2tab {
struct ikev1_ph2 *head;
struct ikev1_ph2 *tail;
int len;
};
/* IKEv2 (RFC4306) */
/* 3.3 Security Association Payload -- generic header */
/* 3.3.1. Proposal Substructure */
struct ikev2_p {
struct isakmp_gen h;
uint8_t p_no; /* Proposal # */
uint8_t prot_id; /* Protocol */
uint8_t spi_size; /* SPI Size */
uint8_t num_t; /* Number of Transforms */
};
/* 3.3.2. Transform Substructure */
struct ikev2_t {
struct isakmp_gen h;
uint8_t t_type; /* Transform Type (ENCR,PRF,INTEG,etc.*/
uint8_t res2; /* reserved byte */
uint16_t t_id; /* Transform ID */
};
enum ikev2_t_type {
IV2_T_ENCR = 1,
IV2_T_PRF = 2,
IV2_T_INTEG= 3,
IV2_T_DH = 4,
IV2_T_ESN = 5
};
/* 3.4. Key Exchange Payload */
struct ikev2_ke {
struct isakmp_gen h;
uint16_t ke_group;
uint16_t ke_res1;
/* KE data */
};
/* 3.5. Identification Payloads */
enum ikev2_id_type {
ID_IPV4_ADDR=1,
ID_FQDN=2,
ID_RFC822_ADDR=3,
ID_IPV6_ADDR=5,
ID_DER_ASN1_DN=9,
ID_DER_ASN1_GN=10,
ID_KEY_ID=11
};
struct ikev2_id {
struct isakmp_gen h;
uint8_t type; /* ID type */
uint8_t res1;
uint16_t res2;
/* SPI */
/* Notification Data */
};
/* 3.10 Notification Payload */
struct ikev2_n {
struct isakmp_gen h;
uint8_t prot_id; /* Protocol-ID */
uint8_t spi_size; /* SPI Size */
uint16_t type; /* Notify Message Type */
};
enum ikev2_n_type {
IV2_NOTIFY_UNSUPPORTED_CRITICAL_PAYLOAD = 1,
IV2_NOTIFY_INVALID_IKE_SPI = 4,
IV2_NOTIFY_INVALID_MAJOR_VERSION = 5,
IV2_NOTIFY_INVALID_SYNTAX = 7,
IV2_NOTIFY_INVALID_MESSAGE_ID = 9,
IV2_NOTIFY_INVALID_SPI =11,
IV2_NOTIFY_NO_PROPOSAL_CHOSEN =14,
IV2_NOTIFY_INVALID_KE_PAYLOAD =17,
IV2_NOTIFY_AUTHENTICATION_FAILED =24,
IV2_NOTIFY_SINGLE_PAIR_REQUIRED =34,
IV2_NOTIFY_NO_ADDITIONAL_SAS =35,
IV2_NOTIFY_INTERNAL_ADDRESS_FAILURE =36,
IV2_NOTIFY_FAILED_CP_REQUIRED =37,
IV2_NOTIFY_INVALID_SELECTORS =39,
IV2_NOTIFY_INITIAL_CONTACT =16384,
IV2_NOTIFY_SET_WINDOW_SIZE =16385,
IV2_NOTIFY_ADDITIONAL_TS_POSSIBLE =16386,
IV2_NOTIFY_IPCOMP_SUPPORTED =16387,
IV2_NOTIFY_NAT_DETECTION_SOURCE_IP =16388,
IV2_NOTIFY_NAT_DETECTION_DESTINATION_IP =16389,
IV2_NOTIFY_COOKIE =16390,
IV2_NOTIFY_USE_TRANSPORT_MODE =16391,
IV2_NOTIFY_HTTP_CERT_LOOKUP_SUPPORTED =16392,
IV2_NOTIFY_REKEY_SA =16393,
IV2_NOTIFY_ESP_TFC_PADDING_NOT_SUPPORTED =16394,
IV2_NOTIFY_NON_FIRST_FRAGMENTS_ALSO =16395
};
struct notify_messages {
uint16_t type;
char *msg;
};
/* 3.8 Authentication Payload */
struct ikev2_auth {
struct isakmp_gen h;
uint8_t auth_method; /* Protocol-ID */
uint8_t reserved[3];
/* authentication data */
};
enum ikev2_auth_type {
IV2_RSA_SIG = 1,
IV2_SHARED = 2,
IV2_DSS_SIG = 3
};
/* refer to RFC 2409 */
#if 0
/* isakmp sa structure */
struct oakley_sa {
uint8_t proto_id; /* OAKLEY */
vchar_t *spi; /* spi */
uint8_t dhgrp; /* DH; group */
uint8_t auth_t; /* method of authentication */
uint8_t prf_t; /* type of prf */
uint8_t hash_t; /* type of hash */
uint8_t enc_t; /* type of cipher */
uint8_t life_t; /* type of duration of lifetime */
uint32_t ldur; /* life duration */
};
#endif
/* refer to RFC 2407 */
#define IPSEC_DOI 1
/* 4.2 IPSEC Situation Definition */
#define IPSECDOI_SIT_IDENTITY_ONLY 0x00000001
#define IPSECDOI_SIT_SECRECY 0x00000002
#define IPSECDOI_SIT_INTEGRITY 0x00000004
/* 4.4.1 IPSEC Security Protocol Identifiers */
/* 4.4.2 IPSEC ISAKMP Transform Values */
#define IPSECDOI_PROTO_ISAKMP 1
#define IPSECDOI_KEY_IKE 1
/* 4.4.1 IPSEC Security Protocol Identifiers */
#define IPSECDOI_PROTO_IPSEC_AH 2
/* 4.4.3 IPSEC AH Transform Values */
#define IPSECDOI_AH_MD5 2
#define IPSECDOI_AH_SHA 3
#define IPSECDOI_AH_DES 4
#define IPSECDOI_AH_SHA2_256 5
#define IPSECDOI_AH_SHA2_384 6
#define IPSECDOI_AH_SHA2_512 7
/* 4.4.1 IPSEC Security Protocol Identifiers */
#define IPSECDOI_PROTO_IPSEC_ESP 3
/* 4.4.4 IPSEC ESP Transform Identifiers */
#define IPSECDOI_ESP_DES_IV64 1
#define IPSECDOI_ESP_DES 2
#define IPSECDOI_ESP_3DES 3
#define IPSECDOI_ESP_RC5 4
#define IPSECDOI_ESP_IDEA 5
#define IPSECDOI_ESP_CAST 6
#define IPSECDOI_ESP_BLOWFISH 7
#define IPSECDOI_ESP_3IDEA 8
#define IPSECDOI_ESP_DES_IV32 9
#define IPSECDOI_ESP_RC4 10
#define IPSECDOI_ESP_NULL 11
#define IPSECDOI_ESP_RIJNDAEL 12
#define IPSECDOI_ESP_AES 12
/* 4.4.1 IPSEC Security Protocol Identifiers */
#define IPSECDOI_PROTO_IPCOMP 4
/* 4.4.5 IPSEC IPCOMP Transform Identifiers */
#define IPSECDOI_IPCOMP_OUI 1
#define IPSECDOI_IPCOMP_DEFLATE 2
#define IPSECDOI_IPCOMP_LZS 3
/* 4.5 IPSEC Security Association Attributes */
#define IPSECDOI_ATTR_SA_LTYPE 1 /* B */
#define IPSECDOI_ATTR_SA_LTYPE_DEFAULT 1
#define IPSECDOI_ATTR_SA_LTYPE_SEC 1
#define IPSECDOI_ATTR_SA_LTYPE_KB 2
#define IPSECDOI_ATTR_SA_LDUR 2 /* V */
#define IPSECDOI_ATTR_SA_LDUR_DEFAULT 28800 /* 8 hours */
#define IPSECDOI_ATTR_GRP_DESC 3 /* B */
#define IPSECDOI_ATTR_ENC_MODE 4 /* B */
/* default value: host dependent */
#define IPSECDOI_ATTR_ENC_MODE_TUNNEL 1
#define IPSECDOI_ATTR_ENC_MODE_TRNS 2
#define IPSECDOI_ATTR_AUTH 5 /* B */
/* 0 means not to use authentication. */
#define IPSECDOI_ATTR_AUTH_HMAC_MD5 1
#define IPSECDOI_ATTR_AUTH_HMAC_SHA1 2
#define IPSECDOI_ATTR_AUTH_DES_MAC 3
#define IPSECDOI_ATTR_AUTH_KPDK 4 /*RFC-1826(Key/Pad/Data/Key)*/
/*
* When negotiating ESP without authentication, the Auth
* Algorithm attribute MUST NOT be included in the proposal.
* When negotiating ESP without confidentiality, the Auth
* Algorithm attribute MUST be included in the proposal and
* the ESP transform ID must be ESP_NULL.
*/
#define IPSECDOI_ATTR_KEY_LENGTH 6 /* B */
#define IPSECDOI_ATTR_KEY_ROUNDS 7 /* B */
#define IPSECDOI_ATTR_COMP_DICT_SIZE 8 /* B */
#define IPSECDOI_ATTR_COMP_PRIVALG 9 /* V */
/* 4.6.1 Security Association Payload */
struct ipsecdoi_sa {
struct isakmp_gen h;
uint32_t doi; /* Domain of Interpretation */
uint32_t sit; /* Situation */
};
struct ipsecdoi_secrecy_h {
uint16_t len;
uint16_t reserved;
};
/* 4.6.2.1 Identification Type Values */
struct ipsecdoi_id {
struct isakmp_gen h;
uint8_t type; /* ID Type */
uint8_t proto_id; /* Protocol ID */
uint16_t port; /* Port */
/* Identification Data */
};
#define IPSECDOI_ID_IPV4_ADDR 1
#define IPSECDOI_ID_FQDN 2
#define IPSECDOI_ID_USER_FQDN 3
#define IPSECDOI_ID_IPV4_ADDR_SUBNET 4
#define IPSECDOI_ID_IPV6_ADDR 5
#define IPSECDOI_ID_IPV6_ADDR_SUBNET 6
#define IPSECDOI_ID_IPV4_ADDR_RANGE 7
#define IPSECDOI_ID_IPV6_ADDR_RANGE 8
#define IPSECDOI_ID_DER_ASN1_DN 9
#define IPSECDOI_ID_DER_ASN1_GN 10
#define IPSECDOI_ID_KEY_ID 11
/* 4.6.3 IPSEC DOI Notify Message Types */
/* Notify Messages - Status Types */
#define IPSECDOI_NTYPE_RESPONDER_LIFETIME 24576
#define IPSECDOI_NTYPE_REPLAY_STATUS 24577
#define IPSECDOI_NTYPE_INITIAL_CONTACT 24578
#define DECLARE_PRINTER(func) static const u_char *ike##func##_print( \
netdissect_options *ndo, u_char tpay, \
const struct isakmp_gen *ext, \
u_int item_len, \
const u_char *end_pointer, \
uint32_t phase,\
uint32_t doi0, \
uint32_t proto0, int depth)
DECLARE_PRINTER(v1_sa);
DECLARE_PRINTER(v1_p);
DECLARE_PRINTER(v1_t);
DECLARE_PRINTER(v1_ke);
DECLARE_PRINTER(v1_id);
DECLARE_PRINTER(v1_cert);
DECLARE_PRINTER(v1_cr);
DECLARE_PRINTER(v1_sig);
DECLARE_PRINTER(v1_hash);
DECLARE_PRINTER(v1_nonce);
DECLARE_PRINTER(v1_n);
DECLARE_PRINTER(v1_d);
DECLARE_PRINTER(v1_vid);
DECLARE_PRINTER(v2_sa);
DECLARE_PRINTER(v2_ke);
DECLARE_PRINTER(v2_ID);
DECLARE_PRINTER(v2_cert);
DECLARE_PRINTER(v2_cr);
DECLARE_PRINTER(v2_auth);
DECLARE_PRINTER(v2_nonce);
DECLARE_PRINTER(v2_n);
DECLARE_PRINTER(v2_d);
DECLARE_PRINTER(v2_vid);
DECLARE_PRINTER(v2_TS);
DECLARE_PRINTER(v2_cp);
DECLARE_PRINTER(v2_eap);
static const u_char *ikev2_e_print(netdissect_options *ndo,
struct isakmp *base,
u_char tpay,
const struct isakmp_gen *ext,
u_int item_len,
const u_char *end_pointer,
uint32_t phase,
uint32_t doi0,
uint32_t proto0, int depth);
static const u_char *ike_sub0_print(netdissect_options *ndo,u_char, const struct isakmp_gen *,
const u_char *, uint32_t, uint32_t, uint32_t, int);
static const u_char *ikev1_sub_print(netdissect_options *ndo,u_char, const struct isakmp_gen *,
const u_char *, uint32_t, uint32_t, uint32_t, int);
static const u_char *ikev2_sub_print(netdissect_options *ndo,
struct isakmp *base,
u_char np, const struct isakmp_gen *ext,
const u_char *ep, uint32_t phase,
uint32_t doi, uint32_t proto,
int depth);
static char *numstr(int);
static void
ikev1_print(netdissect_options *ndo,
const u_char *bp, u_int length,
const u_char *bp2, struct isakmp *base);
#define MAXINITIATORS 20
static int ninitiator = 0;
union inaddr_u {
struct in_addr in4;
struct in6_addr in6;
};
static struct {
cookie_t initiator;
u_int version;
union inaddr_u iaddr;
union inaddr_u raddr;
} cookiecache[MAXINITIATORS];
/* protocol id */
static const char *protoidstr[] = {
NULL, "isakmp", "ipsec-ah", "ipsec-esp", "ipcomp",
};
/* isakmp->np */
static const char *npstr[] = {
"none", "sa", "p", "t", "ke", "id", "cert", "cr", "hash", /* 0 - 8 */
"sig", "nonce", "n", "d", "vid", /* 9 - 13 */
"pay14", "pay15", "pay16", "pay17", "pay18", /* 14- 18 */
"pay19", "pay20", "pay21", "pay22", "pay23", /* 19- 23 */
"pay24", "pay25", "pay26", "pay27", "pay28", /* 24- 28 */
"pay29", "pay30", "pay31", "pay32", /* 29- 32 */
"v2sa", "v2ke", "v2IDi", "v2IDr", "v2cert",/* 33- 37 */
"v2cr", "v2auth","v2nonce", "v2n", "v2d", /* 38- 42 */
"v2vid", "v2TSi", "v2TSr", "v2e", "v2cp", /* 43- 47 */
"v2eap", /* 48 */
};
/* isakmp->np */
static const u_char *(*npfunc[])(netdissect_options *ndo, u_char tpay,
const struct isakmp_gen *ext,
u_int item_len,
const u_char *end_pointer,
uint32_t phase,
uint32_t doi0,
uint32_t proto0, int depth) = {
NULL,
ikev1_sa_print,
ikev1_p_print,
ikev1_t_print,
ikev1_ke_print,
ikev1_id_print,
ikev1_cert_print,
ikev1_cr_print,
ikev1_hash_print,
ikev1_sig_print,
ikev1_nonce_print,
ikev1_n_print,
ikev1_d_print,
ikev1_vid_print, /* 13 */
NULL, NULL, NULL, NULL, NULL, /* 14- 18 */
NULL, NULL, NULL, NULL, NULL, /* 19- 23 */
NULL, NULL, NULL, NULL, NULL, /* 24- 28 */
NULL, NULL, NULL, NULL, /* 29- 32 */
ikev2_sa_print, /* 33 */
ikev2_ke_print, /* 34 */
ikev2_ID_print, /* 35 */
ikev2_ID_print, /* 36 */
ikev2_cert_print, /* 37 */
ikev2_cr_print, /* 38 */
ikev2_auth_print, /* 39 */
ikev2_nonce_print, /* 40 */
ikev2_n_print, /* 41 */
ikev2_d_print, /* 42 */
ikev2_vid_print, /* 43 */
ikev2_TS_print, /* 44 */
ikev2_TS_print, /* 45 */
NULL, /* ikev2_e_print,*/ /* 46 - special */
ikev2_cp_print, /* 47 */
ikev2_eap_print, /* 48 */
};
/* isakmp->etype */
static const char *etypestr[] = {
/* IKEv1 exchange types */
"none", "base", "ident", "auth", "agg", "inf", NULL, NULL, /* 0-7 */
NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, /* 8-15 */
NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, /* 16-23 */
NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, /* 24-31 */
"oakley-quick", "oakley-newgroup", /* 32-33 */
/* IKEv2 exchange types */
"ikev2_init", "ikev2_auth", "child_sa", "inf2" /* 34-37 */
};
#define STR_OR_ID(x, tab) \
(((x) < sizeof(tab)/sizeof(tab[0]) && tab[(x)]) ? tab[(x)] : numstr(x))
#define PROTOIDSTR(x) STR_OR_ID(x, protoidstr)
#define NPSTR(x) STR_OR_ID(x, npstr)
#define ETYPESTR(x) STR_OR_ID(x, etypestr)
#define CHECKLEN(p, np) \
if (ep < (const u_char *)(p)) { \
ND_PRINT((ndo," [|%s]", NPSTR(np))); \
goto done; \
}
#define NPFUNC(x) \
(((x) < sizeof(npfunc)/sizeof(npfunc[0]) && npfunc[(x)]) \
? npfunc[(x)] : NULL)
static int
iszero(const u_char *p, size_t l)
{
while (l--) {
if (*p++)
return 0;
}
return 1;
}
/* find cookie from initiator cache */
static int
cookie_find(cookie_t *in)
{
int i;
for (i = 0; i < MAXINITIATORS; i++) {
if (memcmp(in, &cookiecache[i].initiator, sizeof(*in)) == 0)
return i;
}
return -1;
}
/* record initiator */
static void
cookie_record(cookie_t *in, const u_char *bp2)
{
int i;
const struct ip *ip;
const struct ip6_hdr *ip6;
i = cookie_find(in);
if (0 <= i) {
ninitiator = (i + 1) % MAXINITIATORS;
return;
}
ip = (const struct ip *)bp2;
switch (IP_V(ip)) {
case 4:
cookiecache[ninitiator].version = 4;
UNALIGNED_MEMCPY(&cookiecache[ninitiator].iaddr.in4, &ip->ip_src, sizeof(struct in_addr));
UNALIGNED_MEMCPY(&cookiecache[ninitiator].raddr.in4, &ip->ip_dst, sizeof(struct in_addr));
break;
case 6:
ip6 = (const struct ip6_hdr *)bp2;
cookiecache[ninitiator].version = 6;
UNALIGNED_MEMCPY(&cookiecache[ninitiator].iaddr.in6, &ip6->ip6_src, sizeof(struct in6_addr));
UNALIGNED_MEMCPY(&cookiecache[ninitiator].raddr.in6, &ip6->ip6_dst, sizeof(struct in6_addr));
break;
default:
return;
}
UNALIGNED_MEMCPY(&cookiecache[ninitiator].initiator, in, sizeof(*in));
ninitiator = (ninitiator + 1) % MAXINITIATORS;
}
#define cookie_isinitiator(x, y) cookie_sidecheck((x), (y), 1)
#define cookie_isresponder(x, y) cookie_sidecheck((x), (y), 0)
static int
cookie_sidecheck(int i, const u_char *bp2, int initiator)
{
const struct ip *ip;
const struct ip6_hdr *ip6;
ip = (const struct ip *)bp2;
switch (IP_V(ip)) {
case 4:
if (cookiecache[i].version != 4)
return 0;
if (initiator) {
if (UNALIGNED_MEMCMP(&ip->ip_src, &cookiecache[i].iaddr.in4, sizeof(struct in_addr)) == 0)
return 1;
} else {
if (UNALIGNED_MEMCMP(&ip->ip_src, &cookiecache[i].raddr.in4, sizeof(struct in_addr)) == 0)
return 1;
}
break;
case 6:
if (cookiecache[i].version != 6)
return 0;
ip6 = (const struct ip6_hdr *)bp2;
if (initiator) {
if (UNALIGNED_MEMCMP(&ip6->ip6_src, &cookiecache[i].iaddr.in6, sizeof(struct in6_addr)) == 0)
return 1;
} else {
if (UNALIGNED_MEMCMP(&ip6->ip6_src, &cookiecache[i].raddr.in6, sizeof(struct in6_addr)) == 0)
return 1;
}
break;
default:
break;
}
return 0;
}
static void
hexprint(netdissect_options *ndo, const uint8_t *loc, size_t len)
{
const uint8_t *p;
size_t i;
p = loc;
for (i = 0; i < len; i++)
ND_PRINT((ndo,"%02x", p[i] & 0xff));
}
static int
rawprint(netdissect_options *ndo, const uint8_t *loc, size_t len)
{
ND_TCHECK2(*loc, len);
hexprint(ndo, loc, len);
return 1;
trunc:
return 0;
}
/*
* returns false if we run out of data buffer
*/
static int ike_show_somedata(netdissect_options *ndo,
const u_char *cp, const u_char *ep)
{
/* there is too much data, just show some of it */
const u_char *end = ep - 20;
int elen = 20;
int len = ep - cp;
if(len > 10) {
len = 10;
}
/* really shouldn't happen because of above */
if(end < cp + len) {
end = cp+len;
elen = ep - end;
}
ND_PRINT((ndo," data=("));
if(!rawprint(ndo, (const uint8_t *)(cp), len)) goto trunc;
ND_PRINT((ndo, "..."));
if(elen) {
if(!rawprint(ndo, (const uint8_t *)(end), elen)) goto trunc;
}
ND_PRINT((ndo,")"));
return 1;
trunc:
return 0;
}
struct attrmap {
const char *type;
u_int nvalue;
const char *value[30]; /*XXX*/
};
static const u_char *
ikev1_attrmap_print(netdissect_options *ndo,
const u_char *p, const u_char *ep2,
const struct attrmap *map, size_t nmap)
{
int totlen;
uint32_t t, v;
ND_TCHECK(p[0]);
if (p[0] & 0x80)
totlen = 4;
else {
ND_TCHECK_16BITS(&p[2]);
totlen = 4 + EXTRACT_16BITS(&p[2]);
}
if (ep2 < p + totlen) {
ND_PRINT((ndo,"[|attr]"));
return ep2 + 1;
}
ND_TCHECK_16BITS(&p[0]);
ND_PRINT((ndo,"("));
t = EXTRACT_16BITS(&p[0]) & 0x7fff;
if (map && t < nmap && map[t].type)
ND_PRINT((ndo,"type=%s ", map[t].type));
else
ND_PRINT((ndo,"type=#%d ", t));
if (p[0] & 0x80) {
ND_PRINT((ndo,"value="));
ND_TCHECK_16BITS(&p[2]);
v = EXTRACT_16BITS(&p[2]);
if (map && t < nmap && v < map[t].nvalue && map[t].value[v])
ND_PRINT((ndo,"%s", map[t].value[v]));
else {
if (!rawprint(ndo, (const uint8_t *)&p[2], 2)) {
ND_PRINT((ndo,")"));
goto trunc;
}
}
} else {
ND_PRINT((ndo,"len=%d value=", totlen - 4));
if (!rawprint(ndo, (const uint8_t *)&p[4], totlen - 4)) {
ND_PRINT((ndo,")"));
goto trunc;
}
}
ND_PRINT((ndo,")"));
return p + totlen;
trunc:
return NULL;
}
static const u_char *
ikev1_attr_print(netdissect_options *ndo, const u_char *p, const u_char *ep2)
{
int totlen;
uint32_t t;
ND_TCHECK(p[0]);
if (p[0] & 0x80)
totlen = 4;
else {
ND_TCHECK_16BITS(&p[2]);
totlen = 4 + EXTRACT_16BITS(&p[2]);
}
if (ep2 < p + totlen) {
ND_PRINT((ndo,"[|attr]"));
return ep2 + 1;
}
ND_TCHECK_16BITS(&p[0]);
ND_PRINT((ndo,"("));
t = EXTRACT_16BITS(&p[0]) & 0x7fff;
ND_PRINT((ndo,"type=#%d ", t));
if (p[0] & 0x80) {
ND_PRINT((ndo,"value="));
t = p[2];
if (!rawprint(ndo, (const uint8_t *)&p[2], 2)) {
ND_PRINT((ndo,")"));
goto trunc;
}
} else {
ND_PRINT((ndo,"len=%d value=", totlen - 4));
if (!rawprint(ndo, (const uint8_t *)&p[4], totlen - 4)) {
ND_PRINT((ndo,")"));
goto trunc;
}
}
ND_PRINT((ndo,")"));
return p + totlen;
trunc:
return NULL;
}
static const u_char *
ikev1_sa_print(netdissect_options *ndo, u_char tpay _U_,
const struct isakmp_gen *ext,
u_int item_len _U_,
const u_char *ep, uint32_t phase, uint32_t doi0 _U_,
uint32_t proto0, int depth)
{
const struct ikev1_pl_sa *p;
struct ikev1_pl_sa sa;
uint32_t doi, sit, ident;
const u_char *cp, *np;
int t;
ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_SA)));
p = (const struct ikev1_pl_sa *)ext;
ND_TCHECK(*p);
UNALIGNED_MEMCPY(&sa, ext, sizeof(sa));
doi = ntohl(sa.doi);
sit = ntohl(sa.sit);
if (doi != 1) {
ND_PRINT((ndo," doi=%d", doi));
ND_PRINT((ndo," situation=%u", (uint32_t)ntohl(sa.sit)));
return (const u_char *)(p + 1);
}
ND_PRINT((ndo," doi=ipsec"));
ND_PRINT((ndo," situation="));
t = 0;
if (sit & 0x01) {
ND_PRINT((ndo,"identity"));
t++;
}
if (sit & 0x02) {
ND_PRINT((ndo,"%ssecrecy", t ? "+" : ""));
t++;
}
if (sit & 0x04)
ND_PRINT((ndo,"%sintegrity", t ? "+" : ""));
np = (const u_char *)ext + sizeof(sa);
if (sit != 0x01) {
ND_TCHECK2(*(ext + 1), sizeof(ident));
UNALIGNED_MEMCPY(&ident, ext + 1, sizeof(ident));
ND_PRINT((ndo," ident=%u", (uint32_t)ntohl(ident)));
np += sizeof(ident);
}
ext = (const struct isakmp_gen *)np;
ND_TCHECK(*ext);
cp = ikev1_sub_print(ndo, ISAKMP_NPTYPE_P, ext, ep, phase, doi, proto0,
depth);
return cp;
trunc:
ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_SA)));
return NULL;
}
static const u_char *
ikev1_p_print(netdissect_options *ndo, u_char tpay _U_,
const struct isakmp_gen *ext, u_int item_len _U_,
const u_char *ep, uint32_t phase, uint32_t doi0,
uint32_t proto0 _U_, int depth)
{
const struct ikev1_pl_p *p;
struct ikev1_pl_p prop;
const u_char *cp;
ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_P)));
p = (const struct ikev1_pl_p *)ext;
ND_TCHECK(*p);
UNALIGNED_MEMCPY(&prop, ext, sizeof(prop));
ND_PRINT((ndo," #%d protoid=%s transform=%d",
prop.p_no, PROTOIDSTR(prop.prot_id), prop.num_t));
if (prop.spi_size) {
ND_PRINT((ndo," spi="));
if (!rawprint(ndo, (const uint8_t *)(p + 1), prop.spi_size))
goto trunc;
}
ext = (const struct isakmp_gen *)((const u_char *)(p + 1) + prop.spi_size);
ND_TCHECK(*ext);
cp = ikev1_sub_print(ndo, ISAKMP_NPTYPE_T, ext, ep, phase, doi0,
prop.prot_id, depth);
return cp;
trunc:
ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_P)));
return NULL;
}
static const char *ikev1_p_map[] = {
NULL, "ike",
};
static const char *ikev2_t_type_map[]={
NULL, "encr", "prf", "integ", "dh", "esn"
};
static const char *ah_p_map[] = {
NULL, "(reserved)", "md5", "sha", "1des",
"sha2-256", "sha2-384", "sha2-512",
};
static const char *prf_p_map[] = {
NULL, "hmac-md5", "hmac-sha", "hmac-tiger",
"aes128_xcbc"
};
static const char *integ_p_map[] = {
NULL, "hmac-md5", "hmac-sha", "dec-mac",
"kpdk-md5", "aes-xcbc"
};
static const char *esn_p_map[] = {
"no-esn", "esn"
};
static const char *dh_p_map[] = {
NULL, "modp768",
"modp1024", /* group 2 */
"EC2N 2^155", /* group 3 */
"EC2N 2^185", /* group 4 */
"modp1536", /* group 5 */
"iana-grp06", "iana-grp07", /* reserved */
"iana-grp08", "iana-grp09",
"iana-grp10", "iana-grp11",
"iana-grp12", "iana-grp13",
"modp2048", /* group 14 */
"modp3072", /* group 15 */
"modp4096", /* group 16 */
"modp6144", /* group 17 */
"modp8192", /* group 18 */
};
static const char *esp_p_map[] = {
NULL, "1des-iv64", "1des", "3des", "rc5", "idea", "cast",
"blowfish", "3idea", "1des-iv32", "rc4", "null", "aes"
};
static const char *ipcomp_p_map[] = {
NULL, "oui", "deflate", "lzs",
};
static const struct attrmap ipsec_t_map[] = {
{ NULL, 0, { NULL } },
{ "lifetype", 3, { NULL, "sec", "kb", }, },
{ "life", 0, { NULL } },
{ "group desc", 18, { NULL, "modp768",
"modp1024", /* group 2 */
"EC2N 2^155", /* group 3 */
"EC2N 2^185", /* group 4 */
"modp1536", /* group 5 */
"iana-grp06", "iana-grp07", /* reserved */
"iana-grp08", "iana-grp09",
"iana-grp10", "iana-grp11",
"iana-grp12", "iana-grp13",
"modp2048", /* group 14 */
"modp3072", /* group 15 */
"modp4096", /* group 16 */
"modp6144", /* group 17 */
"modp8192", /* group 18 */
}, },
{ "enc mode", 3, { NULL, "tunnel", "transport", }, },
{ "auth", 5, { NULL, "hmac-md5", "hmac-sha1", "1des-mac", "keyed", }, },
{ "keylen", 0, { NULL } },
{ "rounds", 0, { NULL } },
{ "dictsize", 0, { NULL } },
{ "privalg", 0, { NULL } },
};
static const struct attrmap encr_t_map[] = {
{ NULL, 0, { NULL } }, { NULL, 0, { NULL } }, /* 0, 1 */
{ NULL, 0, { NULL } }, { NULL, 0, { NULL } }, /* 2, 3 */
{ NULL, 0, { NULL } }, { NULL, 0, { NULL } }, /* 4, 5 */
{ NULL, 0, { NULL } }, { NULL, 0, { NULL } }, /* 6, 7 */
{ NULL, 0, { NULL } }, { NULL, 0, { NULL } }, /* 8, 9 */
{ NULL, 0, { NULL } }, { NULL, 0, { NULL } }, /* 10,11*/
{ NULL, 0, { NULL } }, { NULL, 0, { NULL } }, /* 12,13*/
{ "keylen", 14, { NULL }},
};
static const struct attrmap oakley_t_map[] = {
{ NULL, 0, { NULL } },
{ "enc", 8, { NULL, "1des", "idea", "blowfish", "rc5",
"3des", "cast", "aes", }, },
{ "hash", 7, { NULL, "md5", "sha1", "tiger",
"sha2-256", "sha2-384", "sha2-512", }, },
{ "auth", 6, { NULL, "preshared", "dss", "rsa sig", "rsa enc",
"rsa enc revised", }, },
{ "group desc", 18, { NULL, "modp768",
"modp1024", /* group 2 */
"EC2N 2^155", /* group 3 */
"EC2N 2^185", /* group 4 */
"modp1536", /* group 5 */
"iana-grp06", "iana-grp07", /* reserved */
"iana-grp08", "iana-grp09",
"iana-grp10", "iana-grp11",
"iana-grp12", "iana-grp13",
"modp2048", /* group 14 */
"modp3072", /* group 15 */
"modp4096", /* group 16 */
"modp6144", /* group 17 */
"modp8192", /* group 18 */
}, },
{ "group type", 4, { NULL, "MODP", "ECP", "EC2N", }, },
{ "group prime", 0, { NULL } },
{ "group gen1", 0, { NULL } },
{ "group gen2", 0, { NULL } },
{ "group curve A", 0, { NULL } },
{ "group curve B", 0, { NULL } },
{ "lifetype", 3, { NULL, "sec", "kb", }, },
{ "lifeduration", 0, { NULL } },
{ "prf", 0, { NULL } },
{ "keylen", 0, { NULL } },
{ "field", 0, { NULL } },
{ "order", 0, { NULL } },
};
static const u_char *
ikev1_t_print(netdissect_options *ndo, u_char tpay _U_,
const struct isakmp_gen *ext, u_int item_len,
const u_char *ep, uint32_t phase _U_, uint32_t doi _U_,
uint32_t proto, int depth _U_)
{
const struct ikev1_pl_t *p;
struct ikev1_pl_t t;
const u_char *cp;
const char *idstr;
const struct attrmap *map;
size_t nmap;
const u_char *ep2;
ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_T)));
p = (const struct ikev1_pl_t *)ext;
ND_TCHECK(*p);
UNALIGNED_MEMCPY(&t, ext, sizeof(t));
switch (proto) {
case 1:
idstr = STR_OR_ID(t.t_id, ikev1_p_map);
map = oakley_t_map;
nmap = sizeof(oakley_t_map)/sizeof(oakley_t_map[0]);
break;
case 2:
idstr = STR_OR_ID(t.t_id, ah_p_map);
map = ipsec_t_map;
nmap = sizeof(ipsec_t_map)/sizeof(ipsec_t_map[0]);
break;
case 3:
idstr = STR_OR_ID(t.t_id, esp_p_map);
map = ipsec_t_map;
nmap = sizeof(ipsec_t_map)/sizeof(ipsec_t_map[0]);
break;
case 4:
idstr = STR_OR_ID(t.t_id, ipcomp_p_map);
map = ipsec_t_map;
nmap = sizeof(ipsec_t_map)/sizeof(ipsec_t_map[0]);
break;
default:
idstr = NULL;
map = NULL;
nmap = 0;
break;
}
if (idstr)
ND_PRINT((ndo," #%d id=%s ", t.t_no, idstr));
else
ND_PRINT((ndo," #%d id=%d ", t.t_no, t.t_id));
cp = (const u_char *)(p + 1);
ep2 = (const u_char *)p + item_len;
while (cp < ep && cp < ep2) {
if (map && nmap)
cp = ikev1_attrmap_print(ndo, cp, ep2, map, nmap);
else
cp = ikev1_attr_print(ndo, cp, ep2);
if (cp == NULL)
goto trunc;
}
if (ep < ep2)
ND_PRINT((ndo,"..."));
return cp;
trunc:
ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_T)));
return NULL;
}
static const u_char *
ikev1_ke_print(netdissect_options *ndo, u_char tpay _U_,
const struct isakmp_gen *ext, u_int item_len _U_,
const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_,
uint32_t proto _U_, int depth _U_)
{
struct isakmp_gen e;
ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_KE)));
ND_TCHECK(*ext);
UNALIGNED_MEMCPY(&e, ext, sizeof(e));
ND_PRINT((ndo," key len=%d", ntohs(e.len) - 4));
if (2 < ndo->ndo_vflag && 4 < ntohs(e.len)) {
ND_PRINT((ndo," "));
if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4))
goto trunc;
}
return (const u_char *)ext + ntohs(e.len);
trunc:
ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_KE)));
return NULL;
}
static const u_char *
ikev1_id_print(netdissect_options *ndo, u_char tpay _U_,
const struct isakmp_gen *ext, u_int item_len,
const u_char *ep _U_, uint32_t phase, uint32_t doi _U_,
uint32_t proto _U_, int depth _U_)
{
#define USE_IPSECDOI_IN_PHASE1 1
const struct ikev1_pl_id *p;
struct ikev1_pl_id id;
static const char *idtypestr[] = {
"IPv4", "IPv4net", "IPv6", "IPv6net",
};
static const char *ipsecidtypestr[] = {
NULL, "IPv4", "FQDN", "user FQDN", "IPv4net", "IPv6",
"IPv6net", "IPv4range", "IPv6range", "ASN1 DN", "ASN1 GN",
"keyid",
};
int len;
const u_char *data;
ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_ID)));
p = (const struct ikev1_pl_id *)ext;
ND_TCHECK(*p);
UNALIGNED_MEMCPY(&id, ext, sizeof(id));
if (sizeof(*p) < item_len) {
data = (const u_char *)(p + 1);
len = item_len - sizeof(*p);
} else {
data = NULL;
len = 0;
}
#if 0 /*debug*/
ND_PRINT((ndo," [phase=%d doi=%d proto=%d]", phase, doi, proto));
#endif
switch (phase) {
#ifndef USE_IPSECDOI_IN_PHASE1
case 1:
#endif
default:
ND_PRINT((ndo," idtype=%s", STR_OR_ID(id.d.id_type, idtypestr)));
ND_PRINT((ndo," doi_data=%u",
(uint32_t)(ntohl(id.d.doi_data) & 0xffffff)));
break;
#ifdef USE_IPSECDOI_IN_PHASE1
case 1:
#endif
case 2:
{
const struct ipsecdoi_id *doi_p;
struct ipsecdoi_id doi_id;
const char *p_name;
doi_p = (const struct ipsecdoi_id *)ext;
ND_TCHECK(*doi_p);
UNALIGNED_MEMCPY(&doi_id, ext, sizeof(doi_id));
ND_PRINT((ndo," idtype=%s", STR_OR_ID(doi_id.type, ipsecidtypestr)));
/* A protocol ID of 0 DOES NOT mean IPPROTO_IP! */
if (!ndo->ndo_nflag && doi_id.proto_id && (p_name = netdb_protoname(doi_id.proto_id)) != NULL)
ND_PRINT((ndo," protoid=%s", p_name));
else
ND_PRINT((ndo," protoid=%u", doi_id.proto_id));
ND_PRINT((ndo," port=%d", ntohs(doi_id.port)));
if (!len)
break;
if (data == NULL)
goto trunc;
ND_TCHECK2(*data, len);
switch (doi_id.type) {
case IPSECDOI_ID_IPV4_ADDR:
if (len < 4)
ND_PRINT((ndo," len=%d [bad: < 4]", len));
else
ND_PRINT((ndo," len=%d %s", len, ipaddr_string(ndo, data)));
len = 0;
break;
case IPSECDOI_ID_FQDN:
case IPSECDOI_ID_USER_FQDN:
{
int i;
ND_PRINT((ndo," len=%d ", len));
for (i = 0; i < len; i++)
safeputchar(ndo, data[i]);
len = 0;
break;
}
case IPSECDOI_ID_IPV4_ADDR_SUBNET:
{
const u_char *mask;
if (len < 8)
ND_PRINT((ndo," len=%d [bad: < 8]", len));
else {
mask = data + sizeof(struct in_addr);
ND_PRINT((ndo," len=%d %s/%u.%u.%u.%u", len,
ipaddr_string(ndo, data),
mask[0], mask[1], mask[2], mask[3]));
}
len = 0;
break;
}
case IPSECDOI_ID_IPV6_ADDR:
if (len < 16)
ND_PRINT((ndo," len=%d [bad: < 16]", len));
else
ND_PRINT((ndo," len=%d %s", len, ip6addr_string(ndo, data)));
len = 0;
break;
case IPSECDOI_ID_IPV6_ADDR_SUBNET:
{
const u_char *mask;
if (len < 20)
ND_PRINT((ndo," len=%d [bad: < 20]", len));
else {
mask = (const u_char *)(data + sizeof(struct in6_addr));
/*XXX*/
ND_PRINT((ndo," len=%d %s/0x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x", len,
ip6addr_string(ndo, data),
mask[0], mask[1], mask[2], mask[3],
mask[4], mask[5], mask[6], mask[7],
mask[8], mask[9], mask[10], mask[11],
mask[12], mask[13], mask[14], mask[15]));
}
len = 0;
break;
}
case IPSECDOI_ID_IPV4_ADDR_RANGE:
if (len < 8)
ND_PRINT((ndo," len=%d [bad: < 8]", len));
else {
ND_PRINT((ndo," len=%d %s-%s", len,
ipaddr_string(ndo, data),
ipaddr_string(ndo, data + sizeof(struct in_addr))));
}
len = 0;
break;
case IPSECDOI_ID_IPV6_ADDR_RANGE:
if (len < 32)
ND_PRINT((ndo," len=%d [bad: < 32]", len));
else {
ND_PRINT((ndo," len=%d %s-%s", len,
ip6addr_string(ndo, data),
ip6addr_string(ndo, data + sizeof(struct in6_addr))));
}
len = 0;
break;
case IPSECDOI_ID_DER_ASN1_DN:
case IPSECDOI_ID_DER_ASN1_GN:
case IPSECDOI_ID_KEY_ID:
break;
}
break;
}
}
if (data && len) {
ND_PRINT((ndo," len=%d", len));
if (2 < ndo->ndo_vflag) {
ND_PRINT((ndo," "));
if (!rawprint(ndo, (const uint8_t *)data, len))
goto trunc;
}
}
return (const u_char *)ext + item_len;
trunc:
ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_ID)));
return NULL;
}
static const u_char *
ikev1_cert_print(netdissect_options *ndo, u_char tpay _U_,
const struct isakmp_gen *ext, u_int item_len,
const u_char *ep _U_, uint32_t phase _U_,
uint32_t doi0 _U_,
uint32_t proto0 _U_, int depth _U_)
{
const struct ikev1_pl_cert *p;
struct ikev1_pl_cert cert;
static const char *certstr[] = {
"none", "pkcs7", "pgp", "dns",
"x509sign", "x509ke", "kerberos", "crl",
"arl", "spki", "x509attr",
};
ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_CERT)));
p = (const struct ikev1_pl_cert *)ext;
ND_TCHECK(*p);
UNALIGNED_MEMCPY(&cert, ext, sizeof(cert));
ND_PRINT((ndo," len=%d", item_len - 4));
ND_PRINT((ndo," type=%s", STR_OR_ID((cert.encode), certstr)));
if (2 < ndo->ndo_vflag && 4 < item_len) {
ND_PRINT((ndo," "));
if (!rawprint(ndo, (const uint8_t *)(ext + 1), item_len - 4))
goto trunc;
}
return (const u_char *)ext + item_len;
trunc:
ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_CERT)));
return NULL;
}
static const u_char *
ikev1_cr_print(netdissect_options *ndo, u_char tpay _U_,
const struct isakmp_gen *ext, u_int item_len,
const u_char *ep _U_, uint32_t phase _U_, uint32_t doi0 _U_,
uint32_t proto0 _U_, int depth _U_)
{
const struct ikev1_pl_cert *p;
struct ikev1_pl_cert cert;
static const char *certstr[] = {
"none", "pkcs7", "pgp", "dns",
"x509sign", "x509ke", "kerberos", "crl",
"arl", "spki", "x509attr",
};
ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_CR)));
p = (const struct ikev1_pl_cert *)ext;
ND_TCHECK(*p);
UNALIGNED_MEMCPY(&cert, ext, sizeof(cert));
ND_PRINT((ndo," len=%d", item_len - 4));
ND_PRINT((ndo," type=%s", STR_OR_ID((cert.encode), certstr)));
if (2 < ndo->ndo_vflag && 4 < item_len) {
ND_PRINT((ndo," "));
if (!rawprint(ndo, (const uint8_t *)(ext + 1), item_len - 4))
goto trunc;
}
return (const u_char *)ext + item_len;
trunc:
ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_CR)));
return NULL;
}
static const u_char *
ikev1_hash_print(netdissect_options *ndo, u_char tpay _U_,
const struct isakmp_gen *ext, u_int item_len _U_,
const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_,
uint32_t proto _U_, int depth _U_)
{
struct isakmp_gen e;
ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_HASH)));
ND_TCHECK(*ext);
UNALIGNED_MEMCPY(&e, ext, sizeof(e));
ND_PRINT((ndo," len=%d", ntohs(e.len) - 4));
if (2 < ndo->ndo_vflag && 4 < ntohs(e.len)) {
ND_PRINT((ndo," "));
if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4))
goto trunc;
}
return (const u_char *)ext + ntohs(e.len);
trunc:
ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_HASH)));
return NULL;
}
static const u_char *
ikev1_sig_print(netdissect_options *ndo, u_char tpay _U_,
const struct isakmp_gen *ext, u_int item_len _U_,
const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_,
uint32_t proto _U_, int depth _U_)
{
struct isakmp_gen e;
ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_SIG)));
ND_TCHECK(*ext);
UNALIGNED_MEMCPY(&e, ext, sizeof(e));
ND_PRINT((ndo," len=%d", ntohs(e.len) - 4));
if (2 < ndo->ndo_vflag && 4 < ntohs(e.len)) {
ND_PRINT((ndo," "));
if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4))
goto trunc;
}
return (const u_char *)ext + ntohs(e.len);
trunc:
ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_SIG)));
return NULL;
}
static const u_char *
ikev1_nonce_print(netdissect_options *ndo, u_char tpay _U_,
const struct isakmp_gen *ext,
u_int item_len _U_,
const u_char *ep,
uint32_t phase _U_, uint32_t doi _U_,
uint32_t proto _U_, int depth _U_)
{
struct isakmp_gen e;
ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_NONCE)));
ND_TCHECK(*ext);
UNALIGNED_MEMCPY(&e, ext, sizeof(e));
/*
* Our caller has ensured that the length is >= 4.
*/
ND_PRINT((ndo," n len=%u", ntohs(e.len) - 4));
if (ntohs(e.len) > 4) {
if (ndo->ndo_vflag > 2) {
ND_PRINT((ndo, " "));
if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4))
goto trunc;
} else if (ndo->ndo_vflag > 1) {
ND_PRINT((ndo, " "));
if (!ike_show_somedata(ndo, (const u_char *)(ext + 1), ep))
goto trunc;
}
}
return (const u_char *)ext + ntohs(e.len);
trunc:
ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_NONCE)));
return NULL;
}
static const u_char *
ikev1_n_print(netdissect_options *ndo, u_char tpay _U_,
const struct isakmp_gen *ext, u_int item_len,
const u_char *ep, uint32_t phase _U_, uint32_t doi0 _U_,
uint32_t proto0 _U_, int depth _U_)
{
const struct ikev1_pl_n *p;
struct ikev1_pl_n n;
const u_char *cp;
const u_char *ep2;
uint32_t doi;
uint32_t proto;
static const char *notify_error_str[] = {
NULL, "INVALID-PAYLOAD-TYPE",
"DOI-NOT-SUPPORTED", "SITUATION-NOT-SUPPORTED",
"INVALID-COOKIE", "INVALID-MAJOR-VERSION",
"INVALID-MINOR-VERSION", "INVALID-EXCHANGE-TYPE",
"INVALID-FLAGS", "INVALID-MESSAGE-ID",
"INVALID-PROTOCOL-ID", "INVALID-SPI",
"INVALID-TRANSFORM-ID", "ATTRIBUTES-NOT-SUPPORTED",
"NO-PROPOSAL-CHOSEN", "BAD-PROPOSAL-SYNTAX",
"PAYLOAD-MALFORMED", "INVALID-KEY-INFORMATION",
"INVALID-ID-INFORMATION", "INVALID-CERT-ENCODING",
"INVALID-CERTIFICATE", "CERT-TYPE-UNSUPPORTED",
"INVALID-CERT-AUTHORITY", "INVALID-HASH-INFORMATION",
"AUTHENTICATION-FAILED", "INVALID-SIGNATURE",
"ADDRESS-NOTIFICATION", "NOTIFY-SA-LIFETIME",
"CERTIFICATE-UNAVAILABLE", "UNSUPPORTED-EXCHANGE-TYPE",
"UNEQUAL-PAYLOAD-LENGTHS",
};
static const char *ipsec_notify_error_str[] = {
"RESERVED",
};
static const char *notify_status_str[] = {
"CONNECTED",
};
static const char *ipsec_notify_status_str[] = {
"RESPONDER-LIFETIME", "REPLAY-STATUS",
"INITIAL-CONTACT",
};
/* NOTE: these macro must be called with x in proper range */
/* 0 - 8191 */
#define NOTIFY_ERROR_STR(x) \
STR_OR_ID((x), notify_error_str)
/* 8192 - 16383 */
#define IPSEC_NOTIFY_ERROR_STR(x) \
STR_OR_ID((u_int)((x) - 8192), ipsec_notify_error_str)
/* 16384 - 24575 */
#define NOTIFY_STATUS_STR(x) \
STR_OR_ID((u_int)((x) - 16384), notify_status_str)
/* 24576 - 32767 */
#define IPSEC_NOTIFY_STATUS_STR(x) \
STR_OR_ID((u_int)((x) - 24576), ipsec_notify_status_str)
ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_N)));
p = (const struct ikev1_pl_n *)ext;
ND_TCHECK(*p);
UNALIGNED_MEMCPY(&n, ext, sizeof(n));
doi = ntohl(n.doi);
proto = n.prot_id;
if (doi != 1) {
ND_PRINT((ndo," doi=%d", doi));
ND_PRINT((ndo," proto=%d", proto));
if (ntohs(n.type) < 8192)
ND_PRINT((ndo," type=%s", NOTIFY_ERROR_STR(ntohs(n.type))));
else if (ntohs(n.type) < 16384)
ND_PRINT((ndo," type=%s", numstr(ntohs(n.type))));
else if (ntohs(n.type) < 24576)
ND_PRINT((ndo," type=%s", NOTIFY_STATUS_STR(ntohs(n.type))));
else
ND_PRINT((ndo," type=%s", numstr(ntohs(n.type))));
if (n.spi_size) {
ND_PRINT((ndo," spi="));
if (!rawprint(ndo, (const uint8_t *)(p + 1), n.spi_size))
goto trunc;
}
return (const u_char *)(p + 1) + n.spi_size;
}
ND_PRINT((ndo," doi=ipsec"));
ND_PRINT((ndo," proto=%s", PROTOIDSTR(proto)));
if (ntohs(n.type) < 8192)
ND_PRINT((ndo," type=%s", NOTIFY_ERROR_STR(ntohs(n.type))));
else if (ntohs(n.type) < 16384)
ND_PRINT((ndo," type=%s", IPSEC_NOTIFY_ERROR_STR(ntohs(n.type))));
else if (ntohs(n.type) < 24576)
ND_PRINT((ndo," type=%s", NOTIFY_STATUS_STR(ntohs(n.type))));
else if (ntohs(n.type) < 32768)
ND_PRINT((ndo," type=%s", IPSEC_NOTIFY_STATUS_STR(ntohs(n.type))));
else
ND_PRINT((ndo," type=%s", numstr(ntohs(n.type))));
if (n.spi_size) {
ND_PRINT((ndo," spi="));
if (!rawprint(ndo, (const uint8_t *)(p + 1), n.spi_size))
goto trunc;
}
cp = (const u_char *)(p + 1) + n.spi_size;
ep2 = (const u_char *)p + item_len;
if (cp < ep) {
switch (ntohs(n.type)) {
case IPSECDOI_NTYPE_RESPONDER_LIFETIME:
{
const struct attrmap *map = oakley_t_map;
size_t nmap = sizeof(oakley_t_map)/sizeof(oakley_t_map[0]);
ND_PRINT((ndo," attrs=("));
while (cp < ep && cp < ep2) {
cp = ikev1_attrmap_print(ndo, cp, ep2, map, nmap);
if (cp == NULL) {
ND_PRINT((ndo,")"));
goto trunc;
}
}
ND_PRINT((ndo,")"));
break;
}
case IPSECDOI_NTYPE_REPLAY_STATUS:
ND_PRINT((ndo," status=("));
ND_PRINT((ndo,"replay detection %sabled",
EXTRACT_32BITS(cp) ? "en" : "dis"));
ND_PRINT((ndo,")"));
break;
default:
/*
* XXX - fill in more types here; see, for example,
* draft-ietf-ipsec-notifymsg-04.
*/
if (ndo->ndo_vflag > 3) {
ND_PRINT((ndo," data=("));
if (!rawprint(ndo, (const uint8_t *)(cp), ep - cp))
goto trunc;
ND_PRINT((ndo,")"));
} else {
if (!ike_show_somedata(ndo, cp, ep))
goto trunc;
}
break;
}
}
return (const u_char *)ext + item_len;
trunc:
ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_N)));
return NULL;
}
static const u_char *
ikev1_d_print(netdissect_options *ndo, u_char tpay _U_,
const struct isakmp_gen *ext, u_int item_len _U_,
const u_char *ep _U_, uint32_t phase _U_, uint32_t doi0 _U_,
uint32_t proto0 _U_, int depth _U_)
{
const struct ikev1_pl_d *p;
struct ikev1_pl_d d;
const uint8_t *q;
uint32_t doi;
uint32_t proto;
int i;
ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_D)));
p = (const struct ikev1_pl_d *)ext;
ND_TCHECK(*p);
UNALIGNED_MEMCPY(&d, ext, sizeof(d));
doi = ntohl(d.doi);
proto = d.prot_id;
if (doi != 1) {
ND_PRINT((ndo," doi=%u", doi));
ND_PRINT((ndo," proto=%u", proto));
} else {
ND_PRINT((ndo," doi=ipsec"));
ND_PRINT((ndo," proto=%s", PROTOIDSTR(proto)));
}
ND_PRINT((ndo," spilen=%u", d.spi_size));
ND_PRINT((ndo," nspi=%u", ntohs(d.num_spi)));
ND_PRINT((ndo," spi="));
q = (const uint8_t *)(p + 1);
for (i = 0; i < ntohs(d.num_spi); i++) {
if (i != 0)
ND_PRINT((ndo,","));
if (!rawprint(ndo, (const uint8_t *)q, d.spi_size))
goto trunc;
q += d.spi_size;
}
return q;
trunc:
ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_D)));
return NULL;
}
static const u_char *
ikev1_vid_print(netdissect_options *ndo, u_char tpay _U_,
const struct isakmp_gen *ext,
u_int item_len _U_, const u_char *ep _U_,
uint32_t phase _U_, uint32_t doi _U_,
uint32_t proto _U_, int depth _U_)
{
struct isakmp_gen e;
ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_VID)));
ND_TCHECK(*ext);
UNALIGNED_MEMCPY(&e, ext, sizeof(e));
ND_PRINT((ndo," len=%d", ntohs(e.len) - 4));
if (2 < ndo->ndo_vflag && 4 < ntohs(e.len)) {
ND_PRINT((ndo," "));
if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4))
goto trunc;
}
return (const u_char *)ext + ntohs(e.len);
trunc:
ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_VID)));
return NULL;
}
/************************************************************/
/* */
/* IKE v2 - rfc4306 - dissector */
/* */
/************************************************************/
static void
ikev2_pay_print(netdissect_options *ndo, const char *payname, int critical)
{
ND_PRINT((ndo,"%s%s:", payname, critical&0x80 ? "[C]" : ""));
}
static const u_char *
ikev2_gen_print(netdissect_options *ndo, u_char tpay,
const struct isakmp_gen *ext)
{
struct isakmp_gen e;
ND_TCHECK(*ext);
UNALIGNED_MEMCPY(&e, ext, sizeof(e));
ikev2_pay_print(ndo, NPSTR(tpay), e.critical);
ND_PRINT((ndo," len=%d", ntohs(e.len) - 4));
if (2 < ndo->ndo_vflag && 4 < ntohs(e.len)) {
ND_PRINT((ndo," "));
if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4))
goto trunc;
}
return (const u_char *)ext + ntohs(e.len);
trunc:
ND_PRINT((ndo," [|%s]", NPSTR(tpay)));
return NULL;
}
static const u_char *
ikev2_t_print(netdissect_options *ndo, int tcount,
const struct isakmp_gen *ext, u_int item_len,
const u_char *ep)
{
const struct ikev2_t *p;
struct ikev2_t t;
uint16_t t_id;
const u_char *cp;
const char *idstr;
const struct attrmap *map;
size_t nmap;
const u_char *ep2;
p = (const struct ikev2_t *)ext;
ND_TCHECK(*p);
UNALIGNED_MEMCPY(&t, ext, sizeof(t));
ikev2_pay_print(ndo, NPSTR(ISAKMP_NPTYPE_T), t.h.critical);
t_id = ntohs(t.t_id);
map = NULL;
nmap = 0;
switch (t.t_type) {
case IV2_T_ENCR:
idstr = STR_OR_ID(t_id, esp_p_map);
map = encr_t_map;
nmap = sizeof(encr_t_map)/sizeof(encr_t_map[0]);
break;
case IV2_T_PRF:
idstr = STR_OR_ID(t_id, prf_p_map);
break;
case IV2_T_INTEG:
idstr = STR_OR_ID(t_id, integ_p_map);
break;
case IV2_T_DH:
idstr = STR_OR_ID(t_id, dh_p_map);
break;
case IV2_T_ESN:
idstr = STR_OR_ID(t_id, esn_p_map);
break;
default:
idstr = NULL;
break;
}
if (idstr)
ND_PRINT((ndo," #%u type=%s id=%s ", tcount,
STR_OR_ID(t.t_type, ikev2_t_type_map),
idstr));
else
ND_PRINT((ndo," #%u type=%s id=%u ", tcount,
STR_OR_ID(t.t_type, ikev2_t_type_map),
t.t_id));
cp = (const u_char *)(p + 1);
ep2 = (const u_char *)p + item_len;
while (cp < ep && cp < ep2) {
if (map && nmap) {
cp = ikev1_attrmap_print(ndo, cp, ep2, map, nmap);
} else
cp = ikev1_attr_print(ndo, cp, ep2);
if (cp == NULL)
goto trunc;
}
if (ep < ep2)
ND_PRINT((ndo,"..."));
return cp;
trunc:
ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_T)));
return NULL;
}
static const u_char *
ikev2_p_print(netdissect_options *ndo, u_char tpay _U_, int pcount _U_,
const struct isakmp_gen *ext, u_int oprop_length,
const u_char *ep, int depth)
{
const struct ikev2_p *p;
struct ikev2_p prop;
u_int prop_length;
const u_char *cp;
int i;
int tcount;
u_char np;
struct isakmp_gen e;
u_int item_len;
p = (const struct ikev2_p *)ext;
ND_TCHECK(*p);
UNALIGNED_MEMCPY(&prop, ext, sizeof(prop));
ikev2_pay_print(ndo, NPSTR(ISAKMP_NPTYPE_P), prop.h.critical);
/*
* ikev2_sa_print() guarantees that this is >= 4.
*/
prop_length = oprop_length - 4;
ND_PRINT((ndo," #%u protoid=%s transform=%d len=%u",
prop.p_no, PROTOIDSTR(prop.prot_id),
prop.num_t, oprop_length));
cp = (const u_char *)(p + 1);
if (prop.spi_size) {
if (prop_length < prop.spi_size)
goto toolong;
ND_PRINT((ndo," spi="));
if (!rawprint(ndo, (const uint8_t *)cp, prop.spi_size))
goto trunc;
cp += prop.spi_size;
prop_length -= prop.spi_size;
}
/*
* Print the transforms.
*/
tcount = 0;
for (np = ISAKMP_NPTYPE_T; np != 0; np = e.np) {
tcount++;
ext = (const struct isakmp_gen *)cp;
if (prop_length < sizeof(*ext))
goto toolong;
ND_TCHECK(*ext);
UNALIGNED_MEMCPY(&e, ext, sizeof(e));
/*
* Since we can't have a payload length of less than 4 bytes,
* we need to bail out here if the generic header is nonsensical
* or truncated, otherwise we could loop forever processing
* zero-length items or otherwise misdissect the packet.
*/
item_len = ntohs(e.len);
if (item_len <= 4)
goto trunc;
if (prop_length < item_len)
goto toolong;
ND_TCHECK2(*cp, item_len);
depth++;
ND_PRINT((ndo,"\n"));
for (i = 0; i < depth; i++)
ND_PRINT((ndo," "));
ND_PRINT((ndo,"("));
if (np == ISAKMP_NPTYPE_T) {
cp = ikev2_t_print(ndo, tcount, ext, item_len, ep);
if (cp == NULL) {
/* error, already reported */
return NULL;
}
} else {
ND_PRINT((ndo, "%s", NPSTR(np)));
cp += item_len;
}
ND_PRINT((ndo,")"));
depth--;
prop_length -= item_len;
}
return cp;
toolong:
/*
* Skip the rest of the proposal.
*/
cp += prop_length;
ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_P)));
return cp;
trunc:
ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_P)));
return NULL;
}
static const u_char *
ikev2_sa_print(netdissect_options *ndo, u_char tpay,
const struct isakmp_gen *ext1,
u_int osa_length, const u_char *ep,
uint32_t phase _U_, uint32_t doi _U_,
uint32_t proto _U_, int depth)
{
const struct isakmp_gen *ext;
struct isakmp_gen e;
u_int sa_length;
const u_char *cp;
int i;
int pcount;
u_char np;
u_int item_len;
ND_TCHECK(*ext1);
UNALIGNED_MEMCPY(&e, ext1, sizeof(e));
ikev2_pay_print(ndo, "sa", e.critical);
/*
* ikev2_sub0_print() guarantees that this is >= 4.
*/
osa_length= ntohs(e.len);
sa_length = osa_length - 4;
ND_PRINT((ndo," len=%d", sa_length));
/*
* Print the payloads.
*/
cp = (const u_char *)(ext1 + 1);
pcount = 0;
for (np = ISAKMP_NPTYPE_P; np != 0; np = e.np) {
pcount++;
ext = (const struct isakmp_gen *)cp;
if (sa_length < sizeof(*ext))
goto toolong;
ND_TCHECK(*ext);
UNALIGNED_MEMCPY(&e, ext, sizeof(e));
/*
* Since we can't have a payload length of less than 4 bytes,
* we need to bail out here if the generic header is nonsensical
* or truncated, otherwise we could loop forever processing
* zero-length items or otherwise misdissect the packet.
*/
item_len = ntohs(e.len);
if (item_len <= 4)
goto trunc;
if (sa_length < item_len)
goto toolong;
ND_TCHECK2(*cp, item_len);
depth++;
ND_PRINT((ndo,"\n"));
for (i = 0; i < depth; i++)
ND_PRINT((ndo," "));
ND_PRINT((ndo,"("));
if (np == ISAKMP_NPTYPE_P) {
cp = ikev2_p_print(ndo, np, pcount, ext, item_len,
ep, depth);
if (cp == NULL) {
/* error, already reported */
return NULL;
}
} else {
ND_PRINT((ndo, "%s", NPSTR(np)));
cp += item_len;
}
ND_PRINT((ndo,")"));
depth--;
sa_length -= item_len;
}
return cp;
toolong:
/*
* Skip the rest of the SA.
*/
cp += sa_length;
ND_PRINT((ndo," [|%s]", NPSTR(tpay)));
return cp;
trunc:
ND_PRINT((ndo," [|%s]", NPSTR(tpay)));
return NULL;
}
static const u_char *
ikev2_ke_print(netdissect_options *ndo, u_char tpay,
const struct isakmp_gen *ext,
u_int item_len _U_, const u_char *ep _U_,
uint32_t phase _U_, uint32_t doi _U_,
uint32_t proto _U_, int depth _U_)
{
struct ikev2_ke ke;
const struct ikev2_ke *k;
k = (const struct ikev2_ke *)ext;
ND_TCHECK(*ext);
UNALIGNED_MEMCPY(&ke, ext, sizeof(ke));
ikev2_pay_print(ndo, NPSTR(tpay), ke.h.critical);
ND_PRINT((ndo," len=%u group=%s", ntohs(ke.h.len) - 8,
STR_OR_ID(ntohs(ke.ke_group), dh_p_map)));
if (2 < ndo->ndo_vflag && 8 < ntohs(ke.h.len)) {
ND_PRINT((ndo," "));
if (!rawprint(ndo, (const uint8_t *)(k + 1), ntohs(ke.h.len) - 8))
goto trunc;
}
return (const u_char *)ext + ntohs(ke.h.len);
trunc:
ND_PRINT((ndo," [|%s]", NPSTR(tpay)));
return NULL;
}
static const u_char *
ikev2_ID_print(netdissect_options *ndo, u_char tpay,
const struct isakmp_gen *ext,
u_int item_len _U_, const u_char *ep _U_,
uint32_t phase _U_, uint32_t doi _U_,
uint32_t proto _U_, int depth _U_)
{
struct ikev2_id id;
int id_len, idtype_len, i;
unsigned int dumpascii, dumphex;
const unsigned char *typedata;
ND_TCHECK(*ext);
UNALIGNED_MEMCPY(&id, ext, sizeof(id));
ikev2_pay_print(ndo, NPSTR(tpay), id.h.critical);
id_len = ntohs(id.h.len);
ND_PRINT((ndo," len=%d", id_len - 4));
if (2 < ndo->ndo_vflag && 4 < id_len) {
ND_PRINT((ndo," "));
if (!rawprint(ndo, (const uint8_t *)(ext + 1), id_len - 4))
goto trunc;
}
idtype_len =id_len - sizeof(struct ikev2_id);
dumpascii = 0;
dumphex = 0;
typedata = (const unsigned char *)(ext)+sizeof(struct ikev2_id);
switch(id.type) {
case ID_IPV4_ADDR:
ND_PRINT((ndo, " ipv4:"));
dumphex=1;
break;
case ID_FQDN:
ND_PRINT((ndo, " fqdn:"));
dumpascii=1;
break;
case ID_RFC822_ADDR:
ND_PRINT((ndo, " rfc822:"));
dumpascii=1;
break;
case ID_IPV6_ADDR:
ND_PRINT((ndo, " ipv6:"));
dumphex=1;
break;
case ID_DER_ASN1_DN:
ND_PRINT((ndo, " dn:"));
dumphex=1;
break;
case ID_DER_ASN1_GN:
ND_PRINT((ndo, " gn:"));
dumphex=1;
break;
case ID_KEY_ID:
ND_PRINT((ndo, " keyid:"));
dumphex=1;
break;
}
if(dumpascii) {
ND_TCHECK2(*typedata, idtype_len);
for(i=0; i<idtype_len; i++) {
if(ND_ISPRINT(typedata[i])) {
ND_PRINT((ndo, "%c", typedata[i]));
} else {
ND_PRINT((ndo, "."));
}
}
}
if(dumphex) {
if (!rawprint(ndo, (const uint8_t *)typedata, idtype_len))
goto trunc;
}
return (const u_char *)ext + id_len;
trunc:
ND_PRINT((ndo," [|%s]", NPSTR(tpay)));
return NULL;
}
static const u_char *
ikev2_cert_print(netdissect_options *ndo, u_char tpay,
const struct isakmp_gen *ext,
u_int item_len _U_, const u_char *ep _U_,
uint32_t phase _U_, uint32_t doi _U_,
uint32_t proto _U_, int depth _U_)
{
return ikev2_gen_print(ndo, tpay, ext);
}
static const u_char *
ikev2_cr_print(netdissect_options *ndo, u_char tpay,
const struct isakmp_gen *ext,
u_int item_len _U_, const u_char *ep _U_,
uint32_t phase _U_, uint32_t doi _U_,
uint32_t proto _U_, int depth _U_)
{
return ikev2_gen_print(ndo, tpay, ext);
}
static const u_char *
ikev2_auth_print(netdissect_options *ndo, u_char tpay,
const struct isakmp_gen *ext,
u_int item_len _U_, const u_char *ep,
uint32_t phase _U_, uint32_t doi _U_,
uint32_t proto _U_, int depth _U_)
{
struct ikev2_auth a;
const char *v2_auth[]={ "invalid", "rsasig",
"shared-secret", "dsssig" };
const u_char *authdata = (const u_char*)ext + sizeof(a);
unsigned int len;
ND_TCHECK(*ext);
UNALIGNED_MEMCPY(&a, ext, sizeof(a));
ikev2_pay_print(ndo, NPSTR(tpay), a.h.critical);
len = ntohs(a.h.len);
/*
* Our caller has ensured that the length is >= 4.
*/
ND_PRINT((ndo," len=%u method=%s", len-4,
STR_OR_ID(a.auth_method, v2_auth)));
if (len > 4) {
if (ndo->ndo_vflag > 1) {
ND_PRINT((ndo, " authdata=("));
if (!rawprint(ndo, (const uint8_t *)authdata, len - sizeof(a)))
goto trunc;
ND_PRINT((ndo, ") "));
} else if (ndo->ndo_vflag) {
if (!ike_show_somedata(ndo, authdata, ep))
goto trunc;
}
}
return (const u_char *)ext + len;
trunc:
ND_PRINT((ndo," [|%s]", NPSTR(tpay)));
return NULL;
}
static const u_char *
ikev2_nonce_print(netdissect_options *ndo, u_char tpay,
const struct isakmp_gen *ext,
u_int item_len _U_, const u_char *ep,
uint32_t phase _U_, uint32_t doi _U_,
uint32_t proto _U_, int depth _U_)
{
struct isakmp_gen e;
ND_TCHECK(*ext);
UNALIGNED_MEMCPY(&e, ext, sizeof(e));
ikev2_pay_print(ndo, "nonce", e.critical);
ND_PRINT((ndo," len=%d", ntohs(e.len) - 4));
if (1 < ndo->ndo_vflag && 4 < ntohs(e.len)) {
ND_PRINT((ndo," nonce=("));
if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4))
goto trunc;
ND_PRINT((ndo,") "));
} else if(ndo->ndo_vflag && 4 < ntohs(e.len)) {
if(!ike_show_somedata(ndo, (const u_char *)(ext+1), ep)) goto trunc;
}
return (const u_char *)ext + ntohs(e.len);
trunc:
ND_PRINT((ndo," [|%s]", NPSTR(tpay)));
return NULL;
}
/* notify payloads */
static const u_char *
ikev2_n_print(netdissect_options *ndo, u_char tpay _U_,
const struct isakmp_gen *ext,
u_int item_len, const u_char *ep,
uint32_t phase _U_, uint32_t doi _U_,
uint32_t proto _U_, int depth _U_)
{
const struct ikev2_n *p;
struct ikev2_n n;
const u_char *cp;
u_char showspi, showsomedata;
const char *notify_name;
uint32_t type;
p = (const struct ikev2_n *)ext;
ND_TCHECK(*p);
UNALIGNED_MEMCPY(&n, ext, sizeof(n));
ikev2_pay_print(ndo, NPSTR(ISAKMP_NPTYPE_N), n.h.critical);
showspi = 1;
showsomedata=0;
notify_name=NULL;
ND_PRINT((ndo," prot_id=%s", PROTOIDSTR(n.prot_id)));
type = ntohs(n.type);
/* notify space is annoying sparse */
switch(type) {
case IV2_NOTIFY_UNSUPPORTED_CRITICAL_PAYLOAD:
notify_name = "unsupported_critical_payload";
showspi = 0;
break;
case IV2_NOTIFY_INVALID_IKE_SPI:
notify_name = "invalid_ike_spi";
showspi = 1;
break;
case IV2_NOTIFY_INVALID_MAJOR_VERSION:
notify_name = "invalid_major_version";
showspi = 0;
break;
case IV2_NOTIFY_INVALID_SYNTAX:
notify_name = "invalid_syntax";
showspi = 1;
break;
case IV2_NOTIFY_INVALID_MESSAGE_ID:
notify_name = "invalid_message_id";
showspi = 1;
break;
case IV2_NOTIFY_INVALID_SPI:
notify_name = "invalid_spi";
showspi = 1;
break;
case IV2_NOTIFY_NO_PROPOSAL_CHOSEN:
notify_name = "no_protocol_chosen";
showspi = 1;
break;
case IV2_NOTIFY_INVALID_KE_PAYLOAD:
notify_name = "invalid_ke_payload";
showspi = 1;
break;
case IV2_NOTIFY_AUTHENTICATION_FAILED:
notify_name = "authentication_failed";
showspi = 1;
break;
case IV2_NOTIFY_SINGLE_PAIR_REQUIRED:
notify_name = "single_pair_required";
showspi = 1;
break;
case IV2_NOTIFY_NO_ADDITIONAL_SAS:
notify_name = "no_additional_sas";
showspi = 0;
break;
case IV2_NOTIFY_INTERNAL_ADDRESS_FAILURE:
notify_name = "internal_address_failure";
showspi = 0;
break;
case IV2_NOTIFY_FAILED_CP_REQUIRED:
notify_name = "failed:cp_required";
showspi = 0;
break;
case IV2_NOTIFY_INVALID_SELECTORS:
notify_name = "invalid_selectors";
showspi = 0;
break;
case IV2_NOTIFY_INITIAL_CONTACT:
notify_name = "initial_contact";
showspi = 0;
break;
case IV2_NOTIFY_SET_WINDOW_SIZE:
notify_name = "set_window_size";
showspi = 0;
break;
case IV2_NOTIFY_ADDITIONAL_TS_POSSIBLE:
notify_name = "additional_ts_possible";
showspi = 0;
break;
case IV2_NOTIFY_IPCOMP_SUPPORTED:
notify_name = "ipcomp_supported";
showspi = 0;
break;
case IV2_NOTIFY_NAT_DETECTION_SOURCE_IP:
notify_name = "nat_detection_source_ip";
showspi = 1;
break;
case IV2_NOTIFY_NAT_DETECTION_DESTINATION_IP:
notify_name = "nat_detection_destination_ip";
showspi = 1;
break;
case IV2_NOTIFY_COOKIE:
notify_name = "cookie";
showspi = 1;
showsomedata= 1;
break;
case IV2_NOTIFY_USE_TRANSPORT_MODE:
notify_name = "use_transport_mode";
showspi = 0;
break;
case IV2_NOTIFY_HTTP_CERT_LOOKUP_SUPPORTED:
notify_name = "http_cert_lookup_supported";
showspi = 0;
break;
case IV2_NOTIFY_REKEY_SA:
notify_name = "rekey_sa";
showspi = 1;
break;
case IV2_NOTIFY_ESP_TFC_PADDING_NOT_SUPPORTED:
notify_name = "tfc_padding_not_supported";
showspi = 0;
break;
case IV2_NOTIFY_NON_FIRST_FRAGMENTS_ALSO:
notify_name = "non_first_fragment_also";
showspi = 0;
break;
default:
if (type < 8192) {
notify_name="error";
} else if(type < 16384) {
notify_name="private-error";
} else if(type < 40960) {
notify_name="status";
} else {
notify_name="private-status";
}
}
if(notify_name) {
ND_PRINT((ndo," type=%u(%s)", type, notify_name));
}
if (showspi && n.spi_size) {
ND_PRINT((ndo," spi="));
if (!rawprint(ndo, (const uint8_t *)(p + 1), n.spi_size))
goto trunc;
}
cp = (const u_char *)(p + 1) + n.spi_size;
if (cp < ep) {
if (ndo->ndo_vflag > 3 || (showsomedata && ep-cp < 30)) {
ND_PRINT((ndo," data=("));
if (!rawprint(ndo, (const uint8_t *)(cp), ep - cp))
goto trunc;
ND_PRINT((ndo,")"));
} else if (showsomedata) {
if (!ike_show_somedata(ndo, cp, ep))
goto trunc;
}
}
return (const u_char *)ext + item_len;
trunc:
ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_N)));
return NULL;
}
static const u_char *
ikev2_d_print(netdissect_options *ndo, u_char tpay,
const struct isakmp_gen *ext,
u_int item_len _U_, const u_char *ep _U_,
uint32_t phase _U_, uint32_t doi _U_,
uint32_t proto _U_, int depth _U_)
{
return ikev2_gen_print(ndo, tpay, ext);
}
static const u_char *
ikev2_vid_print(netdissect_options *ndo, u_char tpay,
const struct isakmp_gen *ext,
u_int item_len _U_, const u_char *ep _U_,
uint32_t phase _U_, uint32_t doi _U_,
uint32_t proto _U_, int depth _U_)
{
struct isakmp_gen e;
const u_char *vid;
int i, len;
ND_TCHECK(*ext);
UNALIGNED_MEMCPY(&e, ext, sizeof(e));
ikev2_pay_print(ndo, NPSTR(tpay), e.critical);
ND_PRINT((ndo," len=%d vid=", ntohs(e.len) - 4));
vid = (const u_char *)(ext+1);
len = ntohs(e.len) - 4;
ND_TCHECK2(*vid, len);
for(i=0; i<len; i++) {
if(ND_ISPRINT(vid[i])) ND_PRINT((ndo, "%c", vid[i]));
else ND_PRINT((ndo, "."));
}
if (2 < ndo->ndo_vflag && 4 < len) {
ND_PRINT((ndo," "));
if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4))
goto trunc;
}
return (const u_char *)ext + ntohs(e.len);
trunc:
ND_PRINT((ndo," [|%s]", NPSTR(tpay)));
return NULL;
}
static const u_char *
ikev2_TS_print(netdissect_options *ndo, u_char tpay,
const struct isakmp_gen *ext,
u_int item_len _U_, const u_char *ep _U_,
uint32_t phase _U_, uint32_t doi _U_,
uint32_t proto _U_, int depth _U_)
{
return ikev2_gen_print(ndo, tpay, ext);
}
static const u_char *
ikev2_e_print(netdissect_options *ndo,
#ifndef HAVE_LIBCRYPTO
_U_
#endif
struct isakmp *base,
u_char tpay,
const struct isakmp_gen *ext,
u_int item_len _U_, const u_char *ep _U_,
#ifndef HAVE_LIBCRYPTO
_U_
#endif
uint32_t phase,
#ifndef HAVE_LIBCRYPTO
_U_
#endif
uint32_t doi,
#ifndef HAVE_LIBCRYPTO
_U_
#endif
uint32_t proto,
#ifndef HAVE_LIBCRYPTO
_U_
#endif
int depth)
{
struct isakmp_gen e;
const u_char *dat;
volatile int dlen;
ND_TCHECK(*ext);
UNALIGNED_MEMCPY(&e, ext, sizeof(e));
ikev2_pay_print(ndo, NPSTR(tpay), e.critical);
dlen = ntohs(e.len)-4;
ND_PRINT((ndo," len=%d", dlen));
if (2 < ndo->ndo_vflag && 4 < dlen) {
ND_PRINT((ndo," "));
if (!rawprint(ndo, (const uint8_t *)(ext + 1), dlen))
goto trunc;
}
dat = (const u_char *)(ext+1);
ND_TCHECK2(*dat, dlen);
#ifdef HAVE_LIBCRYPTO
/* try to decypt it! */
if(esp_print_decrypt_buffer_by_ikev2(ndo,
base->flags & ISAKMP_FLAG_I,
base->i_ck, base->r_ck,
dat, dat+dlen)) {
ext = (const struct isakmp_gen *)ndo->ndo_packetp;
/* got it decrypted, print stuff inside. */
ikev2_sub_print(ndo, base, e.np, ext, ndo->ndo_snapend,
phase, doi, proto, depth+1);
}
#endif
/* always return NULL, because E must be at end, and NP refers
* to what was inside.
*/
return NULL;
trunc:
ND_PRINT((ndo," [|%s]", NPSTR(tpay)));
return NULL;
}
static const u_char *
ikev2_cp_print(netdissect_options *ndo, u_char tpay,
const struct isakmp_gen *ext,
u_int item_len _U_, const u_char *ep _U_,
uint32_t phase _U_, uint32_t doi _U_,
uint32_t proto _U_, int depth _U_)
{
return ikev2_gen_print(ndo, tpay, ext);
}
static const u_char *
ikev2_eap_print(netdissect_options *ndo, u_char tpay,
const struct isakmp_gen *ext,
u_int item_len _U_, const u_char *ep _U_,
uint32_t phase _U_, uint32_t doi _U_,
uint32_t proto _U_, int depth _U_)
{
return ikev2_gen_print(ndo, tpay, ext);
}
static const u_char *
ike_sub0_print(netdissect_options *ndo,
u_char np, const struct isakmp_gen *ext, const u_char *ep,
uint32_t phase, uint32_t doi, uint32_t proto, int depth)
{
const u_char *cp;
struct isakmp_gen e;
u_int item_len;
cp = (const u_char *)ext;
ND_TCHECK(*ext);
UNALIGNED_MEMCPY(&e, ext, sizeof(e));
/*
* Since we can't have a payload length of less than 4 bytes,
* we need to bail out here if the generic header is nonsensical
* or truncated, otherwise we could loop forever processing
* zero-length items or otherwise misdissect the packet.
*/
item_len = ntohs(e.len);
if (item_len <= 4)
return NULL;
if (NPFUNC(np)) {
/*
* XXX - what if item_len is too short, or too long,
* for this payload type?
*/
cp = (*npfunc[np])(ndo, np, ext, item_len, ep, phase, doi, proto, depth);
} else {
ND_PRINT((ndo,"%s", NPSTR(np)));
cp += item_len;
}
return cp;
trunc:
ND_PRINT((ndo," [|isakmp]"));
return NULL;
}
static const u_char *
ikev1_sub_print(netdissect_options *ndo,
u_char np, const struct isakmp_gen *ext, const u_char *ep,
uint32_t phase, uint32_t doi, uint32_t proto, int depth)
{
const u_char *cp;
int i;
struct isakmp_gen e;
cp = (const u_char *)ext;
while (np) {
ND_TCHECK(*ext);
UNALIGNED_MEMCPY(&e, ext, sizeof(e));
ND_TCHECK2(*ext, ntohs(e.len));
depth++;
ND_PRINT((ndo,"\n"));
for (i = 0; i < depth; i++)
ND_PRINT((ndo," "));
ND_PRINT((ndo,"("));
cp = ike_sub0_print(ndo, np, ext, ep, phase, doi, proto, depth);
ND_PRINT((ndo,")"));
depth--;
if (cp == NULL) {
/* Zero-length subitem */
return NULL;
}
np = e.np;
ext = (const struct isakmp_gen *)cp;
}
return cp;
trunc:
ND_PRINT((ndo," [|%s]", NPSTR(np)));
return NULL;
}
static char *
numstr(int x)
{
static char buf[20];
snprintf(buf, sizeof(buf), "#%d", x);
return buf;
}
static void
ikev1_print(netdissect_options *ndo,
const u_char *bp, u_int length,
const u_char *bp2, struct isakmp *base)
{
const struct isakmp *p;
const u_char *ep;
u_char np;
int i;
int phase;
p = (const struct isakmp *)bp;
ep = ndo->ndo_snapend;
phase = (EXTRACT_32BITS(base->msgid) == 0) ? 1 : 2;
if (phase == 1)
ND_PRINT((ndo," phase %d", phase));
else
ND_PRINT((ndo," phase %d/others", phase));
i = cookie_find(&base->i_ck);
if (i < 0) {
if (iszero((const u_char *)&base->r_ck, sizeof(base->r_ck))) {
/* the first packet */
ND_PRINT((ndo," I"));
if (bp2)
cookie_record(&base->i_ck, bp2);
} else
ND_PRINT((ndo," ?"));
} else {
if (bp2 && cookie_isinitiator(i, bp2))
ND_PRINT((ndo," I"));
else if (bp2 && cookie_isresponder(i, bp2))
ND_PRINT((ndo," R"));
else
ND_PRINT((ndo," ?"));
}
ND_PRINT((ndo," %s", ETYPESTR(base->etype)));
if (base->flags) {
ND_PRINT((ndo,"[%s%s]", base->flags & ISAKMP_FLAG_E ? "E" : "",
base->flags & ISAKMP_FLAG_C ? "C" : ""));
}
if (ndo->ndo_vflag) {
const struct isakmp_gen *ext;
ND_PRINT((ndo,":"));
/* regardless of phase... */
if (base->flags & ISAKMP_FLAG_E) {
/*
* encrypted, nothing we can do right now.
* we hope to decrypt the packet in the future...
*/
ND_PRINT((ndo," [encrypted %s]", NPSTR(base->np)));
goto done;
}
CHECKLEN(p + 1, base->np);
np = base->np;
ext = (const struct isakmp_gen *)(p + 1);
ikev1_sub_print(ndo, np, ext, ep, phase, 0, 0, 0);
}
done:
if (ndo->ndo_vflag) {
if (ntohl(base->len) != length) {
ND_PRINT((ndo," (len mismatch: isakmp %u/ip %u)",
(uint32_t)ntohl(base->len), length));
}
}
}
static const u_char *
ikev2_sub0_print(netdissect_options *ndo, struct isakmp *base,
u_char np,
const struct isakmp_gen *ext, const u_char *ep,
uint32_t phase, uint32_t doi, uint32_t proto, int depth)
{
const u_char *cp;
struct isakmp_gen e;
u_int item_len;
cp = (const u_char *)ext;
ND_TCHECK(*ext);
UNALIGNED_MEMCPY(&e, ext, sizeof(e));
/*
* Since we can't have a payload length of less than 4 bytes,
* we need to bail out here if the generic header is nonsensical
* or truncated, otherwise we could loop forever processing
* zero-length items or otherwise misdissect the packet.
*/
item_len = ntohs(e.len);
if (item_len <= 4)
return NULL;
if (np == ISAKMP_NPTYPE_v2E) {
cp = ikev2_e_print(ndo, base, np, ext, item_len,
ep, phase, doi, proto, depth);
} else if (NPFUNC(np)) {
/*
* XXX - what if item_len is too short, or too long,
* for this payload type?
*/
cp = (*npfunc[np])(ndo, np, ext, item_len,
ep, phase, doi, proto, depth);
} else {
ND_PRINT((ndo,"%s", NPSTR(np)));
cp += item_len;
}
return cp;
trunc:
ND_PRINT((ndo," [|isakmp]"));
return NULL;
}
static const u_char *
ikev2_sub_print(netdissect_options *ndo,
struct isakmp *base,
u_char np, const struct isakmp_gen *ext, const u_char *ep,
uint32_t phase, uint32_t doi, uint32_t proto, int depth)
{
const u_char *cp;
int i;
struct isakmp_gen e;
cp = (const u_char *)ext;
while (np) {
ND_TCHECK(*ext);
UNALIGNED_MEMCPY(&e, ext, sizeof(e));
ND_TCHECK2(*ext, ntohs(e.len));
depth++;
ND_PRINT((ndo,"\n"));
for (i = 0; i < depth; i++)
ND_PRINT((ndo," "));
ND_PRINT((ndo,"("));
cp = ikev2_sub0_print(ndo, base, np,
ext, ep, phase, doi, proto, depth);
ND_PRINT((ndo,")"));
depth--;
if (cp == NULL) {
/* Zero-length subitem */
return NULL;
}
np = e.np;
ext = (const struct isakmp_gen *)cp;
}
return cp;
trunc:
ND_PRINT((ndo," [|%s]", NPSTR(np)));
return NULL;
}
static void
ikev2_print(netdissect_options *ndo,
const u_char *bp, u_int length,
const u_char *bp2 _U_, struct isakmp *base)
{
const struct isakmp *p;
const u_char *ep;
u_char np;
int phase;
p = (const struct isakmp *)bp;
ep = ndo->ndo_snapend;
phase = (EXTRACT_32BITS(base->msgid) == 0) ? 1 : 2;
if (phase == 1)
ND_PRINT((ndo, " parent_sa"));
else
ND_PRINT((ndo, " child_sa "));
ND_PRINT((ndo, " %s", ETYPESTR(base->etype)));
if (base->flags) {
ND_PRINT((ndo, "[%s%s%s]",
base->flags & ISAKMP_FLAG_I ? "I" : "",
base->flags & ISAKMP_FLAG_V ? "V" : "",
base->flags & ISAKMP_FLAG_R ? "R" : ""));
}
if (ndo->ndo_vflag) {
const struct isakmp_gen *ext;
ND_PRINT((ndo, ":"));
/* regardless of phase... */
if (base->flags & ISAKMP_FLAG_E) {
/*
* encrypted, nothing we can do right now.
* we hope to decrypt the packet in the future...
*/
ND_PRINT((ndo, " [encrypted %s]", NPSTR(base->np)));
goto done;
}
CHECKLEN(p + 1, base->np)
np = base->np;
ext = (const struct isakmp_gen *)(p + 1);
ikev2_sub_print(ndo, base, np, ext, ep, phase, 0, 0, 0);
}
done:
if (ndo->ndo_vflag) {
if (ntohl(base->len) != length) {
ND_PRINT((ndo, " (len mismatch: isakmp %u/ip %u)",
(uint32_t)ntohl(base->len), length));
}
}
}
void
isakmp_print(netdissect_options *ndo,
const u_char *bp, u_int length,
const u_char *bp2)
{
const struct isakmp *p;
struct isakmp base;
const u_char *ep;
int major, minor;
#ifdef HAVE_LIBCRYPTO
/* initialize SAs */
if (ndo->ndo_sa_list_head == NULL) {
if (ndo->ndo_espsecret)
esp_print_decodesecret(ndo);
}
#endif
p = (const struct isakmp *)bp;
ep = ndo->ndo_snapend;
if ((const struct isakmp *)ep < p + 1) {
ND_PRINT((ndo,"[|isakmp]"));
return;
}
UNALIGNED_MEMCPY(&base, p, sizeof(base));
ND_PRINT((ndo,"isakmp"));
major = (base.vers & ISAKMP_VERS_MAJOR)
>> ISAKMP_VERS_MAJOR_SHIFT;
minor = (base.vers & ISAKMP_VERS_MINOR)
>> ISAKMP_VERS_MINOR_SHIFT;
if (ndo->ndo_vflag) {
ND_PRINT((ndo," %d.%d", major, minor));
}
if (ndo->ndo_vflag) {
ND_PRINT((ndo," msgid "));
hexprint(ndo, (const uint8_t *)&base.msgid, sizeof(base.msgid));
}
if (1 < ndo->ndo_vflag) {
ND_PRINT((ndo," cookie "));
hexprint(ndo, (const uint8_t *)&base.i_ck, sizeof(base.i_ck));
ND_PRINT((ndo,"->"));
hexprint(ndo, (const uint8_t *)&base.r_ck, sizeof(base.r_ck));
}
ND_PRINT((ndo,":"));
switch(major) {
case IKEv1_MAJOR_VERSION:
ikev1_print(ndo, bp, length, bp2, &base);
break;
case IKEv2_MAJOR_VERSION:
ikev2_print(ndo, bp, length, bp2, &base);
break;
}
}
void
isakmp_rfc3948_print(netdissect_options *ndo,
const u_char *bp, u_int length,
const u_char *bp2)
{
ND_TCHECK(bp[0]);
if(length == 1 && bp[0]==0xff) {
ND_PRINT((ndo, "isakmp-nat-keep-alive"));
return;
}
if(length < 4) {
goto trunc;
}
ND_TCHECK(bp[3]);
/*
* see if this is an IKE packet
*/
if(bp[0]==0 && bp[1]==0 && bp[2]==0 && bp[3]==0) {
ND_PRINT((ndo, "NONESP-encap: "));
isakmp_print(ndo, bp+4, length-4, bp2);
return;
}
/* must be an ESP packet */
{
int nh, enh, padlen;
int advance;
ND_PRINT((ndo, "UDP-encap: "));
advance = esp_print(ndo, bp, length, bp2, &enh, &padlen);
if(advance <= 0)
return;
bp += advance;
length -= advance + padlen;
nh = enh & 0xff;
ip_print_inner(ndo, bp, length, nh, bp2);
return;
}
trunc:
ND_PRINT((ndo,"[|isakmp]"));
return;
}
/*
* Local Variables:
* c-style: whitesmith
* c-basic-offset: 8
* End:
*/
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_2748_0 |
crossvul-cpp_data_bad_3952_0 | /**
* FreeRDP: A Remote Desktop Protocol Implementation
* Drawing Orders
*
* Copyright 2011 Marc-Andre Moreau <marcandre.moreau@gmail.com>
* Copyright 2016 Armin Novak <armin.novak@thincast.com>
* Copyright 2016 Thincast Technologies GmbH
*
* 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 HAVE_CONFIG_H
#include "config.h"
#endif
#include "window.h"
#include <winpr/wtypes.h>
#include <winpr/crt.h>
#include <freerdp/api.h>
#include <freerdp/log.h>
#include <freerdp/graphics.h>
#include <freerdp/codec/bitmap.h>
#include <freerdp/gdi/gdi.h>
#include "orders.h"
#include "../cache/glyph.h"
#include "../cache/bitmap.h"
#include "../cache/brush.h"
#include "../cache/cache.h"
#define TAG FREERDP_TAG("core.orders")
BYTE get_primary_drawing_order_field_bytes(UINT32 orderType, BOOL* pValid)
{
if (pValid)
*pValid = TRUE;
switch (orderType)
{
case 0:
return DSTBLT_ORDER_FIELD_BYTES;
case 1:
return PATBLT_ORDER_FIELD_BYTES;
case 2:
return SCRBLT_ORDER_FIELD_BYTES;
case 3:
return 0;
case 4:
return 0;
case 5:
return 0;
case 6:
return 0;
case 7:
return DRAW_NINE_GRID_ORDER_FIELD_BYTES;
case 8:
return MULTI_DRAW_NINE_GRID_ORDER_FIELD_BYTES;
case 9:
return LINE_TO_ORDER_FIELD_BYTES;
case 10:
return OPAQUE_RECT_ORDER_FIELD_BYTES;
case 11:
return SAVE_BITMAP_ORDER_FIELD_BYTES;
case 12:
return 0;
case 13:
return MEMBLT_ORDER_FIELD_BYTES;
case 14:
return MEM3BLT_ORDER_FIELD_BYTES;
case 15:
return MULTI_DSTBLT_ORDER_FIELD_BYTES;
case 16:
return MULTI_PATBLT_ORDER_FIELD_BYTES;
case 17:
return MULTI_SCRBLT_ORDER_FIELD_BYTES;
case 18:
return MULTI_OPAQUE_RECT_ORDER_FIELD_BYTES;
case 19:
return FAST_INDEX_ORDER_FIELD_BYTES;
case 20:
return POLYGON_SC_ORDER_FIELD_BYTES;
case 21:
return POLYGON_CB_ORDER_FIELD_BYTES;
case 22:
return POLYLINE_ORDER_FIELD_BYTES;
case 23:
return 0;
case 24:
return FAST_GLYPH_ORDER_FIELD_BYTES;
case 25:
return ELLIPSE_SC_ORDER_FIELD_BYTES;
case 26:
return ELLIPSE_CB_ORDER_FIELD_BYTES;
case 27:
return GLYPH_INDEX_ORDER_FIELD_BYTES;
default:
if (pValid)
*pValid = FALSE;
WLog_WARN(TAG, "Invalid orderType 0x%08X received", orderType);
return 0;
}
}
static const BYTE CBR2_BPP[] = { 0, 0, 0, 8, 16, 24, 32 };
static const BYTE BPP_CBR2[] = { 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0,
0, 0, 0, 0, 5, 0, 0, 0, 0, 0, 0, 0, 6, 0, 0, 0, 0, 0, 0, 0 };
static const BYTE CBR23_BPP[] = { 0, 0, 0, 8, 16, 24, 32 };
static const BYTE BPP_CBR23[] = { 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0,
0, 0, 0, 0, 5, 0, 0, 0, 0, 0, 0, 0, 6, 0, 0, 0, 0, 0, 0, 0 };
static const BYTE BMF_BPP[] = { 0, 1, 0, 8, 16, 24, 32, 0 };
static const BYTE BPP_BMF[] = { 0, 1, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0,
0, 0, 0, 0, 5, 0, 0, 0, 0, 0, 0, 0, 6, 0, 0, 0, 0, 0, 0, 0 };
static BOOL check_order_activated(wLog* log, rdpSettings* settings, const char* orderName,
BOOL condition)
{
if (!condition)
{
if (settings->AllowUnanouncedOrdersFromServer)
{
WLog_Print(log, WLOG_WARN,
"%s - SERVER BUG: The support for this feature was not announced!",
orderName);
return TRUE;
}
else
{
WLog_Print(log, WLOG_ERROR,
"%s - SERVER BUG: The support for this feature was not announced! Use "
"/relax-order-checks to ignore",
orderName);
return FALSE;
}
}
return TRUE;
}
static BOOL check_alt_order_supported(wLog* log, rdpSettings* settings, BYTE orderType,
const char* orderName)
{
BOOL condition = FALSE;
switch (orderType)
{
case ORDER_TYPE_CREATE_OFFSCREEN_BITMAP:
case ORDER_TYPE_SWITCH_SURFACE:
condition = settings->OffscreenSupportLevel != 0;
break;
case ORDER_TYPE_CREATE_NINE_GRID_BITMAP:
condition = settings->DrawNineGridEnabled;
break;
case ORDER_TYPE_FRAME_MARKER:
condition = settings->FrameMarkerCommandEnabled;
break;
case ORDER_TYPE_GDIPLUS_FIRST:
case ORDER_TYPE_GDIPLUS_NEXT:
case ORDER_TYPE_GDIPLUS_END:
case ORDER_TYPE_GDIPLUS_CACHE_FIRST:
case ORDER_TYPE_GDIPLUS_CACHE_NEXT:
case ORDER_TYPE_GDIPLUS_CACHE_END:
condition = settings->DrawGdiPlusCacheEnabled;
break;
case ORDER_TYPE_WINDOW:
condition = settings->RemoteWndSupportLevel != WINDOW_LEVEL_NOT_SUPPORTED;
break;
case ORDER_TYPE_STREAM_BITMAP_FIRST:
case ORDER_TYPE_STREAM_BITMAP_NEXT:
case ORDER_TYPE_COMPDESK_FIRST:
condition = TRUE;
break;
default:
WLog_Print(log, WLOG_WARN, "%s - Alternate Secondary Drawing Order UNKNOWN", orderName);
condition = FALSE;
break;
}
return check_order_activated(log, settings, orderName, condition);
}
static BOOL check_secondary_order_supported(wLog* log, rdpSettings* settings, BYTE orderType,
const char* orderName)
{
BOOL condition = FALSE;
switch (orderType)
{
case ORDER_TYPE_BITMAP_UNCOMPRESSED:
case ORDER_TYPE_CACHE_BITMAP_COMPRESSED:
condition = settings->BitmapCacheEnabled;
break;
case ORDER_TYPE_BITMAP_UNCOMPRESSED_V2:
case ORDER_TYPE_BITMAP_COMPRESSED_V2:
condition = settings->BitmapCacheEnabled;
break;
case ORDER_TYPE_BITMAP_COMPRESSED_V3:
condition = settings->BitmapCacheV3Enabled;
break;
case ORDER_TYPE_CACHE_COLOR_TABLE:
condition = (settings->OrderSupport[NEG_MEMBLT_INDEX] ||
settings->OrderSupport[NEG_MEM3BLT_INDEX]);
break;
case ORDER_TYPE_CACHE_GLYPH:
{
switch (settings->GlyphSupportLevel)
{
case GLYPH_SUPPORT_PARTIAL:
case GLYPH_SUPPORT_FULL:
case GLYPH_SUPPORT_ENCODE:
condition = TRUE;
break;
case GLYPH_SUPPORT_NONE:
default:
condition = FALSE;
break;
}
}
break;
case ORDER_TYPE_CACHE_BRUSH:
condition = TRUE;
break;
default:
WLog_Print(log, WLOG_WARN, "SECONDARY ORDER %s not supported", orderName);
break;
}
return check_order_activated(log, settings, orderName, condition);
}
static BOOL check_primary_order_supported(wLog* log, rdpSettings* settings, UINT32 orderType,
const char* orderName)
{
BOOL condition = FALSE;
switch (orderType)
{
case ORDER_TYPE_DSTBLT:
condition = settings->OrderSupport[NEG_DSTBLT_INDEX];
break;
case ORDER_TYPE_SCRBLT:
condition = settings->OrderSupport[NEG_SCRBLT_INDEX];
break;
case ORDER_TYPE_DRAW_NINE_GRID:
condition = settings->OrderSupport[NEG_DRAWNINEGRID_INDEX];
break;
case ORDER_TYPE_MULTI_DRAW_NINE_GRID:
condition = settings->OrderSupport[NEG_MULTI_DRAWNINEGRID_INDEX];
break;
case ORDER_TYPE_LINE_TO:
condition = settings->OrderSupport[NEG_LINETO_INDEX];
break;
/* [MS-RDPEGDI] 2.2.2.2.1.1.2.5 OpaqueRect (OPAQUERECT_ORDER)
* suggests that PatBlt and OpaqueRect imply each other. */
case ORDER_TYPE_PATBLT:
case ORDER_TYPE_OPAQUE_RECT:
condition = settings->OrderSupport[NEG_OPAQUE_RECT_INDEX] ||
settings->OrderSupport[NEG_PATBLT_INDEX];
break;
case ORDER_TYPE_SAVE_BITMAP:
condition = settings->OrderSupport[NEG_SAVEBITMAP_INDEX];
break;
case ORDER_TYPE_MEMBLT:
condition = settings->OrderSupport[NEG_MEMBLT_INDEX];
break;
case ORDER_TYPE_MEM3BLT:
condition = settings->OrderSupport[NEG_MEM3BLT_INDEX];
break;
case ORDER_TYPE_MULTI_DSTBLT:
condition = settings->OrderSupport[NEG_MULTIDSTBLT_INDEX];
break;
case ORDER_TYPE_MULTI_PATBLT:
condition = settings->OrderSupport[NEG_MULTIPATBLT_INDEX];
break;
case ORDER_TYPE_MULTI_SCRBLT:
condition = settings->OrderSupport[NEG_MULTIDSTBLT_INDEX];
break;
case ORDER_TYPE_MULTI_OPAQUE_RECT:
condition = settings->OrderSupport[NEG_MULTIOPAQUERECT_INDEX];
break;
case ORDER_TYPE_FAST_INDEX:
condition = settings->OrderSupport[NEG_FAST_INDEX_INDEX];
break;
case ORDER_TYPE_POLYGON_SC:
condition = settings->OrderSupport[NEG_POLYGON_SC_INDEX];
break;
case ORDER_TYPE_POLYGON_CB:
condition = settings->OrderSupport[NEG_POLYGON_CB_INDEX];
break;
case ORDER_TYPE_POLYLINE:
condition = settings->OrderSupport[NEG_POLYLINE_INDEX];
break;
case ORDER_TYPE_FAST_GLYPH:
condition = settings->OrderSupport[NEG_FAST_GLYPH_INDEX];
break;
case ORDER_TYPE_ELLIPSE_SC:
condition = settings->OrderSupport[NEG_ELLIPSE_SC_INDEX];
break;
case ORDER_TYPE_ELLIPSE_CB:
condition = settings->OrderSupport[NEG_ELLIPSE_CB_INDEX];
break;
case ORDER_TYPE_GLYPH_INDEX:
condition = settings->OrderSupport[NEG_GLYPH_INDEX_INDEX];
break;
default:
WLog_Print(log, WLOG_WARN, "%s Primary Drawing Order not supported", orderName);
break;
}
return check_order_activated(log, settings, orderName, condition);
}
static const char* primary_order_string(UINT32 orderType)
{
const char* orders[] = { "[0x%02" PRIx8 "] DstBlt",
"[0x%02" PRIx8 "] PatBlt",
"[0x%02" PRIx8 "] ScrBlt",
"[0x%02" PRIx8 "] UNUSED",
"[0x%02" PRIx8 "] UNUSED",
"[0x%02" PRIx8 "] UNUSED",
"[0x%02" PRIx8 "] UNUSED",
"[0x%02" PRIx8 "] DrawNineGrid",
"[0x%02" PRIx8 "] MultiDrawNineGrid",
"[0x%02" PRIx8 "] LineTo",
"[0x%02" PRIx8 "] OpaqueRect",
"[0x%02" PRIx8 "] SaveBitmap",
"[0x%02" PRIx8 "] UNUSED",
"[0x%02" PRIx8 "] MemBlt",
"[0x%02" PRIx8 "] Mem3Blt",
"[0x%02" PRIx8 "] MultiDstBlt",
"[0x%02" PRIx8 "] MultiPatBlt",
"[0x%02" PRIx8 "] MultiScrBlt",
"[0x%02" PRIx8 "] MultiOpaqueRect",
"[0x%02" PRIx8 "] FastIndex",
"[0x%02" PRIx8 "] PolygonSC",
"[0x%02" PRIx8 "] PolygonCB",
"[0x%02" PRIx8 "] Polyline",
"[0x%02" PRIx8 "] UNUSED",
"[0x%02" PRIx8 "] FastGlyph",
"[0x%02" PRIx8 "] EllipseSC",
"[0x%02" PRIx8 "] EllipseCB",
"[0x%02" PRIx8 "] GlyphIndex" };
const char* fmt = "[0x%02" PRIx8 "] UNKNOWN";
static char buffer[64] = { 0 };
if (orderType < ARRAYSIZE(orders))
fmt = orders[orderType];
sprintf_s(buffer, ARRAYSIZE(buffer), fmt, orderType);
return buffer;
}
static const char* secondary_order_string(UINT32 orderType)
{
const char* orders[] = { "[0x%02" PRIx8 "] Cache Bitmap",
"[0x%02" PRIx8 "] Cache Color Table",
"[0x%02" PRIx8 "] Cache Bitmap (Compressed)",
"[0x%02" PRIx8 "] Cache Glyph",
"[0x%02" PRIx8 "] Cache Bitmap V2",
"[0x%02" PRIx8 "] Cache Bitmap V2 (Compressed)",
"[0x%02" PRIx8 "] UNUSED",
"[0x%02" PRIx8 "] Cache Brush",
"[0x%02" PRIx8 "] Cache Bitmap V3" };
const char* fmt = "[0x%02" PRIx8 "] UNKNOWN";
static char buffer[64] = { 0 };
if (orderType < ARRAYSIZE(orders))
fmt = orders[orderType];
sprintf_s(buffer, ARRAYSIZE(buffer), fmt, orderType);
return buffer;
}
static const char* altsec_order_string(BYTE orderType)
{
const char* orders[] = {
"[0x%02" PRIx8 "] Switch Surface", "[0x%02" PRIx8 "] Create Offscreen Bitmap",
"[0x%02" PRIx8 "] Stream Bitmap First", "[0x%02" PRIx8 "] Stream Bitmap Next",
"[0x%02" PRIx8 "] Create NineGrid Bitmap", "[0x%02" PRIx8 "] Draw GDI+ First",
"[0x%02" PRIx8 "] Draw GDI+ Next", "[0x%02" PRIx8 "] Draw GDI+ End",
"[0x%02" PRIx8 "] Draw GDI+ Cache First", "[0x%02" PRIx8 "] Draw GDI+ Cache Next",
"[0x%02" PRIx8 "] Draw GDI+ Cache End", "[0x%02" PRIx8 "] Windowing",
"[0x%02" PRIx8 "] Desktop Composition", "[0x%02" PRIx8 "] Frame Marker"
};
const char* fmt = "[0x%02" PRIx8 "] UNKNOWN";
static char buffer[64] = { 0 };
if (orderType < ARRAYSIZE(orders))
fmt = orders[orderType];
sprintf_s(buffer, ARRAYSIZE(buffer), fmt, orderType);
return buffer;
}
static INLINE BOOL update_read_coord(wStream* s, INT32* coord, BOOL delta)
{
INT8 lsi8;
INT16 lsi16;
if (delta)
{
if (Stream_GetRemainingLength(s) < 1)
return FALSE;
Stream_Read_INT8(s, lsi8);
*coord += lsi8;
}
else
{
if (Stream_GetRemainingLength(s) < 2)
return FALSE;
Stream_Read_INT16(s, lsi16);
*coord = lsi16;
}
return TRUE;
}
static INLINE BOOL update_write_coord(wStream* s, INT32 coord)
{
Stream_Write_UINT16(s, coord);
return TRUE;
}
static INLINE BOOL update_read_color(wStream* s, UINT32* color)
{
BYTE byte;
if (Stream_GetRemainingLength(s) < 3)
return FALSE;
*color = 0;
Stream_Read_UINT8(s, byte);
*color = (UINT32)byte;
Stream_Read_UINT8(s, byte);
*color |= ((UINT32)byte << 8) & 0xFF00;
Stream_Read_UINT8(s, byte);
*color |= ((UINT32)byte << 16) & 0xFF0000;
return TRUE;
}
static INLINE BOOL update_write_color(wStream* s, UINT32 color)
{
BYTE byte;
byte = (color & 0xFF);
Stream_Write_UINT8(s, byte);
byte = ((color >> 8) & 0xFF);
Stream_Write_UINT8(s, byte);
byte = ((color >> 16) & 0xFF);
Stream_Write_UINT8(s, byte);
return TRUE;
}
static INLINE BOOL update_read_colorref(wStream* s, UINT32* color)
{
BYTE byte;
if (Stream_GetRemainingLength(s) < 4)
return FALSE;
*color = 0;
Stream_Read_UINT8(s, byte);
*color = byte;
Stream_Read_UINT8(s, byte);
*color |= ((UINT32)byte << 8);
Stream_Read_UINT8(s, byte);
*color |= ((UINT32)byte << 16);
Stream_Seek_UINT8(s);
return TRUE;
}
static INLINE BOOL update_read_color_quad(wStream* s, UINT32* color)
{
return update_read_colorref(s, color);
}
static INLINE void update_write_color_quad(wStream* s, UINT32 color)
{
BYTE byte;
byte = (color >> 16) & 0xFF;
Stream_Write_UINT8(s, byte);
byte = (color >> 8) & 0xFF;
Stream_Write_UINT8(s, byte);
byte = color & 0xFF;
Stream_Write_UINT8(s, byte);
}
static INLINE BOOL update_read_2byte_unsigned(wStream* s, UINT32* value)
{
BYTE byte;
if (Stream_GetRemainingLength(s) < 1)
return FALSE;
Stream_Read_UINT8(s, byte);
if (byte & 0x80)
{
if (Stream_GetRemainingLength(s) < 1)
return FALSE;
*value = (byte & 0x7F) << 8;
Stream_Read_UINT8(s, byte);
*value |= byte;
}
else
{
*value = (byte & 0x7F);
}
return TRUE;
}
static INLINE BOOL update_write_2byte_unsigned(wStream* s, UINT32 value)
{
BYTE byte;
if (value > 0x7FFF)
return FALSE;
if (value >= 0x7F)
{
byte = ((value & 0x7F00) >> 8);
Stream_Write_UINT8(s, byte | 0x80);
byte = (value & 0xFF);
Stream_Write_UINT8(s, byte);
}
else
{
byte = (value & 0x7F);
Stream_Write_UINT8(s, byte);
}
return TRUE;
}
static INLINE BOOL update_read_2byte_signed(wStream* s, INT32* value)
{
BYTE byte;
BOOL negative;
if (Stream_GetRemainingLength(s) < 1)
return FALSE;
Stream_Read_UINT8(s, byte);
negative = (byte & 0x40) ? TRUE : FALSE;
*value = (byte & 0x3F);
if (byte & 0x80)
{
if (Stream_GetRemainingLength(s) < 1)
return FALSE;
Stream_Read_UINT8(s, byte);
*value = (*value << 8) | byte;
}
if (negative)
*value *= -1;
return TRUE;
}
static INLINE BOOL update_write_2byte_signed(wStream* s, INT32 value)
{
BYTE byte;
BOOL negative = FALSE;
if (value < 0)
{
negative = TRUE;
value *= -1;
}
if (value > 0x3FFF)
return FALSE;
if (value >= 0x3F)
{
byte = ((value & 0x3F00) >> 8);
if (negative)
byte |= 0x40;
Stream_Write_UINT8(s, byte | 0x80);
byte = (value & 0xFF);
Stream_Write_UINT8(s, byte);
}
else
{
byte = (value & 0x3F);
if (negative)
byte |= 0x40;
Stream_Write_UINT8(s, byte);
}
return TRUE;
}
static INLINE BOOL update_read_4byte_unsigned(wStream* s, UINT32* value)
{
BYTE byte;
BYTE count;
if (Stream_GetRemainingLength(s) < 1)
return FALSE;
Stream_Read_UINT8(s, byte);
count = (byte & 0xC0) >> 6;
if (Stream_GetRemainingLength(s) < count)
return FALSE;
switch (count)
{
case 0:
*value = (byte & 0x3F);
break;
case 1:
*value = (byte & 0x3F) << 8;
Stream_Read_UINT8(s, byte);
*value |= byte;
break;
case 2:
*value = (byte & 0x3F) << 16;
Stream_Read_UINT8(s, byte);
*value |= (byte << 8);
Stream_Read_UINT8(s, byte);
*value |= byte;
break;
case 3:
*value = (byte & 0x3F) << 24;
Stream_Read_UINT8(s, byte);
*value |= (byte << 16);
Stream_Read_UINT8(s, byte);
*value |= (byte << 8);
Stream_Read_UINT8(s, byte);
*value |= byte;
break;
default:
break;
}
return TRUE;
}
static INLINE BOOL update_write_4byte_unsigned(wStream* s, UINT32 value)
{
BYTE byte;
if (value <= 0x3F)
{
Stream_Write_UINT8(s, value);
}
else if (value <= 0x3FFF)
{
byte = (value >> 8) & 0x3F;
Stream_Write_UINT8(s, byte | 0x40);
byte = (value & 0xFF);
Stream_Write_UINT8(s, byte);
}
else if (value <= 0x3FFFFF)
{
byte = (value >> 16) & 0x3F;
Stream_Write_UINT8(s, byte | 0x80);
byte = (value >> 8) & 0xFF;
Stream_Write_UINT8(s, byte);
byte = (value & 0xFF);
Stream_Write_UINT8(s, byte);
}
else if (value <= 0x3FFFFFFF)
{
byte = (value >> 24) & 0x3F;
Stream_Write_UINT8(s, byte | 0xC0);
byte = (value >> 16) & 0xFF;
Stream_Write_UINT8(s, byte);
byte = (value >> 8) & 0xFF;
Stream_Write_UINT8(s, byte);
byte = (value & 0xFF);
Stream_Write_UINT8(s, byte);
}
else
return FALSE;
return TRUE;
}
static INLINE BOOL update_read_delta(wStream* s, INT32* value)
{
BYTE byte;
if (Stream_GetRemainingLength(s) < 1)
{
WLog_ERR(TAG, "Stream_GetRemainingLength(s) < 1");
return FALSE;
}
Stream_Read_UINT8(s, byte);
if (byte & 0x40)
*value = (byte | ~0x3F);
else
*value = (byte & 0x3F);
if (byte & 0x80)
{
if (Stream_GetRemainingLength(s) < 1)
{
WLog_ERR(TAG, "Stream_GetRemainingLength(s) < 1");
return FALSE;
}
Stream_Read_UINT8(s, byte);
*value = (*value << 8) | byte;
}
return TRUE;
}
#if 0
static INLINE void update_read_glyph_delta(wStream* s, UINT16* value)
{
BYTE byte;
Stream_Read_UINT8(s, byte);
if (byte == 0x80)
Stream_Read_UINT16(s, *value);
else
*value = (byte & 0x3F);
}
static INLINE void update_seek_glyph_delta(wStream* s)
{
BYTE byte;
Stream_Read_UINT8(s, byte);
if (byte & 0x80)
Stream_Seek_UINT8(s);
}
#endif
static INLINE BOOL update_read_brush(wStream* s, rdpBrush* brush, BYTE fieldFlags)
{
if (fieldFlags & ORDER_FIELD_01)
{
if (Stream_GetRemainingLength(s) < 1)
return FALSE;
Stream_Read_UINT8(s, brush->x);
}
if (fieldFlags & ORDER_FIELD_02)
{
if (Stream_GetRemainingLength(s) < 1)
return FALSE;
Stream_Read_UINT8(s, brush->y);
}
if (fieldFlags & ORDER_FIELD_03)
{
if (Stream_GetRemainingLength(s) < 1)
return FALSE;
Stream_Read_UINT8(s, brush->style);
}
if (fieldFlags & ORDER_FIELD_04)
{
if (Stream_GetRemainingLength(s) < 1)
return FALSE;
Stream_Read_UINT8(s, brush->hatch);
}
if (brush->style & CACHED_BRUSH)
{
brush->index = brush->hatch;
brush->bpp = BMF_BPP[brush->style & 0x07];
if (brush->bpp == 0)
brush->bpp = 1;
}
if (fieldFlags & ORDER_FIELD_05)
{
if (Stream_GetRemainingLength(s) < 7)
return FALSE;
brush->data = (BYTE*)brush->p8x8;
Stream_Read_UINT8(s, brush->data[7]);
Stream_Read_UINT8(s, brush->data[6]);
Stream_Read_UINT8(s, brush->data[5]);
Stream_Read_UINT8(s, brush->data[4]);
Stream_Read_UINT8(s, brush->data[3]);
Stream_Read_UINT8(s, brush->data[2]);
Stream_Read_UINT8(s, brush->data[1]);
brush->data[0] = brush->hatch;
}
return TRUE;
}
static INLINE BOOL update_write_brush(wStream* s, rdpBrush* brush, BYTE fieldFlags)
{
if (fieldFlags & ORDER_FIELD_01)
{
Stream_Write_UINT8(s, brush->x);
}
if (fieldFlags & ORDER_FIELD_02)
{
Stream_Write_UINT8(s, brush->y);
}
if (fieldFlags & ORDER_FIELD_03)
{
Stream_Write_UINT8(s, brush->style);
}
if (brush->style & CACHED_BRUSH)
{
brush->hatch = brush->index;
brush->bpp = BMF_BPP[brush->style & 0x07];
if (brush->bpp == 0)
brush->bpp = 1;
}
if (fieldFlags & ORDER_FIELD_04)
{
Stream_Write_UINT8(s, brush->hatch);
}
if (fieldFlags & ORDER_FIELD_05)
{
brush->data = (BYTE*)brush->p8x8;
Stream_Write_UINT8(s, brush->data[7]);
Stream_Write_UINT8(s, brush->data[6]);
Stream_Write_UINT8(s, brush->data[5]);
Stream_Write_UINT8(s, brush->data[4]);
Stream_Write_UINT8(s, brush->data[3]);
Stream_Write_UINT8(s, brush->data[2]);
Stream_Write_UINT8(s, brush->data[1]);
brush->data[0] = brush->hatch;
}
return TRUE;
}
static INLINE BOOL update_read_delta_rects(wStream* s, DELTA_RECT* rectangles, UINT32* nr)
{
UINT32 number = *nr;
UINT32 i;
BYTE flags = 0;
BYTE* zeroBits;
UINT32 zeroBitsSize;
if (number > 45)
{
WLog_WARN(TAG, "Invalid number of delta rectangles %" PRIu32, number);
return FALSE;
}
zeroBitsSize = ((number + 1) / 2);
if (Stream_GetRemainingLength(s) < zeroBitsSize)
return FALSE;
Stream_GetPointer(s, zeroBits);
Stream_Seek(s, zeroBitsSize);
ZeroMemory(rectangles, sizeof(DELTA_RECT) * number);
for (i = 0; i < number; i++)
{
if (i % 2 == 0)
flags = zeroBits[i / 2];
if ((~flags & 0x80) && !update_read_delta(s, &rectangles[i].left))
return FALSE;
if ((~flags & 0x40) && !update_read_delta(s, &rectangles[i].top))
return FALSE;
if (~flags & 0x20)
{
if (!update_read_delta(s, &rectangles[i].width))
return FALSE;
}
else if (i > 0)
rectangles[i].width = rectangles[i - 1].width;
else
rectangles[i].width = 0;
if (~flags & 0x10)
{
if (!update_read_delta(s, &rectangles[i].height))
return FALSE;
}
else if (i > 0)
rectangles[i].height = rectangles[i - 1].height;
else
rectangles[i].height = 0;
if (i > 0)
{
rectangles[i].left += rectangles[i - 1].left;
rectangles[i].top += rectangles[i - 1].top;
}
flags <<= 4;
}
return TRUE;
}
static INLINE BOOL update_read_delta_points(wStream* s, DELTA_POINT* points, int number, INT16 x,
INT16 y)
{
int i;
BYTE flags = 0;
BYTE* zeroBits;
UINT32 zeroBitsSize;
zeroBitsSize = ((number + 3) / 4);
if (Stream_GetRemainingLength(s) < zeroBitsSize)
{
WLog_ERR(TAG, "Stream_GetRemainingLength(s) < %" PRIu32 "", zeroBitsSize);
return FALSE;
}
Stream_GetPointer(s, zeroBits);
Stream_Seek(s, zeroBitsSize);
ZeroMemory(points, sizeof(DELTA_POINT) * number);
for (i = 0; i < number; i++)
{
if (i % 4 == 0)
flags = zeroBits[i / 4];
if ((~flags & 0x80) && !update_read_delta(s, &points[i].x))
{
WLog_ERR(TAG, "update_read_delta(x) failed");
return FALSE;
}
if ((~flags & 0x40) && !update_read_delta(s, &points[i].y))
{
WLog_ERR(TAG, "update_read_delta(y) failed");
return FALSE;
}
flags <<= 2;
}
return TRUE;
}
#define ORDER_FIELD_BYTE(NO, TARGET) \
do \
{ \
if (orderInfo->fieldFlags & (1 << (NO - 1))) \
{ \
if (Stream_GetRemainingLength(s) < 1) \
{ \
WLog_ERR(TAG, "error reading %s", #TARGET); \
return FALSE; \
} \
Stream_Read_UINT8(s, TARGET); \
} \
} while (0)
#define ORDER_FIELD_2BYTE(NO, TARGET1, TARGET2) \
do \
{ \
if (orderInfo->fieldFlags & (1 << (NO - 1))) \
{ \
if (Stream_GetRemainingLength(s) < 2) \
{ \
WLog_ERR(TAG, "error reading %s or %s", #TARGET1, #TARGET2); \
return FALSE; \
} \
Stream_Read_UINT8(s, TARGET1); \
Stream_Read_UINT8(s, TARGET2); \
} \
} while (0)
#define ORDER_FIELD_UINT16(NO, TARGET) \
do \
{ \
if (orderInfo->fieldFlags & (1 << (NO - 1))) \
{ \
if (Stream_GetRemainingLength(s) < 2) \
{ \
WLog_ERR(TAG, "error reading %s", #TARGET); \
return FALSE; \
} \
Stream_Read_UINT16(s, TARGET); \
} \
} while (0)
#define ORDER_FIELD_UINT32(NO, TARGET) \
do \
{ \
if (orderInfo->fieldFlags & (1 << (NO - 1))) \
{ \
if (Stream_GetRemainingLength(s) < 4) \
{ \
WLog_ERR(TAG, "error reading %s", #TARGET); \
return FALSE; \
} \
Stream_Read_UINT32(s, TARGET); \
} \
} while (0)
#define ORDER_FIELD_COORD(NO, TARGET) \
do \
{ \
if ((orderInfo->fieldFlags & (1 << (NO - 1))) && \
!update_read_coord(s, &TARGET, orderInfo->deltaCoordinates)) \
{ \
WLog_ERR(TAG, "error reading %s", #TARGET); \
return FALSE; \
} \
} while (0)
static INLINE BOOL ORDER_FIELD_COLOR(const ORDER_INFO* orderInfo, wStream* s, UINT32 NO,
UINT32* TARGET)
{
if (!TARGET || !orderInfo)
return FALSE;
if ((orderInfo->fieldFlags & (1 << (NO - 1))) && !update_read_color(s, TARGET))
return FALSE;
return TRUE;
}
static INLINE BOOL FIELD_SKIP_BUFFER16(wStream* s, UINT32 TARGET_LEN)
{
if (Stream_GetRemainingLength(s) < 2)
return FALSE;
Stream_Read_UINT16(s, TARGET_LEN);
if (!Stream_SafeSeek(s, TARGET_LEN))
{
WLog_ERR(TAG, "error skipping %" PRIu32 " bytes", TARGET_LEN);
return FALSE;
}
return TRUE;
}
/* Primary Drawing Orders */
static BOOL update_read_dstblt_order(wStream* s, const ORDER_INFO* orderInfo, DSTBLT_ORDER* dstblt)
{
ORDER_FIELD_COORD(1, dstblt->nLeftRect);
ORDER_FIELD_COORD(2, dstblt->nTopRect);
ORDER_FIELD_COORD(3, dstblt->nWidth);
ORDER_FIELD_COORD(4, dstblt->nHeight);
ORDER_FIELD_BYTE(5, dstblt->bRop);
return TRUE;
}
int update_approximate_dstblt_order(ORDER_INFO* orderInfo, const DSTBLT_ORDER* dstblt)
{
return 32;
}
BOOL update_write_dstblt_order(wStream* s, ORDER_INFO* orderInfo, const DSTBLT_ORDER* dstblt)
{
if (!Stream_EnsureRemainingCapacity(s, update_approximate_dstblt_order(orderInfo, dstblt)))
return FALSE;
orderInfo->fieldFlags = 0;
orderInfo->fieldFlags |= ORDER_FIELD_01;
update_write_coord(s, dstblt->nLeftRect);
orderInfo->fieldFlags |= ORDER_FIELD_02;
update_write_coord(s, dstblt->nTopRect);
orderInfo->fieldFlags |= ORDER_FIELD_03;
update_write_coord(s, dstblt->nWidth);
orderInfo->fieldFlags |= ORDER_FIELD_04;
update_write_coord(s, dstblt->nHeight);
orderInfo->fieldFlags |= ORDER_FIELD_05;
Stream_Write_UINT8(s, dstblt->bRop);
return TRUE;
}
static BOOL update_read_patblt_order(wStream* s, const ORDER_INFO* orderInfo, PATBLT_ORDER* patblt)
{
ORDER_FIELD_COORD(1, patblt->nLeftRect);
ORDER_FIELD_COORD(2, patblt->nTopRect);
ORDER_FIELD_COORD(3, patblt->nWidth);
ORDER_FIELD_COORD(4, patblt->nHeight);
ORDER_FIELD_BYTE(5, patblt->bRop);
ORDER_FIELD_COLOR(orderInfo, s, 6, &patblt->backColor);
ORDER_FIELD_COLOR(orderInfo, s, 7, &patblt->foreColor);
return update_read_brush(s, &patblt->brush, orderInfo->fieldFlags >> 7);
}
int update_approximate_patblt_order(ORDER_INFO* orderInfo, PATBLT_ORDER* patblt)
{
return 32;
}
BOOL update_write_patblt_order(wStream* s, ORDER_INFO* orderInfo, PATBLT_ORDER* patblt)
{
if (!Stream_EnsureRemainingCapacity(s, update_approximate_patblt_order(orderInfo, patblt)))
return FALSE;
orderInfo->fieldFlags = 0;
orderInfo->fieldFlags |= ORDER_FIELD_01;
update_write_coord(s, patblt->nLeftRect);
orderInfo->fieldFlags |= ORDER_FIELD_02;
update_write_coord(s, patblt->nTopRect);
orderInfo->fieldFlags |= ORDER_FIELD_03;
update_write_coord(s, patblt->nWidth);
orderInfo->fieldFlags |= ORDER_FIELD_04;
update_write_coord(s, patblt->nHeight);
orderInfo->fieldFlags |= ORDER_FIELD_05;
Stream_Write_UINT8(s, patblt->bRop);
orderInfo->fieldFlags |= ORDER_FIELD_06;
update_write_color(s, patblt->backColor);
orderInfo->fieldFlags |= ORDER_FIELD_07;
update_write_color(s, patblt->foreColor);
orderInfo->fieldFlags |= ORDER_FIELD_08;
orderInfo->fieldFlags |= ORDER_FIELD_09;
orderInfo->fieldFlags |= ORDER_FIELD_10;
orderInfo->fieldFlags |= ORDER_FIELD_11;
orderInfo->fieldFlags |= ORDER_FIELD_12;
update_write_brush(s, &patblt->brush, orderInfo->fieldFlags >> 7);
return TRUE;
}
static BOOL update_read_scrblt_order(wStream* s, const ORDER_INFO* orderInfo, SCRBLT_ORDER* scrblt)
{
ORDER_FIELD_COORD(1, scrblt->nLeftRect);
ORDER_FIELD_COORD(2, scrblt->nTopRect);
ORDER_FIELD_COORD(3, scrblt->nWidth);
ORDER_FIELD_COORD(4, scrblt->nHeight);
ORDER_FIELD_BYTE(5, scrblt->bRop);
ORDER_FIELD_COORD(6, scrblt->nXSrc);
ORDER_FIELD_COORD(7, scrblt->nYSrc);
return TRUE;
}
int update_approximate_scrblt_order(ORDER_INFO* orderInfo, const SCRBLT_ORDER* scrblt)
{
return 32;
}
BOOL update_write_scrblt_order(wStream* s, ORDER_INFO* orderInfo, const SCRBLT_ORDER* scrblt)
{
if (!Stream_EnsureRemainingCapacity(s, update_approximate_scrblt_order(orderInfo, scrblt)))
return FALSE;
orderInfo->fieldFlags = 0;
orderInfo->fieldFlags |= ORDER_FIELD_01;
update_write_coord(s, scrblt->nLeftRect);
orderInfo->fieldFlags |= ORDER_FIELD_02;
update_write_coord(s, scrblt->nTopRect);
orderInfo->fieldFlags |= ORDER_FIELD_03;
update_write_coord(s, scrblt->nWidth);
orderInfo->fieldFlags |= ORDER_FIELD_04;
update_write_coord(s, scrblt->nHeight);
orderInfo->fieldFlags |= ORDER_FIELD_05;
Stream_Write_UINT8(s, scrblt->bRop);
orderInfo->fieldFlags |= ORDER_FIELD_06;
update_write_coord(s, scrblt->nXSrc);
orderInfo->fieldFlags |= ORDER_FIELD_07;
update_write_coord(s, scrblt->nYSrc);
return TRUE;
}
static BOOL update_read_opaque_rect_order(wStream* s, const ORDER_INFO* orderInfo,
OPAQUE_RECT_ORDER* opaque_rect)
{
BYTE byte;
ORDER_FIELD_COORD(1, opaque_rect->nLeftRect);
ORDER_FIELD_COORD(2, opaque_rect->nTopRect);
ORDER_FIELD_COORD(3, opaque_rect->nWidth);
ORDER_FIELD_COORD(4, opaque_rect->nHeight);
if (orderInfo->fieldFlags & ORDER_FIELD_05)
{
if (Stream_GetRemainingLength(s) < 1)
return FALSE;
Stream_Read_UINT8(s, byte);
opaque_rect->color = (opaque_rect->color & 0x00FFFF00) | ((UINT32)byte);
}
if (orderInfo->fieldFlags & ORDER_FIELD_06)
{
if (Stream_GetRemainingLength(s) < 1)
return FALSE;
Stream_Read_UINT8(s, byte);
opaque_rect->color = (opaque_rect->color & 0x00FF00FF) | ((UINT32)byte << 8);
}
if (orderInfo->fieldFlags & ORDER_FIELD_07)
{
if (Stream_GetRemainingLength(s) < 1)
return FALSE;
Stream_Read_UINT8(s, byte);
opaque_rect->color = (opaque_rect->color & 0x0000FFFF) | ((UINT32)byte << 16);
}
return TRUE;
}
int update_approximate_opaque_rect_order(ORDER_INFO* orderInfo,
const OPAQUE_RECT_ORDER* opaque_rect)
{
return 32;
}
BOOL update_write_opaque_rect_order(wStream* s, ORDER_INFO* orderInfo,
const OPAQUE_RECT_ORDER* opaque_rect)
{
BYTE byte;
int inf = update_approximate_opaque_rect_order(orderInfo, opaque_rect);
if (!Stream_EnsureRemainingCapacity(s, inf))
return FALSE;
// TODO: Color format conversion
orderInfo->fieldFlags = 0;
orderInfo->fieldFlags |= ORDER_FIELD_01;
update_write_coord(s, opaque_rect->nLeftRect);
orderInfo->fieldFlags |= ORDER_FIELD_02;
update_write_coord(s, opaque_rect->nTopRect);
orderInfo->fieldFlags |= ORDER_FIELD_03;
update_write_coord(s, opaque_rect->nWidth);
orderInfo->fieldFlags |= ORDER_FIELD_04;
update_write_coord(s, opaque_rect->nHeight);
orderInfo->fieldFlags |= ORDER_FIELD_05;
byte = opaque_rect->color & 0x000000FF;
Stream_Write_UINT8(s, byte);
orderInfo->fieldFlags |= ORDER_FIELD_06;
byte = (opaque_rect->color & 0x0000FF00) >> 8;
Stream_Write_UINT8(s, byte);
orderInfo->fieldFlags |= ORDER_FIELD_07;
byte = (opaque_rect->color & 0x00FF0000) >> 16;
Stream_Write_UINT8(s, byte);
return TRUE;
}
static BOOL update_read_draw_nine_grid_order(wStream* s, const ORDER_INFO* orderInfo,
DRAW_NINE_GRID_ORDER* draw_nine_grid)
{
ORDER_FIELD_COORD(1, draw_nine_grid->srcLeft);
ORDER_FIELD_COORD(2, draw_nine_grid->srcTop);
ORDER_FIELD_COORD(3, draw_nine_grid->srcRight);
ORDER_FIELD_COORD(4, draw_nine_grid->srcBottom);
ORDER_FIELD_UINT16(5, draw_nine_grid->bitmapId);
return TRUE;
}
static BOOL update_read_multi_dstblt_order(wStream* s, const ORDER_INFO* orderInfo,
MULTI_DSTBLT_ORDER* multi_dstblt)
{
ORDER_FIELD_COORD(1, multi_dstblt->nLeftRect);
ORDER_FIELD_COORD(2, multi_dstblt->nTopRect);
ORDER_FIELD_COORD(3, multi_dstblt->nWidth);
ORDER_FIELD_COORD(4, multi_dstblt->nHeight);
ORDER_FIELD_BYTE(5, multi_dstblt->bRop);
ORDER_FIELD_BYTE(6, multi_dstblt->numRectangles);
if (orderInfo->fieldFlags & ORDER_FIELD_07)
{
if (Stream_GetRemainingLength(s) < 2)
return FALSE;
Stream_Read_UINT16(s, multi_dstblt->cbData);
return update_read_delta_rects(s, multi_dstblt->rectangles, &multi_dstblt->numRectangles);
}
return TRUE;
}
static BOOL update_read_multi_patblt_order(wStream* s, const ORDER_INFO* orderInfo,
MULTI_PATBLT_ORDER* multi_patblt)
{
ORDER_FIELD_COORD(1, multi_patblt->nLeftRect);
ORDER_FIELD_COORD(2, multi_patblt->nTopRect);
ORDER_FIELD_COORD(3, multi_patblt->nWidth);
ORDER_FIELD_COORD(4, multi_patblt->nHeight);
ORDER_FIELD_BYTE(5, multi_patblt->bRop);
ORDER_FIELD_COLOR(orderInfo, s, 6, &multi_patblt->backColor);
ORDER_FIELD_COLOR(orderInfo, s, 7, &multi_patblt->foreColor);
if (!update_read_brush(s, &multi_patblt->brush, orderInfo->fieldFlags >> 7))
return FALSE;
ORDER_FIELD_BYTE(13, multi_patblt->numRectangles);
if (orderInfo->fieldFlags & ORDER_FIELD_14)
{
if (Stream_GetRemainingLength(s) < 2)
return FALSE;
Stream_Read_UINT16(s, multi_patblt->cbData);
if (!update_read_delta_rects(s, multi_patblt->rectangles, &multi_patblt->numRectangles))
return FALSE;
}
return TRUE;
}
static BOOL update_read_multi_scrblt_order(wStream* s, const ORDER_INFO* orderInfo,
MULTI_SCRBLT_ORDER* multi_scrblt)
{
ORDER_FIELD_COORD(1, multi_scrblt->nLeftRect);
ORDER_FIELD_COORD(2, multi_scrblt->nTopRect);
ORDER_FIELD_COORD(3, multi_scrblt->nWidth);
ORDER_FIELD_COORD(4, multi_scrblt->nHeight);
ORDER_FIELD_BYTE(5, multi_scrblt->bRop);
ORDER_FIELD_COORD(6, multi_scrblt->nXSrc);
ORDER_FIELD_COORD(7, multi_scrblt->nYSrc);
ORDER_FIELD_BYTE(8, multi_scrblt->numRectangles);
if (orderInfo->fieldFlags & ORDER_FIELD_09)
{
if (Stream_GetRemainingLength(s) < 2)
return FALSE;
Stream_Read_UINT16(s, multi_scrblt->cbData);
return update_read_delta_rects(s, multi_scrblt->rectangles, &multi_scrblt->numRectangles);
}
return TRUE;
}
static BOOL update_read_multi_opaque_rect_order(wStream* s, const ORDER_INFO* orderInfo,
MULTI_OPAQUE_RECT_ORDER* multi_opaque_rect)
{
BYTE byte;
ORDER_FIELD_COORD(1, multi_opaque_rect->nLeftRect);
ORDER_FIELD_COORD(2, multi_opaque_rect->nTopRect);
ORDER_FIELD_COORD(3, multi_opaque_rect->nWidth);
ORDER_FIELD_COORD(4, multi_opaque_rect->nHeight);
if (orderInfo->fieldFlags & ORDER_FIELD_05)
{
if (Stream_GetRemainingLength(s) < 1)
return FALSE;
Stream_Read_UINT8(s, byte);
multi_opaque_rect->color = (multi_opaque_rect->color & 0x00FFFF00) | ((UINT32)byte);
}
if (orderInfo->fieldFlags & ORDER_FIELD_06)
{
if (Stream_GetRemainingLength(s) < 1)
return FALSE;
Stream_Read_UINT8(s, byte);
multi_opaque_rect->color = (multi_opaque_rect->color & 0x00FF00FF) | ((UINT32)byte << 8);
}
if (orderInfo->fieldFlags & ORDER_FIELD_07)
{
if (Stream_GetRemainingLength(s) < 1)
return FALSE;
Stream_Read_UINT8(s, byte);
multi_opaque_rect->color = (multi_opaque_rect->color & 0x0000FFFF) | ((UINT32)byte << 16);
}
ORDER_FIELD_BYTE(8, multi_opaque_rect->numRectangles);
if (orderInfo->fieldFlags & ORDER_FIELD_09)
{
if (Stream_GetRemainingLength(s) < 2)
return FALSE;
Stream_Read_UINT16(s, multi_opaque_rect->cbData);
return update_read_delta_rects(s, multi_opaque_rect->rectangles,
&multi_opaque_rect->numRectangles);
}
return TRUE;
}
static BOOL update_read_multi_draw_nine_grid_order(wStream* s, const ORDER_INFO* orderInfo,
MULTI_DRAW_NINE_GRID_ORDER* multi_draw_nine_grid)
{
ORDER_FIELD_COORD(1, multi_draw_nine_grid->srcLeft);
ORDER_FIELD_COORD(2, multi_draw_nine_grid->srcTop);
ORDER_FIELD_COORD(3, multi_draw_nine_grid->srcRight);
ORDER_FIELD_COORD(4, multi_draw_nine_grid->srcBottom);
ORDER_FIELD_UINT16(5, multi_draw_nine_grid->bitmapId);
ORDER_FIELD_BYTE(6, multi_draw_nine_grid->nDeltaEntries);
if (orderInfo->fieldFlags & ORDER_FIELD_07)
{
if (Stream_GetRemainingLength(s) < 2)
return FALSE;
Stream_Read_UINT16(s, multi_draw_nine_grid->cbData);
return update_read_delta_rects(s, multi_draw_nine_grid->rectangles,
&multi_draw_nine_grid->nDeltaEntries);
}
return TRUE;
}
static BOOL update_read_line_to_order(wStream* s, const ORDER_INFO* orderInfo,
LINE_TO_ORDER* line_to)
{
ORDER_FIELD_UINT16(1, line_to->backMode);
ORDER_FIELD_COORD(2, line_to->nXStart);
ORDER_FIELD_COORD(3, line_to->nYStart);
ORDER_FIELD_COORD(4, line_to->nXEnd);
ORDER_FIELD_COORD(5, line_to->nYEnd);
ORDER_FIELD_COLOR(orderInfo, s, 6, &line_to->backColor);
ORDER_FIELD_BYTE(7, line_to->bRop2);
ORDER_FIELD_BYTE(8, line_to->penStyle);
ORDER_FIELD_BYTE(9, line_to->penWidth);
ORDER_FIELD_COLOR(orderInfo, s, 10, &line_to->penColor);
return TRUE;
}
int update_approximate_line_to_order(ORDER_INFO* orderInfo, const LINE_TO_ORDER* line_to)
{
return 32;
}
BOOL update_write_line_to_order(wStream* s, ORDER_INFO* orderInfo, const LINE_TO_ORDER* line_to)
{
if (!Stream_EnsureRemainingCapacity(s, update_approximate_line_to_order(orderInfo, line_to)))
return FALSE;
orderInfo->fieldFlags = 0;
orderInfo->fieldFlags |= ORDER_FIELD_01;
Stream_Write_UINT16(s, line_to->backMode);
orderInfo->fieldFlags |= ORDER_FIELD_02;
update_write_coord(s, line_to->nXStart);
orderInfo->fieldFlags |= ORDER_FIELD_03;
update_write_coord(s, line_to->nYStart);
orderInfo->fieldFlags |= ORDER_FIELD_04;
update_write_coord(s, line_to->nXEnd);
orderInfo->fieldFlags |= ORDER_FIELD_05;
update_write_coord(s, line_to->nYEnd);
orderInfo->fieldFlags |= ORDER_FIELD_06;
update_write_color(s, line_to->backColor);
orderInfo->fieldFlags |= ORDER_FIELD_07;
Stream_Write_UINT8(s, line_to->bRop2);
orderInfo->fieldFlags |= ORDER_FIELD_08;
Stream_Write_UINT8(s, line_to->penStyle);
orderInfo->fieldFlags |= ORDER_FIELD_09;
Stream_Write_UINT8(s, line_to->penWidth);
orderInfo->fieldFlags |= ORDER_FIELD_10;
update_write_color(s, line_to->penColor);
return TRUE;
}
static BOOL update_read_polyline_order(wStream* s, const ORDER_INFO* orderInfo,
POLYLINE_ORDER* polyline)
{
UINT16 word;
UINT32 new_num = polyline->numDeltaEntries;
ORDER_FIELD_COORD(1, polyline->xStart);
ORDER_FIELD_COORD(2, polyline->yStart);
ORDER_FIELD_BYTE(3, polyline->bRop2);
ORDER_FIELD_UINT16(4, word);
ORDER_FIELD_COLOR(orderInfo, s, 5, &polyline->penColor);
ORDER_FIELD_BYTE(6, new_num);
if (orderInfo->fieldFlags & ORDER_FIELD_07)
{
DELTA_POINT* new_points;
if (new_num == 0)
return FALSE;
if (Stream_GetRemainingLength(s) < 1)
{
WLog_ERR(TAG, "Stream_GetRemainingLength(s) < 1");
return FALSE;
}
Stream_Read_UINT8(s, polyline->cbData);
new_points = (DELTA_POINT*)realloc(polyline->points, sizeof(DELTA_POINT) * new_num);
if (!new_points)
{
WLog_ERR(TAG, "realloc(%" PRIu32 ") failed", new_num);
return FALSE;
}
polyline->points = new_points;
polyline->numDeltaEntries = new_num;
return update_read_delta_points(s, polyline->points, polyline->numDeltaEntries,
polyline->xStart, polyline->yStart);
}
return TRUE;
}
static BOOL update_read_memblt_order(wStream* s, const ORDER_INFO* orderInfo, MEMBLT_ORDER* memblt)
{
if (!s || !orderInfo || !memblt)
return FALSE;
ORDER_FIELD_UINT16(1, memblt->cacheId);
ORDER_FIELD_COORD(2, memblt->nLeftRect);
ORDER_FIELD_COORD(3, memblt->nTopRect);
ORDER_FIELD_COORD(4, memblt->nWidth);
ORDER_FIELD_COORD(5, memblt->nHeight);
ORDER_FIELD_BYTE(6, memblt->bRop);
ORDER_FIELD_COORD(7, memblt->nXSrc);
ORDER_FIELD_COORD(8, memblt->nYSrc);
ORDER_FIELD_UINT16(9, memblt->cacheIndex);
memblt->colorIndex = (memblt->cacheId >> 8);
memblt->cacheId = (memblt->cacheId & 0xFF);
memblt->bitmap = NULL;
return TRUE;
}
int update_approximate_memblt_order(ORDER_INFO* orderInfo, const MEMBLT_ORDER* memblt)
{
return 64;
}
BOOL update_write_memblt_order(wStream* s, ORDER_INFO* orderInfo, const MEMBLT_ORDER* memblt)
{
UINT16 cacheId;
if (!Stream_EnsureRemainingCapacity(s, update_approximate_memblt_order(orderInfo, memblt)))
return FALSE;
cacheId = (memblt->cacheId & 0xFF) | ((memblt->colorIndex & 0xFF) << 8);
orderInfo->fieldFlags |= ORDER_FIELD_01;
Stream_Write_UINT16(s, cacheId);
orderInfo->fieldFlags |= ORDER_FIELD_02;
update_write_coord(s, memblt->nLeftRect);
orderInfo->fieldFlags |= ORDER_FIELD_03;
update_write_coord(s, memblt->nTopRect);
orderInfo->fieldFlags |= ORDER_FIELD_04;
update_write_coord(s, memblt->nWidth);
orderInfo->fieldFlags |= ORDER_FIELD_05;
update_write_coord(s, memblt->nHeight);
orderInfo->fieldFlags |= ORDER_FIELD_06;
Stream_Write_UINT8(s, memblt->bRop);
orderInfo->fieldFlags |= ORDER_FIELD_07;
update_write_coord(s, memblt->nXSrc);
orderInfo->fieldFlags |= ORDER_FIELD_08;
update_write_coord(s, memblt->nYSrc);
orderInfo->fieldFlags |= ORDER_FIELD_09;
Stream_Write_UINT16(s, memblt->cacheIndex);
return TRUE;
}
static BOOL update_read_mem3blt_order(wStream* s, const ORDER_INFO* orderInfo,
MEM3BLT_ORDER* mem3blt)
{
ORDER_FIELD_UINT16(1, mem3blt->cacheId);
ORDER_FIELD_COORD(2, mem3blt->nLeftRect);
ORDER_FIELD_COORD(3, mem3blt->nTopRect);
ORDER_FIELD_COORD(4, mem3blt->nWidth);
ORDER_FIELD_COORD(5, mem3blt->nHeight);
ORDER_FIELD_BYTE(6, mem3blt->bRop);
ORDER_FIELD_COORD(7, mem3blt->nXSrc);
ORDER_FIELD_COORD(8, mem3blt->nYSrc);
ORDER_FIELD_COLOR(orderInfo, s, 9, &mem3blt->backColor);
ORDER_FIELD_COLOR(orderInfo, s, 10, &mem3blt->foreColor);
if (!update_read_brush(s, &mem3blt->brush, orderInfo->fieldFlags >> 10))
return FALSE;
ORDER_FIELD_UINT16(16, mem3blt->cacheIndex);
mem3blt->colorIndex = (mem3blt->cacheId >> 8);
mem3blt->cacheId = (mem3blt->cacheId & 0xFF);
mem3blt->bitmap = NULL;
return TRUE;
}
static BOOL update_read_save_bitmap_order(wStream* s, const ORDER_INFO* orderInfo,
SAVE_BITMAP_ORDER* save_bitmap)
{
ORDER_FIELD_UINT32(1, save_bitmap->savedBitmapPosition);
ORDER_FIELD_COORD(2, save_bitmap->nLeftRect);
ORDER_FIELD_COORD(3, save_bitmap->nTopRect);
ORDER_FIELD_COORD(4, save_bitmap->nRightRect);
ORDER_FIELD_COORD(5, save_bitmap->nBottomRect);
ORDER_FIELD_BYTE(6, save_bitmap->operation);
return TRUE;
}
static BOOL update_read_glyph_index_order(wStream* s, const ORDER_INFO* orderInfo,
GLYPH_INDEX_ORDER* glyph_index)
{
ORDER_FIELD_BYTE(1, glyph_index->cacheId);
ORDER_FIELD_BYTE(2, glyph_index->flAccel);
ORDER_FIELD_BYTE(3, glyph_index->ulCharInc);
ORDER_FIELD_BYTE(4, glyph_index->fOpRedundant);
ORDER_FIELD_COLOR(orderInfo, s, 5, &glyph_index->backColor);
ORDER_FIELD_COLOR(orderInfo, s, 6, &glyph_index->foreColor);
ORDER_FIELD_UINT16(7, glyph_index->bkLeft);
ORDER_FIELD_UINT16(8, glyph_index->bkTop);
ORDER_FIELD_UINT16(9, glyph_index->bkRight);
ORDER_FIELD_UINT16(10, glyph_index->bkBottom);
ORDER_FIELD_UINT16(11, glyph_index->opLeft);
ORDER_FIELD_UINT16(12, glyph_index->opTop);
ORDER_FIELD_UINT16(13, glyph_index->opRight);
ORDER_FIELD_UINT16(14, glyph_index->opBottom);
if (!update_read_brush(s, &glyph_index->brush, orderInfo->fieldFlags >> 14))
return FALSE;
ORDER_FIELD_UINT16(20, glyph_index->x);
ORDER_FIELD_UINT16(21, glyph_index->y);
if (orderInfo->fieldFlags & ORDER_FIELD_22)
{
if (Stream_GetRemainingLength(s) < 1)
return FALSE;
Stream_Read_UINT8(s, glyph_index->cbData);
if (Stream_GetRemainingLength(s) < glyph_index->cbData)
return FALSE;
CopyMemory(glyph_index->data, Stream_Pointer(s), glyph_index->cbData);
Stream_Seek(s, glyph_index->cbData);
}
return TRUE;
}
int update_approximate_glyph_index_order(ORDER_INFO* orderInfo,
const GLYPH_INDEX_ORDER* glyph_index)
{
return 64;
}
BOOL update_write_glyph_index_order(wStream* s, ORDER_INFO* orderInfo,
GLYPH_INDEX_ORDER* glyph_index)
{
int inf = update_approximate_glyph_index_order(orderInfo, glyph_index);
if (!Stream_EnsureRemainingCapacity(s, inf))
return FALSE;
orderInfo->fieldFlags = 0;
orderInfo->fieldFlags |= ORDER_FIELD_01;
Stream_Write_UINT8(s, glyph_index->cacheId);
orderInfo->fieldFlags |= ORDER_FIELD_02;
Stream_Write_UINT8(s, glyph_index->flAccel);
orderInfo->fieldFlags |= ORDER_FIELD_03;
Stream_Write_UINT8(s, glyph_index->ulCharInc);
orderInfo->fieldFlags |= ORDER_FIELD_04;
Stream_Write_UINT8(s, glyph_index->fOpRedundant);
orderInfo->fieldFlags |= ORDER_FIELD_05;
update_write_color(s, glyph_index->backColor);
orderInfo->fieldFlags |= ORDER_FIELD_06;
update_write_color(s, glyph_index->foreColor);
orderInfo->fieldFlags |= ORDER_FIELD_07;
Stream_Write_UINT16(s, glyph_index->bkLeft);
orderInfo->fieldFlags |= ORDER_FIELD_08;
Stream_Write_UINT16(s, glyph_index->bkTop);
orderInfo->fieldFlags |= ORDER_FIELD_09;
Stream_Write_UINT16(s, glyph_index->bkRight);
orderInfo->fieldFlags |= ORDER_FIELD_10;
Stream_Write_UINT16(s, glyph_index->bkBottom);
orderInfo->fieldFlags |= ORDER_FIELD_11;
Stream_Write_UINT16(s, glyph_index->opLeft);
orderInfo->fieldFlags |= ORDER_FIELD_12;
Stream_Write_UINT16(s, glyph_index->opTop);
orderInfo->fieldFlags |= ORDER_FIELD_13;
Stream_Write_UINT16(s, glyph_index->opRight);
orderInfo->fieldFlags |= ORDER_FIELD_14;
Stream_Write_UINT16(s, glyph_index->opBottom);
orderInfo->fieldFlags |= ORDER_FIELD_15;
orderInfo->fieldFlags |= ORDER_FIELD_16;
orderInfo->fieldFlags |= ORDER_FIELD_17;
orderInfo->fieldFlags |= ORDER_FIELD_18;
orderInfo->fieldFlags |= ORDER_FIELD_19;
update_write_brush(s, &glyph_index->brush, orderInfo->fieldFlags >> 14);
orderInfo->fieldFlags |= ORDER_FIELD_20;
Stream_Write_UINT16(s, glyph_index->x);
orderInfo->fieldFlags |= ORDER_FIELD_21;
Stream_Write_UINT16(s, glyph_index->y);
orderInfo->fieldFlags |= ORDER_FIELD_22;
Stream_Write_UINT8(s, glyph_index->cbData);
Stream_Write(s, glyph_index->data, glyph_index->cbData);
return TRUE;
}
static BOOL update_read_fast_index_order(wStream* s, const ORDER_INFO* orderInfo,
FAST_INDEX_ORDER* fast_index)
{
ORDER_FIELD_BYTE(1, fast_index->cacheId);
ORDER_FIELD_2BYTE(2, fast_index->ulCharInc, fast_index->flAccel);
ORDER_FIELD_COLOR(orderInfo, s, 3, &fast_index->backColor);
ORDER_FIELD_COLOR(orderInfo, s, 4, &fast_index->foreColor);
ORDER_FIELD_COORD(5, fast_index->bkLeft);
ORDER_FIELD_COORD(6, fast_index->bkTop);
ORDER_FIELD_COORD(7, fast_index->bkRight);
ORDER_FIELD_COORD(8, fast_index->bkBottom);
ORDER_FIELD_COORD(9, fast_index->opLeft);
ORDER_FIELD_COORD(10, fast_index->opTop);
ORDER_FIELD_COORD(11, fast_index->opRight);
ORDER_FIELD_COORD(12, fast_index->opBottom);
ORDER_FIELD_COORD(13, fast_index->x);
ORDER_FIELD_COORD(14, fast_index->y);
if (orderInfo->fieldFlags & ORDER_FIELD_15)
{
if (Stream_GetRemainingLength(s) < 1)
return FALSE;
Stream_Read_UINT8(s, fast_index->cbData);
if (Stream_GetRemainingLength(s) < fast_index->cbData)
return FALSE;
CopyMemory(fast_index->data, Stream_Pointer(s), fast_index->cbData);
Stream_Seek(s, fast_index->cbData);
}
return TRUE;
}
static BOOL update_read_fast_glyph_order(wStream* s, const ORDER_INFO* orderInfo,
FAST_GLYPH_ORDER* fastGlyph)
{
GLYPH_DATA_V2* glyph = &fastGlyph->glyphData;
ORDER_FIELD_BYTE(1, fastGlyph->cacheId);
ORDER_FIELD_2BYTE(2, fastGlyph->ulCharInc, fastGlyph->flAccel);
ORDER_FIELD_COLOR(orderInfo, s, 3, &fastGlyph->backColor);
ORDER_FIELD_COLOR(orderInfo, s, 4, &fastGlyph->foreColor);
ORDER_FIELD_COORD(5, fastGlyph->bkLeft);
ORDER_FIELD_COORD(6, fastGlyph->bkTop);
ORDER_FIELD_COORD(7, fastGlyph->bkRight);
ORDER_FIELD_COORD(8, fastGlyph->bkBottom);
ORDER_FIELD_COORD(9, fastGlyph->opLeft);
ORDER_FIELD_COORD(10, fastGlyph->opTop);
ORDER_FIELD_COORD(11, fastGlyph->opRight);
ORDER_FIELD_COORD(12, fastGlyph->opBottom);
ORDER_FIELD_COORD(13, fastGlyph->x);
ORDER_FIELD_COORD(14, fastGlyph->y);
if (orderInfo->fieldFlags & ORDER_FIELD_15)
{
if (Stream_GetRemainingLength(s) < 1)
return FALSE;
Stream_Read_UINT8(s, fastGlyph->cbData);
if (Stream_GetRemainingLength(s) < fastGlyph->cbData)
return FALSE;
CopyMemory(fastGlyph->data, Stream_Pointer(s), fastGlyph->cbData);
if (Stream_GetRemainingLength(s) < fastGlyph->cbData)
return FALSE;
if (!Stream_SafeSeek(s, 1))
return FALSE;
if (fastGlyph->cbData > 1)
{
UINT32 new_cb;
/* parse optional glyph data */
glyph->cacheIndex = fastGlyph->data[0];
if (!update_read_2byte_signed(s, &glyph->x) ||
!update_read_2byte_signed(s, &glyph->y) ||
!update_read_2byte_unsigned(s, &glyph->cx) ||
!update_read_2byte_unsigned(s, &glyph->cy))
return FALSE;
glyph->cb = ((glyph->cx + 7) / 8) * glyph->cy;
glyph->cb += ((glyph->cb % 4) > 0) ? 4 - (glyph->cb % 4) : 0;
new_cb = ((glyph->cx + 7) / 8) * glyph->cy;
new_cb += ((new_cb % 4) > 0) ? 4 - (new_cb % 4) : 0;
if (fastGlyph->cbData < new_cb)
return FALSE;
if (new_cb > 0)
{
BYTE* new_aj;
new_aj = (BYTE*)realloc(glyph->aj, new_cb);
if (!new_aj)
return FALSE;
glyph->aj = new_aj;
glyph->cb = new_cb;
Stream_Read(s, glyph->aj, glyph->cb);
}
Stream_Seek(s, fastGlyph->cbData - new_cb);
}
}
return TRUE;
}
static BOOL update_read_polygon_sc_order(wStream* s, const ORDER_INFO* orderInfo,
POLYGON_SC_ORDER* polygon_sc)
{
UINT32 num = polygon_sc->numPoints;
ORDER_FIELD_COORD(1, polygon_sc->xStart);
ORDER_FIELD_COORD(2, polygon_sc->yStart);
ORDER_FIELD_BYTE(3, polygon_sc->bRop2);
ORDER_FIELD_BYTE(4, polygon_sc->fillMode);
ORDER_FIELD_COLOR(orderInfo, s, 5, &polygon_sc->brushColor);
ORDER_FIELD_BYTE(6, num);
if (orderInfo->fieldFlags & ORDER_FIELD_07)
{
DELTA_POINT* newpoints;
if (num == 0)
return FALSE;
if (Stream_GetRemainingLength(s) < 1)
return FALSE;
Stream_Read_UINT8(s, polygon_sc->cbData);
newpoints = (DELTA_POINT*)realloc(polygon_sc->points, sizeof(DELTA_POINT) * num);
if (!newpoints)
return FALSE;
polygon_sc->points = newpoints;
polygon_sc->numPoints = num;
return update_read_delta_points(s, polygon_sc->points, polygon_sc->numPoints,
polygon_sc->xStart, polygon_sc->yStart);
}
return TRUE;
}
static BOOL update_read_polygon_cb_order(wStream* s, const ORDER_INFO* orderInfo,
POLYGON_CB_ORDER* polygon_cb)
{
UINT32 num = polygon_cb->numPoints;
ORDER_FIELD_COORD(1, polygon_cb->xStart);
ORDER_FIELD_COORD(2, polygon_cb->yStart);
ORDER_FIELD_BYTE(3, polygon_cb->bRop2);
ORDER_FIELD_BYTE(4, polygon_cb->fillMode);
ORDER_FIELD_COLOR(orderInfo, s, 5, &polygon_cb->backColor);
ORDER_FIELD_COLOR(orderInfo, s, 6, &polygon_cb->foreColor);
if (!update_read_brush(s, &polygon_cb->brush, orderInfo->fieldFlags >> 6))
return FALSE;
ORDER_FIELD_BYTE(12, num);
if (orderInfo->fieldFlags & ORDER_FIELD_13)
{
DELTA_POINT* newpoints;
if (num == 0)
return FALSE;
if (Stream_GetRemainingLength(s) < 1)
return FALSE;
Stream_Read_UINT8(s, polygon_cb->cbData);
newpoints = (DELTA_POINT*)realloc(polygon_cb->points, sizeof(DELTA_POINT) * num);
if (!newpoints)
return FALSE;
polygon_cb->points = newpoints;
polygon_cb->numPoints = num;
if (!update_read_delta_points(s, polygon_cb->points, polygon_cb->numPoints,
polygon_cb->xStart, polygon_cb->yStart))
return FALSE;
}
polygon_cb->backMode = (polygon_cb->bRop2 & 0x80) ? BACKMODE_TRANSPARENT : BACKMODE_OPAQUE;
polygon_cb->bRop2 = (polygon_cb->bRop2 & 0x1F);
return TRUE;
}
static BOOL update_read_ellipse_sc_order(wStream* s, const ORDER_INFO* orderInfo,
ELLIPSE_SC_ORDER* ellipse_sc)
{
ORDER_FIELD_COORD(1, ellipse_sc->leftRect);
ORDER_FIELD_COORD(2, ellipse_sc->topRect);
ORDER_FIELD_COORD(3, ellipse_sc->rightRect);
ORDER_FIELD_COORD(4, ellipse_sc->bottomRect);
ORDER_FIELD_BYTE(5, ellipse_sc->bRop2);
ORDER_FIELD_BYTE(6, ellipse_sc->fillMode);
ORDER_FIELD_COLOR(orderInfo, s, 7, &ellipse_sc->color);
return TRUE;
}
static BOOL update_read_ellipse_cb_order(wStream* s, const ORDER_INFO* orderInfo,
ELLIPSE_CB_ORDER* ellipse_cb)
{
ORDER_FIELD_COORD(1, ellipse_cb->leftRect);
ORDER_FIELD_COORD(2, ellipse_cb->topRect);
ORDER_FIELD_COORD(3, ellipse_cb->rightRect);
ORDER_FIELD_COORD(4, ellipse_cb->bottomRect);
ORDER_FIELD_BYTE(5, ellipse_cb->bRop2);
ORDER_FIELD_BYTE(6, ellipse_cb->fillMode);
ORDER_FIELD_COLOR(orderInfo, s, 7, &ellipse_cb->backColor);
ORDER_FIELD_COLOR(orderInfo, s, 8, &ellipse_cb->foreColor);
return update_read_brush(s, &ellipse_cb->brush, orderInfo->fieldFlags >> 8);
}
/* Secondary Drawing Orders */
static CACHE_BITMAP_ORDER* update_read_cache_bitmap_order(rdpUpdate* update, wStream* s,
BOOL compressed, UINT16 flags)
{
CACHE_BITMAP_ORDER* cache_bitmap;
if (!update || !s)
return NULL;
cache_bitmap = calloc(1, sizeof(CACHE_BITMAP_ORDER));
if (!cache_bitmap)
goto fail;
if (Stream_GetRemainingLength(s) < 9)
goto fail;
Stream_Read_UINT8(s, cache_bitmap->cacheId); /* cacheId (1 byte) */
Stream_Seek_UINT8(s); /* pad1Octet (1 byte) */
Stream_Read_UINT8(s, cache_bitmap->bitmapWidth); /* bitmapWidth (1 byte) */
Stream_Read_UINT8(s, cache_bitmap->bitmapHeight); /* bitmapHeight (1 byte) */
Stream_Read_UINT8(s, cache_bitmap->bitmapBpp); /* bitmapBpp (1 byte) */
if ((cache_bitmap->bitmapBpp < 1) || (cache_bitmap->bitmapBpp > 32))
{
WLog_Print(update->log, WLOG_ERROR, "invalid bitmap bpp %" PRIu32 "",
cache_bitmap->bitmapBpp);
goto fail;
}
Stream_Read_UINT16(s, cache_bitmap->bitmapLength); /* bitmapLength (2 bytes) */
Stream_Read_UINT16(s, cache_bitmap->cacheIndex); /* cacheIndex (2 bytes) */
if (compressed)
{
if ((flags & NO_BITMAP_COMPRESSION_HDR) == 0)
{
BYTE* bitmapComprHdr = (BYTE*)&(cache_bitmap->bitmapComprHdr);
if (Stream_GetRemainingLength(s) < 8)
goto fail;
Stream_Read(s, bitmapComprHdr, 8); /* bitmapComprHdr (8 bytes) */
cache_bitmap->bitmapLength -= 8;
}
}
if (cache_bitmap->bitmapLength == 0)
goto fail;
if (Stream_GetRemainingLength(s) < cache_bitmap->bitmapLength)
goto fail;
cache_bitmap->bitmapDataStream = malloc(cache_bitmap->bitmapLength);
if (!cache_bitmap->bitmapDataStream)
goto fail;
Stream_Read(s, cache_bitmap->bitmapDataStream, cache_bitmap->bitmapLength);
cache_bitmap->compressed = compressed;
return cache_bitmap;
fail:
free_cache_bitmap_order(update->context, cache_bitmap);
return NULL;
}
int update_approximate_cache_bitmap_order(const CACHE_BITMAP_ORDER* cache_bitmap, BOOL compressed,
UINT16* flags)
{
return 64 + cache_bitmap->bitmapLength;
}
BOOL update_write_cache_bitmap_order(wStream* s, const CACHE_BITMAP_ORDER* cache_bitmap,
BOOL compressed, UINT16* flags)
{
UINT32 bitmapLength = cache_bitmap->bitmapLength;
int inf = update_approximate_cache_bitmap_order(cache_bitmap, compressed, flags);
if (!Stream_EnsureRemainingCapacity(s, inf))
return FALSE;
*flags = NO_BITMAP_COMPRESSION_HDR;
if ((*flags & NO_BITMAP_COMPRESSION_HDR) == 0)
bitmapLength += 8;
Stream_Write_UINT8(s, cache_bitmap->cacheId); /* cacheId (1 byte) */
Stream_Write_UINT8(s, 0); /* pad1Octet (1 byte) */
Stream_Write_UINT8(s, cache_bitmap->bitmapWidth); /* bitmapWidth (1 byte) */
Stream_Write_UINT8(s, cache_bitmap->bitmapHeight); /* bitmapHeight (1 byte) */
Stream_Write_UINT8(s, cache_bitmap->bitmapBpp); /* bitmapBpp (1 byte) */
Stream_Write_UINT16(s, bitmapLength); /* bitmapLength (2 bytes) */
Stream_Write_UINT16(s, cache_bitmap->cacheIndex); /* cacheIndex (2 bytes) */
if (compressed)
{
if ((*flags & NO_BITMAP_COMPRESSION_HDR) == 0)
{
BYTE* bitmapComprHdr = (BYTE*)&(cache_bitmap->bitmapComprHdr);
Stream_Write(s, bitmapComprHdr, 8); /* bitmapComprHdr (8 bytes) */
bitmapLength -= 8;
}
Stream_Write(s, cache_bitmap->bitmapDataStream, bitmapLength);
}
else
{
Stream_Write(s, cache_bitmap->bitmapDataStream, bitmapLength);
}
return TRUE;
}
static CACHE_BITMAP_V2_ORDER* update_read_cache_bitmap_v2_order(rdpUpdate* update, wStream* s,
BOOL compressed, UINT16 flags)
{
BYTE bitsPerPixelId;
CACHE_BITMAP_V2_ORDER* cache_bitmap_v2;
if (!update || !s)
return NULL;
cache_bitmap_v2 = calloc(1, sizeof(CACHE_BITMAP_V2_ORDER));
if (!cache_bitmap_v2)
goto fail;
cache_bitmap_v2->cacheId = flags & 0x0003;
cache_bitmap_v2->flags = (flags & 0xFF80) >> 7;
bitsPerPixelId = (flags & 0x0078) >> 3;
cache_bitmap_v2->bitmapBpp = CBR2_BPP[bitsPerPixelId];
if (cache_bitmap_v2->flags & CBR2_PERSISTENT_KEY_PRESENT)
{
if (Stream_GetRemainingLength(s) < 8)
goto fail;
Stream_Read_UINT32(s, cache_bitmap_v2->key1); /* key1 (4 bytes) */
Stream_Read_UINT32(s, cache_bitmap_v2->key2); /* key2 (4 bytes) */
}
if (cache_bitmap_v2->flags & CBR2_HEIGHT_SAME_AS_WIDTH)
{
if (!update_read_2byte_unsigned(s, &cache_bitmap_v2->bitmapWidth)) /* bitmapWidth */
goto fail;
cache_bitmap_v2->bitmapHeight = cache_bitmap_v2->bitmapWidth;
}
else
{
if (!update_read_2byte_unsigned(s, &cache_bitmap_v2->bitmapWidth) || /* bitmapWidth */
!update_read_2byte_unsigned(s, &cache_bitmap_v2->bitmapHeight)) /* bitmapHeight */
goto fail;
}
if (!update_read_4byte_unsigned(s, &cache_bitmap_v2->bitmapLength) || /* bitmapLength */
!update_read_2byte_unsigned(s, &cache_bitmap_v2->cacheIndex)) /* cacheIndex */
goto fail;
if (cache_bitmap_v2->flags & CBR2_DO_NOT_CACHE)
cache_bitmap_v2->cacheIndex = BITMAP_CACHE_WAITING_LIST_INDEX;
if (compressed)
{
if (!(cache_bitmap_v2->flags & CBR2_NO_BITMAP_COMPRESSION_HDR))
{
if (Stream_GetRemainingLength(s) < 8)
goto fail;
Stream_Read_UINT16(
s, cache_bitmap_v2->cbCompFirstRowSize); /* cbCompFirstRowSize (2 bytes) */
Stream_Read_UINT16(
s, cache_bitmap_v2->cbCompMainBodySize); /* cbCompMainBodySize (2 bytes) */
Stream_Read_UINT16(s, cache_bitmap_v2->cbScanWidth); /* cbScanWidth (2 bytes) */
Stream_Read_UINT16(
s, cache_bitmap_v2->cbUncompressedSize); /* cbUncompressedSize (2 bytes) */
cache_bitmap_v2->bitmapLength = cache_bitmap_v2->cbCompMainBodySize;
}
}
if (cache_bitmap_v2->bitmapLength == 0)
goto fail;
if (Stream_GetRemainingLength(s) < cache_bitmap_v2->bitmapLength)
goto fail;
if (cache_bitmap_v2->bitmapLength == 0)
goto fail;
cache_bitmap_v2->bitmapDataStream = malloc(cache_bitmap_v2->bitmapLength);
if (!cache_bitmap_v2->bitmapDataStream)
goto fail;
Stream_Read(s, cache_bitmap_v2->bitmapDataStream, cache_bitmap_v2->bitmapLength);
cache_bitmap_v2->compressed = compressed;
return cache_bitmap_v2;
fail:
free_cache_bitmap_v2_order(update->context, cache_bitmap_v2);
return NULL;
}
int update_approximate_cache_bitmap_v2_order(CACHE_BITMAP_V2_ORDER* cache_bitmap_v2,
BOOL compressed, UINT16* flags)
{
return 64 + cache_bitmap_v2->bitmapLength;
}
BOOL update_write_cache_bitmap_v2_order(wStream* s, CACHE_BITMAP_V2_ORDER* cache_bitmap_v2,
BOOL compressed, UINT16* flags)
{
BYTE bitsPerPixelId;
if (!Stream_EnsureRemainingCapacity(
s, update_approximate_cache_bitmap_v2_order(cache_bitmap_v2, compressed, flags)))
return FALSE;
bitsPerPixelId = BPP_CBR2[cache_bitmap_v2->bitmapBpp];
*flags = (cache_bitmap_v2->cacheId & 0x0003) | (bitsPerPixelId << 3) |
((cache_bitmap_v2->flags << 7) & 0xFF80);
if (cache_bitmap_v2->flags & CBR2_PERSISTENT_KEY_PRESENT)
{
Stream_Write_UINT32(s, cache_bitmap_v2->key1); /* key1 (4 bytes) */
Stream_Write_UINT32(s, cache_bitmap_v2->key2); /* key2 (4 bytes) */
}
if (cache_bitmap_v2->flags & CBR2_HEIGHT_SAME_AS_WIDTH)
{
if (!update_write_2byte_unsigned(s, cache_bitmap_v2->bitmapWidth)) /* bitmapWidth */
return FALSE;
}
else
{
if (!update_write_2byte_unsigned(s, cache_bitmap_v2->bitmapWidth) || /* bitmapWidth */
!update_write_2byte_unsigned(s, cache_bitmap_v2->bitmapHeight)) /* bitmapHeight */
return FALSE;
}
if (cache_bitmap_v2->flags & CBR2_DO_NOT_CACHE)
cache_bitmap_v2->cacheIndex = BITMAP_CACHE_WAITING_LIST_INDEX;
if (!update_write_4byte_unsigned(s, cache_bitmap_v2->bitmapLength) || /* bitmapLength */
!update_write_2byte_unsigned(s, cache_bitmap_v2->cacheIndex)) /* cacheIndex */
return FALSE;
if (compressed)
{
if (!(cache_bitmap_v2->flags & CBR2_NO_BITMAP_COMPRESSION_HDR))
{
Stream_Write_UINT16(
s, cache_bitmap_v2->cbCompFirstRowSize); /* cbCompFirstRowSize (2 bytes) */
Stream_Write_UINT16(
s, cache_bitmap_v2->cbCompMainBodySize); /* cbCompMainBodySize (2 bytes) */
Stream_Write_UINT16(s, cache_bitmap_v2->cbScanWidth); /* cbScanWidth (2 bytes) */
Stream_Write_UINT16(
s, cache_bitmap_v2->cbUncompressedSize); /* cbUncompressedSize (2 bytes) */
cache_bitmap_v2->bitmapLength = cache_bitmap_v2->cbCompMainBodySize;
}
if (!Stream_EnsureRemainingCapacity(s, cache_bitmap_v2->bitmapLength))
return FALSE;
Stream_Write(s, cache_bitmap_v2->bitmapDataStream, cache_bitmap_v2->bitmapLength);
}
else
{
if (!Stream_EnsureRemainingCapacity(s, cache_bitmap_v2->bitmapLength))
return FALSE;
Stream_Write(s, cache_bitmap_v2->bitmapDataStream, cache_bitmap_v2->bitmapLength);
}
cache_bitmap_v2->compressed = compressed;
return TRUE;
}
static CACHE_BITMAP_V3_ORDER* update_read_cache_bitmap_v3_order(rdpUpdate* update, wStream* s,
UINT16 flags)
{
BYTE bitsPerPixelId;
BITMAP_DATA_EX* bitmapData;
UINT32 new_len;
BYTE* new_data;
CACHE_BITMAP_V3_ORDER* cache_bitmap_v3;
if (!update || !s)
return NULL;
cache_bitmap_v3 = calloc(1, sizeof(CACHE_BITMAP_V3_ORDER));
if (!cache_bitmap_v3)
goto fail;
cache_bitmap_v3->cacheId = flags & 0x00000003;
cache_bitmap_v3->flags = (flags & 0x0000FF80) >> 7;
bitsPerPixelId = (flags & 0x00000078) >> 3;
cache_bitmap_v3->bpp = CBR23_BPP[bitsPerPixelId];
if (Stream_GetRemainingLength(s) < 21)
goto fail;
Stream_Read_UINT16(s, cache_bitmap_v3->cacheIndex); /* cacheIndex (2 bytes) */
Stream_Read_UINT32(s, cache_bitmap_v3->key1); /* key1 (4 bytes) */
Stream_Read_UINT32(s, cache_bitmap_v3->key2); /* key2 (4 bytes) */
bitmapData = &cache_bitmap_v3->bitmapData;
Stream_Read_UINT8(s, bitmapData->bpp);
if ((bitmapData->bpp < 1) || (bitmapData->bpp > 32))
{
WLog_Print(update->log, WLOG_ERROR, "invalid bpp value %" PRIu32 "", bitmapData->bpp);
goto fail;
}
Stream_Seek_UINT8(s); /* reserved1 (1 byte) */
Stream_Seek_UINT8(s); /* reserved2 (1 byte) */
Stream_Read_UINT8(s, bitmapData->codecID); /* codecID (1 byte) */
Stream_Read_UINT16(s, bitmapData->width); /* width (2 bytes) */
Stream_Read_UINT16(s, bitmapData->height); /* height (2 bytes) */
Stream_Read_UINT32(s, new_len); /* length (4 bytes) */
if ((new_len == 0) || (Stream_GetRemainingLength(s) < new_len))
goto fail;
new_data = (BYTE*)realloc(bitmapData->data, new_len);
if (!new_data)
goto fail;
bitmapData->data = new_data;
bitmapData->length = new_len;
Stream_Read(s, bitmapData->data, bitmapData->length);
return cache_bitmap_v3;
fail:
free_cache_bitmap_v3_order(update->context, cache_bitmap_v3);
return NULL;
}
int update_approximate_cache_bitmap_v3_order(CACHE_BITMAP_V3_ORDER* cache_bitmap_v3, UINT16* flags)
{
BITMAP_DATA_EX* bitmapData = &cache_bitmap_v3->bitmapData;
return 64 + bitmapData->length;
}
BOOL update_write_cache_bitmap_v3_order(wStream* s, CACHE_BITMAP_V3_ORDER* cache_bitmap_v3,
UINT16* flags)
{
BYTE bitsPerPixelId;
BITMAP_DATA_EX* bitmapData;
if (!Stream_EnsureRemainingCapacity(
s, update_approximate_cache_bitmap_v3_order(cache_bitmap_v3, flags)))
return FALSE;
bitmapData = &cache_bitmap_v3->bitmapData;
bitsPerPixelId = BPP_CBR23[cache_bitmap_v3->bpp];
*flags = (cache_bitmap_v3->cacheId & 0x00000003) |
((cache_bitmap_v3->flags << 7) & 0x0000FF80) | ((bitsPerPixelId << 3) & 0x00000078);
Stream_Write_UINT16(s, cache_bitmap_v3->cacheIndex); /* cacheIndex (2 bytes) */
Stream_Write_UINT32(s, cache_bitmap_v3->key1); /* key1 (4 bytes) */
Stream_Write_UINT32(s, cache_bitmap_v3->key2); /* key2 (4 bytes) */
Stream_Write_UINT8(s, bitmapData->bpp);
Stream_Write_UINT8(s, 0); /* reserved1 (1 byte) */
Stream_Write_UINT8(s, 0); /* reserved2 (1 byte) */
Stream_Write_UINT8(s, bitmapData->codecID); /* codecID (1 byte) */
Stream_Write_UINT16(s, bitmapData->width); /* width (2 bytes) */
Stream_Write_UINT16(s, bitmapData->height); /* height (2 bytes) */
Stream_Write_UINT32(s, bitmapData->length); /* length (4 bytes) */
Stream_Write(s, bitmapData->data, bitmapData->length);
return TRUE;
}
static CACHE_COLOR_TABLE_ORDER* update_read_cache_color_table_order(rdpUpdate* update, wStream* s,
UINT16 flags)
{
int i;
UINT32* colorTable;
CACHE_COLOR_TABLE_ORDER* cache_color_table = calloc(1, sizeof(CACHE_COLOR_TABLE_ORDER));
if (!cache_color_table)
goto fail;
if (Stream_GetRemainingLength(s) < 3)
goto fail;
Stream_Read_UINT8(s, cache_color_table->cacheIndex); /* cacheIndex (1 byte) */
Stream_Read_UINT16(s, cache_color_table->numberColors); /* numberColors (2 bytes) */
if (cache_color_table->numberColors != 256)
{
/* This field MUST be set to 256 */
goto fail;
}
if (Stream_GetRemainingLength(s) < cache_color_table->numberColors * 4)
goto fail;
colorTable = (UINT32*)&cache_color_table->colorTable;
for (i = 0; i < (int)cache_color_table->numberColors; i++)
update_read_color_quad(s, &colorTable[i]);
return cache_color_table;
fail:
free_cache_color_table_order(update->context, cache_color_table);
return NULL;
}
int update_approximate_cache_color_table_order(const CACHE_COLOR_TABLE_ORDER* cache_color_table,
UINT16* flags)
{
return 16 + (256 * 4);
}
BOOL update_write_cache_color_table_order(wStream* s,
const CACHE_COLOR_TABLE_ORDER* cache_color_table,
UINT16* flags)
{
int i, inf;
UINT32* colorTable;
if (cache_color_table->numberColors != 256)
return FALSE;
inf = update_approximate_cache_color_table_order(cache_color_table, flags);
if (!Stream_EnsureRemainingCapacity(s, inf))
return FALSE;
Stream_Write_UINT8(s, cache_color_table->cacheIndex); /* cacheIndex (1 byte) */
Stream_Write_UINT16(s, cache_color_table->numberColors); /* numberColors (2 bytes) */
colorTable = (UINT32*)&cache_color_table->colorTable;
for (i = 0; i < (int)cache_color_table->numberColors; i++)
{
update_write_color_quad(s, colorTable[i]);
}
return TRUE;
}
static CACHE_GLYPH_ORDER* update_read_cache_glyph_order(rdpUpdate* update, wStream* s, UINT16 flags)
{
UINT32 i;
CACHE_GLYPH_ORDER* cache_glyph_order = calloc(1, sizeof(CACHE_GLYPH_ORDER));
if (!cache_glyph_order || !update || !s)
goto fail;
if (Stream_GetRemainingLength(s) < 2)
goto fail;
Stream_Read_UINT8(s, cache_glyph_order->cacheId); /* cacheId (1 byte) */
Stream_Read_UINT8(s, cache_glyph_order->cGlyphs); /* cGlyphs (1 byte) */
for (i = 0; i < cache_glyph_order->cGlyphs; i++)
{
GLYPH_DATA* glyph = &cache_glyph_order->glyphData[i];
if (Stream_GetRemainingLength(s) < 10)
goto fail;
Stream_Read_UINT16(s, glyph->cacheIndex);
Stream_Read_INT16(s, glyph->x);
Stream_Read_INT16(s, glyph->y);
Stream_Read_UINT16(s, glyph->cx);
Stream_Read_UINT16(s, glyph->cy);
glyph->cb = ((glyph->cx + 7) / 8) * glyph->cy;
glyph->cb += ((glyph->cb % 4) > 0) ? 4 - (glyph->cb % 4) : 0;
if (Stream_GetRemainingLength(s) < glyph->cb)
goto fail;
glyph->aj = (BYTE*)malloc(glyph->cb);
if (!glyph->aj)
goto fail;
Stream_Read(s, glyph->aj, glyph->cb);
}
if ((flags & CG_GLYPH_UNICODE_PRESENT) && (cache_glyph_order->cGlyphs > 0))
{
cache_glyph_order->unicodeCharacters = calloc(cache_glyph_order->cGlyphs, sizeof(WCHAR));
if (!cache_glyph_order->unicodeCharacters)
goto fail;
if (Stream_GetRemainingLength(s) < sizeof(WCHAR) * cache_glyph_order->cGlyphs)
goto fail;
Stream_Read_UTF16_String(s, cache_glyph_order->unicodeCharacters,
cache_glyph_order->cGlyphs);
}
return cache_glyph_order;
fail:
free_cache_glyph_order(update->context, cache_glyph_order);
return NULL;
}
int update_approximate_cache_glyph_order(const CACHE_GLYPH_ORDER* cache_glyph, UINT16* flags)
{
return 2 + cache_glyph->cGlyphs * 32;
}
BOOL update_write_cache_glyph_order(wStream* s, const CACHE_GLYPH_ORDER* cache_glyph, UINT16* flags)
{
int i, inf;
INT16 lsi16;
const GLYPH_DATA* glyph;
inf = update_approximate_cache_glyph_order(cache_glyph, flags);
if (!Stream_EnsureRemainingCapacity(s, inf))
return FALSE;
Stream_Write_UINT8(s, cache_glyph->cacheId); /* cacheId (1 byte) */
Stream_Write_UINT8(s, cache_glyph->cGlyphs); /* cGlyphs (1 byte) */
for (i = 0; i < (int)cache_glyph->cGlyphs; i++)
{
UINT32 cb;
glyph = &cache_glyph->glyphData[i];
Stream_Write_UINT16(s, glyph->cacheIndex); /* cacheIndex (2 bytes) */
lsi16 = glyph->x;
Stream_Write_UINT16(s, lsi16); /* x (2 bytes) */
lsi16 = glyph->y;
Stream_Write_UINT16(s, lsi16); /* y (2 bytes) */
Stream_Write_UINT16(s, glyph->cx); /* cx (2 bytes) */
Stream_Write_UINT16(s, glyph->cy); /* cy (2 bytes) */
cb = ((glyph->cx + 7) / 8) * glyph->cy;
cb += ((cb % 4) > 0) ? 4 - (cb % 4) : 0;
Stream_Write(s, glyph->aj, cb);
}
if (*flags & CG_GLYPH_UNICODE_PRESENT)
{
Stream_Zero(s, cache_glyph->cGlyphs * 2);
}
return TRUE;
}
static CACHE_GLYPH_V2_ORDER* update_read_cache_glyph_v2_order(rdpUpdate* update, wStream* s,
UINT16 flags)
{
UINT32 i;
CACHE_GLYPH_V2_ORDER* cache_glyph_v2 = calloc(1, sizeof(CACHE_GLYPH_V2_ORDER));
if (!cache_glyph_v2)
goto fail;
cache_glyph_v2->cacheId = (flags & 0x000F);
cache_glyph_v2->flags = (flags & 0x00F0) >> 4;
cache_glyph_v2->cGlyphs = (flags & 0xFF00) >> 8;
for (i = 0; i < cache_glyph_v2->cGlyphs; i++)
{
GLYPH_DATA_V2* glyph = &cache_glyph_v2->glyphData[i];
if (Stream_GetRemainingLength(s) < 1)
goto fail;
Stream_Read_UINT8(s, glyph->cacheIndex);
if (!update_read_2byte_signed(s, &glyph->x) || !update_read_2byte_signed(s, &glyph->y) ||
!update_read_2byte_unsigned(s, &glyph->cx) ||
!update_read_2byte_unsigned(s, &glyph->cy))
{
goto fail;
}
glyph->cb = ((glyph->cx + 7) / 8) * glyph->cy;
glyph->cb += ((glyph->cb % 4) > 0) ? 4 - (glyph->cb % 4) : 0;
if (Stream_GetRemainingLength(s) < glyph->cb)
goto fail;
glyph->aj = (BYTE*)malloc(glyph->cb);
if (!glyph->aj)
goto fail;
Stream_Read(s, glyph->aj, glyph->cb);
}
if ((flags & CG_GLYPH_UNICODE_PRESENT) && (cache_glyph_v2->cGlyphs > 0))
{
cache_glyph_v2->unicodeCharacters = calloc(cache_glyph_v2->cGlyphs, sizeof(WCHAR));
if (!cache_glyph_v2->unicodeCharacters)
goto fail;
if (Stream_GetRemainingLength(s) < sizeof(WCHAR) * cache_glyph_v2->cGlyphs)
goto fail;
Stream_Read_UTF16_String(s, cache_glyph_v2->unicodeCharacters, cache_glyph_v2->cGlyphs);
}
return cache_glyph_v2;
fail:
free_cache_glyph_v2_order(update->context, cache_glyph_v2);
return NULL;
}
int update_approximate_cache_glyph_v2_order(const CACHE_GLYPH_V2_ORDER* cache_glyph_v2,
UINT16* flags)
{
return 8 + cache_glyph_v2->cGlyphs * 32;
}
BOOL update_write_cache_glyph_v2_order(wStream* s, const CACHE_GLYPH_V2_ORDER* cache_glyph_v2,
UINT16* flags)
{
UINT32 i, inf;
inf = update_approximate_cache_glyph_v2_order(cache_glyph_v2, flags);
if (!Stream_EnsureRemainingCapacity(s, inf))
return FALSE;
*flags = (cache_glyph_v2->cacheId & 0x000F) | ((cache_glyph_v2->flags & 0x000F) << 4) |
((cache_glyph_v2->cGlyphs & 0x00FF) << 8);
for (i = 0; i < cache_glyph_v2->cGlyphs; i++)
{
UINT32 cb;
const GLYPH_DATA_V2* glyph = &cache_glyph_v2->glyphData[i];
Stream_Write_UINT8(s, glyph->cacheIndex);
if (!update_write_2byte_signed(s, glyph->x) || !update_write_2byte_signed(s, glyph->y) ||
!update_write_2byte_unsigned(s, glyph->cx) ||
!update_write_2byte_unsigned(s, glyph->cy))
{
return FALSE;
}
cb = ((glyph->cx + 7) / 8) * glyph->cy;
cb += ((cb % 4) > 0) ? 4 - (cb % 4) : 0;
Stream_Write(s, glyph->aj, cb);
}
if (*flags & CG_GLYPH_UNICODE_PRESENT)
{
Stream_Zero(s, cache_glyph_v2->cGlyphs * 2);
}
return TRUE;
}
static BOOL update_decompress_brush(wStream* s, BYTE* output, size_t outSize, BYTE bpp)
{
INT32 x, y, k;
BYTE byte = 0;
const BYTE* palette = Stream_Pointer(s) + 16;
const INT32 bytesPerPixel = ((bpp + 1) / 8);
if (!Stream_SafeSeek(s, 16ULL + 7ULL * bytesPerPixel)) // 64 / 4
return FALSE;
for (y = 7; y >= 0; y--)
{
for (x = 0; x < 8; x++)
{
UINT32 index;
if ((x % 4) == 0)
Stream_Read_UINT8(s, byte);
index = ((byte >> ((3 - (x % 4)) * 2)) & 0x03);
for (k = 0; k < bytesPerPixel; k++)
{
const size_t dstIndex = ((y * 8 + x) * bytesPerPixel) + k;
const size_t srcIndex = (index * bytesPerPixel) + k;
if (dstIndex >= outSize)
return FALSE;
output[dstIndex] = palette[srcIndex];
}
}
}
return TRUE;
}
static BOOL update_compress_brush(wStream* s, const BYTE* input, BYTE bpp)
{
return FALSE;
}
static CACHE_BRUSH_ORDER* update_read_cache_brush_order(rdpUpdate* update, wStream* s, UINT16 flags)
{
int i;
BYTE iBitmapFormat;
BOOL compressed = FALSE;
CACHE_BRUSH_ORDER* cache_brush = calloc(1, sizeof(CACHE_BRUSH_ORDER));
if (!cache_brush)
goto fail;
if (Stream_GetRemainingLength(s) < 6)
goto fail;
Stream_Read_UINT8(s, cache_brush->index); /* cacheEntry (1 byte) */
Stream_Read_UINT8(s, iBitmapFormat); /* iBitmapFormat (1 byte) */
if (iBitmapFormat >= ARRAYSIZE(BMF_BPP))
goto fail;
cache_brush->bpp = BMF_BPP[iBitmapFormat];
Stream_Read_UINT8(s, cache_brush->cx); /* cx (1 byte) */
Stream_Read_UINT8(s, cache_brush->cy); /* cy (1 byte) */
Stream_Read_UINT8(s, cache_brush->style); /* style (1 byte) */
Stream_Read_UINT8(s, cache_brush->length); /* iBytes (1 byte) */
if ((cache_brush->cx == 8) && (cache_brush->cy == 8))
{
if (cache_brush->bpp == 1)
{
if (cache_brush->length != 8)
{
WLog_Print(update->log, WLOG_ERROR, "incompatible 1bpp brush of length:%" PRIu32 "",
cache_brush->length);
goto fail;
}
/* rows are encoded in reverse order */
if (Stream_GetRemainingLength(s) < 8)
goto fail;
for (i = 7; i >= 0; i--)
{
Stream_Read_UINT8(s, cache_brush->data[i]);
}
}
else
{
if ((iBitmapFormat == BMF_8BPP) && (cache_brush->length == 20))
compressed = TRUE;
else if ((iBitmapFormat == BMF_16BPP) && (cache_brush->length == 24))
compressed = TRUE;
else if ((iBitmapFormat == BMF_32BPP) && (cache_brush->length == 32))
compressed = TRUE;
if (compressed != FALSE)
{
/* compressed brush */
if (!update_decompress_brush(s, cache_brush->data, sizeof(cache_brush->data),
cache_brush->bpp))
goto fail;
}
else
{
/* uncompressed brush */
UINT32 scanline = (cache_brush->bpp / 8) * 8;
if (Stream_GetRemainingLength(s) < scanline * 8)
goto fail;
for (i = 7; i >= 0; i--)
{
Stream_Read(s, &cache_brush->data[i * scanline], scanline);
}
}
}
}
return cache_brush;
fail:
free_cache_brush_order(update->context, cache_brush);
return NULL;
}
int update_approximate_cache_brush_order(const CACHE_BRUSH_ORDER* cache_brush, UINT16* flags)
{
return 64;
}
BOOL update_write_cache_brush_order(wStream* s, const CACHE_BRUSH_ORDER* cache_brush, UINT16* flags)
{
int i;
BYTE iBitmapFormat;
BOOL compressed = FALSE;
if (!Stream_EnsureRemainingCapacity(s,
update_approximate_cache_brush_order(cache_brush, flags)))
return FALSE;
iBitmapFormat = BPP_BMF[cache_brush->bpp];
Stream_Write_UINT8(s, cache_brush->index); /* cacheEntry (1 byte) */
Stream_Write_UINT8(s, iBitmapFormat); /* iBitmapFormat (1 byte) */
Stream_Write_UINT8(s, cache_brush->cx); /* cx (1 byte) */
Stream_Write_UINT8(s, cache_brush->cy); /* cy (1 byte) */
Stream_Write_UINT8(s, cache_brush->style); /* style (1 byte) */
Stream_Write_UINT8(s, cache_brush->length); /* iBytes (1 byte) */
if ((cache_brush->cx == 8) && (cache_brush->cy == 8))
{
if (cache_brush->bpp == 1)
{
if (cache_brush->length != 8)
{
WLog_ERR(TAG, "incompatible 1bpp brush of length:%" PRIu32 "", cache_brush->length);
return FALSE;
}
for (i = 7; i >= 0; i--)
{
Stream_Write_UINT8(s, cache_brush->data[i]);
}
}
else
{
if ((iBitmapFormat == BMF_8BPP) && (cache_brush->length == 20))
compressed = TRUE;
else if ((iBitmapFormat == BMF_16BPP) && (cache_brush->length == 24))
compressed = TRUE;
else if ((iBitmapFormat == BMF_32BPP) && (cache_brush->length == 32))
compressed = TRUE;
if (compressed != FALSE)
{
/* compressed brush */
if (!update_compress_brush(s, cache_brush->data, cache_brush->bpp))
return FALSE;
}
else
{
/* uncompressed brush */
int scanline = (cache_brush->bpp / 8) * 8;
for (i = 7; i >= 0; i--)
{
Stream_Write(s, &cache_brush->data[i * scanline], scanline);
}
}
}
}
return TRUE;
}
/* Alternate Secondary Drawing Orders */
static BOOL
update_read_create_offscreen_bitmap_order(wStream* s,
CREATE_OFFSCREEN_BITMAP_ORDER* create_offscreen_bitmap)
{
UINT16 flags;
BOOL deleteListPresent;
OFFSCREEN_DELETE_LIST* deleteList;
if (Stream_GetRemainingLength(s) < 6)
return FALSE;
Stream_Read_UINT16(s, flags); /* flags (2 bytes) */
create_offscreen_bitmap->id = flags & 0x7FFF;
deleteListPresent = (flags & 0x8000) ? TRUE : FALSE;
Stream_Read_UINT16(s, create_offscreen_bitmap->cx); /* cx (2 bytes) */
Stream_Read_UINT16(s, create_offscreen_bitmap->cy); /* cy (2 bytes) */
deleteList = &(create_offscreen_bitmap->deleteList);
if (deleteListPresent)
{
UINT32 i;
if (Stream_GetRemainingLength(s) < 2)
return FALSE;
Stream_Read_UINT16(s, deleteList->cIndices);
if (deleteList->cIndices > deleteList->sIndices)
{
UINT16* new_indices;
new_indices = (UINT16*)realloc(deleteList->indices, deleteList->cIndices * 2);
if (!new_indices)
return FALSE;
deleteList->sIndices = deleteList->cIndices;
deleteList->indices = new_indices;
}
if (Stream_GetRemainingLength(s) < 2 * deleteList->cIndices)
return FALSE;
for (i = 0; i < deleteList->cIndices; i++)
{
Stream_Read_UINT16(s, deleteList->indices[i]);
}
}
else
{
deleteList->cIndices = 0;
}
return TRUE;
}
int update_approximate_create_offscreen_bitmap_order(
const CREATE_OFFSCREEN_BITMAP_ORDER* create_offscreen_bitmap)
{
const OFFSCREEN_DELETE_LIST* deleteList = &(create_offscreen_bitmap->deleteList);
return 32 + deleteList->cIndices * 2;
}
BOOL update_write_create_offscreen_bitmap_order(
wStream* s, const CREATE_OFFSCREEN_BITMAP_ORDER* create_offscreen_bitmap)
{
UINT16 flags;
BOOL deleteListPresent;
const OFFSCREEN_DELETE_LIST* deleteList;
if (!Stream_EnsureRemainingCapacity(
s, update_approximate_create_offscreen_bitmap_order(create_offscreen_bitmap)))
return FALSE;
deleteList = &(create_offscreen_bitmap->deleteList);
flags = create_offscreen_bitmap->id & 0x7FFF;
deleteListPresent = (deleteList->cIndices > 0) ? TRUE : FALSE;
if (deleteListPresent)
flags |= 0x8000;
Stream_Write_UINT16(s, flags); /* flags (2 bytes) */
Stream_Write_UINT16(s, create_offscreen_bitmap->cx); /* cx (2 bytes) */
Stream_Write_UINT16(s, create_offscreen_bitmap->cy); /* cy (2 bytes) */
if (deleteListPresent)
{
int i;
Stream_Write_UINT16(s, deleteList->cIndices);
for (i = 0; i < (int)deleteList->cIndices; i++)
{
Stream_Write_UINT16(s, deleteList->indices[i]);
}
}
return TRUE;
}
static BOOL update_read_switch_surface_order(wStream* s, SWITCH_SURFACE_ORDER* switch_surface)
{
if (Stream_GetRemainingLength(s) < 2)
return FALSE;
Stream_Read_UINT16(s, switch_surface->bitmapId); /* bitmapId (2 bytes) */
return TRUE;
}
int update_approximate_switch_surface_order(const SWITCH_SURFACE_ORDER* switch_surface)
{
return 2;
}
BOOL update_write_switch_surface_order(wStream* s, const SWITCH_SURFACE_ORDER* switch_surface)
{
int inf = update_approximate_switch_surface_order(switch_surface);
if (!Stream_EnsureRemainingCapacity(s, inf))
return FALSE;
Stream_Write_UINT16(s, switch_surface->bitmapId); /* bitmapId (2 bytes) */
return TRUE;
}
static BOOL
update_read_create_nine_grid_bitmap_order(wStream* s,
CREATE_NINE_GRID_BITMAP_ORDER* create_nine_grid_bitmap)
{
NINE_GRID_BITMAP_INFO* nineGridInfo;
if (Stream_GetRemainingLength(s) < 19)
return FALSE;
Stream_Read_UINT8(s, create_nine_grid_bitmap->bitmapBpp); /* bitmapBpp (1 byte) */
if ((create_nine_grid_bitmap->bitmapBpp < 1) || (create_nine_grid_bitmap->bitmapBpp > 32))
{
WLog_ERR(TAG, "invalid bpp value %" PRIu32 "", create_nine_grid_bitmap->bitmapBpp);
return FALSE;
}
Stream_Read_UINT16(s, create_nine_grid_bitmap->bitmapId); /* bitmapId (2 bytes) */
nineGridInfo = &(create_nine_grid_bitmap->nineGridInfo);
Stream_Read_UINT32(s, nineGridInfo->flFlags); /* flFlags (4 bytes) */
Stream_Read_UINT16(s, nineGridInfo->ulLeftWidth); /* ulLeftWidth (2 bytes) */
Stream_Read_UINT16(s, nineGridInfo->ulRightWidth); /* ulRightWidth (2 bytes) */
Stream_Read_UINT16(s, nineGridInfo->ulTopHeight); /* ulTopHeight (2 bytes) */
Stream_Read_UINT16(s, nineGridInfo->ulBottomHeight); /* ulBottomHeight (2 bytes) */
update_read_colorref(s, &nineGridInfo->crTransparent); /* crTransparent (4 bytes) */
return TRUE;
}
static BOOL update_read_frame_marker_order(wStream* s, FRAME_MARKER_ORDER* frame_marker)
{
if (Stream_GetRemainingLength(s) < 4)
return FALSE;
Stream_Read_UINT32(s, frame_marker->action); /* action (4 bytes) */
return TRUE;
}
static BOOL update_read_stream_bitmap_first_order(wStream* s,
STREAM_BITMAP_FIRST_ORDER* stream_bitmap_first)
{
if (Stream_GetRemainingLength(s) < 10) // 8 + 2 at least
return FALSE;
Stream_Read_UINT8(s, stream_bitmap_first->bitmapFlags); /* bitmapFlags (1 byte) */
Stream_Read_UINT8(s, stream_bitmap_first->bitmapBpp); /* bitmapBpp (1 byte) */
if ((stream_bitmap_first->bitmapBpp < 1) || (stream_bitmap_first->bitmapBpp > 32))
{
WLog_ERR(TAG, "invalid bpp value %" PRIu32 "", stream_bitmap_first->bitmapBpp);
return FALSE;
}
Stream_Read_UINT16(s, stream_bitmap_first->bitmapType); /* bitmapType (2 bytes) */
Stream_Read_UINT16(s, stream_bitmap_first->bitmapWidth); /* bitmapWidth (2 bytes) */
Stream_Read_UINT16(s, stream_bitmap_first->bitmapHeight); /* bitmapHeigth (2 bytes) */
if (stream_bitmap_first->bitmapFlags & STREAM_BITMAP_V2)
{
if (Stream_GetRemainingLength(s) < 4)
return FALSE;
Stream_Read_UINT32(s, stream_bitmap_first->bitmapSize); /* bitmapSize (4 bytes) */
}
else
{
if (Stream_GetRemainingLength(s) < 2)
return FALSE;
Stream_Read_UINT16(s, stream_bitmap_first->bitmapSize); /* bitmapSize (2 bytes) */
}
FIELD_SKIP_BUFFER16(
s, stream_bitmap_first->bitmapBlockSize); /* bitmapBlockSize(2 bytes) + bitmapBlock */
return TRUE;
}
static BOOL update_read_stream_bitmap_next_order(wStream* s,
STREAM_BITMAP_NEXT_ORDER* stream_bitmap_next)
{
if (Stream_GetRemainingLength(s) < 5)
return FALSE;
Stream_Read_UINT8(s, stream_bitmap_next->bitmapFlags); /* bitmapFlags (1 byte) */
Stream_Read_UINT16(s, stream_bitmap_next->bitmapType); /* bitmapType (2 bytes) */
FIELD_SKIP_BUFFER16(
s, stream_bitmap_next->bitmapBlockSize); /* bitmapBlockSize(2 bytes) + bitmapBlock */
return TRUE;
}
static BOOL update_read_draw_gdiplus_first_order(wStream* s,
DRAW_GDIPLUS_FIRST_ORDER* draw_gdiplus_first)
{
if (Stream_GetRemainingLength(s) < 11)
return FALSE;
Stream_Seek_UINT8(s); /* pad1Octet (1 byte) */
Stream_Read_UINT16(s, draw_gdiplus_first->cbSize); /* cbSize (2 bytes) */
Stream_Read_UINT32(s, draw_gdiplus_first->cbTotalSize); /* cbTotalSize (4 bytes) */
Stream_Read_UINT32(s, draw_gdiplus_first->cbTotalEmfSize); /* cbTotalEmfSize (4 bytes) */
return Stream_SafeSeek(s, draw_gdiplus_first->cbSize); /* emfRecords */
}
static BOOL update_read_draw_gdiplus_next_order(wStream* s,
DRAW_GDIPLUS_NEXT_ORDER* draw_gdiplus_next)
{
if (Stream_GetRemainingLength(s) < 3)
return FALSE;
Stream_Seek_UINT8(s); /* pad1Octet (1 byte) */
FIELD_SKIP_BUFFER16(s, draw_gdiplus_next->cbSize); /* cbSize(2 bytes) + emfRecords */
return TRUE;
}
static BOOL update_read_draw_gdiplus_end_order(wStream* s, DRAW_GDIPLUS_END_ORDER* draw_gdiplus_end)
{
if (Stream_GetRemainingLength(s) < 11)
return FALSE;
Stream_Seek_UINT8(s); /* pad1Octet (1 byte) */
Stream_Read_UINT16(s, draw_gdiplus_end->cbSize); /* cbSize (2 bytes) */
Stream_Read_UINT32(s, draw_gdiplus_end->cbTotalSize); /* cbTotalSize (4 bytes) */
Stream_Read_UINT32(s, draw_gdiplus_end->cbTotalEmfSize); /* cbTotalEmfSize (4 bytes) */
return Stream_SafeSeek(s, draw_gdiplus_end->cbSize); /* emfRecords */
}
static BOOL
update_read_draw_gdiplus_cache_first_order(wStream* s,
DRAW_GDIPLUS_CACHE_FIRST_ORDER* draw_gdiplus_cache_first)
{
if (Stream_GetRemainingLength(s) < 11)
return FALSE;
Stream_Read_UINT8(s, draw_gdiplus_cache_first->flags); /* flags (1 byte) */
Stream_Read_UINT16(s, draw_gdiplus_cache_first->cacheType); /* cacheType (2 bytes) */
Stream_Read_UINT16(s, draw_gdiplus_cache_first->cacheIndex); /* cacheIndex (2 bytes) */
Stream_Read_UINT16(s, draw_gdiplus_cache_first->cbSize); /* cbSize (2 bytes) */
Stream_Read_UINT32(s, draw_gdiplus_cache_first->cbTotalSize); /* cbTotalSize (4 bytes) */
return Stream_SafeSeek(s, draw_gdiplus_cache_first->cbSize); /* emfRecords */
}
static BOOL
update_read_draw_gdiplus_cache_next_order(wStream* s,
DRAW_GDIPLUS_CACHE_NEXT_ORDER* draw_gdiplus_cache_next)
{
if (Stream_GetRemainingLength(s) < 7)
return FALSE;
Stream_Read_UINT8(s, draw_gdiplus_cache_next->flags); /* flags (1 byte) */
Stream_Read_UINT16(s, draw_gdiplus_cache_next->cacheType); /* cacheType (2 bytes) */
Stream_Read_UINT16(s, draw_gdiplus_cache_next->cacheIndex); /* cacheIndex (2 bytes) */
FIELD_SKIP_BUFFER16(s, draw_gdiplus_cache_next->cbSize); /* cbSize(2 bytes) + emfRecords */
return TRUE;
}
static BOOL
update_read_draw_gdiplus_cache_end_order(wStream* s,
DRAW_GDIPLUS_CACHE_END_ORDER* draw_gdiplus_cache_end)
{
if (Stream_GetRemainingLength(s) < 11)
return FALSE;
Stream_Read_UINT8(s, draw_gdiplus_cache_end->flags); /* flags (1 byte) */
Stream_Read_UINT16(s, draw_gdiplus_cache_end->cacheType); /* cacheType (2 bytes) */
Stream_Read_UINT16(s, draw_gdiplus_cache_end->cacheIndex); /* cacheIndex (2 bytes) */
Stream_Read_UINT16(s, draw_gdiplus_cache_end->cbSize); /* cbSize (2 bytes) */
Stream_Read_UINT32(s, draw_gdiplus_cache_end->cbTotalSize); /* cbTotalSize (4 bytes) */
return Stream_SafeSeek(s, draw_gdiplus_cache_end->cbSize); /* emfRecords */
}
static BOOL update_read_field_flags(wStream* s, UINT32* fieldFlags, BYTE flags, BYTE fieldBytes)
{
int i;
BYTE byte;
if (flags & ORDER_ZERO_FIELD_BYTE_BIT0)
fieldBytes--;
if (flags & ORDER_ZERO_FIELD_BYTE_BIT1)
{
if (fieldBytes > 1)
fieldBytes -= 2;
else
fieldBytes = 0;
}
if (Stream_GetRemainingLength(s) < fieldBytes)
return FALSE;
*fieldFlags = 0;
for (i = 0; i < fieldBytes; i++)
{
Stream_Read_UINT8(s, byte);
*fieldFlags |= byte << (i * 8);
}
return TRUE;
}
BOOL update_write_field_flags(wStream* s, UINT32 fieldFlags, BYTE flags, BYTE fieldBytes)
{
BYTE byte;
if (fieldBytes == 1)
{
byte = fieldFlags & 0xFF;
Stream_Write_UINT8(s, byte);
}
else if (fieldBytes == 2)
{
byte = fieldFlags & 0xFF;
Stream_Write_UINT8(s, byte);
byte = (fieldFlags >> 8) & 0xFF;
Stream_Write_UINT8(s, byte);
}
else if (fieldBytes == 3)
{
byte = fieldFlags & 0xFF;
Stream_Write_UINT8(s, byte);
byte = (fieldFlags >> 8) & 0xFF;
Stream_Write_UINT8(s, byte);
byte = (fieldFlags >> 16) & 0xFF;
Stream_Write_UINT8(s, byte);
}
else
{
return FALSE;
}
return TRUE;
}
static BOOL update_read_bounds(wStream* s, rdpBounds* bounds)
{
BYTE flags;
if (Stream_GetRemainingLength(s) < 1)
return FALSE;
Stream_Read_UINT8(s, flags); /* field flags */
if (flags & BOUND_LEFT)
{
if (!update_read_coord(s, &bounds->left, FALSE))
return FALSE;
}
else if (flags & BOUND_DELTA_LEFT)
{
if (!update_read_coord(s, &bounds->left, TRUE))
return FALSE;
}
if (flags & BOUND_TOP)
{
if (!update_read_coord(s, &bounds->top, FALSE))
return FALSE;
}
else if (flags & BOUND_DELTA_TOP)
{
if (!update_read_coord(s, &bounds->top, TRUE))
return FALSE;
}
if (flags & BOUND_RIGHT)
{
if (!update_read_coord(s, &bounds->right, FALSE))
return FALSE;
}
else if (flags & BOUND_DELTA_RIGHT)
{
if (!update_read_coord(s, &bounds->right, TRUE))
return FALSE;
}
if (flags & BOUND_BOTTOM)
{
if (!update_read_coord(s, &bounds->bottom, FALSE))
return FALSE;
}
else if (flags & BOUND_DELTA_BOTTOM)
{
if (!update_read_coord(s, &bounds->bottom, TRUE))
return FALSE;
}
return TRUE;
}
BOOL update_write_bounds(wStream* s, ORDER_INFO* orderInfo)
{
if (!(orderInfo->controlFlags & ORDER_BOUNDS))
return TRUE;
if (orderInfo->controlFlags & ORDER_ZERO_BOUNDS_DELTAS)
return TRUE;
Stream_Write_UINT8(s, orderInfo->boundsFlags); /* field flags */
if (orderInfo->boundsFlags & BOUND_LEFT)
{
if (!update_write_coord(s, orderInfo->bounds.left))
return FALSE;
}
else if (orderInfo->boundsFlags & BOUND_DELTA_LEFT)
{
}
if (orderInfo->boundsFlags & BOUND_TOP)
{
if (!update_write_coord(s, orderInfo->bounds.top))
return FALSE;
}
else if (orderInfo->boundsFlags & BOUND_DELTA_TOP)
{
}
if (orderInfo->boundsFlags & BOUND_RIGHT)
{
if (!update_write_coord(s, orderInfo->bounds.right))
return FALSE;
}
else if (orderInfo->boundsFlags & BOUND_DELTA_RIGHT)
{
}
if (orderInfo->boundsFlags & BOUND_BOTTOM)
{
if (!update_write_coord(s, orderInfo->bounds.bottom))
return FALSE;
}
else if (orderInfo->boundsFlags & BOUND_DELTA_BOTTOM)
{
}
return TRUE;
}
static BOOL read_primary_order(wLog* log, const char* orderName, wStream* s,
const ORDER_INFO* orderInfo, rdpPrimaryUpdate* primary)
{
BOOL rc = FALSE;
if (!s || !orderInfo || !primary || !orderName)
return FALSE;
switch (orderInfo->orderType)
{
case ORDER_TYPE_DSTBLT:
rc = update_read_dstblt_order(s, orderInfo, &(primary->dstblt));
break;
case ORDER_TYPE_PATBLT:
rc = update_read_patblt_order(s, orderInfo, &(primary->patblt));
break;
case ORDER_TYPE_SCRBLT:
rc = update_read_scrblt_order(s, orderInfo, &(primary->scrblt));
break;
case ORDER_TYPE_OPAQUE_RECT:
rc = update_read_opaque_rect_order(s, orderInfo, &(primary->opaque_rect));
break;
case ORDER_TYPE_DRAW_NINE_GRID:
rc = update_read_draw_nine_grid_order(s, orderInfo, &(primary->draw_nine_grid));
break;
case ORDER_TYPE_MULTI_DSTBLT:
rc = update_read_multi_dstblt_order(s, orderInfo, &(primary->multi_dstblt));
break;
case ORDER_TYPE_MULTI_PATBLT:
rc = update_read_multi_patblt_order(s, orderInfo, &(primary->multi_patblt));
break;
case ORDER_TYPE_MULTI_SCRBLT:
rc = update_read_multi_scrblt_order(s, orderInfo, &(primary->multi_scrblt));
break;
case ORDER_TYPE_MULTI_OPAQUE_RECT:
rc = update_read_multi_opaque_rect_order(s, orderInfo, &(primary->multi_opaque_rect));
break;
case ORDER_TYPE_MULTI_DRAW_NINE_GRID:
rc = update_read_multi_draw_nine_grid_order(s, orderInfo,
&(primary->multi_draw_nine_grid));
break;
case ORDER_TYPE_LINE_TO:
rc = update_read_line_to_order(s, orderInfo, &(primary->line_to));
break;
case ORDER_TYPE_POLYLINE:
rc = update_read_polyline_order(s, orderInfo, &(primary->polyline));
break;
case ORDER_TYPE_MEMBLT:
rc = update_read_memblt_order(s, orderInfo, &(primary->memblt));
break;
case ORDER_TYPE_MEM3BLT:
rc = update_read_mem3blt_order(s, orderInfo, &(primary->mem3blt));
break;
case ORDER_TYPE_SAVE_BITMAP:
rc = update_read_save_bitmap_order(s, orderInfo, &(primary->save_bitmap));
break;
case ORDER_TYPE_GLYPH_INDEX:
rc = update_read_glyph_index_order(s, orderInfo, &(primary->glyph_index));
break;
case ORDER_TYPE_FAST_INDEX:
rc = update_read_fast_index_order(s, orderInfo, &(primary->fast_index));
break;
case ORDER_TYPE_FAST_GLYPH:
rc = update_read_fast_glyph_order(s, orderInfo, &(primary->fast_glyph));
break;
case ORDER_TYPE_POLYGON_SC:
rc = update_read_polygon_sc_order(s, orderInfo, &(primary->polygon_sc));
break;
case ORDER_TYPE_POLYGON_CB:
rc = update_read_polygon_cb_order(s, orderInfo, &(primary->polygon_cb));
break;
case ORDER_TYPE_ELLIPSE_SC:
rc = update_read_ellipse_sc_order(s, orderInfo, &(primary->ellipse_sc));
break;
case ORDER_TYPE_ELLIPSE_CB:
rc = update_read_ellipse_cb_order(s, orderInfo, &(primary->ellipse_cb));
break;
default:
WLog_Print(log, WLOG_WARN, "Primary Drawing Order %s not supported, ignoring",
orderName);
rc = TRUE;
break;
}
if (!rc)
{
WLog_Print(log, WLOG_ERROR, "%s - update_read_dstblt_order() failed", orderName);
return FALSE;
}
return TRUE;
}
static BOOL update_recv_primary_order(rdpUpdate* update, wStream* s, BYTE flags)
{
BYTE field;
BOOL rc = FALSE;
rdpContext* context = update->context;
rdpPrimaryUpdate* primary = update->primary;
ORDER_INFO* orderInfo = &(primary->order_info);
rdpSettings* settings = context->settings;
const char* orderName;
if (flags & ORDER_TYPE_CHANGE)
{
if (Stream_GetRemainingLength(s) < 1)
{
WLog_Print(update->log, WLOG_ERROR, "Stream_GetRemainingLength(s) < 1");
return FALSE;
}
Stream_Read_UINT8(s, orderInfo->orderType); /* orderType (1 byte) */
}
orderName = primary_order_string(orderInfo->orderType);
if (!check_primary_order_supported(update->log, settings, orderInfo->orderType, orderName))
return FALSE;
field = get_primary_drawing_order_field_bytes(orderInfo->orderType, &rc);
if (!rc)
return FALSE;
if (!update_read_field_flags(s, &(orderInfo->fieldFlags), flags, field))
{
WLog_Print(update->log, WLOG_ERROR, "update_read_field_flags() failed");
return FALSE;
}
if (flags & ORDER_BOUNDS)
{
if (!(flags & ORDER_ZERO_BOUNDS_DELTAS))
{
if (!update_read_bounds(s, &orderInfo->bounds))
{
WLog_Print(update->log, WLOG_ERROR, "update_read_bounds() failed");
return FALSE;
}
}
rc = IFCALLRESULT(FALSE, update->SetBounds, context, &orderInfo->bounds);
if (!rc)
return FALSE;
}
orderInfo->deltaCoordinates = (flags & ORDER_DELTA_COORDINATES) ? TRUE : FALSE;
if (!read_primary_order(update->log, orderName, s, orderInfo, primary))
return FALSE;
switch (orderInfo->orderType)
{
case ORDER_TYPE_DSTBLT:
{
WLog_Print(update->log, WLOG_DEBUG, "Primary Drawing Order %s rop=%s [0x%08" PRIx32 "]",
orderName, gdi_rop3_code_string(primary->dstblt.bRop),
gdi_rop3_code(primary->dstblt.bRop));
rc = IFCALLRESULT(FALSE, primary->DstBlt, context, &primary->dstblt);
}
break;
case ORDER_TYPE_PATBLT:
{
WLog_Print(update->log, WLOG_DEBUG, "Primary Drawing Order %s rop=%s [0x%08" PRIx32 "]",
orderName, gdi_rop3_code_string(primary->patblt.bRop),
gdi_rop3_code(primary->patblt.bRop));
rc = IFCALLRESULT(FALSE, primary->PatBlt, context, &primary->patblt);
}
break;
case ORDER_TYPE_SCRBLT:
{
WLog_Print(update->log, WLOG_DEBUG, "Primary Drawing Order %s rop=%s [0x%08" PRIx32 "]",
orderName, gdi_rop3_code_string(primary->scrblt.bRop),
gdi_rop3_code(primary->scrblt.bRop));
rc = IFCALLRESULT(FALSE, primary->ScrBlt, context, &primary->scrblt);
}
break;
case ORDER_TYPE_OPAQUE_RECT:
{
WLog_Print(update->log, WLOG_DEBUG, "Primary Drawing Order %s", orderName);
rc = IFCALLRESULT(FALSE, primary->OpaqueRect, context, &primary->opaque_rect);
}
break;
case ORDER_TYPE_DRAW_NINE_GRID:
{
WLog_Print(update->log, WLOG_DEBUG, "Primary Drawing Order %s", orderName);
rc = IFCALLRESULT(FALSE, primary->DrawNineGrid, context, &primary->draw_nine_grid);
}
break;
case ORDER_TYPE_MULTI_DSTBLT:
{
WLog_Print(update->log, WLOG_DEBUG, "Primary Drawing Order %s rop=%s [0x%08" PRIx32 "]",
orderName, gdi_rop3_code_string(primary->multi_dstblt.bRop),
gdi_rop3_code(primary->multi_dstblt.bRop));
rc = IFCALLRESULT(FALSE, primary->MultiDstBlt, context, &primary->multi_dstblt);
}
break;
case ORDER_TYPE_MULTI_PATBLT:
{
WLog_Print(update->log, WLOG_DEBUG, "Primary Drawing Order %s rop=%s [0x%08" PRIx32 "]",
orderName, gdi_rop3_code_string(primary->multi_patblt.bRop),
gdi_rop3_code(primary->multi_patblt.bRop));
rc = IFCALLRESULT(FALSE, primary->MultiPatBlt, context, &primary->multi_patblt);
}
break;
case ORDER_TYPE_MULTI_SCRBLT:
{
WLog_Print(update->log, WLOG_DEBUG, "Primary Drawing Order %s rop=%s [0x%08" PRIx32 "]",
orderName, gdi_rop3_code_string(primary->multi_scrblt.bRop),
gdi_rop3_code(primary->multi_scrblt.bRop));
rc = IFCALLRESULT(FALSE, primary->MultiScrBlt, context, &primary->multi_scrblt);
}
break;
case ORDER_TYPE_MULTI_OPAQUE_RECT:
{
WLog_Print(update->log, WLOG_DEBUG, "Primary Drawing Order %s", orderName);
rc =
IFCALLRESULT(FALSE, primary->MultiOpaqueRect, context, &primary->multi_opaque_rect);
}
break;
case ORDER_TYPE_MULTI_DRAW_NINE_GRID:
{
WLog_Print(update->log, WLOG_DEBUG, "Primary Drawing Order %s", orderName);
rc = IFCALLRESULT(FALSE, primary->MultiDrawNineGrid, context,
&primary->multi_draw_nine_grid);
}
break;
case ORDER_TYPE_LINE_TO:
{
WLog_Print(update->log, WLOG_DEBUG, "Primary Drawing Order %s", orderName);
rc = IFCALLRESULT(FALSE, primary->LineTo, context, &primary->line_to);
}
break;
case ORDER_TYPE_POLYLINE:
{
WLog_Print(update->log, WLOG_DEBUG, "Primary Drawing Order %s", orderName);
rc = IFCALLRESULT(FALSE, primary->Polyline, context, &primary->polyline);
}
break;
case ORDER_TYPE_MEMBLT:
{
WLog_Print(update->log, WLOG_DEBUG, "Primary Drawing Order %s rop=%s [0x%08" PRIx32 "]",
orderName, gdi_rop3_code_string(primary->memblt.bRop),
gdi_rop3_code(primary->memblt.bRop));
rc = IFCALLRESULT(FALSE, primary->MemBlt, context, &primary->memblt);
}
break;
case ORDER_TYPE_MEM3BLT:
{
WLog_Print(update->log, WLOG_DEBUG, "Primary Drawing Order %s rop=%s [0x%08" PRIx32 "]",
orderName, gdi_rop3_code_string(primary->mem3blt.bRop),
gdi_rop3_code(primary->mem3blt.bRop));
rc = IFCALLRESULT(FALSE, primary->Mem3Blt, context, &primary->mem3blt);
}
break;
case ORDER_TYPE_SAVE_BITMAP:
{
WLog_Print(update->log, WLOG_DEBUG, "Primary Drawing Order %s", orderName);
rc = IFCALLRESULT(FALSE, primary->SaveBitmap, context, &primary->save_bitmap);
}
break;
case ORDER_TYPE_GLYPH_INDEX:
{
WLog_Print(update->log, WLOG_DEBUG, "Primary Drawing Order %s", orderName);
rc = IFCALLRESULT(FALSE, primary->GlyphIndex, context, &primary->glyph_index);
}
break;
case ORDER_TYPE_FAST_INDEX:
{
WLog_Print(update->log, WLOG_DEBUG, "Primary Drawing Order %s", orderName);
rc = IFCALLRESULT(FALSE, primary->FastIndex, context, &primary->fast_index);
}
break;
case ORDER_TYPE_FAST_GLYPH:
{
WLog_Print(update->log, WLOG_DEBUG, "Primary Drawing Order %s", orderName);
rc = IFCALLRESULT(FALSE, primary->FastGlyph, context, &primary->fast_glyph);
}
break;
case ORDER_TYPE_POLYGON_SC:
{
WLog_Print(update->log, WLOG_DEBUG, "Primary Drawing Order %s", orderName);
rc = IFCALLRESULT(FALSE, primary->PolygonSC, context, &primary->polygon_sc);
}
break;
case ORDER_TYPE_POLYGON_CB:
{
WLog_Print(update->log, WLOG_DEBUG, "Primary Drawing Order %s", orderName);
rc = IFCALLRESULT(FALSE, primary->PolygonCB, context, &primary->polygon_cb);
}
break;
case ORDER_TYPE_ELLIPSE_SC:
{
WLog_Print(update->log, WLOG_DEBUG, "Primary Drawing Order %s", orderName);
rc = IFCALLRESULT(FALSE, primary->EllipseSC, context, &primary->ellipse_sc);
}
break;
case ORDER_TYPE_ELLIPSE_CB:
{
WLog_Print(update->log, WLOG_DEBUG, "Primary Drawing Order %s", orderName);
rc = IFCALLRESULT(FALSE, primary->EllipseCB, context, &primary->ellipse_cb);
}
break;
default:
WLog_Print(update->log, WLOG_WARN, "Primary Drawing Order %s not supported", orderName);
break;
}
if (!rc)
{
WLog_Print(update->log, WLOG_WARN, "Primary Drawing Order %s failed", orderName);
return FALSE;
}
if (flags & ORDER_BOUNDS)
{
rc = IFCALLRESULT(FALSE, update->SetBounds, context, NULL);
}
return rc;
}
static BOOL update_recv_secondary_order(rdpUpdate* update, wStream* s, BYTE flags)
{
BOOL rc = FALSE;
size_t start, end, diff;
BYTE orderType;
UINT16 extraFlags;
UINT16 orderLength;
rdpContext* context = update->context;
rdpSettings* settings = context->settings;
rdpSecondaryUpdate* secondary = update->secondary;
const char* name;
if (Stream_GetRemainingLength(s) < 5)
{
WLog_Print(update->log, WLOG_ERROR, "Stream_GetRemainingLength(s) < 5");
return FALSE;
}
Stream_Read_UINT16(s, orderLength); /* orderLength (2 bytes) */
Stream_Read_UINT16(s, extraFlags); /* extraFlags (2 bytes) */
Stream_Read_UINT8(s, orderType); /* orderType (1 byte) */
if (Stream_GetRemainingLength(s) < orderLength + 7U)
{
WLog_Print(update->log, WLOG_ERROR, "Stream_GetRemainingLength(s) %" PRIuz " < %" PRIu16,
Stream_GetRemainingLength(s), orderLength + 7);
return FALSE;
}
start = Stream_GetPosition(s);
name = secondary_order_string(orderType);
WLog_Print(update->log, WLOG_DEBUG, "Secondary Drawing Order %s", name);
if (!check_secondary_order_supported(update->log, settings, orderType, name))
return FALSE;
switch (orderType)
{
case ORDER_TYPE_BITMAP_UNCOMPRESSED:
case ORDER_TYPE_CACHE_BITMAP_COMPRESSED:
{
const BOOL compressed = (orderType == ORDER_TYPE_CACHE_BITMAP_COMPRESSED);
CACHE_BITMAP_ORDER* order =
update_read_cache_bitmap_order(update, s, compressed, extraFlags);
if (order)
{
rc = IFCALLRESULT(FALSE, secondary->CacheBitmap, context, order);
free_cache_bitmap_order(context, order);
}
}
break;
case ORDER_TYPE_BITMAP_UNCOMPRESSED_V2:
case ORDER_TYPE_BITMAP_COMPRESSED_V2:
{
const BOOL compressed = (orderType == ORDER_TYPE_BITMAP_COMPRESSED_V2);
CACHE_BITMAP_V2_ORDER* order =
update_read_cache_bitmap_v2_order(update, s, compressed, extraFlags);
if (order)
{
rc = IFCALLRESULT(FALSE, secondary->CacheBitmapV2, context, order);
free_cache_bitmap_v2_order(context, order);
}
}
break;
case ORDER_TYPE_BITMAP_COMPRESSED_V3:
{
CACHE_BITMAP_V3_ORDER* order = update_read_cache_bitmap_v3_order(update, s, extraFlags);
if (order)
{
rc = IFCALLRESULT(FALSE, secondary->CacheBitmapV3, context, order);
free_cache_bitmap_v3_order(context, order);
}
}
break;
case ORDER_TYPE_CACHE_COLOR_TABLE:
{
CACHE_COLOR_TABLE_ORDER* order =
update_read_cache_color_table_order(update, s, extraFlags);
if (order)
{
rc = IFCALLRESULT(FALSE, secondary->CacheColorTable, context, order);
free_cache_color_table_order(context, order);
}
}
break;
case ORDER_TYPE_CACHE_GLYPH:
{
switch (settings->GlyphSupportLevel)
{
case GLYPH_SUPPORT_PARTIAL:
case GLYPH_SUPPORT_FULL:
{
CACHE_GLYPH_ORDER* order = update_read_cache_glyph_order(update, s, extraFlags);
if (order)
{
rc = IFCALLRESULT(FALSE, secondary->CacheGlyph, context, order);
free_cache_glyph_order(context, order);
}
}
break;
case GLYPH_SUPPORT_ENCODE:
{
CACHE_GLYPH_V2_ORDER* order =
update_read_cache_glyph_v2_order(update, s, extraFlags);
if (order)
{
rc = IFCALLRESULT(FALSE, secondary->CacheGlyphV2, context, order);
free_cache_glyph_v2_order(context, order);
}
}
break;
case GLYPH_SUPPORT_NONE:
default:
break;
}
}
break;
case ORDER_TYPE_CACHE_BRUSH:
/* [MS-RDPEGDI] 2.2.2.2.1.2.7 Cache Brush (CACHE_BRUSH_ORDER) */
{
CACHE_BRUSH_ORDER* order = update_read_cache_brush_order(update, s, extraFlags);
if (order)
{
rc = IFCALLRESULT(FALSE, secondary->CacheBrush, context, order);
free_cache_brush_order(context, order);
}
}
break;
default:
WLog_Print(update->log, WLOG_WARN, "SECONDARY ORDER %s not supported", name);
break;
}
if (!rc)
{
WLog_Print(update->log, WLOG_ERROR, "SECONDARY ORDER %s failed", name);
}
start += orderLength + 7;
end = Stream_GetPosition(s);
if (start > end)
{
WLog_Print(update->log, WLOG_WARN, "SECONDARY_ORDER %s: read %" PRIuz "bytes too much",
name, end - start);
return FALSE;
}
diff = start - end;
if (diff > 0)
{
WLog_Print(update->log, WLOG_DEBUG,
"SECONDARY_ORDER %s: read %" PRIuz "bytes short, skipping", name, diff);
Stream_Seek(s, diff);
}
return rc;
}
static BOOL read_altsec_order(wStream* s, BYTE orderType, rdpAltSecUpdate* altsec)
{
BOOL rc = FALSE;
switch (orderType)
{
case ORDER_TYPE_CREATE_OFFSCREEN_BITMAP:
rc = update_read_create_offscreen_bitmap_order(s, &(altsec->create_offscreen_bitmap));
break;
case ORDER_TYPE_SWITCH_SURFACE:
rc = update_read_switch_surface_order(s, &(altsec->switch_surface));
break;
case ORDER_TYPE_CREATE_NINE_GRID_BITMAP:
rc = update_read_create_nine_grid_bitmap_order(s, &(altsec->create_nine_grid_bitmap));
break;
case ORDER_TYPE_FRAME_MARKER:
rc = update_read_frame_marker_order(s, &(altsec->frame_marker));
break;
case ORDER_TYPE_STREAM_BITMAP_FIRST:
rc = update_read_stream_bitmap_first_order(s, &(altsec->stream_bitmap_first));
break;
case ORDER_TYPE_STREAM_BITMAP_NEXT:
rc = update_read_stream_bitmap_next_order(s, &(altsec->stream_bitmap_next));
break;
case ORDER_TYPE_GDIPLUS_FIRST:
rc = update_read_draw_gdiplus_first_order(s, &(altsec->draw_gdiplus_first));
break;
case ORDER_TYPE_GDIPLUS_NEXT:
rc = update_read_draw_gdiplus_next_order(s, &(altsec->draw_gdiplus_next));
break;
case ORDER_TYPE_GDIPLUS_END:
rc = update_read_draw_gdiplus_end_order(s, &(altsec->draw_gdiplus_end));
break;
case ORDER_TYPE_GDIPLUS_CACHE_FIRST:
rc = update_read_draw_gdiplus_cache_first_order(s, &(altsec->draw_gdiplus_cache_first));
break;
case ORDER_TYPE_GDIPLUS_CACHE_NEXT:
rc = update_read_draw_gdiplus_cache_next_order(s, &(altsec->draw_gdiplus_cache_next));
break;
case ORDER_TYPE_GDIPLUS_CACHE_END:
rc = update_read_draw_gdiplus_cache_end_order(s, &(altsec->draw_gdiplus_cache_end));
break;
case ORDER_TYPE_WINDOW:
/* This order is handled elsewhere. */
rc = TRUE;
break;
case ORDER_TYPE_COMPDESK_FIRST:
rc = TRUE;
break;
default:
break;
}
return rc;
}
static BOOL update_recv_altsec_order(rdpUpdate* update, wStream* s, BYTE flags)
{
BYTE orderType = flags >>= 2; /* orderType is in higher 6 bits of flags field */
BOOL rc = FALSE;
rdpContext* context = update->context;
rdpSettings* settings = context->settings;
rdpAltSecUpdate* altsec = update->altsec;
const char* orderName = altsec_order_string(orderType);
WLog_Print(update->log, WLOG_DEBUG, "Alternate Secondary Drawing Order %s", orderName);
if (!check_alt_order_supported(update->log, settings, orderType, orderName))
return FALSE;
if (!read_altsec_order(s, orderType, altsec))
return FALSE;
switch (orderType)
{
case ORDER_TYPE_CREATE_OFFSCREEN_BITMAP:
IFCALLRET(altsec->CreateOffscreenBitmap, rc, context,
&(altsec->create_offscreen_bitmap));
break;
case ORDER_TYPE_SWITCH_SURFACE:
IFCALLRET(altsec->SwitchSurface, rc, context, &(altsec->switch_surface));
break;
case ORDER_TYPE_CREATE_NINE_GRID_BITMAP:
IFCALLRET(altsec->CreateNineGridBitmap, rc, context,
&(altsec->create_nine_grid_bitmap));
break;
case ORDER_TYPE_FRAME_MARKER:
IFCALLRET(altsec->FrameMarker, rc, context, &(altsec->frame_marker));
break;
case ORDER_TYPE_STREAM_BITMAP_FIRST:
IFCALLRET(altsec->StreamBitmapFirst, rc, context, &(altsec->stream_bitmap_first));
break;
case ORDER_TYPE_STREAM_BITMAP_NEXT:
IFCALLRET(altsec->StreamBitmapNext, rc, context, &(altsec->stream_bitmap_next));
break;
case ORDER_TYPE_GDIPLUS_FIRST:
IFCALLRET(altsec->DrawGdiPlusFirst, rc, context, &(altsec->draw_gdiplus_first));
break;
case ORDER_TYPE_GDIPLUS_NEXT:
IFCALLRET(altsec->DrawGdiPlusNext, rc, context, &(altsec->draw_gdiplus_next));
break;
case ORDER_TYPE_GDIPLUS_END:
IFCALLRET(altsec->DrawGdiPlusEnd, rc, context, &(altsec->draw_gdiplus_end));
break;
case ORDER_TYPE_GDIPLUS_CACHE_FIRST:
IFCALLRET(altsec->DrawGdiPlusCacheFirst, rc, context,
&(altsec->draw_gdiplus_cache_first));
break;
case ORDER_TYPE_GDIPLUS_CACHE_NEXT:
IFCALLRET(altsec->DrawGdiPlusCacheNext, rc, context,
&(altsec->draw_gdiplus_cache_next));
break;
case ORDER_TYPE_GDIPLUS_CACHE_END:
IFCALLRET(altsec->DrawGdiPlusCacheEnd, rc, context, &(altsec->draw_gdiplus_cache_end));
break;
case ORDER_TYPE_WINDOW:
rc = update_recv_altsec_window_order(update, s);
break;
case ORDER_TYPE_COMPDESK_FIRST:
rc = TRUE;
break;
default:
break;
}
if (!rc)
{
WLog_Print(update->log, WLOG_WARN, "Alternate Secondary Drawing Order %s failed",
orderName);
}
return rc;
}
BOOL update_recv_order(rdpUpdate* update, wStream* s)
{
BOOL rc;
BYTE controlFlags;
if (Stream_GetRemainingLength(s) < 1)
{
WLog_Print(update->log, WLOG_ERROR, "Stream_GetRemainingLength(s) < 1");
return FALSE;
}
Stream_Read_UINT8(s, controlFlags); /* controlFlags (1 byte) */
if (!(controlFlags & ORDER_STANDARD))
rc = update_recv_altsec_order(update, s, controlFlags);
else if (controlFlags & ORDER_SECONDARY)
rc = update_recv_secondary_order(update, s, controlFlags);
else
rc = update_recv_primary_order(update, s, controlFlags);
if (!rc)
WLog_Print(update->log, WLOG_ERROR, "order flags %02" PRIx8 " failed", controlFlags);
return rc;
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_3952_0 |
crossvul-cpp_data_bad_2889_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)
vstart += verdef->vd_aux;
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);
vstart += entry->vn_aux;
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-125/c/bad_2889_0 |
crossvul-cpp_data_bad_2640_0 | /*
* Copyright (c) 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997
* The Regents of the University of California. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that: (1) source code distributions
* retain the above copyright notice and this paragraph in its entirety, (2)
* distributions including binary code include the above copyright notice and
* this paragraph in its entirety in the documentation or other materials
* provided with the distribution, and (3) all advertising materials mentioning
* features or use of this software display the following acknowledgement:
* ``This product includes software developed by the University of California,
* Lawrence Berkeley Laboratory and its contributors.'' Neither the name of
* the University nor the names of its contributors may be used to endorse
* or promote products derived from this software without specific prior
* written permission.
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*
* Internet, ethernet, port, and protocol string to address
* and address to string conversion routines
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#ifdef HAVE_CASPER
#include <libcasper.h>
#include <casper/cap_dns.h>
#endif /* HAVE_CASPER */
#include <netdissect-stdinc.h>
#ifdef USE_ETHER_NTOHOST
#ifdef HAVE_NETINET_IF_ETHER_H
struct mbuf; /* Squelch compiler warnings on some platforms for */
struct rtentry; /* declarations in <net/if.h> */
#include <net/if.h> /* for "struct ifnet" in "struct arpcom" on Solaris */
#include <netinet/if_ether.h>
#endif /* HAVE_NETINET_IF_ETHER_H */
#ifdef NETINET_ETHER_H_DECLARES_ETHER_NTOHOST
#include <netinet/ether.h>
#endif /* NETINET_ETHER_H_DECLARES_ETHER_NTOHOST */
#if !defined(HAVE_DECL_ETHER_NTOHOST) || !HAVE_DECL_ETHER_NTOHOST
#ifndef HAVE_STRUCT_ETHER_ADDR
struct ether_addr {
unsigned char ether_addr_octet[6];
};
#endif
extern int ether_ntohost(char *, const struct ether_addr *);
#endif
#endif /* USE_ETHER_NTOHOST */
#include <pcap.h>
#include <pcap-namedb.h>
#include <signal.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "netdissect.h"
#include "addrtoname.h"
#include "addrtostr.h"
#include "ethertype.h"
#include "llc.h"
#include "setsignal.h"
#include "extract.h"
#include "oui.h"
#ifndef ETHER_ADDR_LEN
#define ETHER_ADDR_LEN 6
#endif
/*
* hash tables for whatever-to-name translations
*
* ndo_error() called on strdup(3) failure
*/
#define HASHNAMESIZE 4096
struct hnamemem {
uint32_t addr;
const char *name;
struct hnamemem *nxt;
};
static struct hnamemem hnametable[HASHNAMESIZE];
static struct hnamemem tporttable[HASHNAMESIZE];
static struct hnamemem uporttable[HASHNAMESIZE];
static struct hnamemem eprototable[HASHNAMESIZE];
static struct hnamemem dnaddrtable[HASHNAMESIZE];
static struct hnamemem ipxsaptable[HASHNAMESIZE];
#ifdef _WIN32
/*
* fake gethostbyaddr for Win2k/XP
* gethostbyaddr() returns incorrect value when AF_INET6 is passed
* to 3rd argument.
*
* h_name in struct hostent is only valid.
*/
static struct hostent *
win32_gethostbyaddr(const char *addr, int len, int type)
{
static struct hostent host;
static char hostbuf[NI_MAXHOST];
char hname[NI_MAXHOST];
struct sockaddr_in6 addr6;
host.h_name = hostbuf;
switch (type) {
case AF_INET:
return gethostbyaddr(addr, len, type);
break;
case AF_INET6:
memset(&addr6, 0, sizeof(addr6));
addr6.sin6_family = AF_INET6;
memcpy(&addr6.sin6_addr, addr, len);
if (getnameinfo((struct sockaddr *)&addr6, sizeof(addr6),
hname, sizeof(hname), NULL, 0, 0)) {
return NULL;
} else {
strcpy(host.h_name, hname);
return &host;
}
break;
default:
return NULL;
}
}
#define gethostbyaddr win32_gethostbyaddr
#endif /* _WIN32 */
struct h6namemem {
struct in6_addr addr;
char *name;
struct h6namemem *nxt;
};
static struct h6namemem h6nametable[HASHNAMESIZE];
struct enamemem {
u_short e_addr0;
u_short e_addr1;
u_short e_addr2;
const char *e_name;
u_char *e_nsap; /* used only for nsaptable[] */
#define e_bs e_nsap /* for bytestringtable */
struct enamemem *e_nxt;
};
static struct enamemem enametable[HASHNAMESIZE];
static struct enamemem nsaptable[HASHNAMESIZE];
static struct enamemem bytestringtable[HASHNAMESIZE];
struct protoidmem {
uint32_t p_oui;
u_short p_proto;
const char *p_name;
struct protoidmem *p_nxt;
};
static struct protoidmem protoidtable[HASHNAMESIZE];
/*
* A faster replacement for inet_ntoa().
*/
const char *
intoa(uint32_t addr)
{
register char *cp;
register u_int byte;
register int n;
static char buf[sizeof(".xxx.xxx.xxx.xxx")];
NTOHL(addr);
cp = buf + sizeof(buf);
*--cp = '\0';
n = 4;
do {
byte = addr & 0xff;
*--cp = byte % 10 + '0';
byte /= 10;
if (byte > 0) {
*--cp = byte % 10 + '0';
byte /= 10;
if (byte > 0)
*--cp = byte + '0';
}
*--cp = '.';
addr >>= 8;
} while (--n > 0);
return cp + 1;
}
static uint32_t f_netmask;
static uint32_t f_localnet;
#ifdef HAVE_CASPER
extern cap_channel_t *capdns;
#endif
/*
* Return a name for the IP address pointed to by ap. This address
* is assumed to be in network byte order.
*
* NOTE: ap is *NOT* necessarily part of the packet data (not even if
* this is being called with the "ipaddr_string()" macro), so you
* *CANNOT* use the ND_TCHECK{2}/ND_TTEST{2} macros on it. Furthermore,
* even in cases where it *is* part of the packet data, the caller
* would still have to check for a null return value, even if it's
* just printing the return value with "%s" - not all versions of
* printf print "(null)" with "%s" and a null pointer, some of them
* don't check for a null pointer and crash in that case.
*
* The callers of this routine should, before handing this routine
* a pointer to packet data, be sure that the data is present in
* the packet buffer. They should probably do those checks anyway,
* as other data at that layer might not be IP addresses, and it
* also needs to check whether they're present in the packet buffer.
*/
const char *
getname(netdissect_options *ndo, const u_char *ap)
{
register struct hostent *hp;
uint32_t addr;
struct hnamemem *p;
memcpy(&addr, ap, sizeof(addr));
p = &hnametable[addr & (HASHNAMESIZE-1)];
for (; p->nxt; p = p->nxt) {
if (p->addr == addr)
return (p->name);
}
p->addr = addr;
p->nxt = newhnamemem(ndo);
/*
* Print names unless:
* (1) -n was given.
* (2) Address is foreign and -f was given. (If -f was not
* given, f_netmask and f_localnet are 0 and the test
* evaluates to true)
*/
if (!ndo->ndo_nflag &&
(addr & f_netmask) == f_localnet) {
#ifdef HAVE_CASPER
if (capdns != NULL) {
hp = cap_gethostbyaddr(capdns, (char *)&addr, 4,
AF_INET);
} else
#endif
hp = gethostbyaddr((char *)&addr, 4, AF_INET);
if (hp) {
char *dotp;
p->name = strdup(hp->h_name);
if (p->name == NULL)
(*ndo->ndo_error)(ndo,
"getname: strdup(hp->h_name)");
if (ndo->ndo_Nflag) {
/* Remove domain qualifications */
dotp = strchr(p->name, '.');
if (dotp)
*dotp = '\0';
}
return (p->name);
}
}
p->name = strdup(intoa(addr));
if (p->name == NULL)
(*ndo->ndo_error)(ndo, "getname: strdup(intoa(addr))");
return (p->name);
}
/*
* Return a name for the IP6 address pointed to by ap. This address
* is assumed to be in network byte order.
*/
const char *
getname6(netdissect_options *ndo, const u_char *ap)
{
register struct hostent *hp;
union {
struct in6_addr addr;
struct for_hash_addr {
char fill[14];
uint16_t d;
} addra;
} addr;
struct h6namemem *p;
register const char *cp;
char ntop_buf[INET6_ADDRSTRLEN];
memcpy(&addr, ap, sizeof(addr));
p = &h6nametable[addr.addra.d & (HASHNAMESIZE-1)];
for (; p->nxt; p = p->nxt) {
if (memcmp(&p->addr, &addr, sizeof(addr)) == 0)
return (p->name);
}
p->addr = addr.addr;
p->nxt = newh6namemem(ndo);
/*
* Do not print names if -n was given.
*/
if (!ndo->ndo_nflag) {
#ifdef HAVE_CASPER
if (capdns != NULL) {
hp = cap_gethostbyaddr(capdns, (char *)&addr,
sizeof(addr), AF_INET6);
} else
#endif
hp = gethostbyaddr((char *)&addr, sizeof(addr),
AF_INET6);
if (hp) {
char *dotp;
p->name = strdup(hp->h_name);
if (p->name == NULL)
(*ndo->ndo_error)(ndo,
"getname6: strdup(hp->h_name)");
if (ndo->ndo_Nflag) {
/* Remove domain qualifications */
dotp = strchr(p->name, '.');
if (dotp)
*dotp = '\0';
}
return (p->name);
}
}
cp = addrtostr6(ap, ntop_buf, sizeof(ntop_buf));
p->name = strdup(cp);
if (p->name == NULL)
(*ndo->ndo_error)(ndo, "getname6: strdup(cp)");
return (p->name);
}
static const char hex[] = "0123456789abcdef";
/* Find the hash node that corresponds the ether address 'ep' */
static inline struct enamemem *
lookup_emem(netdissect_options *ndo, const u_char *ep)
{
register u_int i, j, k;
struct enamemem *tp;
k = (ep[0] << 8) | ep[1];
j = (ep[2] << 8) | ep[3];
i = (ep[4] << 8) | ep[5];
tp = &enametable[(i ^ j) & (HASHNAMESIZE-1)];
while (tp->e_nxt)
if (tp->e_addr0 == i &&
tp->e_addr1 == j &&
tp->e_addr2 == k)
return tp;
else
tp = tp->e_nxt;
tp->e_addr0 = i;
tp->e_addr1 = j;
tp->e_addr2 = k;
tp->e_nxt = (struct enamemem *)calloc(1, sizeof(*tp));
if (tp->e_nxt == NULL)
(*ndo->ndo_error)(ndo, "lookup_emem: calloc");
return tp;
}
/*
* Find the hash node that corresponds to the bytestring 'bs'
* with length 'nlen'
*/
static inline struct enamemem *
lookup_bytestring(netdissect_options *ndo, register const u_char *bs,
const unsigned int nlen)
{
struct enamemem *tp;
register u_int i, j, k;
if (nlen >= 6) {
k = (bs[0] << 8) | bs[1];
j = (bs[2] << 8) | bs[3];
i = (bs[4] << 8) | bs[5];
} else if (nlen >= 4) {
k = (bs[0] << 8) | bs[1];
j = (bs[2] << 8) | bs[3];
i = 0;
} else
i = j = k = 0;
tp = &bytestringtable[(i ^ j) & (HASHNAMESIZE-1)];
while (tp->e_nxt)
if (tp->e_addr0 == i &&
tp->e_addr1 == j &&
tp->e_addr2 == k &&
memcmp((const char *)bs, (const char *)(tp->e_bs), nlen) == 0)
return tp;
else
tp = tp->e_nxt;
tp->e_addr0 = i;
tp->e_addr1 = j;
tp->e_addr2 = k;
tp->e_bs = (u_char *) calloc(1, nlen + 1);
if (tp->e_bs == NULL)
(*ndo->ndo_error)(ndo, "lookup_bytestring: calloc");
memcpy(tp->e_bs, bs, nlen);
tp->e_nxt = (struct enamemem *)calloc(1, sizeof(*tp));
if (tp->e_nxt == NULL)
(*ndo->ndo_error)(ndo, "lookup_bytestring: calloc");
return tp;
}
/* Find the hash node that corresponds the NSAP 'nsap' */
static inline struct enamemem *
lookup_nsap(netdissect_options *ndo, register const u_char *nsap,
register u_int nsap_length)
{
register u_int i, j, k;
struct enamemem *tp;
const u_char *ensap;
if (nsap_length > 6) {
ensap = nsap + nsap_length - 6;
k = (ensap[0] << 8) | ensap[1];
j = (ensap[2] << 8) | ensap[3];
i = (ensap[4] << 8) | ensap[5];
}
else
i = j = k = 0;
tp = &nsaptable[(i ^ j) & (HASHNAMESIZE-1)];
while (tp->e_nxt)
if (tp->e_addr0 == i &&
tp->e_addr1 == j &&
tp->e_addr2 == k &&
tp->e_nsap[0] == nsap_length &&
memcmp((const char *)&(nsap[1]),
(char *)&(tp->e_nsap[1]), nsap_length) == 0)
return tp;
else
tp = tp->e_nxt;
tp->e_addr0 = i;
tp->e_addr1 = j;
tp->e_addr2 = k;
tp->e_nsap = (u_char *)malloc(nsap_length + 1);
if (tp->e_nsap == NULL)
(*ndo->ndo_error)(ndo, "lookup_nsap: malloc");
tp->e_nsap[0] = (u_char)nsap_length; /* guaranteed < ISONSAP_MAX_LENGTH */
memcpy((char *)&tp->e_nsap[1], (const char *)nsap, nsap_length);
tp->e_nxt = (struct enamemem *)calloc(1, sizeof(*tp));
if (tp->e_nxt == NULL)
(*ndo->ndo_error)(ndo, "lookup_nsap: calloc");
return tp;
}
/* Find the hash node that corresponds the protoid 'pi'. */
static inline struct protoidmem *
lookup_protoid(netdissect_options *ndo, const u_char *pi)
{
register u_int i, j;
struct protoidmem *tp;
/* 5 octets won't be aligned */
i = (((pi[0] << 8) + pi[1]) << 8) + pi[2];
j = (pi[3] << 8) + pi[4];
/* XXX should be endian-insensitive, but do big-endian testing XXX */
tp = &protoidtable[(i ^ j) & (HASHNAMESIZE-1)];
while (tp->p_nxt)
if (tp->p_oui == i && tp->p_proto == j)
return tp;
else
tp = tp->p_nxt;
tp->p_oui = i;
tp->p_proto = j;
tp->p_nxt = (struct protoidmem *)calloc(1, sizeof(*tp));
if (tp->p_nxt == NULL)
(*ndo->ndo_error)(ndo, "lookup_protoid: calloc");
return tp;
}
const char *
etheraddr_string(netdissect_options *ndo, register const u_char *ep)
{
register int i;
register char *cp;
register struct enamemem *tp;
int oui;
char buf[BUFSIZE];
tp = lookup_emem(ndo, ep);
if (tp->e_name)
return (tp->e_name);
#ifdef USE_ETHER_NTOHOST
if (!ndo->ndo_nflag) {
char buf2[BUFSIZE];
if (ether_ntohost(buf2, (const struct ether_addr *)ep) == 0) {
tp->e_name = strdup(buf2);
if (tp->e_name == NULL)
(*ndo->ndo_error)(ndo,
"etheraddr_string: strdup(buf2)");
return (tp->e_name);
}
}
#endif
cp = buf;
oui = EXTRACT_24BITS(ep);
*cp++ = hex[*ep >> 4 ];
*cp++ = hex[*ep++ & 0xf];
for (i = 5; --i >= 0;) {
*cp++ = ':';
*cp++ = hex[*ep >> 4 ];
*cp++ = hex[*ep++ & 0xf];
}
if (!ndo->ndo_nflag) {
snprintf(cp, BUFSIZE - (2 + 5*3), " (oui %s)",
tok2str(oui_values, "Unknown", oui));
} else
*cp = '\0';
tp->e_name = strdup(buf);
if (tp->e_name == NULL)
(*ndo->ndo_error)(ndo, "etheraddr_string: strdup(buf)");
return (tp->e_name);
}
const char *
le64addr_string(netdissect_options *ndo, const u_char *ep)
{
const unsigned int len = 8;
register u_int i;
register char *cp;
register struct enamemem *tp;
char buf[BUFSIZE];
tp = lookup_bytestring(ndo, ep, len);
if (tp->e_name)
return (tp->e_name);
cp = buf;
for (i = len; i > 0 ; --i) {
*cp++ = hex[*(ep + i - 1) >> 4];
*cp++ = hex[*(ep + i - 1) & 0xf];
*cp++ = ':';
}
cp --;
*cp = '\0';
tp->e_name = strdup(buf);
if (tp->e_name == NULL)
(*ndo->ndo_error)(ndo, "le64addr_string: strdup(buf)");
return (tp->e_name);
}
const char *
linkaddr_string(netdissect_options *ndo, const u_char *ep,
const unsigned int type, const unsigned int len)
{
register u_int i;
register char *cp;
register struct enamemem *tp;
if (len == 0)
return ("<empty>");
if (type == LINKADDR_ETHER && len == ETHER_ADDR_LEN)
return (etheraddr_string(ndo, ep));
if (type == LINKADDR_FRELAY)
return (q922_string(ndo, ep, len));
tp = lookup_bytestring(ndo, ep, len);
if (tp->e_name)
return (tp->e_name);
tp->e_name = cp = (char *)malloc(len*3);
if (tp->e_name == NULL)
(*ndo->ndo_error)(ndo, "linkaddr_string: malloc");
*cp++ = hex[*ep >> 4];
*cp++ = hex[*ep++ & 0xf];
for (i = len-1; i > 0 ; --i) {
*cp++ = ':';
*cp++ = hex[*ep >> 4];
*cp++ = hex[*ep++ & 0xf];
}
*cp = '\0';
return (tp->e_name);
}
const char *
etherproto_string(netdissect_options *ndo, u_short port)
{
register char *cp;
register struct hnamemem *tp;
register uint32_t i = port;
char buf[sizeof("0000")];
for (tp = &eprototable[i & (HASHNAMESIZE-1)]; tp->nxt; tp = tp->nxt)
if (tp->addr == i)
return (tp->name);
tp->addr = i;
tp->nxt = newhnamemem(ndo);
cp = buf;
NTOHS(port);
*cp++ = hex[port >> 12 & 0xf];
*cp++ = hex[port >> 8 & 0xf];
*cp++ = hex[port >> 4 & 0xf];
*cp++ = hex[port & 0xf];
*cp++ = '\0';
tp->name = strdup(buf);
if (tp->name == NULL)
(*ndo->ndo_error)(ndo, "etherproto_string: strdup(buf)");
return (tp->name);
}
const char *
protoid_string(netdissect_options *ndo, register const u_char *pi)
{
register u_int i, j;
register char *cp;
register struct protoidmem *tp;
char buf[sizeof("00:00:00:00:00")];
tp = lookup_protoid(ndo, pi);
if (tp->p_name)
return tp->p_name;
cp = buf;
if ((j = *pi >> 4) != 0)
*cp++ = hex[j];
*cp++ = hex[*pi++ & 0xf];
for (i = 4; (int)--i >= 0;) {
*cp++ = ':';
if ((j = *pi >> 4) != 0)
*cp++ = hex[j];
*cp++ = hex[*pi++ & 0xf];
}
*cp = '\0';
tp->p_name = strdup(buf);
if (tp->p_name == NULL)
(*ndo->ndo_error)(ndo, "protoid_string: strdup(buf)");
return (tp->p_name);
}
#define ISONSAP_MAX_LENGTH 20
const char *
isonsap_string(netdissect_options *ndo, const u_char *nsap,
register u_int nsap_length)
{
register u_int nsap_idx;
register char *cp;
register struct enamemem *tp;
if (nsap_length < 1 || nsap_length > ISONSAP_MAX_LENGTH)
return ("isonsap_string: illegal length");
tp = lookup_nsap(ndo, nsap, nsap_length);
if (tp->e_name)
return tp->e_name;
tp->e_name = cp = (char *)malloc(sizeof("xx.xxxx.xxxx.xxxx.xxxx.xxxx.xxxx.xxxx.xxxx.xxxx.xx"));
if (cp == NULL)
(*ndo->ndo_error)(ndo, "isonsap_string: malloc");
for (nsap_idx = 0; nsap_idx < nsap_length; nsap_idx++) {
*cp++ = hex[*nsap >> 4];
*cp++ = hex[*nsap++ & 0xf];
if (((nsap_idx & 1) == 0) &&
(nsap_idx + 1 < nsap_length)) {
*cp++ = '.';
}
}
*cp = '\0';
return (tp->e_name);
}
const char *
tcpport_string(netdissect_options *ndo, u_short port)
{
register struct hnamemem *tp;
register uint32_t i = port;
char buf[sizeof("00000")];
for (tp = &tporttable[i & (HASHNAMESIZE-1)]; tp->nxt; tp = tp->nxt)
if (tp->addr == i)
return (tp->name);
tp->addr = i;
tp->nxt = newhnamemem(ndo);
(void)snprintf(buf, sizeof(buf), "%u", i);
tp->name = strdup(buf);
if (tp->name == NULL)
(*ndo->ndo_error)(ndo, "tcpport_string: strdup(buf)");
return (tp->name);
}
const char *
udpport_string(netdissect_options *ndo, register u_short port)
{
register struct hnamemem *tp;
register uint32_t i = port;
char buf[sizeof("00000")];
for (tp = &uporttable[i & (HASHNAMESIZE-1)]; tp->nxt; tp = tp->nxt)
if (tp->addr == i)
return (tp->name);
tp->addr = i;
tp->nxt = newhnamemem(ndo);
(void)snprintf(buf, sizeof(buf), "%u", i);
tp->name = strdup(buf);
if (tp->name == NULL)
(*ndo->ndo_error)(ndo, "udpport_string: strdup(buf)");
return (tp->name);
}
const char *
ipxsap_string(netdissect_options *ndo, u_short port)
{
register char *cp;
register struct hnamemem *tp;
register uint32_t i = port;
char buf[sizeof("0000")];
for (tp = &ipxsaptable[i & (HASHNAMESIZE-1)]; tp->nxt; tp = tp->nxt)
if (tp->addr == i)
return (tp->name);
tp->addr = i;
tp->nxt = newhnamemem(ndo);
cp = buf;
NTOHS(port);
*cp++ = hex[port >> 12 & 0xf];
*cp++ = hex[port >> 8 & 0xf];
*cp++ = hex[port >> 4 & 0xf];
*cp++ = hex[port & 0xf];
*cp++ = '\0';
tp->name = strdup(buf);
if (tp->name == NULL)
(*ndo->ndo_error)(ndo, "ipxsap_string: strdup(buf)");
return (tp->name);
}
static void
init_servarray(netdissect_options *ndo)
{
struct servent *sv;
register struct hnamemem *table;
register int i;
char buf[sizeof("0000000000")];
while ((sv = getservent()) != NULL) {
int port = ntohs(sv->s_port);
i = port & (HASHNAMESIZE-1);
if (strcmp(sv->s_proto, "tcp") == 0)
table = &tporttable[i];
else if (strcmp(sv->s_proto, "udp") == 0)
table = &uporttable[i];
else
continue;
while (table->name)
table = table->nxt;
if (ndo->ndo_nflag) {
(void)snprintf(buf, sizeof(buf), "%d", port);
table->name = strdup(buf);
} else
table->name = strdup(sv->s_name);
if (table->name == NULL)
(*ndo->ndo_error)(ndo, "init_servarray: strdup");
table->addr = port;
table->nxt = newhnamemem(ndo);
}
endservent();
}
static const struct eproto {
const char *s;
u_short p;
} eproto_db[] = {
{ "pup", ETHERTYPE_PUP },
{ "xns", ETHERTYPE_NS },
{ "ip", ETHERTYPE_IP },
{ "ip6", ETHERTYPE_IPV6 },
{ "arp", ETHERTYPE_ARP },
{ "rarp", ETHERTYPE_REVARP },
{ "sprite", ETHERTYPE_SPRITE },
{ "mopdl", ETHERTYPE_MOPDL },
{ "moprc", ETHERTYPE_MOPRC },
{ "decnet", ETHERTYPE_DN },
{ "lat", ETHERTYPE_LAT },
{ "sca", ETHERTYPE_SCA },
{ "lanbridge", ETHERTYPE_LANBRIDGE },
{ "vexp", ETHERTYPE_VEXP },
{ "vprod", ETHERTYPE_VPROD },
{ "atalk", ETHERTYPE_ATALK },
{ "atalkarp", ETHERTYPE_AARP },
{ "loopback", ETHERTYPE_LOOPBACK },
{ "decdts", ETHERTYPE_DECDTS },
{ "decdns", ETHERTYPE_DECDNS },
{ (char *)0, 0 }
};
static void
init_eprotoarray(netdissect_options *ndo)
{
register int i;
register struct hnamemem *table;
for (i = 0; eproto_db[i].s; i++) {
int j = htons(eproto_db[i].p) & (HASHNAMESIZE-1);
table = &eprototable[j];
while (table->name)
table = table->nxt;
table->name = eproto_db[i].s;
table->addr = htons(eproto_db[i].p);
table->nxt = newhnamemem(ndo);
}
}
static const struct protoidlist {
const u_char protoid[5];
const char *name;
} protoidlist[] = {
{{ 0x00, 0x00, 0x0c, 0x01, 0x07 }, "CiscoMLS" },
{{ 0x00, 0x00, 0x0c, 0x20, 0x00 }, "CiscoCDP" },
{{ 0x00, 0x00, 0x0c, 0x20, 0x01 }, "CiscoCGMP" },
{{ 0x00, 0x00, 0x0c, 0x20, 0x03 }, "CiscoVTP" },
{{ 0x00, 0xe0, 0x2b, 0x00, 0xbb }, "ExtremeEDP" },
{{ 0x00, 0x00, 0x00, 0x00, 0x00 }, NULL }
};
/*
* SNAP proto IDs with org code 0:0:0 are actually encapsulated Ethernet
* types.
*/
static void
init_protoidarray(netdissect_options *ndo)
{
register int i;
register struct protoidmem *tp;
const struct protoidlist *pl;
u_char protoid[5];
protoid[0] = 0;
protoid[1] = 0;
protoid[2] = 0;
for (i = 0; eproto_db[i].s; i++) {
u_short etype = htons(eproto_db[i].p);
memcpy((char *)&protoid[3], (char *)&etype, 2);
tp = lookup_protoid(ndo, protoid);
tp->p_name = strdup(eproto_db[i].s);
if (tp->p_name == NULL)
(*ndo->ndo_error)(ndo,
"init_protoidarray: strdup(eproto_db[i].s)");
}
/* Hardwire some SNAP proto ID names */
for (pl = protoidlist; pl->name != NULL; ++pl) {
tp = lookup_protoid(ndo, pl->protoid);
/* Don't override existing name */
if (tp->p_name != NULL)
continue;
tp->p_name = pl->name;
}
}
static const struct etherlist {
const u_char addr[6];
const char *name;
} etherlist[] = {
{{ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff }, "Broadcast" },
{{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }, NULL }
};
/*
* Initialize the ethers hash table. We take two different approaches
* depending on whether or not the system provides the ethers name
* service. If it does, we just wire in a few names at startup,
* and etheraddr_string() fills in the table on demand. If it doesn't,
* then we suck in the entire /etc/ethers file at startup. The idea
* is that parsing the local file will be fast, but spinning through
* all the ethers entries via NIS & next_etherent might be very slow.
*
* XXX pcap_next_etherent doesn't belong in the pcap interface, but
* since the pcap module already does name-to-address translation,
* it's already does most of the work for the ethernet address-to-name
* translation, so we just pcap_next_etherent as a convenience.
*/
static void
init_etherarray(netdissect_options *ndo)
{
register const struct etherlist *el;
register struct enamemem *tp;
#ifdef USE_ETHER_NTOHOST
char name[256];
#else
register struct pcap_etherent *ep;
register FILE *fp;
/* Suck in entire ethers file */
fp = fopen(PCAP_ETHERS_FILE, "r");
if (fp != NULL) {
while ((ep = pcap_next_etherent(fp)) != NULL) {
tp = lookup_emem(ndo, ep->addr);
tp->e_name = strdup(ep->name);
if (tp->e_name == NULL)
(*ndo->ndo_error)(ndo,
"init_etherarray: strdup(ep->addr)");
}
(void)fclose(fp);
}
#endif
/* Hardwire some ethernet names */
for (el = etherlist; el->name != NULL; ++el) {
tp = lookup_emem(ndo, el->addr);
/* Don't override existing name */
if (tp->e_name != NULL)
continue;
#ifdef USE_ETHER_NTOHOST
/*
* Use YP/NIS version of name if available.
*/
if (ether_ntohost(name, (const struct ether_addr *)el->addr) == 0) {
tp->e_name = strdup(name);
if (tp->e_name == NULL)
(*ndo->ndo_error)(ndo,
"init_etherarray: strdup(name)");
continue;
}
#endif
tp->e_name = el->name;
}
}
static const struct tok ipxsap_db[] = {
{ 0x0000, "Unknown" },
{ 0x0001, "User" },
{ 0x0002, "User Group" },
{ 0x0003, "PrintQueue" },
{ 0x0004, "FileServer" },
{ 0x0005, "JobServer" },
{ 0x0006, "Gateway" },
{ 0x0007, "PrintServer" },
{ 0x0008, "ArchiveQueue" },
{ 0x0009, "ArchiveServer" },
{ 0x000a, "JobQueue" },
{ 0x000b, "Administration" },
{ 0x000F, "Novell TI-RPC" },
{ 0x0017, "Diagnostics" },
{ 0x0020, "NetBIOS" },
{ 0x0021, "NAS SNA Gateway" },
{ 0x0023, "NACS AsyncGateway" },
{ 0x0024, "RemoteBridge/RoutingService" },
{ 0x0026, "BridgeServer" },
{ 0x0027, "TCP/IP Gateway" },
{ 0x0028, "Point-to-point X.25 BridgeServer" },
{ 0x0029, "3270 Gateway" },
{ 0x002a, "CHI Corp" },
{ 0x002c, "PC Chalkboard" },
{ 0x002d, "TimeSynchServer" },
{ 0x002e, "ARCserve5.0/PalindromeBackup" },
{ 0x0045, "DI3270 Gateway" },
{ 0x0047, "AdvertisingPrintServer" },
{ 0x004a, "NetBlazerModems" },
{ 0x004b, "BtrieveVAP" },
{ 0x004c, "NetwareSQL" },
{ 0x004d, "XtreeNetwork" },
{ 0x0050, "BtrieveVAP4.11" },
{ 0x0052, "QuickLink" },
{ 0x0053, "PrintQueueUser" },
{ 0x0058, "Multipoint X.25 Router" },
{ 0x0060, "STLB/NLM" },
{ 0x0064, "ARCserve" },
{ 0x0066, "ARCserve3.0" },
{ 0x0072, "WAN CopyUtility" },
{ 0x007a, "TES-NetwareVMS" },
{ 0x0092, "WATCOM Debugger/EmeraldTapeBackupServer" },
{ 0x0095, "DDA OBGYN" },
{ 0x0098, "NetwareAccessServer" },
{ 0x009a, "Netware for VMS II/NamedPipeServer" },
{ 0x009b, "NetwareAccessServer" },
{ 0x009e, "PortableNetwareServer/SunLinkNVT" },
{ 0x00a1, "PowerchuteAPC UPS" },
{ 0x00aa, "LAWserve" },
{ 0x00ac, "CompaqIDA StatusMonitor" },
{ 0x0100, "PIPE STAIL" },
{ 0x0102, "LAN ProtectBindery" },
{ 0x0103, "OracleDataBaseServer" },
{ 0x0107, "Netware386/RSPX RemoteConsole" },
{ 0x010f, "NovellSNA Gateway" },
{ 0x0111, "TestServer" },
{ 0x0112, "HP PrintServer" },
{ 0x0114, "CSA MUX" },
{ 0x0115, "CSA LCA" },
{ 0x0116, "CSA CM" },
{ 0x0117, "CSA SMA" },
{ 0x0118, "CSA DBA" },
{ 0x0119, "CSA NMA" },
{ 0x011a, "CSA SSA" },
{ 0x011b, "CSA STATUS" },
{ 0x011e, "CSA APPC" },
{ 0x0126, "SNA TEST SSA Profile" },
{ 0x012a, "CSA TRACE" },
{ 0x012b, "NetwareSAA" },
{ 0x012e, "IKARUS VirusScan" },
{ 0x0130, "CommunicationsExecutive" },
{ 0x0133, "NNS DomainServer/NetwareNamingServicesDomain" },
{ 0x0135, "NetwareNamingServicesProfile" },
{ 0x0137, "Netware386 PrintQueue/NNS PrintQueue" },
{ 0x0141, "LAN SpoolServer" },
{ 0x0152, "IRMALAN Gateway" },
{ 0x0154, "NamedPipeServer" },
{ 0x0166, "NetWareManagement" },
{ 0x0168, "Intel PICKIT CommServer/Intel CAS TalkServer" },
{ 0x0173, "Compaq" },
{ 0x0174, "Compaq SNMP Agent" },
{ 0x0175, "Compaq" },
{ 0x0180, "XTreeServer/XTreeTools" },
{ 0x018A, "NASI ServicesBroadcastServer" },
{ 0x01b0, "GARP Gateway" },
{ 0x01b1, "Binfview" },
{ 0x01bf, "IntelLanDeskManager" },
{ 0x01ca, "AXTEC" },
{ 0x01cb, "ShivaNetModem/E" },
{ 0x01cc, "ShivaLanRover/E" },
{ 0x01cd, "ShivaLanRover/T" },
{ 0x01ce, "ShivaUniversal" },
{ 0x01d8, "CastelleFAXPressServer" },
{ 0x01da, "CastelleLANPressPrintServer" },
{ 0x01dc, "CastelleFAX/Xerox7033 FaxServer/ExcelLanFax" },
{ 0x01f0, "LEGATO" },
{ 0x01f5, "LEGATO" },
{ 0x0233, "NMS Agent/NetwareManagementAgent" },
{ 0x0237, "NMS IPX Discovery/LANternReadWriteChannel" },
{ 0x0238, "NMS IP Discovery/LANternTrapAlarmChannel" },
{ 0x023a, "LANtern" },
{ 0x023c, "MAVERICK" },
{ 0x023f, "NovellSMDR" },
{ 0x024e, "NetwareConnect" },
{ 0x024f, "NASI ServerBroadcast Cisco" },
{ 0x026a, "NMS ServiceConsole" },
{ 0x026b, "TimeSynchronizationServer Netware 4.x" },
{ 0x0278, "DirectoryServer Netware 4.x" },
{ 0x027b, "NetwareManagementAgent" },
{ 0x0280, "Novell File and Printer Sharing Service for PC" },
{ 0x0304, "NovellSAA Gateway" },
{ 0x0308, "COM/VERMED" },
{ 0x030a, "GalacticommWorldgroupServer" },
{ 0x030c, "IntelNetport2/HP JetDirect/HP Quicksilver" },
{ 0x0320, "AttachmateGateway" },
{ 0x0327, "MicrosoftDiagnostiocs" },
{ 0x0328, "WATCOM SQL Server" },
{ 0x0335, "MultiTechSystems MultisynchCommServer" },
{ 0x0343, "Xylogics RemoteAccessServer/LANModem" },
{ 0x0355, "ArcadaBackupExec" },
{ 0x0358, "MSLCD1" },
{ 0x0361, "NETINELO" },
{ 0x037e, "Powerchute UPS Monitoring" },
{ 0x037f, "ViruSafeNotify" },
{ 0x0386, "HP Bridge" },
{ 0x0387, "HP Hub" },
{ 0x0394, "NetWare SAA Gateway" },
{ 0x039b, "LotusNotes" },
{ 0x03b7, "CertusAntiVirus" },
{ 0x03c4, "ARCserve4.0" },
{ 0x03c7, "LANspool3.5" },
{ 0x03d7, "LexmarkPrinterServer" },
{ 0x03d8, "LexmarkXLE PrinterServer" },
{ 0x03dd, "BanyanENS NetwareClient" },
{ 0x03de, "GuptaSequelBaseServer/NetWareSQL" },
{ 0x03e1, "UnivelUnixware" },
{ 0x03e4, "UnivelUnixware" },
{ 0x03fc, "IntelNetport" },
{ 0x03fd, "PrintServerQueue" },
{ 0x040A, "ipnServer" },
{ 0x040D, "LVERRMAN" },
{ 0x040E, "LVLIC" },
{ 0x0414, "NET Silicon (DPI)/Kyocera" },
{ 0x0429, "SiteLockVirus" },
{ 0x0432, "UFHELPR???" },
{ 0x0433, "Synoptics281xAdvancedSNMPAgent" },
{ 0x0444, "MicrosoftNT SNA Server" },
{ 0x0448, "Oracle" },
{ 0x044c, "ARCserve5.01" },
{ 0x0457, "CanonGP55" },
{ 0x045a, "QMS Printers" },
{ 0x045b, "DellSCSI Array" },
{ 0x0491, "NetBlazerModems" },
{ 0x04ac, "OnTimeScheduler" },
{ 0x04b0, "CD-Net" },
{ 0x0513, "EmulexNQA" },
{ 0x0520, "SiteLockChecks" },
{ 0x0529, "SiteLockChecks" },
{ 0x052d, "CitrixOS2 AppServer" },
{ 0x0535, "Tektronix" },
{ 0x0536, "Milan" },
{ 0x055d, "Attachmate SNA gateway" },
{ 0x056b, "IBM8235 ModemServer" },
{ 0x056c, "ShivaLanRover/E PLUS" },
{ 0x056d, "ShivaLanRover/T PLUS" },
{ 0x0580, "McAfeeNetShield" },
{ 0x05B8, "NLM to workstation communication (Revelation Software)" },
{ 0x05BA, "CompatibleSystemsRouters" },
{ 0x05BE, "CheyenneHierarchicalStorageManager" },
{ 0x0606, "JCWatermarkImaging" },
{ 0x060c, "AXISNetworkPrinter" },
{ 0x0610, "AdaptecSCSIManagement" },
{ 0x0621, "IBM AntiVirus" },
{ 0x0640, "Windows95 RemoteRegistryService" },
{ 0x064e, "MicrosoftIIS" },
{ 0x067b, "Microsoft Win95/98 File and Print Sharing for NetWare" },
{ 0x067c, "Microsoft Win95/98 File and Print Sharing for NetWare" },
{ 0x076C, "Xerox" },
{ 0x079b, "ShivaLanRover/E 115" },
{ 0x079c, "ShivaLanRover/T 115" },
{ 0x07B4, "CubixWorldDesk" },
{ 0x07c2, "Quarterdeck IWare Connect V2.x NLM" },
{ 0x07c1, "Quarterdeck IWare Connect V3.x NLM" },
{ 0x0810, "ELAN License Server Demo" },
{ 0x0824, "ShivaLanRoverAccessSwitch/E" },
{ 0x086a, "ISSC Collector" },
{ 0x087f, "ISSC DAS AgentAIX" },
{ 0x0880, "Intel Netport PRO" },
{ 0x0881, "Intel Netport PRO" },
{ 0x0b29, "SiteLock" },
{ 0x0c29, "SiteLockApplications" },
{ 0x0c2c, "LicensingServer" },
{ 0x2101, "PerformanceTechnologyInstantInternet" },
{ 0x2380, "LAI SiteLock" },
{ 0x238c, "MeetingMaker" },
{ 0x4808, "SiteLockServer/SiteLockMetering" },
{ 0x5555, "SiteLockUser" },
{ 0x6312, "Tapeware" },
{ 0x6f00, "RabbitGateway" },
{ 0x7703, "MODEM" },
{ 0x8002, "NetPortPrinters" },
{ 0x8008, "WordPerfectNetworkVersion" },
{ 0x85BE, "Cisco EIGRP" },
{ 0x8888, "WordPerfectNetworkVersion/QuickNetworkManagement" },
{ 0x9000, "McAfeeNetShield" },
{ 0x9604, "CSA-NT_MON" },
{ 0xb6a8, "OceanIsleReachoutRemoteControl" },
{ 0xf11f, "SiteLockMetering" },
{ 0xf1ff, "SiteLock" },
{ 0xf503, "Microsoft SQL Server" },
{ 0xF905, "IBM TimeAndPlace" },
{ 0xfbfb, "TopCallIII FaxServer" },
{ 0xffff, "AnyService/Wildcard" },
{ 0, (char *)0 }
};
static void
init_ipxsaparray(netdissect_options *ndo)
{
register int i;
register struct hnamemem *table;
for (i = 0; ipxsap_db[i].s != NULL; i++) {
int j = htons(ipxsap_db[i].v) & (HASHNAMESIZE-1);
table = &ipxsaptable[j];
while (table->name)
table = table->nxt;
table->name = ipxsap_db[i].s;
table->addr = htons(ipxsap_db[i].v);
table->nxt = newhnamemem(ndo);
}
}
/*
* Initialize the address to name translation machinery. We map all
* non-local IP addresses to numeric addresses if ndo->ndo_fflag is true
* (i.e., to prevent blocking on the nameserver). localnet is the IP address
* of the local network. mask is its subnet mask.
*/
void
init_addrtoname(netdissect_options *ndo, uint32_t localnet, uint32_t mask)
{
if (ndo->ndo_fflag) {
f_localnet = localnet;
f_netmask = mask;
}
if (ndo->ndo_nflag)
/*
* Simplest way to suppress names.
*/
return;
init_etherarray(ndo);
init_servarray(ndo);
init_eprotoarray(ndo);
init_protoidarray(ndo);
init_ipxsaparray(ndo);
}
const char *
dnaddr_string(netdissect_options *ndo, u_short dnaddr)
{
register struct hnamemem *tp;
for (tp = &dnaddrtable[dnaddr & (HASHNAMESIZE-1)]; tp->nxt != NULL;
tp = tp->nxt)
if (tp->addr == dnaddr)
return (tp->name);
tp->addr = dnaddr;
tp->nxt = newhnamemem(ndo);
if (ndo->ndo_nflag)
tp->name = dnnum_string(ndo, dnaddr);
else
tp->name = dnname_string(ndo, dnaddr);
return(tp->name);
}
/* Return a zero'ed hnamemem struct and cuts down on calloc() overhead */
struct hnamemem *
newhnamemem(netdissect_options *ndo)
{
register struct hnamemem *p;
static struct hnamemem *ptr = NULL;
static u_int num = 0;
if (num <= 0) {
num = 64;
ptr = (struct hnamemem *)calloc(num, sizeof (*ptr));
if (ptr == NULL)
(*ndo->ndo_error)(ndo, "newhnamemem: calloc");
}
--num;
p = ptr++;
return (p);
}
/* Return a zero'ed h6namemem struct and cuts down on calloc() overhead */
struct h6namemem *
newh6namemem(netdissect_options *ndo)
{
register struct h6namemem *p;
static struct h6namemem *ptr = NULL;
static u_int num = 0;
if (num <= 0) {
num = 64;
ptr = (struct h6namemem *)calloc(num, sizeof (*ptr));
if (ptr == NULL)
(*ndo->ndo_error)(ndo, "newh6namemem: calloc");
}
--num;
p = ptr++;
return (p);
}
/* Represent TCI part of the 802.1Q 4-octet tag as text. */
const char *
ieee8021q_tci_string(const uint16_t tci)
{
static char buf[128];
snprintf(buf, sizeof(buf), "vlan %u, p %u%s",
tci & 0xfff,
tci >> 13,
(tci & 0x1000) ? ", DEI" : "");
return buf;
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_2640_0 |
crossvul-cpp_data_good_2724_0 | /*
* Copyright (c) 1998-2007 The TCPDUMP project
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that: (1) source code
* distributions retain the above copyright notice and this paragraph
* in its entirety, and (2) distributions including binary code include
* the above copyright notice and this paragraph in its entirety in
* the documentation or other materials provided with the distribution.
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND
* WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, WITHOUT
* LIMITATION, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE.
*
* Original code by Hannes Gredler (hannes@gredler.at)
*/
/* \summary: Resource ReSerVation Protocol (RSVP) printer */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <netdissect-stdinc.h>
#include "netdissect.h"
#include "extract.h"
#include "addrtoname.h"
#include "ethertype.h"
#include "gmpls.h"
#include "af.h"
#include "signature.h"
static const char tstr[] = " [|rsvp]";
/*
* RFC 2205 common header
*
* 0 1 2 3
* +-------------+-------------+-------------+-------------+
* | Vers | Flags| Msg Type | RSVP Checksum |
* +-------------+-------------+-------------+-------------+
* | Send_TTL | (Reserved) | RSVP Length |
* +-------------+-------------+-------------+-------------+
*
*/
struct rsvp_common_header {
uint8_t version_flags;
uint8_t msg_type;
uint8_t checksum[2];
uint8_t ttl;
uint8_t reserved;
uint8_t length[2];
};
/*
* RFC2205 object header
*
*
* 0 1 2 3
* +-------------+-------------+-------------+-------------+
* | Length (bytes) | Class-Num | C-Type |
* +-------------+-------------+-------------+-------------+
* | |
* // (Object contents) //
* | |
* +-------------+-------------+-------------+-------------+
*/
struct rsvp_object_header {
uint8_t length[2];
uint8_t class_num;
uint8_t ctype;
};
#define RSVP_VERSION 1
#define RSVP_EXTRACT_VERSION(x) (((x)&0xf0)>>4)
#define RSVP_EXTRACT_FLAGS(x) ((x)&0x0f)
#define RSVP_MSGTYPE_PATH 1
#define RSVP_MSGTYPE_RESV 2
#define RSVP_MSGTYPE_PATHERR 3
#define RSVP_MSGTYPE_RESVERR 4
#define RSVP_MSGTYPE_PATHTEAR 5
#define RSVP_MSGTYPE_RESVTEAR 6
#define RSVP_MSGTYPE_RESVCONF 7
#define RSVP_MSGTYPE_BUNDLE 12
#define RSVP_MSGTYPE_ACK 13
#define RSVP_MSGTYPE_HELLO_OLD 14 /* ancient Hellos */
#define RSVP_MSGTYPE_SREFRESH 15
#define RSVP_MSGTYPE_HELLO 20
static const struct tok rsvp_msg_type_values[] = {
{ RSVP_MSGTYPE_PATH, "Path" },
{ RSVP_MSGTYPE_RESV, "Resv" },
{ RSVP_MSGTYPE_PATHERR, "PathErr" },
{ RSVP_MSGTYPE_RESVERR, "ResvErr" },
{ RSVP_MSGTYPE_PATHTEAR, "PathTear" },
{ RSVP_MSGTYPE_RESVTEAR, "ResvTear" },
{ RSVP_MSGTYPE_RESVCONF, "ResvConf" },
{ RSVP_MSGTYPE_BUNDLE, "Bundle" },
{ RSVP_MSGTYPE_ACK, "Acknowledgement" },
{ RSVP_MSGTYPE_HELLO_OLD, "Hello (Old)" },
{ RSVP_MSGTYPE_SREFRESH, "Refresh" },
{ RSVP_MSGTYPE_HELLO, "Hello" },
{ 0, NULL}
};
static const struct tok rsvp_header_flag_values[] = {
{ 0x01, "Refresh reduction capable" }, /* rfc2961 */
{ 0, NULL}
};
#define RSVP_OBJ_SESSION 1 /* rfc2205 */
#define RSVP_OBJ_RSVP_HOP 3 /* rfc2205, rfc3473 */
#define RSVP_OBJ_INTEGRITY 4 /* rfc2747 */
#define RSVP_OBJ_TIME_VALUES 5 /* rfc2205 */
#define RSVP_OBJ_ERROR_SPEC 6
#define RSVP_OBJ_SCOPE 7
#define RSVP_OBJ_STYLE 8 /* rfc2205 */
#define RSVP_OBJ_FLOWSPEC 9 /* rfc2215 */
#define RSVP_OBJ_FILTERSPEC 10 /* rfc2215 */
#define RSVP_OBJ_SENDER_TEMPLATE 11
#define RSVP_OBJ_SENDER_TSPEC 12 /* rfc2215 */
#define RSVP_OBJ_ADSPEC 13 /* rfc2215 */
#define RSVP_OBJ_POLICY_DATA 14
#define RSVP_OBJ_CONFIRM 15 /* rfc2205 */
#define RSVP_OBJ_LABEL 16 /* rfc3209 */
#define RSVP_OBJ_LABEL_REQ 19 /* rfc3209 */
#define RSVP_OBJ_ERO 20 /* rfc3209 */
#define RSVP_OBJ_RRO 21 /* rfc3209 */
#define RSVP_OBJ_HELLO 22 /* rfc3209 */
#define RSVP_OBJ_MESSAGE_ID 23 /* rfc2961 */
#define RSVP_OBJ_MESSAGE_ID_ACK 24 /* rfc2961 */
#define RSVP_OBJ_MESSAGE_ID_LIST 25 /* rfc2961 */
#define RSVP_OBJ_RECOVERY_LABEL 34 /* rfc3473 */
#define RSVP_OBJ_UPSTREAM_LABEL 35 /* rfc3473 */
#define RSVP_OBJ_LABEL_SET 36 /* rfc3473 */
#define RSVP_OBJ_PROTECTION 37 /* rfc3473 */
#define RSVP_OBJ_S2L 50 /* rfc4875 */
#define RSVP_OBJ_DETOUR 63 /* draft-ietf-mpls-rsvp-lsp-fastreroute-07 */
#define RSVP_OBJ_CLASSTYPE 66 /* rfc4124 */
#define RSVP_OBJ_CLASSTYPE_OLD 125 /* draft-ietf-tewg-diff-te-proto-07 */
#define RSVP_OBJ_SUGGESTED_LABEL 129 /* rfc3473 */
#define RSVP_OBJ_ACCEPT_LABEL_SET 130 /* rfc3473 */
#define RSVP_OBJ_RESTART_CAPABILITY 131 /* rfc3473 */
#define RSVP_OBJ_NOTIFY_REQ 195 /* rfc3473 */
#define RSVP_OBJ_ADMIN_STATUS 196 /* rfc3473 */
#define RSVP_OBJ_PROPERTIES 204 /* juniper proprietary */
#define RSVP_OBJ_FASTREROUTE 205 /* draft-ietf-mpls-rsvp-lsp-fastreroute-07 */
#define RSVP_OBJ_SESSION_ATTRIBUTE 207 /* rfc3209 */
#define RSVP_OBJ_GENERALIZED_UNI 229 /* OIF RSVP extensions UNI 1.0 Signaling, Rel. 2 */
#define RSVP_OBJ_CALL_ID 230 /* rfc3474 */
#define RSVP_OBJ_CALL_OPS 236 /* rfc3474 */
static const struct tok rsvp_obj_values[] = {
{ RSVP_OBJ_SESSION, "Session" },
{ RSVP_OBJ_RSVP_HOP, "RSVP Hop" },
{ RSVP_OBJ_INTEGRITY, "Integrity" },
{ RSVP_OBJ_TIME_VALUES, "Time Values" },
{ RSVP_OBJ_ERROR_SPEC, "Error Spec" },
{ RSVP_OBJ_SCOPE, "Scope" },
{ RSVP_OBJ_STYLE, "Style" },
{ RSVP_OBJ_FLOWSPEC, "Flowspec" },
{ RSVP_OBJ_FILTERSPEC, "FilterSpec" },
{ RSVP_OBJ_SENDER_TEMPLATE, "Sender Template" },
{ RSVP_OBJ_SENDER_TSPEC, "Sender TSpec" },
{ RSVP_OBJ_ADSPEC, "Adspec" },
{ RSVP_OBJ_POLICY_DATA, "Policy Data" },
{ RSVP_OBJ_CONFIRM, "Confirm" },
{ RSVP_OBJ_LABEL, "Label" },
{ RSVP_OBJ_LABEL_REQ, "Label Request" },
{ RSVP_OBJ_ERO, "ERO" },
{ RSVP_OBJ_RRO, "RRO" },
{ RSVP_OBJ_HELLO, "Hello" },
{ RSVP_OBJ_MESSAGE_ID, "Message ID" },
{ RSVP_OBJ_MESSAGE_ID_ACK, "Message ID Ack" },
{ RSVP_OBJ_MESSAGE_ID_LIST, "Message ID List" },
{ RSVP_OBJ_RECOVERY_LABEL, "Recovery Label" },
{ RSVP_OBJ_UPSTREAM_LABEL, "Upstream Label" },
{ RSVP_OBJ_LABEL_SET, "Label Set" },
{ RSVP_OBJ_ACCEPT_LABEL_SET, "Acceptable Label Set" },
{ RSVP_OBJ_DETOUR, "Detour" },
{ RSVP_OBJ_CLASSTYPE, "Class Type" },
{ RSVP_OBJ_CLASSTYPE_OLD, "Class Type (old)" },
{ RSVP_OBJ_SUGGESTED_LABEL, "Suggested Label" },
{ RSVP_OBJ_PROPERTIES, "Properties" },
{ RSVP_OBJ_FASTREROUTE, "Fast Re-Route" },
{ RSVP_OBJ_SESSION_ATTRIBUTE, "Session Attribute" },
{ RSVP_OBJ_GENERALIZED_UNI, "Generalized UNI" },
{ RSVP_OBJ_CALL_ID, "Call-ID" },
{ RSVP_OBJ_CALL_OPS, "Call Capability" },
{ RSVP_OBJ_RESTART_CAPABILITY, "Restart Capability" },
{ RSVP_OBJ_NOTIFY_REQ, "Notify Request" },
{ RSVP_OBJ_PROTECTION, "Protection" },
{ RSVP_OBJ_ADMIN_STATUS, "Administrative Status" },
{ RSVP_OBJ_S2L, "Sub-LSP to LSP" },
{ 0, NULL}
};
#define RSVP_CTYPE_IPV4 1
#define RSVP_CTYPE_IPV6 2
#define RSVP_CTYPE_TUNNEL_IPV4 7
#define RSVP_CTYPE_TUNNEL_IPV6 8
#define RSVP_CTYPE_UNI_IPV4 11 /* OIF RSVP extensions UNI 1.0 Signaling Rel. 2 */
#define RSVP_CTYPE_1 1
#define RSVP_CTYPE_2 2
#define RSVP_CTYPE_3 3
#define RSVP_CTYPE_4 4
#define RSVP_CTYPE_12 12
#define RSVP_CTYPE_13 13
#define RSVP_CTYPE_14 14
/*
* the ctypes are not globally unique so for
* translating it to strings we build a table based
* on objects offsetted by the ctype
*/
static const struct tok rsvp_ctype_values[] = {
{ 256*RSVP_OBJ_RSVP_HOP+RSVP_CTYPE_IPV4, "IPv4" },
{ 256*RSVP_OBJ_RSVP_HOP+RSVP_CTYPE_IPV6, "IPv6" },
{ 256*RSVP_OBJ_RSVP_HOP+RSVP_CTYPE_3, "IPv4 plus opt. TLVs" },
{ 256*RSVP_OBJ_RSVP_HOP+RSVP_CTYPE_4, "IPv6 plus opt. TLVs" },
{ 256*RSVP_OBJ_NOTIFY_REQ+RSVP_CTYPE_IPV4, "IPv4" },
{ 256*RSVP_OBJ_NOTIFY_REQ+RSVP_CTYPE_IPV6, "IPv6" },
{ 256*RSVP_OBJ_CONFIRM+RSVP_CTYPE_IPV4, "IPv4" },
{ 256*RSVP_OBJ_CONFIRM+RSVP_CTYPE_IPV6, "IPv6" },
{ 256*RSVP_OBJ_TIME_VALUES+RSVP_CTYPE_1, "1" },
{ 256*RSVP_OBJ_FLOWSPEC+RSVP_CTYPE_1, "obsolete" },
{ 256*RSVP_OBJ_FLOWSPEC+RSVP_CTYPE_2, "IntServ" },
{ 256*RSVP_OBJ_SENDER_TSPEC+RSVP_CTYPE_2, "IntServ" },
{ 256*RSVP_OBJ_ADSPEC+RSVP_CTYPE_2, "IntServ" },
{ 256*RSVP_OBJ_FILTERSPEC+RSVP_CTYPE_IPV4, "IPv4" },
{ 256*RSVP_OBJ_FILTERSPEC+RSVP_CTYPE_IPV6, "IPv6" },
{ 256*RSVP_OBJ_FILTERSPEC+RSVP_CTYPE_3, "IPv6 Flow-label" },
{ 256*RSVP_OBJ_FILTERSPEC+RSVP_CTYPE_TUNNEL_IPV4, "Tunnel IPv4" },
{ 256*RSVP_OBJ_FILTERSPEC+RSVP_CTYPE_12, "IPv4 P2MP LSP Tunnel" },
{ 256*RSVP_OBJ_FILTERSPEC+RSVP_CTYPE_13, "IPv6 P2MP LSP Tunnel" },
{ 256*RSVP_OBJ_SESSION+RSVP_CTYPE_IPV4, "IPv4" },
{ 256*RSVP_OBJ_SESSION+RSVP_CTYPE_IPV6, "IPv6" },
{ 256*RSVP_OBJ_SESSION+RSVP_CTYPE_TUNNEL_IPV4, "Tunnel IPv4" },
{ 256*RSVP_OBJ_SESSION+RSVP_CTYPE_UNI_IPV4, "UNI IPv4" },
{ 256*RSVP_OBJ_SESSION+RSVP_CTYPE_13, "IPv4 P2MP LSP Tunnel" },
{ 256*RSVP_OBJ_SESSION+RSVP_CTYPE_14, "IPv6 P2MP LSP Tunnel" },
{ 256*RSVP_OBJ_SENDER_TEMPLATE+RSVP_CTYPE_IPV4, "IPv4" },
{ 256*RSVP_OBJ_SENDER_TEMPLATE+RSVP_CTYPE_IPV6, "IPv6" },
{ 256*RSVP_OBJ_SENDER_TEMPLATE+RSVP_CTYPE_TUNNEL_IPV4, "Tunnel IPv4" },
{ 256*RSVP_OBJ_SENDER_TEMPLATE+RSVP_CTYPE_12, "IPv4 P2MP LSP Tunnel" },
{ 256*RSVP_OBJ_SENDER_TEMPLATE+RSVP_CTYPE_13, "IPv6 P2MP LSP Tunnel" },
{ 256*RSVP_OBJ_MESSAGE_ID+RSVP_CTYPE_1, "1" },
{ 256*RSVP_OBJ_MESSAGE_ID_ACK+RSVP_CTYPE_1, "Message id ack" },
{ 256*RSVP_OBJ_MESSAGE_ID_ACK+RSVP_CTYPE_2, "Message id nack" },
{ 256*RSVP_OBJ_MESSAGE_ID_LIST+RSVP_CTYPE_1, "1" },
{ 256*RSVP_OBJ_STYLE+RSVP_CTYPE_1, "1" },
{ 256*RSVP_OBJ_HELLO+RSVP_CTYPE_1, "Hello Request" },
{ 256*RSVP_OBJ_HELLO+RSVP_CTYPE_2, "Hello Ack" },
{ 256*RSVP_OBJ_LABEL_REQ+RSVP_CTYPE_1, "without label range" },
{ 256*RSVP_OBJ_LABEL_REQ+RSVP_CTYPE_2, "with ATM label range" },
{ 256*RSVP_OBJ_LABEL_REQ+RSVP_CTYPE_3, "with FR label range" },
{ 256*RSVP_OBJ_LABEL_REQ+RSVP_CTYPE_4, "Generalized Label" },
{ 256*RSVP_OBJ_LABEL+RSVP_CTYPE_1, "Label" },
{ 256*RSVP_OBJ_LABEL+RSVP_CTYPE_2, "Generalized Label" },
{ 256*RSVP_OBJ_LABEL+RSVP_CTYPE_3, "Waveband Switching" },
{ 256*RSVP_OBJ_SUGGESTED_LABEL+RSVP_CTYPE_1, "Label" },
{ 256*RSVP_OBJ_SUGGESTED_LABEL+RSVP_CTYPE_2, "Generalized Label" },
{ 256*RSVP_OBJ_SUGGESTED_LABEL+RSVP_CTYPE_3, "Waveband Switching" },
{ 256*RSVP_OBJ_UPSTREAM_LABEL+RSVP_CTYPE_1, "Label" },
{ 256*RSVP_OBJ_UPSTREAM_LABEL+RSVP_CTYPE_2, "Generalized Label" },
{ 256*RSVP_OBJ_UPSTREAM_LABEL+RSVP_CTYPE_3, "Waveband Switching" },
{ 256*RSVP_OBJ_RECOVERY_LABEL+RSVP_CTYPE_1, "Label" },
{ 256*RSVP_OBJ_RECOVERY_LABEL+RSVP_CTYPE_2, "Generalized Label" },
{ 256*RSVP_OBJ_RECOVERY_LABEL+RSVP_CTYPE_3, "Waveband Switching" },
{ 256*RSVP_OBJ_ERO+RSVP_CTYPE_IPV4, "IPv4" },
{ 256*RSVP_OBJ_RRO+RSVP_CTYPE_IPV4, "IPv4" },
{ 256*RSVP_OBJ_ERROR_SPEC+RSVP_CTYPE_IPV4, "IPv4" },
{ 256*RSVP_OBJ_ERROR_SPEC+RSVP_CTYPE_IPV6, "IPv6" },
{ 256*RSVP_OBJ_ERROR_SPEC+RSVP_CTYPE_3, "IPv4 plus opt. TLVs" },
{ 256*RSVP_OBJ_ERROR_SPEC+RSVP_CTYPE_4, "IPv6 plus opt. TLVs" },
{ 256*RSVP_OBJ_RESTART_CAPABILITY+RSVP_CTYPE_1, "IPv4" },
{ 256*RSVP_OBJ_SESSION_ATTRIBUTE+RSVP_CTYPE_TUNNEL_IPV4, "Tunnel IPv4" },
{ 256*RSVP_OBJ_FASTREROUTE+RSVP_CTYPE_TUNNEL_IPV4, "Tunnel IPv4" }, /* old style*/
{ 256*RSVP_OBJ_FASTREROUTE+RSVP_CTYPE_1, "1" }, /* new style */
{ 256*RSVP_OBJ_DETOUR+RSVP_CTYPE_TUNNEL_IPV4, "Tunnel IPv4" },
{ 256*RSVP_OBJ_PROPERTIES+RSVP_CTYPE_1, "1" },
{ 256*RSVP_OBJ_ADMIN_STATUS+RSVP_CTYPE_1, "1" },
{ 256*RSVP_OBJ_CLASSTYPE+RSVP_CTYPE_1, "1" },
{ 256*RSVP_OBJ_CLASSTYPE_OLD+RSVP_CTYPE_1, "1" },
{ 256*RSVP_OBJ_LABEL_SET+RSVP_CTYPE_1, "1" },
{ 256*RSVP_OBJ_GENERALIZED_UNI+RSVP_CTYPE_1, "1" },
{ 256*RSVP_OBJ_S2L+RSVP_CTYPE_IPV4, "IPv4 sub-LSP" },
{ 256*RSVP_OBJ_S2L+RSVP_CTYPE_IPV6, "IPv6 sub-LSP" },
{ 0, NULL}
};
struct rsvp_obj_integrity_t {
uint8_t flags;
uint8_t res;
uint8_t key_id[6];
uint8_t sequence[8];
uint8_t digest[16];
};
static const struct tok rsvp_obj_integrity_flag_values[] = {
{ 0x80, "Handshake" },
{ 0, NULL}
};
struct rsvp_obj_frr_t {
uint8_t setup_prio;
uint8_t hold_prio;
uint8_t hop_limit;
uint8_t flags;
uint8_t bandwidth[4];
uint8_t include_any[4];
uint8_t exclude_any[4];
uint8_t include_all[4];
};
#define RSVP_OBJ_XRO_MASK_SUBOBJ(x) ((x)&0x7f)
#define RSVP_OBJ_XRO_MASK_LOOSE(x) ((x)&0x80)
#define RSVP_OBJ_XRO_RES 0
#define RSVP_OBJ_XRO_IPV4 1
#define RSVP_OBJ_XRO_IPV6 2
#define RSVP_OBJ_XRO_LABEL 3
#define RSVP_OBJ_XRO_ASN 32
#define RSVP_OBJ_XRO_MPLS 64
static const struct tok rsvp_obj_xro_values[] = {
{ RSVP_OBJ_XRO_RES, "Reserved" },
{ RSVP_OBJ_XRO_IPV4, "IPv4 prefix" },
{ RSVP_OBJ_XRO_IPV6, "IPv6 prefix" },
{ RSVP_OBJ_XRO_LABEL, "Label" },
{ RSVP_OBJ_XRO_ASN, "Autonomous system number" },
{ RSVP_OBJ_XRO_MPLS, "MPLS label switched path termination" },
{ 0, NULL}
};
/* draft-ietf-mpls-rsvp-lsp-fastreroute-07.txt */
static const struct tok rsvp_obj_rro_flag_values[] = {
{ 0x01, "Local protection available" },
{ 0x02, "Local protection in use" },
{ 0x04, "Bandwidth protection" },
{ 0x08, "Node protection" },
{ 0, NULL}
};
/* RFC3209 */
static const struct tok rsvp_obj_rro_label_flag_values[] = {
{ 0x01, "Global" },
{ 0, NULL}
};
static const struct tok rsvp_resstyle_values[] = {
{ 17, "Wildcard Filter" },
{ 10, "Fixed Filter" },
{ 18, "Shared Explicit" },
{ 0, NULL}
};
#define RSVP_OBJ_INTSERV_GUARANTEED_SERV 2
#define RSVP_OBJ_INTSERV_CONTROLLED_LOAD 5
static const struct tok rsvp_intserv_service_type_values[] = {
{ 1, "Default/Global Information" },
{ RSVP_OBJ_INTSERV_GUARANTEED_SERV, "Guaranteed Service" },
{ RSVP_OBJ_INTSERV_CONTROLLED_LOAD, "Controlled Load" },
{ 0, NULL}
};
static const struct tok rsvp_intserv_parameter_id_values[] = {
{ 4, "IS hop cnt" },
{ 6, "Path b/w estimate" },
{ 8, "Minimum path latency" },
{ 10, "Composed MTU" },
{ 127, "Token Bucket TSpec" },
{ 130, "Guaranteed Service RSpec" },
{ 133, "End-to-end composed value for C" },
{ 134, "End-to-end composed value for D" },
{ 135, "Since-last-reshaping point composed C" },
{ 136, "Since-last-reshaping point composed D" },
{ 0, NULL}
};
static const struct tok rsvp_session_attribute_flag_values[] = {
{ 0x01, "Local Protection" },
{ 0x02, "Label Recording" },
{ 0x04, "SE Style" },
{ 0x08, "Bandwidth protection" }, /* RFC4090 */
{ 0x10, "Node protection" }, /* RFC4090 */
{ 0, NULL}
};
static const struct tok rsvp_obj_prop_tlv_values[] = {
{ 0x01, "Cos" },
{ 0x02, "Metric 1" },
{ 0x04, "Metric 2" },
{ 0x08, "CCC Status" },
{ 0x10, "Path Type" },
{ 0, NULL}
};
#define RSVP_OBJ_ERROR_SPEC_CODE_ROUTING 24
#define RSVP_OBJ_ERROR_SPEC_CODE_NOTIFY 25
#define RSVP_OBJ_ERROR_SPEC_CODE_DIFFSERV_TE 28
#define RSVP_OBJ_ERROR_SPEC_CODE_DIFFSERV_TE_OLD 125
static const struct tok rsvp_obj_error_code_values[] = {
{ RSVP_OBJ_ERROR_SPEC_CODE_ROUTING, "Routing Problem" },
{ RSVP_OBJ_ERROR_SPEC_CODE_NOTIFY, "Notify Error" },
{ RSVP_OBJ_ERROR_SPEC_CODE_DIFFSERV_TE, "Diffserv TE Error" },
{ RSVP_OBJ_ERROR_SPEC_CODE_DIFFSERV_TE_OLD, "Diffserv TE Error (Old)" },
{ 0, NULL}
};
static const struct tok rsvp_obj_error_code_routing_values[] = {
{ 1, "Bad EXPLICIT_ROUTE object" },
{ 2, "Bad strict node" },
{ 3, "Bad loose node" },
{ 4, "Bad initial subobject" },
{ 5, "No route available toward destination" },
{ 6, "Unacceptable label value" },
{ 7, "RRO indicated routing loops" },
{ 8, "non-RSVP-capable router in the path" },
{ 9, "MPLS label allocation failure" },
{ 10, "Unsupported L3PID" },
{ 0, NULL}
};
static const struct tok rsvp_obj_error_code_diffserv_te_values[] = {
{ 1, "Unexpected CT object" },
{ 2, "Unsupported CT" },
{ 3, "Invalid CT value" },
{ 4, "CT/setup priority do not form a configured TE-Class" },
{ 5, "CT/holding priority do not form a configured TE-Class" },
{ 6, "CT/setup priority and CT/holding priority do not form a configured TE-Class" },
{ 7, "Inconsistency between signaled PSC and signaled CT" },
{ 8, "Inconsistency between signaled PHBs and signaled CT" },
{ 0, NULL}
};
/* rfc3473 / rfc 3471 */
static const struct tok rsvp_obj_admin_status_flag_values[] = {
{ 0x80000000, "Reflect" },
{ 0x00000004, "Testing" },
{ 0x00000002, "Admin-down" },
{ 0x00000001, "Delete-in-progress" },
{ 0, NULL}
};
/* label set actions - rfc3471 */
#define LABEL_SET_INCLUSIVE_LIST 0
#define LABEL_SET_EXCLUSIVE_LIST 1
#define LABEL_SET_INCLUSIVE_RANGE 2
#define LABEL_SET_EXCLUSIVE_RANGE 3
static const struct tok rsvp_obj_label_set_action_values[] = {
{ LABEL_SET_INCLUSIVE_LIST, "Inclusive list" },
{ LABEL_SET_EXCLUSIVE_LIST, "Exclusive list" },
{ LABEL_SET_INCLUSIVE_RANGE, "Inclusive range" },
{ LABEL_SET_EXCLUSIVE_RANGE, "Exclusive range" },
{ 0, NULL}
};
/* OIF RSVP extensions UNI 1.0 Signaling, release 2 */
#define RSVP_GEN_UNI_SUBOBJ_SOURCE_TNA_ADDRESS 1
#define RSVP_GEN_UNI_SUBOBJ_DESTINATION_TNA_ADDRESS 2
#define RSVP_GEN_UNI_SUBOBJ_DIVERSITY 3
#define RSVP_GEN_UNI_SUBOBJ_EGRESS_LABEL 4
#define RSVP_GEN_UNI_SUBOBJ_SERVICE_LEVEL 5
static const struct tok rsvp_obj_generalized_uni_values[] = {
{ RSVP_GEN_UNI_SUBOBJ_SOURCE_TNA_ADDRESS, "Source TNA address" },
{ RSVP_GEN_UNI_SUBOBJ_DESTINATION_TNA_ADDRESS, "Destination TNA address" },
{ RSVP_GEN_UNI_SUBOBJ_DIVERSITY, "Diversity" },
{ RSVP_GEN_UNI_SUBOBJ_EGRESS_LABEL, "Egress label" },
{ RSVP_GEN_UNI_SUBOBJ_SERVICE_LEVEL, "Service level" },
{ 0, NULL}
};
/*
* this is a dissector for all the intserv defined
* specs as defined per rfc2215
* it is called from various rsvp objects;
* returns the amount of bytes being processed
*/
static int
rsvp_intserv_print(netdissect_options *ndo,
const u_char *tptr, u_short obj_tlen)
{
int parameter_id,parameter_length;
union {
float f;
uint32_t i;
} bw;
if (obj_tlen < 4)
return 0;
parameter_id = *(tptr);
ND_TCHECK2(*(tptr + 2), 2);
parameter_length = EXTRACT_16BITS(tptr+2)<<2; /* convert wordcount to bytecount */
ND_PRINT((ndo, "\n\t Parameter ID: %s (%u), length: %u, Flags: [0x%02x]",
tok2str(rsvp_intserv_parameter_id_values,"unknown",parameter_id),
parameter_id,
parameter_length,
*(tptr + 1)));
if (obj_tlen < parameter_length+4)
return 0;
switch(parameter_id) { /* parameter_id */
case 4:
/*
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | 4 (e) | (f) | 1 (g) |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | IS hop cnt (32-bit unsigned integer) |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*/
if (parameter_length == 4) {
ND_TCHECK2(*(tptr + 4), 4);
ND_PRINT((ndo, "\n\t\tIS hop count: %u", EXTRACT_32BITS(tptr + 4)));
}
break;
case 6:
/*
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | 6 (h) | (i) | 1 (j) |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Path b/w estimate (32-bit IEEE floating point number) |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*/
if (parameter_length == 4) {
ND_TCHECK2(*(tptr + 4), 4);
bw.i = EXTRACT_32BITS(tptr+4);
ND_PRINT((ndo, "\n\t\tPath b/w estimate: %.10g Mbps", bw.f / 125000));
}
break;
case 8:
/*
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | 8 (k) | (l) | 1 (m) |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Minimum path latency (32-bit integer) |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*/
if (parameter_length == 4) {
ND_TCHECK2(*(tptr + 4), 4);
ND_PRINT((ndo, "\n\t\tMinimum path latency: "));
if (EXTRACT_32BITS(tptr+4) == 0xffffffff)
ND_PRINT((ndo, "don't care"));
else
ND_PRINT((ndo, "%u", EXTRACT_32BITS(tptr + 4)));
}
break;
case 10:
/*
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | 10 (n) | (o) | 1 (p) |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Composed MTU (32-bit unsigned integer) |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*/
if (parameter_length == 4) {
ND_TCHECK2(*(tptr + 4), 4);
ND_PRINT((ndo, "\n\t\tComposed MTU: %u bytes", EXTRACT_32BITS(tptr + 4)));
}
break;
case 127:
/*
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | 127 (e) | 0 (f) | 5 (g) |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Token Bucket Rate [r] (32-bit IEEE floating point number) |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Token Bucket Size [b] (32-bit IEEE floating point number) |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Peak Data Rate [p] (32-bit IEEE floating point number) |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Minimum Policed Unit [m] (32-bit integer) |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Maximum Packet Size [M] (32-bit integer) |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*/
if (parameter_length == 20) {
ND_TCHECK2(*(tptr + 4), 20);
bw.i = EXTRACT_32BITS(tptr+4);
ND_PRINT((ndo, "\n\t\tToken Bucket Rate: %.10g Mbps", bw.f / 125000));
bw.i = EXTRACT_32BITS(tptr+8);
ND_PRINT((ndo, "\n\t\tToken Bucket Size: %.10g bytes", bw.f));
bw.i = EXTRACT_32BITS(tptr+12);
ND_PRINT((ndo, "\n\t\tPeak Data Rate: %.10g Mbps", bw.f / 125000));
ND_PRINT((ndo, "\n\t\tMinimum Policed Unit: %u bytes", EXTRACT_32BITS(tptr + 16)));
ND_PRINT((ndo, "\n\t\tMaximum Packet Size: %u bytes", EXTRACT_32BITS(tptr + 20)));
}
break;
case 130:
/*
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | 130 (h) | 0 (i) | 2 (j) |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Rate [R] (32-bit IEEE floating point number) |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Slack Term [S] (32-bit integer) |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*/
if (parameter_length == 8) {
ND_TCHECK2(*(tptr + 4), 8);
bw.i = EXTRACT_32BITS(tptr+4);
ND_PRINT((ndo, "\n\t\tRate: %.10g Mbps", bw.f / 125000));
ND_PRINT((ndo, "\n\t\tSlack Term: %u", EXTRACT_32BITS(tptr + 8)));
}
break;
case 133:
case 134:
case 135:
case 136:
if (parameter_length == 4) {
ND_TCHECK2(*(tptr + 4), 4);
ND_PRINT((ndo, "\n\t\tValue: %u", EXTRACT_32BITS(tptr + 4)));
}
break;
default:
if (ndo->ndo_vflag <= 1)
print_unknown_data(ndo, tptr + 4, "\n\t\t", parameter_length);
}
return (parameter_length+4); /* header length 4 bytes */
trunc:
ND_PRINT((ndo, "%s", tstr));
return 0;
}
/*
* Clear checksum prior to signature verification.
*/
static void
rsvp_clear_checksum(void *header)
{
struct rsvp_common_header *rsvp_com_header = (struct rsvp_common_header *) header;
rsvp_com_header->checksum[0] = 0;
rsvp_com_header->checksum[1] = 0;
}
static int
rsvp_obj_print(netdissect_options *ndo,
const u_char *pptr, u_int plen, const u_char *tptr,
const char *ident, u_int tlen,
const struct rsvp_common_header *rsvp_com_header)
{
const struct rsvp_object_header *rsvp_obj_header;
const u_char *obj_tptr;
union {
const struct rsvp_obj_integrity_t *rsvp_obj_integrity;
const struct rsvp_obj_frr_t *rsvp_obj_frr;
} obj_ptr;
u_short rsvp_obj_len,rsvp_obj_ctype,obj_tlen,intserv_serv_tlen;
int hexdump,processed,padbytes,error_code,error_value,i,sigcheck;
union {
float f;
uint32_t i;
} bw;
uint8_t namelen;
u_int action, subchannel;
while(tlen>=sizeof(struct rsvp_object_header)) {
/* did we capture enough for fully decoding the object header ? */
ND_TCHECK2(*tptr, sizeof(struct rsvp_object_header));
rsvp_obj_header = (const struct rsvp_object_header *)tptr;
rsvp_obj_len=EXTRACT_16BITS(rsvp_obj_header->length);
rsvp_obj_ctype=rsvp_obj_header->ctype;
if(rsvp_obj_len % 4) {
ND_PRINT((ndo, "%sERROR: object header size %u not a multiple of 4", ident, rsvp_obj_len));
return -1;
}
if(rsvp_obj_len < sizeof(struct rsvp_object_header)) {
ND_PRINT((ndo, "%sERROR: object header too short %u < %lu", ident, rsvp_obj_len,
(unsigned long)sizeof(const struct rsvp_object_header)));
return -1;
}
ND_PRINT((ndo, "%s%s Object (%u) Flags: [%s",
ident,
tok2str(rsvp_obj_values,
"Unknown",
rsvp_obj_header->class_num),
rsvp_obj_header->class_num,
((rsvp_obj_header->class_num) & 0x80) ? "ignore" : "reject"));
if (rsvp_obj_header->class_num > 128)
ND_PRINT((ndo, " %s",
((rsvp_obj_header->class_num) & 0x40) ? "and forward" : "silently"));
ND_PRINT((ndo, " if unknown], Class-Type: %s (%u), length: %u",
tok2str(rsvp_ctype_values,
"Unknown",
((rsvp_obj_header->class_num)<<8)+rsvp_obj_ctype),
rsvp_obj_ctype,
rsvp_obj_len));
if(tlen < rsvp_obj_len) {
ND_PRINT((ndo, "%sERROR: object goes past end of objects TLV", ident));
return -1;
}
obj_tptr=tptr+sizeof(struct rsvp_object_header);
obj_tlen=rsvp_obj_len-sizeof(struct rsvp_object_header);
/* did we capture enough for fully decoding the object ? */
if (!ND_TTEST2(*tptr, rsvp_obj_len))
return -1;
hexdump=FALSE;
switch(rsvp_obj_header->class_num) {
case RSVP_OBJ_SESSION:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_IPV4:
if (obj_tlen < 8)
return -1;
ND_PRINT((ndo, "%s IPv4 DestAddress: %s, Protocol ID: 0x%02x",
ident,
ipaddr_string(ndo, obj_tptr),
*(obj_tptr + sizeof(struct in_addr))));
ND_PRINT((ndo, "%s Flags: [0x%02x], DestPort %u",
ident,
*(obj_tptr+5),
EXTRACT_16BITS(obj_tptr + 6)));
obj_tlen-=8;
obj_tptr+=8;
break;
case RSVP_CTYPE_IPV6:
if (obj_tlen < 20)
return -1;
ND_PRINT((ndo, "%s IPv6 DestAddress: %s, Protocol ID: 0x%02x",
ident,
ip6addr_string(ndo, obj_tptr),
*(obj_tptr + sizeof(struct in6_addr))));
ND_PRINT((ndo, "%s Flags: [0x%02x], DestPort %u",
ident,
*(obj_tptr+sizeof(struct in6_addr)+1),
EXTRACT_16BITS(obj_tptr + sizeof(struct in6_addr) + 2)));
obj_tlen-=20;
obj_tptr+=20;
break;
case RSVP_CTYPE_TUNNEL_IPV6:
if (obj_tlen < 36)
return -1;
ND_PRINT((ndo, "%s IPv6 Tunnel EndPoint: %s, Tunnel ID: 0x%04x, Extended Tunnel ID: %s",
ident,
ip6addr_string(ndo, obj_tptr),
EXTRACT_16BITS(obj_tptr+18),
ip6addr_string(ndo, obj_tptr + 20)));
obj_tlen-=36;
obj_tptr+=36;
break;
case RSVP_CTYPE_14: /* IPv6 p2mp LSP Tunnel */
if (obj_tlen < 26)
return -1;
ND_PRINT((ndo, "%s IPv6 P2MP LSP ID: 0x%08x, Tunnel ID: 0x%04x, Extended Tunnel ID: %s",
ident,
EXTRACT_32BITS(obj_tptr),
EXTRACT_16BITS(obj_tptr+6),
ip6addr_string(ndo, obj_tptr + 8)));
obj_tlen-=26;
obj_tptr+=26;
break;
case RSVP_CTYPE_13: /* IPv4 p2mp LSP Tunnel */
if (obj_tlen < 12)
return -1;
ND_PRINT((ndo, "%s IPv4 P2MP LSP ID: %s, Tunnel ID: 0x%04x, Extended Tunnel ID: %s",
ident,
ipaddr_string(ndo, obj_tptr),
EXTRACT_16BITS(obj_tptr+6),
ipaddr_string(ndo, obj_tptr + 8)));
obj_tlen-=12;
obj_tptr+=12;
break;
case RSVP_CTYPE_TUNNEL_IPV4:
case RSVP_CTYPE_UNI_IPV4:
if (obj_tlen < 12)
return -1;
ND_PRINT((ndo, "%s IPv4 Tunnel EndPoint: %s, Tunnel ID: 0x%04x, Extended Tunnel ID: %s",
ident,
ipaddr_string(ndo, obj_tptr),
EXTRACT_16BITS(obj_tptr+6),
ipaddr_string(ndo, obj_tptr + 8)));
obj_tlen-=12;
obj_tptr+=12;
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_CONFIRM:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_IPV4:
if (obj_tlen < sizeof(struct in_addr))
return -1;
ND_PRINT((ndo, "%s IPv4 Receiver Address: %s",
ident,
ipaddr_string(ndo, obj_tptr)));
obj_tlen-=sizeof(struct in_addr);
obj_tptr+=sizeof(struct in_addr);
break;
case RSVP_CTYPE_IPV6:
if (obj_tlen < sizeof(struct in6_addr))
return -1;
ND_PRINT((ndo, "%s IPv6 Receiver Address: %s",
ident,
ip6addr_string(ndo, obj_tptr)));
obj_tlen-=sizeof(struct in6_addr);
obj_tptr+=sizeof(struct in6_addr);
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_NOTIFY_REQ:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_IPV4:
if (obj_tlen < sizeof(struct in_addr))
return -1;
ND_PRINT((ndo, "%s IPv4 Notify Node Address: %s",
ident,
ipaddr_string(ndo, obj_tptr)));
obj_tlen-=sizeof(struct in_addr);
obj_tptr+=sizeof(struct in_addr);
break;
case RSVP_CTYPE_IPV6:
if (obj_tlen < sizeof(struct in6_addr))
return-1;
ND_PRINT((ndo, "%s IPv6 Notify Node Address: %s",
ident,
ip6addr_string(ndo, obj_tptr)));
obj_tlen-=sizeof(struct in6_addr);
obj_tptr+=sizeof(struct in6_addr);
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_SUGGESTED_LABEL: /* fall through */
case RSVP_OBJ_UPSTREAM_LABEL: /* fall through */
case RSVP_OBJ_RECOVERY_LABEL: /* fall through */
case RSVP_OBJ_LABEL:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_1:
while(obj_tlen >= 4 ) {
ND_PRINT((ndo, "%s Label: %u", ident, EXTRACT_32BITS(obj_tptr)));
obj_tlen-=4;
obj_tptr+=4;
}
break;
case RSVP_CTYPE_2:
if (obj_tlen < 4)
return-1;
ND_PRINT((ndo, "%s Generalized Label: %u",
ident,
EXTRACT_32BITS(obj_tptr)));
obj_tlen-=4;
obj_tptr+=4;
break;
case RSVP_CTYPE_3:
if (obj_tlen < 12)
return-1;
ND_PRINT((ndo, "%s Waveband ID: %u%s Start Label: %u, Stop Label: %u",
ident,
EXTRACT_32BITS(obj_tptr),
ident,
EXTRACT_32BITS(obj_tptr+4),
EXTRACT_32BITS(obj_tptr + 8)));
obj_tlen-=12;
obj_tptr+=12;
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_STYLE:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_1:
if (obj_tlen < 4)
return-1;
ND_PRINT((ndo, "%s Reservation Style: %s, Flags: [0x%02x]",
ident,
tok2str(rsvp_resstyle_values,
"Unknown",
EXTRACT_24BITS(obj_tptr+1)),
*(obj_tptr)));
obj_tlen-=4;
obj_tptr+=4;
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_SENDER_TEMPLATE:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_IPV4:
if (obj_tlen < 8)
return-1;
ND_PRINT((ndo, "%s Source Address: %s, Source Port: %u",
ident,
ipaddr_string(ndo, obj_tptr),
EXTRACT_16BITS(obj_tptr + 6)));
obj_tlen-=8;
obj_tptr+=8;
break;
case RSVP_CTYPE_IPV6:
if (obj_tlen < 20)
return-1;
ND_PRINT((ndo, "%s Source Address: %s, Source Port: %u",
ident,
ip6addr_string(ndo, obj_tptr),
EXTRACT_16BITS(obj_tptr + 18)));
obj_tlen-=20;
obj_tptr+=20;
break;
case RSVP_CTYPE_13: /* IPv6 p2mp LSP tunnel */
if (obj_tlen < 40)
return-1;
ND_PRINT((ndo, "%s IPv6 Tunnel Sender Address: %s, LSP ID: 0x%04x"
"%s Sub-Group Originator ID: %s, Sub-Group ID: 0x%04x",
ident,
ip6addr_string(ndo, obj_tptr),
EXTRACT_16BITS(obj_tptr+18),
ident,
ip6addr_string(ndo, obj_tptr+20),
EXTRACT_16BITS(obj_tptr + 38)));
obj_tlen-=40;
obj_tptr+=40;
break;
case RSVP_CTYPE_TUNNEL_IPV4:
if (obj_tlen < 8)
return-1;
ND_PRINT((ndo, "%s IPv4 Tunnel Sender Address: %s, LSP-ID: 0x%04x",
ident,
ipaddr_string(ndo, obj_tptr),
EXTRACT_16BITS(obj_tptr + 6)));
obj_tlen-=8;
obj_tptr+=8;
break;
case RSVP_CTYPE_12: /* IPv4 p2mp LSP tunnel */
if (obj_tlen < 16)
return-1;
ND_PRINT((ndo, "%s IPv4 Tunnel Sender Address: %s, LSP ID: 0x%04x"
"%s Sub-Group Originator ID: %s, Sub-Group ID: 0x%04x",
ident,
ipaddr_string(ndo, obj_tptr),
EXTRACT_16BITS(obj_tptr+6),
ident,
ipaddr_string(ndo, obj_tptr+8),
EXTRACT_16BITS(obj_tptr + 12)));
obj_tlen-=16;
obj_tptr+=16;
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_LABEL_REQ:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_1:
while(obj_tlen >= 4 ) {
ND_PRINT((ndo, "%s L3 Protocol ID: %s",
ident,
tok2str(ethertype_values,
"Unknown Protocol (0x%04x)",
EXTRACT_16BITS(obj_tptr + 2))));
obj_tlen-=4;
obj_tptr+=4;
}
break;
case RSVP_CTYPE_2:
if (obj_tlen < 12)
return-1;
ND_PRINT((ndo, "%s L3 Protocol ID: %s",
ident,
tok2str(ethertype_values,
"Unknown Protocol (0x%04x)",
EXTRACT_16BITS(obj_tptr + 2))));
ND_PRINT((ndo, ",%s merge capability",((*(obj_tptr + 4)) & 0x80) ? "no" : "" ));
ND_PRINT((ndo, "%s Minimum VPI/VCI: %u/%u",
ident,
(EXTRACT_16BITS(obj_tptr+4))&0xfff,
(EXTRACT_16BITS(obj_tptr + 6)) & 0xfff));
ND_PRINT((ndo, "%s Maximum VPI/VCI: %u/%u",
ident,
(EXTRACT_16BITS(obj_tptr+8))&0xfff,
(EXTRACT_16BITS(obj_tptr + 10)) & 0xfff));
obj_tlen-=12;
obj_tptr+=12;
break;
case RSVP_CTYPE_3:
if (obj_tlen < 12)
return-1;
ND_PRINT((ndo, "%s L3 Protocol ID: %s",
ident,
tok2str(ethertype_values,
"Unknown Protocol (0x%04x)",
EXTRACT_16BITS(obj_tptr + 2))));
ND_PRINT((ndo, "%s Minimum/Maximum DLCI: %u/%u, %s%s bit DLCI",
ident,
(EXTRACT_32BITS(obj_tptr+4))&0x7fffff,
(EXTRACT_32BITS(obj_tptr+8))&0x7fffff,
(((EXTRACT_16BITS(obj_tptr+4)>>7)&3) == 0 ) ? "10" : "",
(((EXTRACT_16BITS(obj_tptr + 4) >> 7) & 3) == 2 ) ? "23" : ""));
obj_tlen-=12;
obj_tptr+=12;
break;
case RSVP_CTYPE_4:
if (obj_tlen < 4)
return-1;
ND_PRINT((ndo, "%s LSP Encoding Type: %s (%u)",
ident,
tok2str(gmpls_encoding_values,
"Unknown",
*obj_tptr),
*obj_tptr));
ND_PRINT((ndo, "%s Switching Type: %s (%u), Payload ID: %s (0x%04x)",
ident,
tok2str(gmpls_switch_cap_values,
"Unknown",
*(obj_tptr+1)),
*(obj_tptr+1),
tok2str(gmpls_payload_values,
"Unknown",
EXTRACT_16BITS(obj_tptr+2)),
EXTRACT_16BITS(obj_tptr + 2)));
obj_tlen-=4;
obj_tptr+=4;
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_RRO:
case RSVP_OBJ_ERO:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_IPV4:
while(obj_tlen >= 4 ) {
u_char length;
ND_TCHECK2(*obj_tptr, 4);
length = *(obj_tptr + 1);
ND_PRINT((ndo, "%s Subobject Type: %s, length %u",
ident,
tok2str(rsvp_obj_xro_values,
"Unknown %u",
RSVP_OBJ_XRO_MASK_SUBOBJ(*obj_tptr)),
length));
if (length == 0) { /* prevent infinite loops */
ND_PRINT((ndo, "%s ERROR: zero length ERO subtype", ident));
break;
}
switch(RSVP_OBJ_XRO_MASK_SUBOBJ(*obj_tptr)) {
u_char prefix_length;
case RSVP_OBJ_XRO_IPV4:
if (length != 8) {
ND_PRINT((ndo, " ERROR: length != 8"));
goto invalid;
}
ND_TCHECK2(*obj_tptr, 8);
prefix_length = *(obj_tptr+6);
if (prefix_length != 32) {
ND_PRINT((ndo, " ERROR: Prefix length %u != 32",
prefix_length));
goto invalid;
}
ND_PRINT((ndo, ", %s, %s/%u, Flags: [%s]",
RSVP_OBJ_XRO_MASK_LOOSE(*obj_tptr) ? "Loose" : "Strict",
ipaddr_string(ndo, obj_tptr+2),
*(obj_tptr+6),
bittok2str(rsvp_obj_rro_flag_values,
"none",
*(obj_tptr + 7)))); /* rfc3209 says that this field is rsvd. */
break;
case RSVP_OBJ_XRO_LABEL:
if (length != 8) {
ND_PRINT((ndo, " ERROR: length != 8"));
goto invalid;
}
ND_TCHECK2(*obj_tptr, 8);
ND_PRINT((ndo, ", Flags: [%s] (%#x), Class-Type: %s (%u), %u",
bittok2str(rsvp_obj_rro_label_flag_values,
"none",
*(obj_tptr+2)),
*(obj_tptr+2),
tok2str(rsvp_ctype_values,
"Unknown",
*(obj_tptr+3) + 256*RSVP_OBJ_RRO),
*(obj_tptr+3),
EXTRACT_32BITS(obj_tptr + 4)));
}
obj_tlen-=*(obj_tptr+1);
obj_tptr+=*(obj_tptr+1);
}
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_HELLO:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_1:
case RSVP_CTYPE_2:
if (obj_tlen < 8)
return-1;
ND_PRINT((ndo, "%s Source Instance: 0x%08x, Destination Instance: 0x%08x",
ident,
EXTRACT_32BITS(obj_tptr),
EXTRACT_32BITS(obj_tptr + 4)));
obj_tlen-=8;
obj_tptr+=8;
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_RESTART_CAPABILITY:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_1:
if (obj_tlen < 8)
return-1;
ND_PRINT((ndo, "%s Restart Time: %ums, Recovery Time: %ums",
ident,
EXTRACT_32BITS(obj_tptr),
EXTRACT_32BITS(obj_tptr + 4)));
obj_tlen-=8;
obj_tptr+=8;
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_SESSION_ATTRIBUTE:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_TUNNEL_IPV4:
if (obj_tlen < 4)
return-1;
namelen = *(obj_tptr+3);
if (obj_tlen < 4+namelen)
return-1;
ND_PRINT((ndo, "%s Session Name: ", ident));
for (i = 0; i < namelen; i++)
safeputchar(ndo, *(obj_tptr + 4 + i));
ND_PRINT((ndo, "%s Setup Priority: %u, Holding Priority: %u, Flags: [%s] (%#x)",
ident,
(int)*obj_tptr,
(int)*(obj_tptr+1),
bittok2str(rsvp_session_attribute_flag_values,
"none",
*(obj_tptr+2)),
*(obj_tptr + 2)));
obj_tlen-=4+*(obj_tptr+3);
obj_tptr+=4+*(obj_tptr+3);
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_GENERALIZED_UNI:
switch(rsvp_obj_ctype) {
int subobj_type,af,subobj_len,total_subobj_len;
case RSVP_CTYPE_1:
if (obj_tlen < 4)
return-1;
/* read variable length subobjects */
total_subobj_len = obj_tlen;
while(total_subobj_len > 0) {
subobj_len = EXTRACT_16BITS(obj_tptr);
subobj_type = (EXTRACT_16BITS(obj_tptr+2))>>8;
af = (EXTRACT_16BITS(obj_tptr+2))&0x00FF;
ND_PRINT((ndo, "%s Subobject Type: %s (%u), AF: %s (%u), length: %u",
ident,
tok2str(rsvp_obj_generalized_uni_values, "Unknown", subobj_type),
subobj_type,
tok2str(af_values, "Unknown", af), af,
subobj_len));
if(subobj_len == 0)
goto invalid;
switch(subobj_type) {
case RSVP_GEN_UNI_SUBOBJ_SOURCE_TNA_ADDRESS:
case RSVP_GEN_UNI_SUBOBJ_DESTINATION_TNA_ADDRESS:
switch(af) {
case AFNUM_INET:
if (subobj_len < 8)
return -1;
ND_PRINT((ndo, "%s UNI IPv4 TNA address: %s",
ident, ipaddr_string(ndo, obj_tptr + 4)));
break;
case AFNUM_INET6:
if (subobj_len < 20)
return -1;
ND_PRINT((ndo, "%s UNI IPv6 TNA address: %s",
ident, ip6addr_string(ndo, obj_tptr + 4)));
break;
case AFNUM_NSAP:
if (subobj_len) {
/* unless we have a TLV parser lets just hexdump */
hexdump=TRUE;
}
break;
}
break;
case RSVP_GEN_UNI_SUBOBJ_DIVERSITY:
if (subobj_len) {
/* unless we have a TLV parser lets just hexdump */
hexdump=TRUE;
}
break;
case RSVP_GEN_UNI_SUBOBJ_EGRESS_LABEL:
if (subobj_len < 16) {
return -1;
}
ND_PRINT((ndo, "%s U-bit: %x, Label type: %u, Logical port id: %u, Label: %u",
ident,
((EXTRACT_32BITS(obj_tptr+4))>>31),
((EXTRACT_32BITS(obj_tptr+4))&0xFF),
EXTRACT_32BITS(obj_tptr+8),
EXTRACT_32BITS(obj_tptr + 12)));
break;
case RSVP_GEN_UNI_SUBOBJ_SERVICE_LEVEL:
if (subobj_len < 8) {
return -1;
}
ND_PRINT((ndo, "%s Service level: %u",
ident, (EXTRACT_32BITS(obj_tptr + 4)) >> 24));
break;
default:
hexdump=TRUE;
break;
}
total_subobj_len-=subobj_len;
obj_tptr+=subobj_len;
obj_tlen+=subobj_len;
}
if (total_subobj_len) {
/* unless we have a TLV parser lets just hexdump */
hexdump=TRUE;
}
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_RSVP_HOP:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_3: /* fall through - FIXME add TLV parser */
case RSVP_CTYPE_IPV4:
if (obj_tlen < 8)
return-1;
ND_PRINT((ndo, "%s Previous/Next Interface: %s, Logical Interface Handle: 0x%08x",
ident,
ipaddr_string(ndo, obj_tptr),
EXTRACT_32BITS(obj_tptr + 4)));
obj_tlen-=8;
obj_tptr+=8;
if (obj_tlen)
hexdump=TRUE; /* unless we have a TLV parser lets just hexdump */
break;
case RSVP_CTYPE_4: /* fall through - FIXME add TLV parser */
case RSVP_CTYPE_IPV6:
if (obj_tlen < 20)
return-1;
ND_PRINT((ndo, "%s Previous/Next Interface: %s, Logical Interface Handle: 0x%08x",
ident,
ip6addr_string(ndo, obj_tptr),
EXTRACT_32BITS(obj_tptr + 16)));
obj_tlen-=20;
obj_tptr+=20;
hexdump=TRUE; /* unless we have a TLV parser lets just hexdump */
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_TIME_VALUES:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_1:
if (obj_tlen < 4)
return-1;
ND_PRINT((ndo, "%s Refresh Period: %ums",
ident,
EXTRACT_32BITS(obj_tptr)));
obj_tlen-=4;
obj_tptr+=4;
break;
default:
hexdump=TRUE;
}
break;
/* those three objects do share the same semantics */
case RSVP_OBJ_SENDER_TSPEC:
case RSVP_OBJ_ADSPEC:
case RSVP_OBJ_FLOWSPEC:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_2:
if (obj_tlen < 4)
return-1;
ND_PRINT((ndo, "%s Msg-Version: %u, length: %u",
ident,
(*obj_tptr & 0xf0) >> 4,
EXTRACT_16BITS(obj_tptr + 2) << 2));
obj_tptr+=4; /* get to the start of the service header */
obj_tlen-=4;
while (obj_tlen >= 4) {
intserv_serv_tlen=EXTRACT_16BITS(obj_tptr+2)<<2;
ND_PRINT((ndo, "%s Service Type: %s (%u), break bit %s set, Service length: %u",
ident,
tok2str(rsvp_intserv_service_type_values,"unknown",*(obj_tptr)),
*(obj_tptr),
(*(obj_tptr+1)&0x80) ? "" : "not",
intserv_serv_tlen));
obj_tptr+=4; /* get to the start of the parameter list */
obj_tlen-=4;
while (intserv_serv_tlen>=4) {
processed = rsvp_intserv_print(ndo, obj_tptr, obj_tlen);
if (processed == 0)
break;
obj_tlen-=processed;
intserv_serv_tlen-=processed;
obj_tptr+=processed;
}
}
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_FILTERSPEC:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_IPV4:
if (obj_tlen < 8)
return-1;
ND_PRINT((ndo, "%s Source Address: %s, Source Port: %u",
ident,
ipaddr_string(ndo, obj_tptr),
EXTRACT_16BITS(obj_tptr + 6)));
obj_tlen-=8;
obj_tptr+=8;
break;
case RSVP_CTYPE_IPV6:
if (obj_tlen < 20)
return-1;
ND_PRINT((ndo, "%s Source Address: %s, Source Port: %u",
ident,
ip6addr_string(ndo, obj_tptr),
EXTRACT_16BITS(obj_tptr + 18)));
obj_tlen-=20;
obj_tptr+=20;
break;
case RSVP_CTYPE_3:
if (obj_tlen < 20)
return-1;
ND_PRINT((ndo, "%s Source Address: %s, Flow Label: %u",
ident,
ip6addr_string(ndo, obj_tptr),
EXTRACT_24BITS(obj_tptr + 17)));
obj_tlen-=20;
obj_tptr+=20;
break;
case RSVP_CTYPE_TUNNEL_IPV6:
if (obj_tlen < 20)
return-1;
ND_PRINT((ndo, "%s Source Address: %s, LSP-ID: 0x%04x",
ident,
ipaddr_string(ndo, obj_tptr),
EXTRACT_16BITS(obj_tptr + 18)));
obj_tlen-=20;
obj_tptr+=20;
break;
case RSVP_CTYPE_13: /* IPv6 p2mp LSP tunnel */
if (obj_tlen < 40)
return-1;
ND_PRINT((ndo, "%s IPv6 Tunnel Sender Address: %s, LSP ID: 0x%04x"
"%s Sub-Group Originator ID: %s, Sub-Group ID: 0x%04x",
ident,
ip6addr_string(ndo, obj_tptr),
EXTRACT_16BITS(obj_tptr+18),
ident,
ip6addr_string(ndo, obj_tptr+20),
EXTRACT_16BITS(obj_tptr + 38)));
obj_tlen-=40;
obj_tptr+=40;
break;
case RSVP_CTYPE_TUNNEL_IPV4:
if (obj_tlen < 8)
return-1;
ND_PRINT((ndo, "%s Source Address: %s, LSP-ID: 0x%04x",
ident,
ipaddr_string(ndo, obj_tptr),
EXTRACT_16BITS(obj_tptr + 6)));
obj_tlen-=8;
obj_tptr+=8;
break;
case RSVP_CTYPE_12: /* IPv4 p2mp LSP tunnel */
if (obj_tlen < 16)
return-1;
ND_PRINT((ndo, "%s IPv4 Tunnel Sender Address: %s, LSP ID: 0x%04x"
"%s Sub-Group Originator ID: %s, Sub-Group ID: 0x%04x",
ident,
ipaddr_string(ndo, obj_tptr),
EXTRACT_16BITS(obj_tptr+6),
ident,
ipaddr_string(ndo, obj_tptr+8),
EXTRACT_16BITS(obj_tptr + 12)));
obj_tlen-=16;
obj_tptr+=16;
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_FASTREROUTE:
/* the differences between c-type 1 and 7 are minor */
obj_ptr.rsvp_obj_frr = (const struct rsvp_obj_frr_t *)obj_tptr;
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_1: /* new style */
if (obj_tlen < sizeof(struct rsvp_obj_frr_t))
return-1;
bw.i = EXTRACT_32BITS(obj_ptr.rsvp_obj_frr->bandwidth);
ND_PRINT((ndo, "%s Setup Priority: %u, Holding Priority: %u, Hop-limit: %u, Bandwidth: %.10g Mbps",
ident,
(int)obj_ptr.rsvp_obj_frr->setup_prio,
(int)obj_ptr.rsvp_obj_frr->hold_prio,
(int)obj_ptr.rsvp_obj_frr->hop_limit,
bw.f * 8 / 1000000));
ND_PRINT((ndo, "%s Include-any: 0x%08x, Exclude-any: 0x%08x, Include-all: 0x%08x",
ident,
EXTRACT_32BITS(obj_ptr.rsvp_obj_frr->include_any),
EXTRACT_32BITS(obj_ptr.rsvp_obj_frr->exclude_any),
EXTRACT_32BITS(obj_ptr.rsvp_obj_frr->include_all)));
obj_tlen-=sizeof(struct rsvp_obj_frr_t);
obj_tptr+=sizeof(struct rsvp_obj_frr_t);
break;
case RSVP_CTYPE_TUNNEL_IPV4: /* old style */
if (obj_tlen < 16)
return-1;
bw.i = EXTRACT_32BITS(obj_ptr.rsvp_obj_frr->bandwidth);
ND_PRINT((ndo, "%s Setup Priority: %u, Holding Priority: %u, Hop-limit: %u, Bandwidth: %.10g Mbps",
ident,
(int)obj_ptr.rsvp_obj_frr->setup_prio,
(int)obj_ptr.rsvp_obj_frr->hold_prio,
(int)obj_ptr.rsvp_obj_frr->hop_limit,
bw.f * 8 / 1000000));
ND_PRINT((ndo, "%s Include Colors: 0x%08x, Exclude Colors: 0x%08x",
ident,
EXTRACT_32BITS(obj_ptr.rsvp_obj_frr->include_any),
EXTRACT_32BITS(obj_ptr.rsvp_obj_frr->exclude_any)));
obj_tlen-=16;
obj_tptr+=16;
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_DETOUR:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_TUNNEL_IPV4:
while(obj_tlen >= 8) {
ND_PRINT((ndo, "%s PLR-ID: %s, Avoid-Node-ID: %s",
ident,
ipaddr_string(ndo, obj_tptr),
ipaddr_string(ndo, obj_tptr + 4)));
obj_tlen-=8;
obj_tptr+=8;
}
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_CLASSTYPE:
case RSVP_OBJ_CLASSTYPE_OLD: /* fall through */
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_1:
ND_PRINT((ndo, "%s CT: %u",
ident,
EXTRACT_32BITS(obj_tptr) & 0x7));
obj_tlen-=4;
obj_tptr+=4;
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_ERROR_SPEC:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_3: /* fall through - FIXME add TLV parser */
case RSVP_CTYPE_IPV4:
if (obj_tlen < 8)
return-1;
error_code=*(obj_tptr+5);
error_value=EXTRACT_16BITS(obj_tptr+6);
ND_PRINT((ndo, "%s Error Node Address: %s, Flags: [0x%02x]%s Error Code: %s (%u)",
ident,
ipaddr_string(ndo, obj_tptr),
*(obj_tptr+4),
ident,
tok2str(rsvp_obj_error_code_values,"unknown",error_code),
error_code));
switch (error_code) {
case RSVP_OBJ_ERROR_SPEC_CODE_ROUTING:
ND_PRINT((ndo, ", Error Value: %s (%u)",
tok2str(rsvp_obj_error_code_routing_values,"unknown",error_value),
error_value));
break;
case RSVP_OBJ_ERROR_SPEC_CODE_DIFFSERV_TE: /* fall through */
case RSVP_OBJ_ERROR_SPEC_CODE_DIFFSERV_TE_OLD:
ND_PRINT((ndo, ", Error Value: %s (%u)",
tok2str(rsvp_obj_error_code_diffserv_te_values,"unknown",error_value),
error_value));
break;
default:
ND_PRINT((ndo, ", Unknown Error Value (%u)", error_value));
break;
}
obj_tlen-=8;
obj_tptr+=8;
break;
case RSVP_CTYPE_4: /* fall through - FIXME add TLV parser */
case RSVP_CTYPE_IPV6:
if (obj_tlen < 20)
return-1;
error_code=*(obj_tptr+17);
error_value=EXTRACT_16BITS(obj_tptr+18);
ND_PRINT((ndo, "%s Error Node Address: %s, Flags: [0x%02x]%s Error Code: %s (%u)",
ident,
ip6addr_string(ndo, obj_tptr),
*(obj_tptr+16),
ident,
tok2str(rsvp_obj_error_code_values,"unknown",error_code),
error_code));
switch (error_code) {
case RSVP_OBJ_ERROR_SPEC_CODE_ROUTING:
ND_PRINT((ndo, ", Error Value: %s (%u)",
tok2str(rsvp_obj_error_code_routing_values,"unknown",error_value),
error_value));
break;
default:
break;
}
obj_tlen-=20;
obj_tptr+=20;
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_PROPERTIES:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_1:
if (obj_tlen < 4)
return-1;
padbytes = EXTRACT_16BITS(obj_tptr+2);
ND_PRINT((ndo, "%s TLV count: %u, padding bytes: %u",
ident,
EXTRACT_16BITS(obj_tptr),
padbytes));
obj_tlen-=4;
obj_tptr+=4;
/* loop through as long there is anything longer than the TLV header (2) */
while(obj_tlen >= 2 + padbytes) {
ND_PRINT((ndo, "%s %s TLV (0x%02x), length: %u", /* length includes header */
ident,
tok2str(rsvp_obj_prop_tlv_values,"unknown",*obj_tptr),
*obj_tptr,
*(obj_tptr + 1)));
if (obj_tlen < *(obj_tptr+1))
return-1;
if (*(obj_tptr+1) < 2)
return -1;
print_unknown_data(ndo, obj_tptr + 2, "\n\t\t", *(obj_tptr + 1) - 2);
obj_tlen-=*(obj_tptr+1);
obj_tptr+=*(obj_tptr+1);
}
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_MESSAGE_ID: /* fall through */
case RSVP_OBJ_MESSAGE_ID_ACK: /* fall through */
case RSVP_OBJ_MESSAGE_ID_LIST:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_1:
case RSVP_CTYPE_2:
if (obj_tlen < 8)
return-1;
ND_PRINT((ndo, "%s Flags [0x%02x], epoch: %u",
ident,
*obj_tptr,
EXTRACT_24BITS(obj_tptr + 1)));
obj_tlen-=4;
obj_tptr+=4;
/* loop through as long there are no messages left */
while(obj_tlen >= 4) {
ND_PRINT((ndo, "%s Message-ID 0x%08x (%u)",
ident,
EXTRACT_32BITS(obj_tptr),
EXTRACT_32BITS(obj_tptr)));
obj_tlen-=4;
obj_tptr+=4;
}
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_INTEGRITY:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_1:
if (obj_tlen < sizeof(struct rsvp_obj_integrity_t))
return-1;
obj_ptr.rsvp_obj_integrity = (const struct rsvp_obj_integrity_t *)obj_tptr;
ND_PRINT((ndo, "%s Key-ID 0x%04x%08x, Sequence 0x%08x%08x, Flags [%s]",
ident,
EXTRACT_16BITS(obj_ptr.rsvp_obj_integrity->key_id),
EXTRACT_32BITS(obj_ptr.rsvp_obj_integrity->key_id+2),
EXTRACT_32BITS(obj_ptr.rsvp_obj_integrity->sequence),
EXTRACT_32BITS(obj_ptr.rsvp_obj_integrity->sequence+4),
bittok2str(rsvp_obj_integrity_flag_values,
"none",
obj_ptr.rsvp_obj_integrity->flags)));
ND_PRINT((ndo, "%s MD5-sum 0x%08x%08x%08x%08x ",
ident,
EXTRACT_32BITS(obj_ptr.rsvp_obj_integrity->digest),
EXTRACT_32BITS(obj_ptr.rsvp_obj_integrity->digest+4),
EXTRACT_32BITS(obj_ptr.rsvp_obj_integrity->digest+8),
EXTRACT_32BITS(obj_ptr.rsvp_obj_integrity->digest + 12)));
sigcheck = signature_verify(ndo, pptr, plen,
obj_ptr.rsvp_obj_integrity->digest,
rsvp_clear_checksum,
rsvp_com_header);
ND_PRINT((ndo, " (%s)", tok2str(signature_check_values, "Unknown", sigcheck)));
obj_tlen+=sizeof(struct rsvp_obj_integrity_t);
obj_tptr+=sizeof(struct rsvp_obj_integrity_t);
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_ADMIN_STATUS:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_1:
if (obj_tlen < 4)
return-1;
ND_PRINT((ndo, "%s Flags [%s]", ident,
bittok2str(rsvp_obj_admin_status_flag_values, "none",
EXTRACT_32BITS(obj_tptr))));
obj_tlen-=4;
obj_tptr+=4;
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_LABEL_SET:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_1:
if (obj_tlen < 4)
return-1;
action = (EXTRACT_16BITS(obj_tptr)>>8);
ND_PRINT((ndo, "%s Action: %s (%u), Label type: %u", ident,
tok2str(rsvp_obj_label_set_action_values, "Unknown", action),
action, ((EXTRACT_32BITS(obj_tptr) & 0x7F))));
switch (action) {
case LABEL_SET_INCLUSIVE_RANGE:
case LABEL_SET_EXCLUSIVE_RANGE: /* fall through */
/* only a couple of subchannels are expected */
if (obj_tlen < 12)
return -1;
ND_PRINT((ndo, "%s Start range: %u, End range: %u", ident,
EXTRACT_32BITS(obj_tptr+4),
EXTRACT_32BITS(obj_tptr + 8)));
obj_tlen-=12;
obj_tptr+=12;
break;
default:
obj_tlen-=4;
obj_tptr+=4;
subchannel = 1;
while(obj_tlen >= 4 ) {
ND_PRINT((ndo, "%s Subchannel #%u: %u", ident, subchannel,
EXTRACT_32BITS(obj_tptr)));
obj_tptr+=4;
obj_tlen-=4;
subchannel++;
}
break;
}
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_S2L:
switch (rsvp_obj_ctype) {
case RSVP_CTYPE_IPV4:
if (obj_tlen < 4)
return-1;
ND_PRINT((ndo, "%s Sub-LSP destination address: %s",
ident, ipaddr_string(ndo, obj_tptr)));
obj_tlen-=4;
obj_tptr+=4;
break;
case RSVP_CTYPE_IPV6:
if (obj_tlen < 16)
return-1;
ND_PRINT((ndo, "%s Sub-LSP destination address: %s",
ident, ip6addr_string(ndo, obj_tptr)));
obj_tlen-=16;
obj_tptr+=16;
break;
default:
hexdump=TRUE;
}
break;
/*
* FIXME those are the defined objects that lack a decoder
* you are welcome to contribute code ;-)
*/
case RSVP_OBJ_SCOPE:
case RSVP_OBJ_POLICY_DATA:
case RSVP_OBJ_ACCEPT_LABEL_SET:
case RSVP_OBJ_PROTECTION:
default:
if (ndo->ndo_vflag <= 1)
print_unknown_data(ndo, obj_tptr, "\n\t ", obj_tlen); /* FIXME indentation */
break;
}
/* do we also want to see a hex dump ? */
if (ndo->ndo_vflag > 1 || hexdump == TRUE)
print_unknown_data(ndo, tptr + sizeof(struct rsvp_object_header), "\n\t ", /* FIXME indentation */
rsvp_obj_len - sizeof(struct rsvp_object_header));
tptr+=rsvp_obj_len;
tlen-=rsvp_obj_len;
}
return 0;
invalid:
ND_PRINT((ndo, "%s", istr));
return -1;
trunc:
ND_PRINT((ndo, "\n\t\t"));
ND_PRINT((ndo, "%s", tstr));
return -1;
}
void
rsvp_print(netdissect_options *ndo,
register const u_char *pptr, register u_int len)
{
const struct rsvp_common_header *rsvp_com_header;
const u_char *tptr;
u_short plen, tlen;
tptr=pptr;
rsvp_com_header = (const struct rsvp_common_header *)pptr;
ND_TCHECK(*rsvp_com_header);
/*
* Sanity checking of the header.
*/
if (RSVP_EXTRACT_VERSION(rsvp_com_header->version_flags) != RSVP_VERSION) {
ND_PRINT((ndo, "ERROR: RSVP version %u packet not supported",
RSVP_EXTRACT_VERSION(rsvp_com_header->version_flags)));
return;
}
/* in non-verbose mode just lets print the basic Message Type*/
if (ndo->ndo_vflag < 1) {
ND_PRINT((ndo, "RSVPv%u %s Message, length: %u",
RSVP_EXTRACT_VERSION(rsvp_com_header->version_flags),
tok2str(rsvp_msg_type_values, "unknown (%u)",rsvp_com_header->msg_type),
len));
return;
}
/* ok they seem to want to know everything - lets fully decode it */
plen = tlen = EXTRACT_16BITS(rsvp_com_header->length);
ND_PRINT((ndo, "\n\tRSVPv%u %s Message (%u), Flags: [%s], length: %u, ttl: %u, checksum: 0x%04x",
RSVP_EXTRACT_VERSION(rsvp_com_header->version_flags),
tok2str(rsvp_msg_type_values, "unknown, type: %u",rsvp_com_header->msg_type),
rsvp_com_header->msg_type,
bittok2str(rsvp_header_flag_values,"none",RSVP_EXTRACT_FLAGS(rsvp_com_header->version_flags)),
tlen,
rsvp_com_header->ttl,
EXTRACT_16BITS(rsvp_com_header->checksum)));
if (tlen < sizeof(const struct rsvp_common_header)) {
ND_PRINT((ndo, "ERROR: common header too short %u < %lu", tlen,
(unsigned long)sizeof(const struct rsvp_common_header)));
return;
}
tptr+=sizeof(const struct rsvp_common_header);
tlen-=sizeof(const struct rsvp_common_header);
switch(rsvp_com_header->msg_type) {
case RSVP_MSGTYPE_BUNDLE:
/*
* Process each submessage in the bundle message.
* Bundle messages may not contain bundle submessages, so we don't
* need to handle bundle submessages specially.
*/
while(tlen > 0) {
const u_char *subpptr=tptr, *subtptr;
u_short subplen, subtlen;
subtptr=subpptr;
rsvp_com_header = (const struct rsvp_common_header *)subpptr;
ND_TCHECK(*rsvp_com_header);
/*
* Sanity checking of the header.
*/
if (RSVP_EXTRACT_VERSION(rsvp_com_header->version_flags) != RSVP_VERSION) {
ND_PRINT((ndo, "ERROR: RSVP version %u packet not supported",
RSVP_EXTRACT_VERSION(rsvp_com_header->version_flags)));
return;
}
subplen = subtlen = EXTRACT_16BITS(rsvp_com_header->length);
ND_PRINT((ndo, "\n\t RSVPv%u %s Message (%u), Flags: [%s], length: %u, ttl: %u, checksum: 0x%04x",
RSVP_EXTRACT_VERSION(rsvp_com_header->version_flags),
tok2str(rsvp_msg_type_values, "unknown, type: %u",rsvp_com_header->msg_type),
rsvp_com_header->msg_type,
bittok2str(rsvp_header_flag_values,"none",RSVP_EXTRACT_FLAGS(rsvp_com_header->version_flags)),
subtlen,
rsvp_com_header->ttl,
EXTRACT_16BITS(rsvp_com_header->checksum)));
if (subtlen < sizeof(const struct rsvp_common_header)) {
ND_PRINT((ndo, "ERROR: common header too short %u < %lu", subtlen,
(unsigned long)sizeof(const struct rsvp_common_header)));
return;
}
if (tlen < subtlen) {
ND_PRINT((ndo, "ERROR: common header too large %u > %u", subtlen,
tlen));
return;
}
subtptr+=sizeof(const struct rsvp_common_header);
subtlen-=sizeof(const struct rsvp_common_header);
/*
* Print all objects in the submessage.
*/
if (rsvp_obj_print(ndo, subpptr, subplen, subtptr, "\n\t ", subtlen, rsvp_com_header) == -1)
return;
tptr+=subtlen+sizeof(const struct rsvp_common_header);
tlen-=subtlen+sizeof(const struct rsvp_common_header);
}
break;
case RSVP_MSGTYPE_PATH:
case RSVP_MSGTYPE_RESV:
case RSVP_MSGTYPE_PATHERR:
case RSVP_MSGTYPE_RESVERR:
case RSVP_MSGTYPE_PATHTEAR:
case RSVP_MSGTYPE_RESVTEAR:
case RSVP_MSGTYPE_RESVCONF:
case RSVP_MSGTYPE_HELLO_OLD:
case RSVP_MSGTYPE_HELLO:
case RSVP_MSGTYPE_ACK:
case RSVP_MSGTYPE_SREFRESH:
/*
* Print all objects in the message.
*/
if (rsvp_obj_print(ndo, pptr, plen, tptr, "\n\t ", tlen, rsvp_com_header) == -1)
return;
break;
default:
print_unknown_data(ndo, tptr, "\n\t ", tlen);
break;
}
return;
trunc:
ND_PRINT((ndo, "\n\t\t"));
ND_PRINT((ndo, "%s", tstr));
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/good_2724_0 |
crossvul-cpp_data_bad_2708_0 | /*
* Copyright (C) 2000 Alfredo Andres Omella. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* 3. The 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 ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
/* \summary: Radius protocol printer */
/*
* Radius printer routines as specified on:
*
* RFC 2865:
* "Remote Authentication Dial In User Service (RADIUS)"
*
* RFC 2866:
* "RADIUS Accounting"
*
* RFC 2867:
* "RADIUS Accounting Modifications for Tunnel Protocol Support"
*
* RFC 2868:
* "RADIUS Attributes for Tunnel Protocol Support"
*
* RFC 2869:
* "RADIUS Extensions"
*
* RFC 3580:
* "IEEE 802.1X Remote Authentication Dial In User Service (RADIUS)"
* "Usage Guidelines"
*
* RFC 4675:
* "RADIUS Attributes for Virtual LAN and Priority Support"
*
* RFC 4849:
* "RADIUS Filter Rule Attribute"
*
* RFC 5176:
* "Dynamic Authorization Extensions to RADIUS"
*
* RFC 7155:
* "Diameter Network Access Server Application"
*
* Alfredo Andres Omella (aandres@s21sec.com) v0.1 2000/09/15
*
* TODO: Among other things to print ok MacIntosh and Vendor values
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <netdissect-stdinc.h>
#include <string.h>
#include "netdissect.h"
#include "addrtoname.h"
#include "extract.h"
#include "oui.h"
static const char tstr[] = " [|radius]";
#define TAM_SIZE(x) (sizeof(x)/sizeof(x[0]) )
#define PRINT_HEX(bytes_len, ptr_data) \
while(bytes_len) \
{ \
ND_PRINT((ndo, "%02X", *ptr_data )); \
ptr_data++; \
bytes_len--; \
}
/* Radius packet codes */
#define RADCMD_ACCESS_REQ 1 /* Access-Request */
#define RADCMD_ACCESS_ACC 2 /* Access-Accept */
#define RADCMD_ACCESS_REJ 3 /* Access-Reject */
#define RADCMD_ACCOUN_REQ 4 /* Accounting-Request */
#define RADCMD_ACCOUN_RES 5 /* Accounting-Response */
#define RADCMD_ACCESS_CHA 11 /* Access-Challenge */
#define RADCMD_STATUS_SER 12 /* Status-Server */
#define RADCMD_STATUS_CLI 13 /* Status-Client */
#define RADCMD_DISCON_REQ 40 /* Disconnect-Request */
#define RADCMD_DISCON_ACK 41 /* Disconnect-ACK */
#define RADCMD_DISCON_NAK 42 /* Disconnect-NAK */
#define RADCMD_COA_REQ 43 /* CoA-Request */
#define RADCMD_COA_ACK 44 /* CoA-ACK */
#define RADCMD_COA_NAK 45 /* CoA-NAK */
#define RADCMD_RESERVED 255 /* Reserved */
static const struct tok radius_command_values[] = {
{ RADCMD_ACCESS_REQ, "Access-Request" },
{ RADCMD_ACCESS_ACC, "Access-Accept" },
{ RADCMD_ACCESS_REJ, "Access-Reject" },
{ RADCMD_ACCOUN_REQ, "Accounting-Request" },
{ RADCMD_ACCOUN_RES, "Accounting-Response" },
{ RADCMD_ACCESS_CHA, "Access-Challenge" },
{ RADCMD_STATUS_SER, "Status-Server" },
{ RADCMD_STATUS_CLI, "Status-Client" },
{ RADCMD_DISCON_REQ, "Disconnect-Request" },
{ RADCMD_DISCON_ACK, "Disconnect-ACK" },
{ RADCMD_DISCON_NAK, "Disconnect-NAK" },
{ RADCMD_COA_REQ, "CoA-Request" },
{ RADCMD_COA_ACK, "CoA-ACK" },
{ RADCMD_COA_NAK, "CoA-NAK" },
{ RADCMD_RESERVED, "Reserved" },
{ 0, NULL}
};
/********************************/
/* Begin Radius Attribute types */
/********************************/
#define SERV_TYPE 6
#define FRM_IPADDR 8
#define LOG_IPHOST 14
#define LOG_SERVICE 15
#define FRM_IPX 23
#define SESSION_TIMEOUT 27
#define IDLE_TIMEOUT 28
#define FRM_ATALK_LINK 37
#define FRM_ATALK_NETWORK 38
#define ACCT_DELAY 41
#define ACCT_SESSION_TIME 46
#define EGRESS_VLAN_ID 56
#define EGRESS_VLAN_NAME 58
#define TUNNEL_TYPE 64
#define TUNNEL_MEDIUM 65
#define TUNNEL_CLIENT_END 66
#define TUNNEL_SERVER_END 67
#define TUNNEL_PASS 69
#define ARAP_PASS 70
#define ARAP_FEATURES 71
#define TUNNEL_PRIV_GROUP 81
#define TUNNEL_ASSIGN_ID 82
#define TUNNEL_PREFERENCE 83
#define ARAP_CHALLENGE_RESP 84
#define ACCT_INT_INTERVAL 85
#define TUNNEL_CLIENT_AUTH 90
#define TUNNEL_SERVER_AUTH 91
/********************************/
/* End Radius Attribute types */
/********************************/
#define RFC4675_TAGGED 0x31
#define RFC4675_UNTAGGED 0x32
static const struct tok rfc4675_tagged[] = {
{ RFC4675_TAGGED, "Tagged" },
{ RFC4675_UNTAGGED, "Untagged" },
{ 0, NULL}
};
static void print_attr_string(netdissect_options *, register const u_char *, u_int, u_short );
static void print_attr_num(netdissect_options *, register const u_char *, u_int, u_short );
static void print_vendor_attr(netdissect_options *, register const u_char *, u_int, u_short );
static void print_attr_address(netdissect_options *, register const u_char *, u_int, u_short);
static void print_attr_time(netdissect_options *, register const u_char *, u_int, u_short);
static void print_attr_strange(netdissect_options *, register const u_char *, u_int, u_short);
struct radius_hdr { uint8_t code; /* Radius packet code */
uint8_t id; /* Radius packet id */
uint16_t len; /* Radius total length */
uint8_t auth[16]; /* Authenticator */
};
#define MIN_RADIUS_LEN 20
struct radius_attr { uint8_t type; /* Attribute type */
uint8_t len; /* Attribute length */
};
/* Service-Type Attribute standard values */
static const char *serv_type[]={ NULL,
"Login",
"Framed",
"Callback Login",
"Callback Framed",
"Outbound",
"Administrative",
"NAS Prompt",
"Authenticate Only",
"Callback NAS Prompt",
"Call Check",
"Callback Administrative",
};
/* Framed-Protocol Attribute standard values */
static const char *frm_proto[]={ NULL,
"PPP",
"SLIP",
"ARAP",
"Gandalf proprietary",
"Xylogics IPX/SLIP",
"X.75 Synchronous",
};
/* Framed-Routing Attribute standard values */
static const char *frm_routing[]={ "None",
"Send",
"Listen",
"Send&Listen",
};
/* Framed-Compression Attribute standard values */
static const char *frm_comp[]={ "None",
"VJ TCP/IP",
"IPX",
"Stac-LZS",
};
/* Login-Service Attribute standard values */
static const char *login_serv[]={ "Telnet",
"Rlogin",
"TCP Clear",
"PortMaster(proprietary)",
"LAT",
"X.25-PAD",
"X.25-T3POS",
"Unassigned",
"TCP Clear Quiet",
};
/* Termination-Action Attribute standard values */
static const char *term_action[]={ "Default",
"RADIUS-Request",
};
/* Ingress-Filters Attribute standard values */
static const char *ingress_filters[]={ NULL,
"Enabled",
"Disabled",
};
/* NAS-Port-Type Attribute standard values */
static const char *nas_port_type[]={ "Async",
"Sync",
"ISDN Sync",
"ISDN Async V.120",
"ISDN Async V.110",
"Virtual",
"PIAFS",
"HDLC Clear Channel",
"X.25",
"X.75",
"G.3 Fax",
"SDSL",
"ADSL-CAP",
"ADSL-DMT",
"ISDN-DSL",
"Ethernet",
"xDSL",
"Cable",
"Wireless - Other",
"Wireless - IEEE 802.11",
};
/* Acct-Status-Type Accounting Attribute standard values */
static const char *acct_status[]={ NULL,
"Start",
"Stop",
"Interim-Update",
"Unassigned",
"Unassigned",
"Unassigned",
"Accounting-On",
"Accounting-Off",
"Tunnel-Start",
"Tunnel-Stop",
"Tunnel-Reject",
"Tunnel-Link-Start",
"Tunnel-Link-Stop",
"Tunnel-Link-Reject",
"Failed",
};
/* Acct-Authentic Accounting Attribute standard values */
static const char *acct_auth[]={ NULL,
"RADIUS",
"Local",
"Remote",
};
/* Acct-Terminate-Cause Accounting Attribute standard values */
static const char *acct_term[]={ NULL,
"User Request",
"Lost Carrier",
"Lost Service",
"Idle Timeout",
"Session Timeout",
"Admin Reset",
"Admin Reboot",
"Port Error",
"NAS Error",
"NAS Request",
"NAS Reboot",
"Port Unneeded",
"Port Preempted",
"Port Suspended",
"Service Unavailable",
"Callback",
"User Error",
"Host Request",
};
/* Tunnel-Type Attribute standard values */
static const char *tunnel_type[]={ NULL,
"PPTP",
"L2F",
"L2TP",
"ATMP",
"VTP",
"AH",
"IP-IP",
"MIN-IP-IP",
"ESP",
"GRE",
"DVS",
"IP-in-IP Tunneling",
"VLAN",
};
/* Tunnel-Medium-Type Attribute standard values */
static const char *tunnel_medium[]={ NULL,
"IPv4",
"IPv6",
"NSAP",
"HDLC",
"BBN 1822",
"802",
"E.163",
"E.164",
"F.69",
"X.121",
"IPX",
"Appletalk",
"Decnet IV",
"Banyan Vines",
"E.164 with NSAP subaddress",
};
/* ARAP-Zone-Access Attribute standard values */
static const char *arap_zone[]={ NULL,
"Only access to dfl zone",
"Use zone filter inc.",
"Not used",
"Use zone filter exc.",
};
static const char *prompt[]={ "No Echo",
"Echo",
};
static struct attrtype {
const char *name; /* Attribute name */
const char **subtypes; /* Standard Values (if any) */
u_char siz_subtypes; /* Size of total standard values */
u_char first_subtype; /* First standard value is 0 or 1 */
void (*print_func)(netdissect_options *, register const u_char *, u_int, u_short);
} attr_type[]=
{
{ NULL, NULL, 0, 0, NULL },
{ "User-Name", NULL, 0, 0, print_attr_string },
{ "User-Password", NULL, 0, 0, NULL },
{ "CHAP-Password", NULL, 0, 0, NULL },
{ "NAS-IP-Address", NULL, 0, 0, print_attr_address },
{ "NAS-Port", NULL, 0, 0, print_attr_num },
{ "Service-Type", serv_type, TAM_SIZE(serv_type)-1, 1, print_attr_num },
{ "Framed-Protocol", frm_proto, TAM_SIZE(frm_proto)-1, 1, print_attr_num },
{ "Framed-IP-Address", NULL, 0, 0, print_attr_address },
{ "Framed-IP-Netmask", NULL, 0, 0, print_attr_address },
{ "Framed-Routing", frm_routing, TAM_SIZE(frm_routing), 0, print_attr_num },
{ "Filter-Id", NULL, 0, 0, print_attr_string },
{ "Framed-MTU", NULL, 0, 0, print_attr_num },
{ "Framed-Compression", frm_comp, TAM_SIZE(frm_comp), 0, print_attr_num },
{ "Login-IP-Host", NULL, 0, 0, print_attr_address },
{ "Login-Service", login_serv, TAM_SIZE(login_serv), 0, print_attr_num },
{ "Login-TCP-Port", NULL, 0, 0, print_attr_num },
{ "Unassigned", NULL, 0, 0, NULL }, /*17*/
{ "Reply-Message", NULL, 0, 0, print_attr_string },
{ "Callback-Number", NULL, 0, 0, print_attr_string },
{ "Callback-Id", NULL, 0, 0, print_attr_string },
{ "Unassigned", NULL, 0, 0, NULL }, /*21*/
{ "Framed-Route", NULL, 0, 0, print_attr_string },
{ "Framed-IPX-Network", NULL, 0, 0, print_attr_num },
{ "State", NULL, 0, 0, print_attr_string },
{ "Class", NULL, 0, 0, print_attr_string },
{ "Vendor-Specific", NULL, 0, 0, print_vendor_attr },
{ "Session-Timeout", NULL, 0, 0, print_attr_num },
{ "Idle-Timeout", NULL, 0, 0, print_attr_num },
{ "Termination-Action", term_action, TAM_SIZE(term_action), 0, print_attr_num },
{ "Called-Station-Id", NULL, 0, 0, print_attr_string },
{ "Calling-Station-Id", NULL, 0, 0, print_attr_string },
{ "NAS-Identifier", NULL, 0, 0, print_attr_string },
{ "Proxy-State", NULL, 0, 0, print_attr_string },
{ "Login-LAT-Service", NULL, 0, 0, print_attr_string },
{ "Login-LAT-Node", NULL, 0, 0, print_attr_string },
{ "Login-LAT-Group", NULL, 0, 0, print_attr_string },
{ "Framed-AppleTalk-Link", NULL, 0, 0, print_attr_num },
{ "Framed-AppleTalk-Network", NULL, 0, 0, print_attr_num },
{ "Framed-AppleTalk-Zone", NULL, 0, 0, print_attr_string },
{ "Acct-Status-Type", acct_status, TAM_SIZE(acct_status)-1, 1, print_attr_num },
{ "Acct-Delay-Time", NULL, 0, 0, print_attr_num },
{ "Acct-Input-Octets", NULL, 0, 0, print_attr_num },
{ "Acct-Output-Octets", NULL, 0, 0, print_attr_num },
{ "Acct-Session-Id", NULL, 0, 0, print_attr_string },
{ "Acct-Authentic", acct_auth, TAM_SIZE(acct_auth)-1, 1, print_attr_num },
{ "Acct-Session-Time", NULL, 0, 0, print_attr_num },
{ "Acct-Input-Packets", NULL, 0, 0, print_attr_num },
{ "Acct-Output-Packets", NULL, 0, 0, print_attr_num },
{ "Acct-Terminate-Cause", acct_term, TAM_SIZE(acct_term)-1, 1, print_attr_num },
{ "Acct-Multi-Session-Id", NULL, 0, 0, print_attr_string },
{ "Acct-Link-Count", NULL, 0, 0, print_attr_num },
{ "Acct-Input-Gigawords", NULL, 0, 0, print_attr_num },
{ "Acct-Output-Gigawords", NULL, 0, 0, print_attr_num },
{ "Unassigned", NULL, 0, 0, NULL }, /*54*/
{ "Event-Timestamp", NULL, 0, 0, print_attr_time },
{ "Egress-VLANID", NULL, 0, 0, print_attr_num },
{ "Ingress-Filters", ingress_filters, TAM_SIZE(ingress_filters)-1, 1, print_attr_num },
{ "Egress-VLAN-Name", NULL, 0, 0, print_attr_string },
{ "User-Priority-Table", NULL, 0, 0, NULL },
{ "CHAP-Challenge", NULL, 0, 0, print_attr_string },
{ "NAS-Port-Type", nas_port_type, TAM_SIZE(nas_port_type), 0, print_attr_num },
{ "Port-Limit", NULL, 0, 0, print_attr_num },
{ "Login-LAT-Port", NULL, 0, 0, print_attr_string }, /*63*/
{ "Tunnel-Type", tunnel_type, TAM_SIZE(tunnel_type)-1, 1, print_attr_num },
{ "Tunnel-Medium-Type", tunnel_medium, TAM_SIZE(tunnel_medium)-1, 1, print_attr_num },
{ "Tunnel-Client-Endpoint", NULL, 0, 0, print_attr_string },
{ "Tunnel-Server-Endpoint", NULL, 0, 0, print_attr_string },
{ "Acct-Tunnel-Connection", NULL, 0, 0, print_attr_string },
{ "Tunnel-Password", NULL, 0, 0, print_attr_string },
{ "ARAP-Password", NULL, 0, 0, print_attr_strange },
{ "ARAP-Features", NULL, 0, 0, print_attr_strange },
{ "ARAP-Zone-Access", arap_zone, TAM_SIZE(arap_zone)-1, 1, print_attr_num }, /*72*/
{ "ARAP-Security", NULL, 0, 0, print_attr_string },
{ "ARAP-Security-Data", NULL, 0, 0, print_attr_string },
{ "Password-Retry", NULL, 0, 0, print_attr_num },
{ "Prompt", prompt, TAM_SIZE(prompt), 0, print_attr_num },
{ "Connect-Info", NULL, 0, 0, print_attr_string },
{ "Configuration-Token", NULL, 0, 0, print_attr_string },
{ "EAP-Message", NULL, 0, 0, print_attr_string },
{ "Message-Authenticator", NULL, 0, 0, print_attr_string }, /*80*/
{ "Tunnel-Private-Group-ID", NULL, 0, 0, print_attr_string },
{ "Tunnel-Assignment-ID", NULL, 0, 0, print_attr_string },
{ "Tunnel-Preference", NULL, 0, 0, print_attr_num },
{ "ARAP-Challenge-Response", NULL, 0, 0, print_attr_strange },
{ "Acct-Interim-Interval", NULL, 0, 0, print_attr_num },
{ "Acct-Tunnel-Packets-Lost", NULL, 0, 0, print_attr_num }, /*86*/
{ "NAS-Port-Id", NULL, 0, 0, print_attr_string },
{ "Framed-Pool", NULL, 0, 0, print_attr_string },
{ "CUI", NULL, 0, 0, print_attr_string },
{ "Tunnel-Client-Auth-ID", NULL, 0, 0, print_attr_string },
{ "Tunnel-Server-Auth-ID", NULL, 0, 0, print_attr_string },
{ "NAS-Filter-Rule", NULL, 0, 0, print_attr_string },
{ "Unassigned", NULL, 0, 0, NULL }, /*93*/
{ "Originating-Line-Info", NULL, 0, 0, NULL }
};
/*****************************/
/* Print an attribute string */
/* value pointed by 'data' */
/* and 'length' size. */
/*****************************/
/* Returns nothing. */
/*****************************/
static void
print_attr_string(netdissect_options *ndo,
register const u_char *data, u_int length, u_short attr_code)
{
register u_int i;
ND_TCHECK2(data[0],length);
switch(attr_code)
{
case TUNNEL_PASS:
if (length < 3)
{
ND_PRINT((ndo, "%s", tstr));
return;
}
if (*data && (*data <=0x1F) )
ND_PRINT((ndo, "Tag[%u] ", *data));
else
ND_PRINT((ndo, "Tag[Unused] "));
data++;
length--;
ND_PRINT((ndo, "Salt %u ", EXTRACT_16BITS(data)));
data+=2;
length-=2;
break;
case TUNNEL_CLIENT_END:
case TUNNEL_SERVER_END:
case TUNNEL_PRIV_GROUP:
case TUNNEL_ASSIGN_ID:
case TUNNEL_CLIENT_AUTH:
case TUNNEL_SERVER_AUTH:
if (*data <= 0x1F)
{
if (length < 1)
{
ND_PRINT((ndo, "%s", tstr));
return;
}
if (*data)
ND_PRINT((ndo, "Tag[%u] ", *data));
else
ND_PRINT((ndo, "Tag[Unused] "));
data++;
length--;
}
break;
case EGRESS_VLAN_NAME:
ND_PRINT((ndo, "%s (0x%02x) ",
tok2str(rfc4675_tagged,"Unknown tag",*data),
*data));
data++;
length--;
break;
}
for (i=0; *data && i < length ; i++, data++)
ND_PRINT((ndo, "%c", (*data < 32 || *data > 126) ? '.' : *data));
return;
trunc:
ND_PRINT((ndo, "%s", tstr));
}
/*
* print vendor specific attributes
*/
static void
print_vendor_attr(netdissect_options *ndo,
register const u_char *data, u_int length, u_short attr_code _U_)
{
u_int idx;
u_int vendor_id;
u_int vendor_type;
u_int vendor_length;
if (length < 4)
goto trunc;
ND_TCHECK2(*data, 4);
vendor_id = EXTRACT_32BITS(data);
data+=4;
length-=4;
ND_PRINT((ndo, "Vendor: %s (%u)",
tok2str(smi_values,"Unknown",vendor_id),
vendor_id));
while (length >= 2) {
ND_TCHECK2(*data, 2);
vendor_type = *(data);
vendor_length = *(data+1);
if (vendor_length < 2)
{
ND_PRINT((ndo, "\n\t Vendor Attribute: %u, Length: %u (bogus, must be >= 2)",
vendor_type,
vendor_length));
return;
}
if (vendor_length > length)
{
ND_PRINT((ndo, "\n\t Vendor Attribute: %u, Length: %u (bogus, goes past end of vendor-specific attribute)",
vendor_type,
vendor_length));
return;
}
data+=2;
vendor_length-=2;
length-=2;
ND_TCHECK2(*data, vendor_length);
ND_PRINT((ndo, "\n\t Vendor Attribute: %u, Length: %u, Value: ",
vendor_type,
vendor_length));
for (idx = 0; idx < vendor_length ; idx++, data++)
ND_PRINT((ndo, "%c", (*data < 32 || *data > 126) ? '.' : *data));
length-=vendor_length;
}
return;
trunc:
ND_PRINT((ndo, "%s", tstr));
}
/******************************/
/* Print an attribute numeric */
/* value pointed by 'data' */
/* and 'length' size. */
/******************************/
/* Returns nothing. */
/******************************/
static void
print_attr_num(netdissect_options *ndo,
register const u_char *data, u_int length, u_short attr_code)
{
uint32_t timeout;
if (length != 4)
{
ND_PRINT((ndo, "ERROR: length %u != 4", length));
return;
}
ND_TCHECK2(data[0],4);
/* This attribute has standard values */
if (attr_type[attr_code].siz_subtypes)
{
static const char **table;
uint32_t data_value;
table = attr_type[attr_code].subtypes;
if ( (attr_code == TUNNEL_TYPE) || (attr_code == TUNNEL_MEDIUM) )
{
if (!*data)
ND_PRINT((ndo, "Tag[Unused] "));
else
ND_PRINT((ndo, "Tag[%d] ", *data));
data++;
data_value = EXTRACT_24BITS(data);
}
else
{
data_value = EXTRACT_32BITS(data);
}
if ( data_value <= (uint32_t)(attr_type[attr_code].siz_subtypes - 1 +
attr_type[attr_code].first_subtype) &&
data_value >= attr_type[attr_code].first_subtype )
ND_PRINT((ndo, "%s", table[data_value]));
else
ND_PRINT((ndo, "#%u", data_value));
}
else
{
switch(attr_code) /* Be aware of special cases... */
{
case FRM_IPX:
if (EXTRACT_32BITS( data) == 0xFFFFFFFE )
ND_PRINT((ndo, "NAS Select"));
else
ND_PRINT((ndo, "%d", EXTRACT_32BITS(data)));
break;
case SESSION_TIMEOUT:
case IDLE_TIMEOUT:
case ACCT_DELAY:
case ACCT_SESSION_TIME:
case ACCT_INT_INTERVAL:
timeout = EXTRACT_32BITS( data);
if ( timeout < 60 )
ND_PRINT((ndo, "%02d secs", timeout));
else
{
if ( timeout < 3600 )
ND_PRINT((ndo, "%02d:%02d min",
timeout / 60, timeout % 60));
else
ND_PRINT((ndo, "%02d:%02d:%02d hours",
timeout / 3600, (timeout % 3600) / 60,
timeout % 60));
}
break;
case FRM_ATALK_LINK:
if (EXTRACT_32BITS(data) )
ND_PRINT((ndo, "%d", EXTRACT_32BITS(data)));
else
ND_PRINT((ndo, "Unnumbered"));
break;
case FRM_ATALK_NETWORK:
if (EXTRACT_32BITS(data) )
ND_PRINT((ndo, "%d", EXTRACT_32BITS(data)));
else
ND_PRINT((ndo, "NAS assigned"));
break;
case TUNNEL_PREFERENCE:
if (*data)
ND_PRINT((ndo, "Tag[%d] ", *data));
else
ND_PRINT((ndo, "Tag[Unused] "));
data++;
ND_PRINT((ndo, "%d", EXTRACT_24BITS(data)));
break;
case EGRESS_VLAN_ID:
ND_PRINT((ndo, "%s (0x%02x) ",
tok2str(rfc4675_tagged,"Unknown tag",*data),
*data));
data++;
ND_PRINT((ndo, "%d", EXTRACT_24BITS(data)));
break;
default:
ND_PRINT((ndo, "%d", EXTRACT_32BITS(data)));
break;
} /* switch */
} /* if-else */
return;
trunc:
ND_PRINT((ndo, "%s", tstr));
}
/*****************************/
/* Print an attribute IPv4 */
/* address value pointed by */
/* 'data' and 'length' size. */
/*****************************/
/* Returns nothing. */
/*****************************/
static void
print_attr_address(netdissect_options *ndo,
register const u_char *data, u_int length, u_short attr_code)
{
if (length != 4)
{
ND_PRINT((ndo, "ERROR: length %u != 4", length));
return;
}
ND_TCHECK2(data[0],4);
switch(attr_code)
{
case FRM_IPADDR:
case LOG_IPHOST:
if (EXTRACT_32BITS(data) == 0xFFFFFFFF )
ND_PRINT((ndo, "User Selected"));
else
if (EXTRACT_32BITS(data) == 0xFFFFFFFE )
ND_PRINT((ndo, "NAS Select"));
else
ND_PRINT((ndo, "%s",ipaddr_string(ndo, data)));
break;
default:
ND_PRINT((ndo, "%s", ipaddr_string(ndo, data)));
break;
}
return;
trunc:
ND_PRINT((ndo, "%s", tstr));
}
/*************************************/
/* Print an attribute of 'secs since */
/* January 1, 1970 00:00 UTC' value */
/* pointed by 'data' and 'length' */
/* size. */
/*************************************/
/* Returns nothing. */
/*************************************/
static void
print_attr_time(netdissect_options *ndo,
register const u_char *data, u_int length, u_short attr_code _U_)
{
time_t attr_time;
char string[26];
if (length != 4)
{
ND_PRINT((ndo, "ERROR: length %u != 4", length));
return;
}
ND_TCHECK2(data[0],4);
attr_time = EXTRACT_32BITS(data);
strlcpy(string, ctime(&attr_time), sizeof(string));
/* Get rid of the newline */
string[24] = '\0';
ND_PRINT((ndo, "%.24s", string));
return;
trunc:
ND_PRINT((ndo, "%s", tstr));
}
/***********************************/
/* Print an attribute of 'strange' */
/* data format pointed by 'data' */
/* and 'length' size. */
/***********************************/
/* Returns nothing. */
/***********************************/
static void
print_attr_strange(netdissect_options *ndo,
register const u_char *data, u_int length, u_short attr_code)
{
u_short len_data;
switch(attr_code)
{
case ARAP_PASS:
if (length != 16)
{
ND_PRINT((ndo, "ERROR: length %u != 16", length));
return;
}
ND_PRINT((ndo, "User_challenge ("));
ND_TCHECK2(data[0],8);
len_data = 8;
PRINT_HEX(len_data, data);
ND_PRINT((ndo, ") User_resp("));
ND_TCHECK2(data[0],8);
len_data = 8;
PRINT_HEX(len_data, data);
ND_PRINT((ndo, ")"));
break;
case ARAP_FEATURES:
if (length != 14)
{
ND_PRINT((ndo, "ERROR: length %u != 14", length));
return;
}
ND_TCHECK2(data[0],1);
if (*data)
ND_PRINT((ndo, "User can change password"));
else
ND_PRINT((ndo, "User cannot change password"));
data++;
ND_TCHECK2(data[0],1);
ND_PRINT((ndo, ", Min password length: %d", *data));
data++;
ND_PRINT((ndo, ", created at: "));
ND_TCHECK2(data[0],4);
len_data = 4;
PRINT_HEX(len_data, data);
ND_PRINT((ndo, ", expires in: "));
ND_TCHECK2(data[0],4);
len_data = 4;
PRINT_HEX(len_data, data);
ND_PRINT((ndo, ", Current Time: "));
ND_TCHECK2(data[0],4);
len_data = 4;
PRINT_HEX(len_data, data);
break;
case ARAP_CHALLENGE_RESP:
if (length < 8)
{
ND_PRINT((ndo, "ERROR: length %u != 8", length));
return;
}
ND_TCHECK2(data[0],8);
len_data = 8;
PRINT_HEX(len_data, data);
break;
}
return;
trunc:
ND_PRINT((ndo, "%s", tstr));
}
static void
radius_attrs_print(netdissect_options *ndo,
register const u_char *attr, u_int length)
{
register const struct radius_attr *rad_attr = (const struct radius_attr *)attr;
const char *attr_string;
while (length > 0)
{
if (length < 2)
goto trunc;
ND_TCHECK(*rad_attr);
if (rad_attr->type > 0 && rad_attr->type < TAM_SIZE(attr_type))
attr_string = attr_type[rad_attr->type].name;
else
attr_string = "Unknown";
if (rad_attr->len < 2)
{
ND_PRINT((ndo, "\n\t %s Attribute (%u), length: %u (bogus, must be >= 2)",
attr_string,
rad_attr->type,
rad_attr->len));
return;
}
if (rad_attr->len > length)
{
ND_PRINT((ndo, "\n\t %s Attribute (%u), length: %u (bogus, goes past end of packet)",
attr_string,
rad_attr->type,
rad_attr->len));
return;
}
ND_PRINT((ndo, "\n\t %s Attribute (%u), length: %u, Value: ",
attr_string,
rad_attr->type,
rad_attr->len));
if (rad_attr->type < TAM_SIZE(attr_type))
{
if (rad_attr->len > 2)
{
if ( attr_type[rad_attr->type].print_func )
(*attr_type[rad_attr->type].print_func)(
ndo, ((const u_char *)(rad_attr+1)),
rad_attr->len - 2, rad_attr->type);
}
}
/* do we also want to see a hex dump ? */
if (ndo->ndo_vflag> 1)
print_unknown_data(ndo, (const u_char *)rad_attr+2, "\n\t ", (rad_attr->len)-2);
length-=(rad_attr->len);
rad_attr = (const struct radius_attr *)( ((const char *)(rad_attr))+rad_attr->len);
}
return;
trunc:
ND_PRINT((ndo, "%s", tstr));
}
void
radius_print(netdissect_options *ndo,
const u_char *dat, u_int length)
{
register const struct radius_hdr *rad;
u_int len, auth_idx;
ND_TCHECK2(*dat, MIN_RADIUS_LEN);
rad = (const struct radius_hdr *)dat;
len = EXTRACT_16BITS(&rad->len);
if (len < MIN_RADIUS_LEN)
{
ND_PRINT((ndo, "%s", tstr));
return;
}
if (len > length)
len = length;
if (ndo->ndo_vflag < 1) {
ND_PRINT((ndo, "RADIUS, %s (%u), id: 0x%02x length: %u",
tok2str(radius_command_values,"Unknown Command",rad->code),
rad->code,
rad->id,
len));
return;
}
else {
ND_PRINT((ndo, "RADIUS, length: %u\n\t%s (%u), id: 0x%02x, Authenticator: ",
len,
tok2str(radius_command_values,"Unknown Command",rad->code),
rad->code,
rad->id));
for(auth_idx=0; auth_idx < 16; auth_idx++)
ND_PRINT((ndo, "%02x", rad->auth[auth_idx]));
}
if (len > MIN_RADIUS_LEN)
radius_attrs_print(ndo, dat + MIN_RADIUS_LEN, len - MIN_RADIUS_LEN);
return;
trunc:
ND_PRINT((ndo, "%s", tstr));
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_2708_0 |
crossvul-cpp_data_bad_4025_0 | /**
* WinPR: Windows Portable Runtime
* NTLM Security Package (Message)
*
* Copyright 2011-2014 Marc-Andre Moreau <marcandre.moreau@gmail.com>
*
* 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 HAVE_CONFIG_H
#include "config.h"
#endif
#include "ntlm.h"
#include "../sspi.h"
#include <winpr/crt.h>
#include <winpr/print.h>
#include <winpr/stream.h>
#include <winpr/sysinfo.h>
#include "ntlm_compute.h"
#include "ntlm_message.h"
#include "../log.h"
#define TAG WINPR_TAG("sspi.NTLM")
static const char NTLM_SIGNATURE[8] = { 'N', 'T', 'L', 'M', 'S', 'S', 'P', '\0' };
#ifdef WITH_DEBUG_NTLM
static const char* const NTLM_NEGOTIATE_STRINGS[] = { "NTLMSSP_NEGOTIATE_56",
"NTLMSSP_NEGOTIATE_KEY_EXCH",
"NTLMSSP_NEGOTIATE_128",
"NTLMSSP_RESERVED1",
"NTLMSSP_RESERVED2",
"NTLMSSP_RESERVED3",
"NTLMSSP_NEGOTIATE_VERSION",
"NTLMSSP_RESERVED4",
"NTLMSSP_NEGOTIATE_TARGET_INFO",
"NTLMSSP_REQUEST_NON_NT_SESSION_KEY",
"NTLMSSP_RESERVED5",
"NTLMSSP_NEGOTIATE_IDENTIFY",
"NTLMSSP_NEGOTIATE_EXTENDED_SESSION_SECURITY",
"NTLMSSP_RESERVED6",
"NTLMSSP_TARGET_TYPE_SERVER",
"NTLMSSP_TARGET_TYPE_DOMAIN",
"NTLMSSP_NEGOTIATE_ALWAYS_SIGN",
"NTLMSSP_RESERVED7",
"NTLMSSP_NEGOTIATE_WORKSTATION_SUPPLIED",
"NTLMSSP_NEGOTIATE_DOMAIN_SUPPLIED",
"NTLMSSP_NEGOTIATE_ANONYMOUS",
"NTLMSSP_RESERVED8",
"NTLMSSP_NEGOTIATE_NTLM",
"NTLMSSP_RESERVED9",
"NTLMSSP_NEGOTIATE_LM_KEY",
"NTLMSSP_NEGOTIATE_DATAGRAM",
"NTLMSSP_NEGOTIATE_SEAL",
"NTLMSSP_NEGOTIATE_SIGN",
"NTLMSSP_RESERVED10",
"NTLMSSP_REQUEST_TARGET",
"NTLMSSP_NEGOTIATE_OEM",
"NTLMSSP_NEGOTIATE_UNICODE" };
static void ntlm_print_negotiate_flags(UINT32 flags)
{
int i;
const char* str;
WLog_INFO(TAG, "negotiateFlags \"0x%08" PRIX32 "\"", flags);
for (i = 31; i >= 0; i--)
{
if ((flags >> i) & 1)
{
str = NTLM_NEGOTIATE_STRINGS[(31 - i)];
WLog_INFO(TAG, "\t%s (%d),", str, (31 - i));
}
}
}
#endif
static int ntlm_read_message_header(wStream* s, NTLM_MESSAGE_HEADER* header)
{
if (Stream_GetRemainingLength(s) < 12)
return -1;
Stream_Read(s, header->Signature, 8);
Stream_Read_UINT32(s, header->MessageType);
if (strncmp((char*)header->Signature, NTLM_SIGNATURE, 8) != 0)
return -1;
return 1;
}
static void ntlm_write_message_header(wStream* s, NTLM_MESSAGE_HEADER* header)
{
Stream_Write(s, header->Signature, sizeof(NTLM_SIGNATURE));
Stream_Write_UINT32(s, header->MessageType);
}
static void ntlm_populate_message_header(NTLM_MESSAGE_HEADER* header, UINT32 MessageType)
{
CopyMemory(header->Signature, NTLM_SIGNATURE, sizeof(NTLM_SIGNATURE));
header->MessageType = MessageType;
}
static int ntlm_read_message_fields(wStream* s, NTLM_MESSAGE_FIELDS* fields)
{
if (Stream_GetRemainingLength(s) < 8)
return -1;
Stream_Read_UINT16(s, fields->Len); /* Len (2 bytes) */
Stream_Read_UINT16(s, fields->MaxLen); /* MaxLen (2 bytes) */
Stream_Read_UINT32(s, fields->BufferOffset); /* BufferOffset (4 bytes) */
return 1;
}
static void ntlm_write_message_fields(wStream* s, NTLM_MESSAGE_FIELDS* fields)
{
if (fields->MaxLen < 1)
fields->MaxLen = fields->Len;
Stream_Write_UINT16(s, fields->Len); /* Len (2 bytes) */
Stream_Write_UINT16(s, fields->MaxLen); /* MaxLen (2 bytes) */
Stream_Write_UINT32(s, fields->BufferOffset); /* BufferOffset (4 bytes) */
}
static int ntlm_read_message_fields_buffer(wStream* s, NTLM_MESSAGE_FIELDS* fields)
{
if (fields->Len > 0)
{
const UINT32 offset = fields->BufferOffset + fields->Len;
if (fields->BufferOffset > UINT32_MAX - fields->Len)
return -1;
if (offset > Stream_Length(s))
return -1;
fields->Buffer = (PBYTE)malloc(fields->Len);
if (!fields->Buffer)
return -1;
Stream_SetPosition(s, fields->BufferOffset);
Stream_Read(s, fields->Buffer, fields->Len);
}
return 1;
}
static void ntlm_write_message_fields_buffer(wStream* s, NTLM_MESSAGE_FIELDS* fields)
{
if (fields->Len > 0)
{
Stream_SetPosition(s, fields->BufferOffset);
Stream_Write(s, fields->Buffer, fields->Len);
}
}
static void ntlm_free_message_fields_buffer(NTLM_MESSAGE_FIELDS* fields)
{
if (fields)
{
if (fields->Buffer)
{
free(fields->Buffer);
fields->Len = 0;
fields->MaxLen = 0;
fields->Buffer = NULL;
fields->BufferOffset = 0;
}
}
}
#ifdef WITH_DEBUG_NTLM
static void ntlm_print_message_fields(NTLM_MESSAGE_FIELDS* fields, const char* name)
{
WLog_DBG(TAG, "%s (Len: %" PRIu16 " MaxLen: %" PRIu16 " BufferOffset: %" PRIu32 ")", name,
fields->Len, fields->MaxLen, fields->BufferOffset);
if (fields->Len > 0)
winpr_HexDump(TAG, WLOG_DEBUG, fields->Buffer, fields->Len);
}
#endif
SECURITY_STATUS ntlm_read_NegotiateMessage(NTLM_CONTEXT* context, PSecBuffer buffer)
{
wStream* s;
size_t length;
NTLM_NEGOTIATE_MESSAGE* message;
message = &context->NEGOTIATE_MESSAGE;
ZeroMemory(message, sizeof(NTLM_NEGOTIATE_MESSAGE));
s = Stream_New((BYTE*)buffer->pvBuffer, buffer->cbBuffer);
if (!s)
return SEC_E_INTERNAL_ERROR;
if (ntlm_read_message_header(s, (NTLM_MESSAGE_HEADER*)message) < 0)
{
Stream_Free(s, FALSE);
return SEC_E_INVALID_TOKEN;
}
if (message->MessageType != MESSAGE_TYPE_NEGOTIATE)
{
Stream_Free(s, FALSE);
return SEC_E_INVALID_TOKEN;
}
if (Stream_GetRemainingLength(s) < 4)
{
Stream_Free(s, FALSE);
return SEC_E_INVALID_TOKEN;
}
Stream_Read_UINT32(s, message->NegotiateFlags); /* NegotiateFlags (4 bytes) */
if (!((message->NegotiateFlags & NTLMSSP_REQUEST_TARGET) &&
(message->NegotiateFlags & NTLMSSP_NEGOTIATE_NTLM) &&
(message->NegotiateFlags & NTLMSSP_NEGOTIATE_UNICODE)))
{
Stream_Free(s, FALSE);
return SEC_E_INVALID_TOKEN;
}
context->NegotiateFlags = message->NegotiateFlags;
/* only set if NTLMSSP_NEGOTIATE_DOMAIN_SUPPLIED is set */
if (ntlm_read_message_fields(s, &(message->DomainName)) < 0) /* DomainNameFields (8 bytes) */
{
Stream_Free(s, FALSE);
return SEC_E_INVALID_TOKEN;
}
/* only set if NTLMSSP_NEGOTIATE_WORKSTATION_SUPPLIED is set */
if (ntlm_read_message_fields(s, &(message->Workstation)) < 0) /* WorkstationFields (8 bytes) */
{
Stream_Free(s, FALSE);
return SEC_E_INVALID_TOKEN;
}
if (message->NegotiateFlags & NTLMSSP_NEGOTIATE_VERSION)
{
if (ntlm_read_version_info(s, &(message->Version)) < 0) /* Version (8 bytes) */
{
Stream_Free(s, FALSE);
return SEC_E_INVALID_TOKEN;
}
}
length = Stream_GetPosition(s);
buffer->cbBuffer = length;
if (!sspi_SecBufferAlloc(&context->NegotiateMessage, length))
{
Stream_Free(s, FALSE);
return SEC_E_INTERNAL_ERROR;
}
CopyMemory(context->NegotiateMessage.pvBuffer, buffer->pvBuffer, buffer->cbBuffer);
context->NegotiateMessage.BufferType = buffer->BufferType;
#ifdef WITH_DEBUG_NTLM
WLog_DBG(TAG, "NEGOTIATE_MESSAGE (length = %" PRIu32 ")", context->NegotiateMessage.cbBuffer);
winpr_HexDump(TAG, WLOG_DEBUG, context->NegotiateMessage.pvBuffer,
context->NegotiateMessage.cbBuffer);
ntlm_print_negotiate_flags(message->NegotiateFlags);
if (message->NegotiateFlags & NTLMSSP_NEGOTIATE_VERSION)
ntlm_print_version_info(&(message->Version));
#endif
context->state = NTLM_STATE_CHALLENGE;
Stream_Free(s, FALSE);
return SEC_I_CONTINUE_NEEDED;
}
SECURITY_STATUS ntlm_write_NegotiateMessage(NTLM_CONTEXT* context, PSecBuffer buffer)
{
wStream* s;
size_t length;
NTLM_NEGOTIATE_MESSAGE* message;
message = &context->NEGOTIATE_MESSAGE;
ZeroMemory(message, sizeof(NTLM_NEGOTIATE_MESSAGE));
s = Stream_New((BYTE*)buffer->pvBuffer, buffer->cbBuffer);
if (!s)
return SEC_E_INTERNAL_ERROR;
ntlm_populate_message_header((NTLM_MESSAGE_HEADER*)message, MESSAGE_TYPE_NEGOTIATE);
if (context->NTLMv2)
{
message->NegotiateFlags |= NTLMSSP_NEGOTIATE_56;
message->NegotiateFlags |= NTLMSSP_NEGOTIATE_VERSION;
message->NegotiateFlags |= NTLMSSP_NEGOTIATE_LM_KEY;
message->NegotiateFlags |= NTLMSSP_NEGOTIATE_OEM;
}
message->NegotiateFlags |= NTLMSSP_NEGOTIATE_KEY_EXCH;
message->NegotiateFlags |= NTLMSSP_NEGOTIATE_128;
message->NegotiateFlags |= NTLMSSP_NEGOTIATE_EXTENDED_SESSION_SECURITY;
message->NegotiateFlags |= NTLMSSP_NEGOTIATE_ALWAYS_SIGN;
message->NegotiateFlags |= NTLMSSP_NEGOTIATE_NTLM;
message->NegotiateFlags |= NTLMSSP_NEGOTIATE_SIGN;
message->NegotiateFlags |= NTLMSSP_REQUEST_TARGET;
message->NegotiateFlags |= NTLMSSP_NEGOTIATE_UNICODE;
if (context->confidentiality)
message->NegotiateFlags |= NTLMSSP_NEGOTIATE_SEAL;
if (context->SendVersionInfo)
message->NegotiateFlags |= NTLMSSP_NEGOTIATE_VERSION;
if (message->NegotiateFlags & NTLMSSP_NEGOTIATE_VERSION)
ntlm_get_version_info(&(message->Version));
context->NegotiateFlags = message->NegotiateFlags;
/* Message Header (12 bytes) */
ntlm_write_message_header(s, (NTLM_MESSAGE_HEADER*)message);
Stream_Write_UINT32(s, message->NegotiateFlags); /* NegotiateFlags (4 bytes) */
/* only set if NTLMSSP_NEGOTIATE_DOMAIN_SUPPLIED is set */
/* DomainNameFields (8 bytes) */
ntlm_write_message_fields(s, &(message->DomainName));
/* only set if NTLMSSP_NEGOTIATE_WORKSTATION_SUPPLIED is set */
/* WorkstationFields (8 bytes) */
ntlm_write_message_fields(s, &(message->Workstation));
if (message->NegotiateFlags & NTLMSSP_NEGOTIATE_VERSION)
ntlm_write_version_info(s, &(message->Version));
length = Stream_GetPosition(s);
buffer->cbBuffer = length;
if (!sspi_SecBufferAlloc(&context->NegotiateMessage, length))
{
Stream_Free(s, FALSE);
return SEC_E_INTERNAL_ERROR;
}
CopyMemory(context->NegotiateMessage.pvBuffer, buffer->pvBuffer, buffer->cbBuffer);
context->NegotiateMessage.BufferType = buffer->BufferType;
#ifdef WITH_DEBUG_NTLM
WLog_DBG(TAG, "NEGOTIATE_MESSAGE (length = %d)", length);
winpr_HexDump(TAG, WLOG_DEBUG, Stream_Buffer(s), length);
if (message->NegotiateFlags & NTLMSSP_NEGOTIATE_VERSION)
ntlm_print_version_info(&(message->Version));
#endif
context->state = NTLM_STATE_CHALLENGE;
Stream_Free(s, FALSE);
return SEC_I_CONTINUE_NEEDED;
}
SECURITY_STATUS ntlm_read_ChallengeMessage(NTLM_CONTEXT* context, PSecBuffer buffer)
{
wStream* s;
int length;
PBYTE StartOffset;
PBYTE PayloadOffset;
NTLM_AV_PAIR* AvTimestamp;
NTLM_CHALLENGE_MESSAGE* message;
ntlm_generate_client_challenge(context);
message = &context->CHALLENGE_MESSAGE;
ZeroMemory(message, sizeof(NTLM_CHALLENGE_MESSAGE));
s = Stream_New((BYTE*)buffer->pvBuffer, buffer->cbBuffer);
if (!s)
return SEC_E_INTERNAL_ERROR;
StartOffset = Stream_Pointer(s);
if (ntlm_read_message_header(s, (NTLM_MESSAGE_HEADER*)message) < 0)
{
Stream_Free(s, FALSE);
return SEC_E_INVALID_TOKEN;
}
if (message->MessageType != MESSAGE_TYPE_CHALLENGE)
{
Stream_Free(s, FALSE);
return SEC_E_INVALID_TOKEN;
}
if (ntlm_read_message_fields(s, &(message->TargetName)) < 0) /* TargetNameFields (8 bytes) */
{
Stream_Free(s, FALSE);
return SEC_E_INVALID_TOKEN;
}
if (Stream_GetRemainingLength(s) < 4)
{
Stream_Free(s, FALSE);
return SEC_E_INVALID_TOKEN;
}
Stream_Read_UINT32(s, message->NegotiateFlags); /* NegotiateFlags (4 bytes) */
context->NegotiateFlags = message->NegotiateFlags;
if (Stream_GetRemainingLength(s) < 8)
{
Stream_Free(s, FALSE);
return SEC_E_INVALID_TOKEN;
}
Stream_Read(s, message->ServerChallenge, 8); /* ServerChallenge (8 bytes) */
CopyMemory(context->ServerChallenge, message->ServerChallenge, 8);
if (Stream_GetRemainingLength(s) < 8)
{
Stream_Free(s, FALSE);
return SEC_E_INVALID_TOKEN;
}
Stream_Read(s, message->Reserved, 8); /* Reserved (8 bytes), should be ignored */
if (ntlm_read_message_fields(s, &(message->TargetInfo)) < 0) /* TargetInfoFields (8 bytes) */
{
Stream_Free(s, FALSE);
return SEC_E_INVALID_TOKEN;
}
if (context->NegotiateFlags & NTLMSSP_NEGOTIATE_VERSION)
{
if (ntlm_read_version_info(s, &(message->Version)) < 0) /* Version (8 bytes) */
{
Stream_Free(s, FALSE);
return SEC_E_INVALID_TOKEN;
}
}
/* Payload (variable) */
PayloadOffset = Stream_Pointer(s);
if (message->TargetName.Len > 0)
{
if (ntlm_read_message_fields_buffer(s, &(message->TargetName)) < 0)
{
Stream_Free(s, FALSE);
return SEC_E_INTERNAL_ERROR;
}
}
if (message->TargetInfo.Len > 0)
{
size_t cbAvTimestamp;
if (ntlm_read_message_fields_buffer(s, &(message->TargetInfo)) < 0)
{
Stream_Free(s, FALSE);
return SEC_E_INTERNAL_ERROR;
}
context->ChallengeTargetInfo.pvBuffer = message->TargetInfo.Buffer;
context->ChallengeTargetInfo.cbBuffer = message->TargetInfo.Len;
AvTimestamp = ntlm_av_pair_get((NTLM_AV_PAIR*)message->TargetInfo.Buffer,
message->TargetInfo.Len, MsvAvTimestamp, &cbAvTimestamp);
if (AvTimestamp)
{
PBYTE ptr = ntlm_av_pair_get_value_pointer(AvTimestamp);
if (!ptr)
return SEC_E_INTERNAL_ERROR;
if (context->NTLMv2)
context->UseMIC = TRUE;
CopyMemory(context->ChallengeTimestamp, ptr, 8);
}
}
length = (PayloadOffset - StartOffset) + message->TargetName.Len + message->TargetInfo.Len;
if (!sspi_SecBufferAlloc(&context->ChallengeMessage, length))
{
Stream_Free(s, FALSE);
return SEC_E_INTERNAL_ERROR;
}
CopyMemory(context->ChallengeMessage.pvBuffer, StartOffset, length);
#ifdef WITH_DEBUG_NTLM
WLog_DBG(TAG, "CHALLENGE_MESSAGE (length = %d)", length);
winpr_HexDump(TAG, WLOG_DEBUG, context->ChallengeMessage.pvBuffer,
context->ChallengeMessage.cbBuffer);
ntlm_print_negotiate_flags(context->NegotiateFlags);
if (context->NegotiateFlags & NTLMSSP_NEGOTIATE_VERSION)
ntlm_print_version_info(&(message->Version));
ntlm_print_message_fields(&(message->TargetName), "TargetName");
ntlm_print_message_fields(&(message->TargetInfo), "TargetInfo");
if (context->ChallengeTargetInfo.cbBuffer > 0)
{
WLog_DBG(TAG, "ChallengeTargetInfo (%" PRIu32 "):", context->ChallengeTargetInfo.cbBuffer);
ntlm_print_av_pair_list(context->ChallengeTargetInfo.pvBuffer,
context->ChallengeTargetInfo.cbBuffer);
}
#endif
/* AV_PAIRs */
if (context->NTLMv2)
{
if (ntlm_construct_authenticate_target_info(context) < 0)
{
Stream_Free(s, FALSE);
return SEC_E_INTERNAL_ERROR;
}
sspi_SecBufferFree(&context->ChallengeTargetInfo);
context->ChallengeTargetInfo.pvBuffer = context->AuthenticateTargetInfo.pvBuffer;
context->ChallengeTargetInfo.cbBuffer = context->AuthenticateTargetInfo.cbBuffer;
}
ntlm_generate_timestamp(context); /* Timestamp */
if (ntlm_compute_lm_v2_response(context) < 0) /* LmChallengeResponse */
{
Stream_Free(s, FALSE);
return SEC_E_INTERNAL_ERROR;
}
if (ntlm_compute_ntlm_v2_response(context) < 0) /* NtChallengeResponse */
{
Stream_Free(s, FALSE);
return SEC_E_INTERNAL_ERROR;
}
ntlm_generate_key_exchange_key(context); /* KeyExchangeKey */
ntlm_generate_random_session_key(context); /* RandomSessionKey */
ntlm_generate_exported_session_key(context); /* ExportedSessionKey */
ntlm_encrypt_random_session_key(context); /* EncryptedRandomSessionKey */
/* Generate signing keys */
ntlm_generate_client_signing_key(context);
ntlm_generate_server_signing_key(context);
/* Generate sealing keys */
ntlm_generate_client_sealing_key(context);
ntlm_generate_server_sealing_key(context);
/* Initialize RC4 seal state using client sealing key */
ntlm_init_rc4_seal_states(context);
#ifdef WITH_DEBUG_NTLM
WLog_DBG(TAG, "ClientChallenge");
winpr_HexDump(TAG, WLOG_DEBUG, context->ClientChallenge, 8);
WLog_DBG(TAG, "ServerChallenge");
winpr_HexDump(TAG, WLOG_DEBUG, context->ServerChallenge, 8);
WLog_DBG(TAG, "SessionBaseKey");
winpr_HexDump(TAG, WLOG_DEBUG, context->SessionBaseKey, 16);
WLog_DBG(TAG, "KeyExchangeKey");
winpr_HexDump(TAG, WLOG_DEBUG, context->KeyExchangeKey, 16);
WLog_DBG(TAG, "ExportedSessionKey");
winpr_HexDump(TAG, WLOG_DEBUG, context->ExportedSessionKey, 16);
WLog_DBG(TAG, "RandomSessionKey");
winpr_HexDump(TAG, WLOG_DEBUG, context->RandomSessionKey, 16);
WLog_DBG(TAG, "ClientSigningKey");
winpr_HexDump(TAG, WLOG_DEBUG, context->ClientSigningKey, 16);
WLog_DBG(TAG, "ClientSealingKey");
winpr_HexDump(TAG, WLOG_DEBUG, context->ClientSealingKey, 16);
WLog_DBG(TAG, "ServerSigningKey");
winpr_HexDump(TAG, WLOG_DEBUG, context->ServerSigningKey, 16);
WLog_DBG(TAG, "ServerSealingKey");
winpr_HexDump(TAG, WLOG_DEBUG, context->ServerSealingKey, 16);
WLog_DBG(TAG, "Timestamp");
winpr_HexDump(TAG, WLOG_DEBUG, context->Timestamp, 8);
#endif
context->state = NTLM_STATE_AUTHENTICATE;
ntlm_free_message_fields_buffer(&(message->TargetName));
Stream_Free(s, FALSE);
return SEC_I_CONTINUE_NEEDED;
}
SECURITY_STATUS ntlm_write_ChallengeMessage(NTLM_CONTEXT* context, PSecBuffer buffer)
{
wStream* s;
size_t length;
UINT32 PayloadOffset;
NTLM_CHALLENGE_MESSAGE* message;
message = &context->CHALLENGE_MESSAGE;
ZeroMemory(message, sizeof(NTLM_CHALLENGE_MESSAGE));
s = Stream_New((BYTE*)buffer->pvBuffer, buffer->cbBuffer);
if (!s)
return SEC_E_INTERNAL_ERROR;
ntlm_get_version_info(&(message->Version)); /* Version */
ntlm_generate_server_challenge(context); /* Server Challenge */
ntlm_generate_timestamp(context); /* Timestamp */
if (ntlm_construct_challenge_target_info(context) < 0) /* TargetInfo */
{
Stream_Free(s, FALSE);
return SEC_E_INTERNAL_ERROR;
}
CopyMemory(message->ServerChallenge, context->ServerChallenge, 8); /* ServerChallenge */
message->NegotiateFlags = context->NegotiateFlags;
ntlm_populate_message_header((NTLM_MESSAGE_HEADER*)message, MESSAGE_TYPE_CHALLENGE);
/* Message Header (12 bytes) */
ntlm_write_message_header(s, (NTLM_MESSAGE_HEADER*)message);
if (message->NegotiateFlags & NTLMSSP_REQUEST_TARGET)
{
message->TargetName.Len = (UINT16)context->TargetName.cbBuffer;
message->TargetName.Buffer = (PBYTE)context->TargetName.pvBuffer;
}
message->NegotiateFlags |= NTLMSSP_NEGOTIATE_TARGET_INFO;
if (message->NegotiateFlags & NTLMSSP_NEGOTIATE_TARGET_INFO)
{
message->TargetInfo.Len = (UINT16)context->ChallengeTargetInfo.cbBuffer;
message->TargetInfo.Buffer = (PBYTE)context->ChallengeTargetInfo.pvBuffer;
}
PayloadOffset = 48;
if (message->NegotiateFlags & NTLMSSP_NEGOTIATE_VERSION)
PayloadOffset += 8;
message->TargetName.BufferOffset = PayloadOffset;
message->TargetInfo.BufferOffset = message->TargetName.BufferOffset + message->TargetName.Len;
/* TargetNameFields (8 bytes) */
ntlm_write_message_fields(s, &(message->TargetName));
Stream_Write_UINT32(s, message->NegotiateFlags); /* NegotiateFlags (4 bytes) */
Stream_Write(s, message->ServerChallenge, 8); /* ServerChallenge (8 bytes) */
Stream_Write(s, message->Reserved, 8); /* Reserved (8 bytes), should be ignored */
/* TargetInfoFields (8 bytes) */
ntlm_write_message_fields(s, &(message->TargetInfo));
if (message->NegotiateFlags & NTLMSSP_NEGOTIATE_VERSION)
ntlm_write_version_info(s, &(message->Version)); /* Version (8 bytes) */
/* Payload (variable) */
if (message->NegotiateFlags & NTLMSSP_REQUEST_TARGET)
ntlm_write_message_fields_buffer(s, &(message->TargetName));
if (message->NegotiateFlags & NTLMSSP_NEGOTIATE_TARGET_INFO)
ntlm_write_message_fields_buffer(s, &(message->TargetInfo));
length = Stream_GetPosition(s);
buffer->cbBuffer = length;
if (!sspi_SecBufferAlloc(&context->ChallengeMessage, length))
{
Stream_Free(s, FALSE);
return SEC_E_INTERNAL_ERROR;
}
CopyMemory(context->ChallengeMessage.pvBuffer, Stream_Buffer(s), length);
#ifdef WITH_DEBUG_NTLM
WLog_DBG(TAG, "CHALLENGE_MESSAGE (length = %d)", length);
winpr_HexDump(TAG, WLOG_DEBUG, context->ChallengeMessage.pvBuffer,
context->ChallengeMessage.cbBuffer);
ntlm_print_negotiate_flags(message->NegotiateFlags);
if (message->NegotiateFlags & NTLMSSP_NEGOTIATE_VERSION)
ntlm_print_version_info(&(message->Version));
ntlm_print_message_fields(&(message->TargetName), "TargetName");
ntlm_print_message_fields(&(message->TargetInfo), "TargetInfo");
#endif
context->state = NTLM_STATE_AUTHENTICATE;
Stream_Free(s, FALSE);
return SEC_I_CONTINUE_NEEDED;
}
SECURITY_STATUS ntlm_read_AuthenticateMessage(NTLM_CONTEXT* context, PSecBuffer buffer)
{
SECURITY_STATUS status = SEC_E_INVALID_TOKEN;
wStream* s;
size_t length;
UINT32 flags = 0;
NTLM_AV_PAIR* AvFlags = NULL;
UINT32 PayloadBufferOffset;
NTLM_AUTHENTICATE_MESSAGE* message;
SSPI_CREDENTIALS* credentials = context->credentials;
message = &context->AUTHENTICATE_MESSAGE;
ZeroMemory(message, sizeof(NTLM_AUTHENTICATE_MESSAGE));
s = Stream_New((BYTE*)buffer->pvBuffer, buffer->cbBuffer);
if (!s)
return SEC_E_INTERNAL_ERROR;
if (ntlm_read_message_header(s, (NTLM_MESSAGE_HEADER*)message) < 0)
goto fail;
if (message->MessageType != MESSAGE_TYPE_AUTHENTICATE)
goto fail;
if (ntlm_read_message_fields(s, &(message->LmChallengeResponse)) <
0) /* LmChallengeResponseFields (8 bytes) */
goto fail;
if (ntlm_read_message_fields(s, &(message->NtChallengeResponse)) <
0) /* NtChallengeResponseFields (8 bytes) */
goto fail;
if (ntlm_read_message_fields(s, &(message->DomainName)) < 0) /* DomainNameFields (8 bytes) */
goto fail;
if (ntlm_read_message_fields(s, &(message->UserName)) < 0) /* UserNameFields (8 bytes) */
goto fail;
if (ntlm_read_message_fields(s, &(message->Workstation)) < 0) /* WorkstationFields (8 bytes) */
goto fail;
if (ntlm_read_message_fields(s, &(message->EncryptedRandomSessionKey)) <
0) /* EncryptedRandomSessionKeyFields (8 bytes) */
goto fail;
if (Stream_GetRemainingLength(s) < 4)
goto fail;
Stream_Read_UINT32(s, message->NegotiateFlags); /* NegotiateFlags (4 bytes) */
context->NegotiateKeyExchange =
(message->NegotiateFlags & NTLMSSP_NEGOTIATE_KEY_EXCH) ? TRUE : FALSE;
if ((context->NegotiateKeyExchange && !message->EncryptedRandomSessionKey.Len) ||
(!context->NegotiateKeyExchange && message->EncryptedRandomSessionKey.Len))
goto fail;
if (message->NegotiateFlags & NTLMSSP_NEGOTIATE_VERSION)
{
if (ntlm_read_version_info(s, &(message->Version)) < 0) /* Version (8 bytes) */
goto fail;
}
PayloadBufferOffset = Stream_GetPosition(s);
status = SEC_E_INTERNAL_ERROR;
if (ntlm_read_message_fields_buffer(s, &(message->DomainName)) < 0) /* DomainName */
goto fail;
if (ntlm_read_message_fields_buffer(s, &(message->UserName)) < 0) /* UserName */
goto fail;
if (ntlm_read_message_fields_buffer(s, &(message->Workstation)) < 0) /* Workstation */
goto fail;
if (ntlm_read_message_fields_buffer(s, &(message->LmChallengeResponse)) <
0) /* LmChallengeResponse */
goto fail;
if (ntlm_read_message_fields_buffer(s, &(message->NtChallengeResponse)) <
0) /* NtChallengeResponse */
goto fail;
if (message->NtChallengeResponse.Len > 0)
{
int rc;
size_t cbAvFlags;
wStream* snt =
Stream_New(message->NtChallengeResponse.Buffer, message->NtChallengeResponse.Len);
if (!snt)
goto fail;
status = SEC_E_INVALID_TOKEN;
rc = ntlm_read_ntlm_v2_response(snt, &(context->NTLMv2Response));
Stream_Free(snt, FALSE);
if (rc < 0)
goto fail;
status = SEC_E_INTERNAL_ERROR;
context->NtChallengeResponse.pvBuffer = message->NtChallengeResponse.Buffer;
context->NtChallengeResponse.cbBuffer = message->NtChallengeResponse.Len;
sspi_SecBufferFree(&(context->ChallengeTargetInfo));
context->ChallengeTargetInfo.pvBuffer = (void*)context->NTLMv2Response.Challenge.AvPairs;
context->ChallengeTargetInfo.cbBuffer = message->NtChallengeResponse.Len - (28 + 16);
CopyMemory(context->ClientChallenge, context->NTLMv2Response.Challenge.ClientChallenge, 8);
AvFlags =
ntlm_av_pair_get(context->NTLMv2Response.Challenge.AvPairs,
context->NTLMv2Response.Challenge.cbAvPairs, MsvAvFlags, &cbAvFlags);
if (AvFlags)
Data_Read_UINT32(ntlm_av_pair_get_value_pointer(AvFlags), flags);
}
if (ntlm_read_message_fields_buffer(s, &(message->EncryptedRandomSessionKey)) <
0) /* EncryptedRandomSessionKey */
goto fail;
if (message->EncryptedRandomSessionKey.Len > 0)
{
if (message->EncryptedRandomSessionKey.Len != 16)
goto fail;
CopyMemory(context->EncryptedRandomSessionKey, message->EncryptedRandomSessionKey.Buffer,
16);
}
length = Stream_GetPosition(s);
if (!sspi_SecBufferAlloc(&context->AuthenticateMessage, length))
goto fail;
CopyMemory(context->AuthenticateMessage.pvBuffer, Stream_Buffer(s), length);
buffer->cbBuffer = length;
Stream_SetPosition(s, PayloadBufferOffset);
if (flags & MSV_AV_FLAGS_MESSAGE_INTEGRITY_CHECK)
{
context->MessageIntegrityCheckOffset = (UINT32)Stream_GetPosition(s);
status = SEC_E_INVALID_TOKEN;
if (Stream_GetRemainingLength(s) < 16)
goto fail;
Stream_Read(s, message->MessageIntegrityCheck, 16);
}
status = SEC_E_INTERNAL_ERROR;
#ifdef WITH_DEBUG_NTLM
WLog_DBG(TAG, "AUTHENTICATE_MESSAGE (length = %" PRIu32 ")",
context->AuthenticateMessage.cbBuffer);
winpr_HexDump(TAG, WLOG_DEBUG, context->AuthenticateMessage.pvBuffer,
context->AuthenticateMessage.cbBuffer);
if (message->NegotiateFlags & NTLMSSP_NEGOTIATE_VERSION)
ntlm_print_version_info(&(message->Version));
ntlm_print_message_fields(&(message->DomainName), "DomainName");
ntlm_print_message_fields(&(message->UserName), "UserName");
ntlm_print_message_fields(&(message->Workstation), "Workstation");
ntlm_print_message_fields(&(message->LmChallengeResponse), "LmChallengeResponse");
ntlm_print_message_fields(&(message->NtChallengeResponse), "NtChallengeResponse");
ntlm_print_message_fields(&(message->EncryptedRandomSessionKey), "EncryptedRandomSessionKey");
ntlm_print_av_pair_list(context->NTLMv2Response.Challenge.AvPairs,
context->NTLMv2Response.Challenge.cbAvPairs);
if (flags & MSV_AV_FLAGS_MESSAGE_INTEGRITY_CHECK)
{
WLog_DBG(TAG, "MessageIntegrityCheck:");
winpr_HexDump(TAG, WLOG_DEBUG, message->MessageIntegrityCheck, 16);
}
#endif
if (message->UserName.Len > 0)
{
credentials->identity.User = (UINT16*)malloc(message->UserName.Len);
if (!credentials->identity.User)
goto fail;
CopyMemory(credentials->identity.User, message->UserName.Buffer, message->UserName.Len);
credentials->identity.UserLength = message->UserName.Len / 2;
}
if (message->DomainName.Len > 0)
{
credentials->identity.Domain = (UINT16*)malloc(message->DomainName.Len);
if (!credentials->identity.Domain)
goto fail;
CopyMemory(credentials->identity.Domain, message->DomainName.Buffer,
message->DomainName.Len);
credentials->identity.DomainLength = message->DomainName.Len / 2;
}
Stream_Free(s, FALSE);
/* Computations beyond this point require the NTLM hash of the password */
context->state = NTLM_STATE_COMPLETION;
return SEC_I_COMPLETE_NEEDED;
fail:
Stream_Free(s, FALSE);
return status;
}
/**
* Send NTLMSSP AUTHENTICATE_MESSAGE.\n
* AUTHENTICATE_MESSAGE @msdn{cc236643}
* @param NTLM context
* @param buffer
*/
SECURITY_STATUS ntlm_write_AuthenticateMessage(NTLM_CONTEXT* context, PSecBuffer buffer)
{
wStream* s;
size_t length;
UINT32 PayloadBufferOffset;
NTLM_AUTHENTICATE_MESSAGE* message;
SSPI_CREDENTIALS* credentials = context->credentials;
message = &context->AUTHENTICATE_MESSAGE;
ZeroMemory(message, sizeof(NTLM_AUTHENTICATE_MESSAGE));
s = Stream_New((BYTE*)buffer->pvBuffer, buffer->cbBuffer);
if (!s)
return SEC_E_INTERNAL_ERROR;
if (context->NTLMv2)
{
message->NegotiateFlags |= NTLMSSP_NEGOTIATE_56;
if (context->SendVersionInfo)
message->NegotiateFlags |= NTLMSSP_NEGOTIATE_VERSION;
}
if (context->UseMIC)
message->NegotiateFlags |= NTLMSSP_NEGOTIATE_TARGET_INFO;
if (context->SendWorkstationName)
message->NegotiateFlags |= NTLMSSP_NEGOTIATE_WORKSTATION_SUPPLIED;
if (context->confidentiality)
message->NegotiateFlags |= NTLMSSP_NEGOTIATE_SEAL;
if (context->CHALLENGE_MESSAGE.NegotiateFlags & NTLMSSP_NEGOTIATE_KEY_EXCH)
message->NegotiateFlags |= NTLMSSP_NEGOTIATE_KEY_EXCH;
message->NegotiateFlags |= NTLMSSP_NEGOTIATE_128;
message->NegotiateFlags |= NTLMSSP_NEGOTIATE_EXTENDED_SESSION_SECURITY;
message->NegotiateFlags |= NTLMSSP_NEGOTIATE_ALWAYS_SIGN;
message->NegotiateFlags |= NTLMSSP_NEGOTIATE_NTLM;
message->NegotiateFlags |= NTLMSSP_NEGOTIATE_SIGN;
message->NegotiateFlags |= NTLMSSP_REQUEST_TARGET;
message->NegotiateFlags |= NTLMSSP_NEGOTIATE_UNICODE;
if (message->NegotiateFlags & NTLMSSP_NEGOTIATE_VERSION)
ntlm_get_version_info(&(message->Version));
if (message->NegotiateFlags & NTLMSSP_NEGOTIATE_WORKSTATION_SUPPLIED)
{
message->Workstation.Len = context->Workstation.Length;
message->Workstation.Buffer = (BYTE*)context->Workstation.Buffer;
}
if (credentials->identity.DomainLength > 0)
{
message->NegotiateFlags |= NTLMSSP_NEGOTIATE_DOMAIN_SUPPLIED;
message->DomainName.Len = (UINT16)credentials->identity.DomainLength * 2;
message->DomainName.Buffer = (BYTE*)credentials->identity.Domain;
}
message->UserName.Len = (UINT16)credentials->identity.UserLength * 2;
message->UserName.Buffer = (BYTE*)credentials->identity.User;
message->LmChallengeResponse.Len = (UINT16)context->LmChallengeResponse.cbBuffer;
message->LmChallengeResponse.Buffer = (BYTE*)context->LmChallengeResponse.pvBuffer;
message->NtChallengeResponse.Len = (UINT16)context->NtChallengeResponse.cbBuffer;
message->NtChallengeResponse.Buffer = (BYTE*)context->NtChallengeResponse.pvBuffer;
if (message->NegotiateFlags & NTLMSSP_NEGOTIATE_KEY_EXCH)
{
message->EncryptedRandomSessionKey.Len = 16;
message->EncryptedRandomSessionKey.Buffer = context->EncryptedRandomSessionKey;
}
PayloadBufferOffset = 64;
if (message->NegotiateFlags & NTLMSSP_NEGOTIATE_VERSION)
PayloadBufferOffset += 8; /* Version (8 bytes) */
if (context->UseMIC)
PayloadBufferOffset += 16; /* Message Integrity Check (16 bytes) */
message->DomainName.BufferOffset = PayloadBufferOffset;
message->UserName.BufferOffset = message->DomainName.BufferOffset + message->DomainName.Len;
message->Workstation.BufferOffset = message->UserName.BufferOffset + message->UserName.Len;
message->LmChallengeResponse.BufferOffset =
message->Workstation.BufferOffset + message->Workstation.Len;
message->NtChallengeResponse.BufferOffset =
message->LmChallengeResponse.BufferOffset + message->LmChallengeResponse.Len;
message->EncryptedRandomSessionKey.BufferOffset =
message->NtChallengeResponse.BufferOffset + message->NtChallengeResponse.Len;
ntlm_populate_message_header((NTLM_MESSAGE_HEADER*)message, MESSAGE_TYPE_AUTHENTICATE);
ntlm_write_message_header(s, (NTLM_MESSAGE_HEADER*)message); /* Message Header (12 bytes) */
ntlm_write_message_fields(
s, &(message->LmChallengeResponse)); /* LmChallengeResponseFields (8 bytes) */
ntlm_write_message_fields(
s, &(message->NtChallengeResponse)); /* NtChallengeResponseFields (8 bytes) */
ntlm_write_message_fields(s, &(message->DomainName)); /* DomainNameFields (8 bytes) */
ntlm_write_message_fields(s, &(message->UserName)); /* UserNameFields (8 bytes) */
ntlm_write_message_fields(s, &(message->Workstation)); /* WorkstationFields (8 bytes) */
ntlm_write_message_fields(
s, &(message->EncryptedRandomSessionKey)); /* EncryptedRandomSessionKeyFields (8 bytes) */
Stream_Write_UINT32(s, message->NegotiateFlags); /* NegotiateFlags (4 bytes) */
if (message->NegotiateFlags & NTLMSSP_NEGOTIATE_VERSION)
ntlm_write_version_info(s, &(message->Version)); /* Version (8 bytes) */
if (context->UseMIC)
{
context->MessageIntegrityCheckOffset = (UINT32)Stream_GetPosition(s);
Stream_Zero(s, 16); /* Message Integrity Check (16 bytes) */
}
if (message->NegotiateFlags & NTLMSSP_NEGOTIATE_DOMAIN_SUPPLIED)
ntlm_write_message_fields_buffer(s, &(message->DomainName)); /* DomainName */
ntlm_write_message_fields_buffer(s, &(message->UserName)); /* UserName */
if (message->NegotiateFlags & NTLMSSP_NEGOTIATE_WORKSTATION_SUPPLIED)
ntlm_write_message_fields_buffer(s, &(message->Workstation)); /* Workstation */
ntlm_write_message_fields_buffer(s, &(message->LmChallengeResponse)); /* LmChallengeResponse */
ntlm_write_message_fields_buffer(s, &(message->NtChallengeResponse)); /* NtChallengeResponse */
if (message->NegotiateFlags & NTLMSSP_NEGOTIATE_KEY_EXCH)
ntlm_write_message_fields_buffer(
s, &(message->EncryptedRandomSessionKey)); /* EncryptedRandomSessionKey */
length = Stream_GetPosition(s);
if (!sspi_SecBufferAlloc(&context->AuthenticateMessage, length))
{
Stream_Free(s, FALSE);
return SEC_E_INTERNAL_ERROR;
}
CopyMemory(context->AuthenticateMessage.pvBuffer, Stream_Buffer(s), length);
buffer->cbBuffer = length;
if (context->UseMIC)
{
/* Message Integrity Check */
ntlm_compute_message_integrity_check(context, message->MessageIntegrityCheck, 16);
Stream_SetPosition(s, context->MessageIntegrityCheckOffset);
Stream_Write(s, message->MessageIntegrityCheck, 16);
Stream_SetPosition(s, length);
}
#ifdef WITH_DEBUG_NTLM
WLog_DBG(TAG, "AUTHENTICATE_MESSAGE (length = %d)", length);
winpr_HexDump(TAG, WLOG_DEBUG, Stream_Buffer(s), length);
ntlm_print_negotiate_flags(message->NegotiateFlags);
if (message->NegotiateFlags & NTLMSSP_NEGOTIATE_VERSION)
ntlm_print_version_info(&(message->Version));
if (context->AuthenticateTargetInfo.cbBuffer > 0)
{
WLog_DBG(TAG,
"AuthenticateTargetInfo (%" PRIu32 "):", context->AuthenticateTargetInfo.cbBuffer);
ntlm_print_av_pair_list(context->AuthenticateTargetInfo.pvBuffer,
context->AuthenticateTargetInfo.cbBuffer);
}
ntlm_print_message_fields(&(message->DomainName), "DomainName");
ntlm_print_message_fields(&(message->UserName), "UserName");
ntlm_print_message_fields(&(message->Workstation), "Workstation");
ntlm_print_message_fields(&(message->LmChallengeResponse), "LmChallengeResponse");
ntlm_print_message_fields(&(message->NtChallengeResponse), "NtChallengeResponse");
ntlm_print_message_fields(&(message->EncryptedRandomSessionKey), "EncryptedRandomSessionKey");
if (context->UseMIC)
{
WLog_DBG(TAG, "MessageIntegrityCheck (length = 16)");
winpr_HexDump(TAG, WLOG_DEBUG, message->MessageIntegrityCheck, 16);
}
#endif
context->state = NTLM_STATE_FINAL;
Stream_Free(s, FALSE);
return SEC_I_COMPLETE_NEEDED;
}
SECURITY_STATUS ntlm_server_AuthenticateComplete(NTLM_CONTEXT* context)
{
UINT32 flags = 0;
size_t cbAvFlags;
NTLM_AV_PAIR* AvFlags = NULL;
NTLM_AUTHENTICATE_MESSAGE* message;
BYTE messageIntegrityCheck[16];
if (!context)
return SEC_E_INVALID_PARAMETER;
if (context->state != NTLM_STATE_COMPLETION)
return SEC_E_OUT_OF_SEQUENCE;
message = &context->AUTHENTICATE_MESSAGE;
AvFlags = ntlm_av_pair_get(context->NTLMv2Response.Challenge.AvPairs,
context->NTLMv2Response.Challenge.cbAvPairs, MsvAvFlags, &cbAvFlags);
if (AvFlags)
Data_Read_UINT32(ntlm_av_pair_get_value_pointer(AvFlags), flags);
if (ntlm_compute_lm_v2_response(context) < 0) /* LmChallengeResponse */
return SEC_E_INTERNAL_ERROR;
if (ntlm_compute_ntlm_v2_response(context) < 0) /* NtChallengeResponse */
return SEC_E_INTERNAL_ERROR;
/* KeyExchangeKey */
ntlm_generate_key_exchange_key(context);
/* EncryptedRandomSessionKey */
ntlm_decrypt_random_session_key(context);
/* ExportedSessionKey */
ntlm_generate_exported_session_key(context);
if (flags & MSV_AV_FLAGS_MESSAGE_INTEGRITY_CHECK)
{
ZeroMemory(
&((PBYTE)context->AuthenticateMessage.pvBuffer)[context->MessageIntegrityCheckOffset],
16);
ntlm_compute_message_integrity_check(context, messageIntegrityCheck,
sizeof(messageIntegrityCheck));
CopyMemory(
&((PBYTE)context->AuthenticateMessage.pvBuffer)[context->MessageIntegrityCheckOffset],
message->MessageIntegrityCheck, 16);
if (memcmp(messageIntegrityCheck, message->MessageIntegrityCheck, 16) != 0)
{
WLog_ERR(TAG, "Message Integrity Check (MIC) verification failed!");
#ifdef WITH_DEBUG_NTLM
WLog_ERR(TAG, "Expected MIC:");
winpr_HexDump(TAG, WLOG_ERROR, messageIntegrityCheck, sizeof(messageIntegrityCheck));
WLog_ERR(TAG, "Actual MIC:");
winpr_HexDump(TAG, WLOG_ERROR, message->MessageIntegrityCheck,
sizeof(message->MessageIntegrityCheck));
#endif
return SEC_E_MESSAGE_ALTERED;
}
}
else
{
/* no mic message was present
https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-nlmp/f9e6fbc4-a953-4f24-b229-ccdcc213b9ec
the mic is optional, as not supported in Windows NT, Windows 2000, Windows XP, and
Windows Server 2003 and, as it seems, in the NTLMv2 implementation of Qt5.
now check the NtProofString, to detect if the entered client password matches the
expected password.
*/
#ifdef WITH_DEBUG_NTLM
WLog_DBG(TAG, "No MIC present, using NtProofString for verification.");
#endif
if (memcmp(context->NTLMv2Response.Response, context->NtProofString, 16) != 0)
{
WLog_ERR(TAG, "NtProofString verification failed!");
#ifdef WITH_DEBUG_NTLM
WLog_ERR(TAG, "Expected NtProofString:");
winpr_HexDump(TAG, WLOG_ERROR, context->NtProofString, sizeof(context->NtProofString));
WLog_ERR(TAG, "Actual NtProofString:");
winpr_HexDump(TAG, WLOG_ERROR, context->NTLMv2Response.Response,
sizeof(context->NTLMv2Response));
#endif
return SEC_E_LOGON_DENIED;
}
}
/* Generate signing keys */
ntlm_generate_client_signing_key(context);
ntlm_generate_server_signing_key(context);
/* Generate sealing keys */
ntlm_generate_client_sealing_key(context);
ntlm_generate_server_sealing_key(context);
/* Initialize RC4 seal state */
ntlm_init_rc4_seal_states(context);
#ifdef WITH_DEBUG_NTLM
WLog_DBG(TAG, "ClientChallenge");
winpr_HexDump(TAG, WLOG_DEBUG, context->ClientChallenge, 8);
WLog_DBG(TAG, "ServerChallenge");
winpr_HexDump(TAG, WLOG_DEBUG, context->ServerChallenge, 8);
WLog_DBG(TAG, "SessionBaseKey");
winpr_HexDump(TAG, WLOG_DEBUG, context->SessionBaseKey, 16);
WLog_DBG(TAG, "KeyExchangeKey");
winpr_HexDump(TAG, WLOG_DEBUG, context->KeyExchangeKey, 16);
WLog_DBG(TAG, "ExportedSessionKey");
winpr_HexDump(TAG, WLOG_DEBUG, context->ExportedSessionKey, 16);
WLog_DBG(TAG, "RandomSessionKey");
winpr_HexDump(TAG, WLOG_DEBUG, context->RandomSessionKey, 16);
WLog_DBG(TAG, "ClientSigningKey");
winpr_HexDump(TAG, WLOG_DEBUG, context->ClientSigningKey, 16);
WLog_DBG(TAG, "ClientSealingKey");
winpr_HexDump(TAG, WLOG_DEBUG, context->ClientSealingKey, 16);
WLog_DBG(TAG, "ServerSigningKey");
winpr_HexDump(TAG, WLOG_DEBUG, context->ServerSigningKey, 16);
WLog_DBG(TAG, "ServerSealingKey");
winpr_HexDump(TAG, WLOG_DEBUG, context->ServerSealingKey, 16);
WLog_DBG(TAG, "Timestamp");
winpr_HexDump(TAG, WLOG_DEBUG, context->Timestamp, 8);
#endif
context->state = NTLM_STATE_FINAL;
ntlm_free_message_fields_buffer(&(message->DomainName));
ntlm_free_message_fields_buffer(&(message->UserName));
ntlm_free_message_fields_buffer(&(message->Workstation));
ntlm_free_message_fields_buffer(&(message->LmChallengeResponse));
ntlm_free_message_fields_buffer(&(message->NtChallengeResponse));
ntlm_free_message_fields_buffer(&(message->EncryptedRandomSessionKey));
return SEC_E_OK;
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_4025_0 |
crossvul-cpp_data_good_699_0 | /*
* SSLv3/TLSv1 client-side functions
*
* Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
* SPDX-License-Identifier: Apache-2.0
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* This file is part of mbed TLS (https://tls.mbed.org)
*/
#if !defined(MBEDTLS_CONFIG_FILE)
#include "mbedtls/config.h"
#else
#include MBEDTLS_CONFIG_FILE
#endif
#if defined(MBEDTLS_SSL_CLI_C)
#if defined(MBEDTLS_PLATFORM_C)
#include "mbedtls/platform.h"
#else
#include <stdlib.h>
#define mbedtls_calloc calloc
#define mbedtls_free free
#endif
#include "mbedtls/debug.h"
#include "mbedtls/ssl.h"
#include "mbedtls/ssl_internal.h"
#include <string.h>
#include <stdint.h>
#if defined(MBEDTLS_HAVE_TIME)
#include "mbedtls/platform_time.h"
#endif
#if defined(MBEDTLS_SSL_SESSION_TICKETS)
/* Implementation that should never be optimized out by the compiler */
static void mbedtls_zeroize( void *v, size_t n ) {
volatile unsigned char *p = v; while( n-- ) *p++ = 0;
}
#endif
#if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION)
static void ssl_write_hostname_ext( mbedtls_ssl_context *ssl,
unsigned char *buf,
size_t *olen )
{
unsigned char *p = buf;
const unsigned char *end = ssl->out_msg + MBEDTLS_SSL_MAX_CONTENT_LEN;
size_t hostname_len;
*olen = 0;
if( ssl->hostname == NULL )
return;
MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, adding server name extension: %s",
ssl->hostname ) );
hostname_len = strlen( ssl->hostname );
if( end < p || (size_t)( end - p ) < hostname_len + 9 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "buffer too small" ) );
return;
}
/*
* Sect. 3, RFC 6066 (TLS Extensions Definitions)
*
* In order to provide any of the server names, clients MAY include an
* extension of type "server_name" in the (extended) client hello. The
* "extension_data" field of this extension SHALL contain
* "ServerNameList" where:
*
* struct {
* NameType name_type;
* select (name_type) {
* case host_name: HostName;
* } name;
* } ServerName;
*
* enum {
* host_name(0), (255)
* } NameType;
*
* opaque HostName<1..2^16-1>;
*
* struct {
* ServerName server_name_list<1..2^16-1>
* } ServerNameList;
*
*/
*p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_SERVERNAME >> 8 ) & 0xFF );
*p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_SERVERNAME ) & 0xFF );
*p++ = (unsigned char)( ( (hostname_len + 5) >> 8 ) & 0xFF );
*p++ = (unsigned char)( ( (hostname_len + 5) ) & 0xFF );
*p++ = (unsigned char)( ( (hostname_len + 3) >> 8 ) & 0xFF );
*p++ = (unsigned char)( ( (hostname_len + 3) ) & 0xFF );
*p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_SERVERNAME_HOSTNAME ) & 0xFF );
*p++ = (unsigned char)( ( hostname_len >> 8 ) & 0xFF );
*p++ = (unsigned char)( ( hostname_len ) & 0xFF );
memcpy( p, ssl->hostname, hostname_len );
*olen = hostname_len + 9;
}
#endif /* MBEDTLS_SSL_SERVER_NAME_INDICATION */
#if defined(MBEDTLS_SSL_RENEGOTIATION)
static void ssl_write_renegotiation_ext( mbedtls_ssl_context *ssl,
unsigned char *buf,
size_t *olen )
{
unsigned char *p = buf;
const unsigned char *end = ssl->out_msg + MBEDTLS_SSL_MAX_CONTENT_LEN;
*olen = 0;
/* We're always including an TLS_EMPTY_RENEGOTIATION_INFO_SCSV in the
* initial ClientHello, in which case also adding the renegotiation
* info extension is NOT RECOMMENDED as per RFC 5746 Section 3.4. */
if( ssl->renego_status != MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS )
return;
MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, adding renegotiation extension" ) );
if( end < p || (size_t)( end - p ) < 5 + ssl->verify_data_len )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "buffer too small" ) );
return;
}
/*
* Secure renegotiation
*/
*p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_RENEGOTIATION_INFO >> 8 ) & 0xFF );
*p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_RENEGOTIATION_INFO ) & 0xFF );
*p++ = 0x00;
*p++ = ( ssl->verify_data_len + 1 ) & 0xFF;
*p++ = ssl->verify_data_len & 0xFF;
memcpy( p, ssl->own_verify_data, ssl->verify_data_len );
*olen = 5 + ssl->verify_data_len;
}
#endif /* MBEDTLS_SSL_RENEGOTIATION */
/*
* Only if we handle at least one key exchange that needs signatures.
*/
#if defined(MBEDTLS_SSL_PROTO_TLS1_2) && \
defined(MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED)
static void ssl_write_signature_algorithms_ext( mbedtls_ssl_context *ssl,
unsigned char *buf,
size_t *olen )
{
unsigned char *p = buf;
const unsigned char *end = ssl->out_msg + MBEDTLS_SSL_MAX_CONTENT_LEN;
size_t sig_alg_len = 0;
const int *md;
#if defined(MBEDTLS_RSA_C) || defined(MBEDTLS_ECDSA_C)
unsigned char *sig_alg_list = buf + 6;
#endif
*olen = 0;
if( ssl->conf->max_minor_ver != MBEDTLS_SSL_MINOR_VERSION_3 )
return;
MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, adding signature_algorithms extension" ) );
for( md = ssl->conf->sig_hashes; *md != MBEDTLS_MD_NONE; md++ )
{
#if defined(MBEDTLS_ECDSA_C)
sig_alg_len += 2;
#endif
#if defined(MBEDTLS_RSA_C)
sig_alg_len += 2;
#endif
}
if( end < p || (size_t)( end - p ) < sig_alg_len + 6 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "buffer too small" ) );
return;
}
/*
* Prepare signature_algorithms extension (TLS 1.2)
*/
sig_alg_len = 0;
for( md = ssl->conf->sig_hashes; *md != MBEDTLS_MD_NONE; md++ )
{
#if defined(MBEDTLS_ECDSA_C)
sig_alg_list[sig_alg_len++] = mbedtls_ssl_hash_from_md_alg( *md );
sig_alg_list[sig_alg_len++] = MBEDTLS_SSL_SIG_ECDSA;
#endif
#if defined(MBEDTLS_RSA_C)
sig_alg_list[sig_alg_len++] = mbedtls_ssl_hash_from_md_alg( *md );
sig_alg_list[sig_alg_len++] = MBEDTLS_SSL_SIG_RSA;
#endif
}
/*
* enum {
* none(0), md5(1), sha1(2), sha224(3), sha256(4), sha384(5),
* sha512(6), (255)
* } HashAlgorithm;
*
* enum { anonymous(0), rsa(1), dsa(2), ecdsa(3), (255) }
* SignatureAlgorithm;
*
* struct {
* HashAlgorithm hash;
* SignatureAlgorithm signature;
* } SignatureAndHashAlgorithm;
*
* SignatureAndHashAlgorithm
* supported_signature_algorithms<2..2^16-2>;
*/
*p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_SIG_ALG >> 8 ) & 0xFF );
*p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_SIG_ALG ) & 0xFF );
*p++ = (unsigned char)( ( ( sig_alg_len + 2 ) >> 8 ) & 0xFF );
*p++ = (unsigned char)( ( ( sig_alg_len + 2 ) ) & 0xFF );
*p++ = (unsigned char)( ( sig_alg_len >> 8 ) & 0xFF );
*p++ = (unsigned char)( ( sig_alg_len ) & 0xFF );
*olen = 6 + sig_alg_len;
}
#endif /* MBEDTLS_SSL_PROTO_TLS1_2 &&
MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED */
#if defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_ECDSA_C) || \
defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
static void ssl_write_supported_elliptic_curves_ext( mbedtls_ssl_context *ssl,
unsigned char *buf,
size_t *olen )
{
unsigned char *p = buf;
const unsigned char *end = ssl->out_msg + MBEDTLS_SSL_MAX_CONTENT_LEN;
unsigned char *elliptic_curve_list = p + 6;
size_t elliptic_curve_len = 0;
const mbedtls_ecp_curve_info *info;
#if defined(MBEDTLS_ECP_C)
const mbedtls_ecp_group_id *grp_id;
#else
((void) ssl);
#endif
*olen = 0;
MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, adding supported_elliptic_curves extension" ) );
#if defined(MBEDTLS_ECP_C)
for( grp_id = ssl->conf->curve_list; *grp_id != MBEDTLS_ECP_DP_NONE; grp_id++ )
#else
for( info = mbedtls_ecp_curve_list(); info->grp_id != MBEDTLS_ECP_DP_NONE; info++ )
#endif
{
#if defined(MBEDTLS_ECP_C)
info = mbedtls_ecp_curve_info_from_grp_id( *grp_id );
#endif
if( info == NULL )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "invalid curve in ssl configuration" ) );
return;
}
elliptic_curve_len += 2;
}
if( end < p || (size_t)( end - p ) < 6 + elliptic_curve_len )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "buffer too small" ) );
return;
}
elliptic_curve_len = 0;
#if defined(MBEDTLS_ECP_C)
for( grp_id = ssl->conf->curve_list; *grp_id != MBEDTLS_ECP_DP_NONE; grp_id++ )
#else
for( info = mbedtls_ecp_curve_list(); info->grp_id != MBEDTLS_ECP_DP_NONE; info++ )
#endif
{
#if defined(MBEDTLS_ECP_C)
info = mbedtls_ecp_curve_info_from_grp_id( *grp_id );
#endif
elliptic_curve_list[elliptic_curve_len++] = info->tls_id >> 8;
elliptic_curve_list[elliptic_curve_len++] = info->tls_id & 0xFF;
}
if( elliptic_curve_len == 0 )
return;
*p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_SUPPORTED_ELLIPTIC_CURVES >> 8 ) & 0xFF );
*p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_SUPPORTED_ELLIPTIC_CURVES ) & 0xFF );
*p++ = (unsigned char)( ( ( elliptic_curve_len + 2 ) >> 8 ) & 0xFF );
*p++ = (unsigned char)( ( ( elliptic_curve_len + 2 ) ) & 0xFF );
*p++ = (unsigned char)( ( ( elliptic_curve_len ) >> 8 ) & 0xFF );
*p++ = (unsigned char)( ( ( elliptic_curve_len ) ) & 0xFF );
*olen = 6 + elliptic_curve_len;
}
static void ssl_write_supported_point_formats_ext( mbedtls_ssl_context *ssl,
unsigned char *buf,
size_t *olen )
{
unsigned char *p = buf;
const unsigned char *end = ssl->out_msg + MBEDTLS_SSL_MAX_CONTENT_LEN;
*olen = 0;
MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, adding supported_point_formats extension" ) );
if( end < p || (size_t)( end - p ) < 6 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "buffer too small" ) );
return;
}
*p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_SUPPORTED_POINT_FORMATS >> 8 ) & 0xFF );
*p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_SUPPORTED_POINT_FORMATS ) & 0xFF );
*p++ = 0x00;
*p++ = 2;
*p++ = 1;
*p++ = MBEDTLS_ECP_PF_UNCOMPRESSED;
*olen = 6;
}
#endif /* MBEDTLS_ECDH_C || MBEDTLS_ECDSA_C ||
MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
#if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
static void ssl_write_ecjpake_kkpp_ext( mbedtls_ssl_context *ssl,
unsigned char *buf,
size_t *olen )
{
int ret;
unsigned char *p = buf;
const unsigned char *end = ssl->out_msg + MBEDTLS_SSL_MAX_CONTENT_LEN;
size_t kkpp_len;
*olen = 0;
/* Skip costly extension if we can't use EC J-PAKE anyway */
if( mbedtls_ecjpake_check( &ssl->handshake->ecjpake_ctx ) != 0 )
return;
MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, adding ecjpake_kkpp extension" ) );
if( end - p < 4 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "buffer too small" ) );
return;
}
*p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_ECJPAKE_KKPP >> 8 ) & 0xFF );
*p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_ECJPAKE_KKPP ) & 0xFF );
/*
* We may need to send ClientHello multiple times for Hello verification.
* We don't want to compute fresh values every time (both for performance
* and consistency reasons), so cache the extension content.
*/
if( ssl->handshake->ecjpake_cache == NULL ||
ssl->handshake->ecjpake_cache_len == 0 )
{
MBEDTLS_SSL_DEBUG_MSG( 3, ( "generating new ecjpake parameters" ) );
ret = mbedtls_ecjpake_write_round_one( &ssl->handshake->ecjpake_ctx,
p + 2, end - p - 2, &kkpp_len,
ssl->conf->f_rng, ssl->conf->p_rng );
if( ret != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1 , "mbedtls_ecjpake_write_round_one", ret );
return;
}
ssl->handshake->ecjpake_cache = mbedtls_calloc( 1, kkpp_len );
if( ssl->handshake->ecjpake_cache == NULL )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "allocation failed" ) );
return;
}
memcpy( ssl->handshake->ecjpake_cache, p + 2, kkpp_len );
ssl->handshake->ecjpake_cache_len = kkpp_len;
}
else
{
MBEDTLS_SSL_DEBUG_MSG( 3, ( "re-using cached ecjpake parameters" ) );
kkpp_len = ssl->handshake->ecjpake_cache_len;
if( (size_t)( end - p - 2 ) < kkpp_len )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "buffer too small" ) );
return;
}
memcpy( p + 2, ssl->handshake->ecjpake_cache, kkpp_len );
}
*p++ = (unsigned char)( ( kkpp_len >> 8 ) & 0xFF );
*p++ = (unsigned char)( ( kkpp_len ) & 0xFF );
*olen = kkpp_len + 4;
}
#endif /* MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
#if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)
static void ssl_write_max_fragment_length_ext( mbedtls_ssl_context *ssl,
unsigned char *buf,
size_t *olen )
{
unsigned char *p = buf;
const unsigned char *end = ssl->out_msg + MBEDTLS_SSL_MAX_CONTENT_LEN;
*olen = 0;
if( ssl->conf->mfl_code == MBEDTLS_SSL_MAX_FRAG_LEN_NONE ) {
return;
}
MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, adding max_fragment_length extension" ) );
if( end < p || (size_t)( end - p ) < 5 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "buffer too small" ) );
return;
}
*p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_MAX_FRAGMENT_LENGTH >> 8 ) & 0xFF );
*p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_MAX_FRAGMENT_LENGTH ) & 0xFF );
*p++ = 0x00;
*p++ = 1;
*p++ = ssl->conf->mfl_code;
*olen = 5;
}
#endif /* MBEDTLS_SSL_MAX_FRAGMENT_LENGTH */
#if defined(MBEDTLS_SSL_TRUNCATED_HMAC)
static void ssl_write_truncated_hmac_ext( mbedtls_ssl_context *ssl,
unsigned char *buf, size_t *olen )
{
unsigned char *p = buf;
const unsigned char *end = ssl->out_msg + MBEDTLS_SSL_MAX_CONTENT_LEN;
*olen = 0;
if( ssl->conf->trunc_hmac == MBEDTLS_SSL_TRUNC_HMAC_DISABLED )
{
return;
}
MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, adding truncated_hmac extension" ) );
if( end < p || (size_t)( end - p ) < 4 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "buffer too small" ) );
return;
}
*p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_TRUNCATED_HMAC >> 8 ) & 0xFF );
*p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_TRUNCATED_HMAC ) & 0xFF );
*p++ = 0x00;
*p++ = 0x00;
*olen = 4;
}
#endif /* MBEDTLS_SSL_TRUNCATED_HMAC */
#if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
static void ssl_write_encrypt_then_mac_ext( mbedtls_ssl_context *ssl,
unsigned char *buf, size_t *olen )
{
unsigned char *p = buf;
const unsigned char *end = ssl->out_msg + MBEDTLS_SSL_MAX_CONTENT_LEN;
*olen = 0;
if( ssl->conf->encrypt_then_mac == MBEDTLS_SSL_ETM_DISABLED ||
ssl->conf->max_minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 )
{
return;
}
MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, adding encrypt_then_mac "
"extension" ) );
if( end < p || (size_t)( end - p ) < 4 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "buffer too small" ) );
return;
}
*p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_ENCRYPT_THEN_MAC >> 8 ) & 0xFF );
*p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_ENCRYPT_THEN_MAC ) & 0xFF );
*p++ = 0x00;
*p++ = 0x00;
*olen = 4;
}
#endif /* MBEDTLS_SSL_ENCRYPT_THEN_MAC */
#if defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET)
static void ssl_write_extended_ms_ext( mbedtls_ssl_context *ssl,
unsigned char *buf, size_t *olen )
{
unsigned char *p = buf;
const unsigned char *end = ssl->out_msg + MBEDTLS_SSL_MAX_CONTENT_LEN;
*olen = 0;
if( ssl->conf->extended_ms == MBEDTLS_SSL_EXTENDED_MS_DISABLED ||
ssl->conf->max_minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 )
{
return;
}
MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, adding extended_master_secret "
"extension" ) );
if( end < p || (size_t)( end - p ) < 4 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "buffer too small" ) );
return;
}
*p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_EXTENDED_MASTER_SECRET >> 8 ) & 0xFF );
*p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_EXTENDED_MASTER_SECRET ) & 0xFF );
*p++ = 0x00;
*p++ = 0x00;
*olen = 4;
}
#endif /* MBEDTLS_SSL_EXTENDED_MASTER_SECRET */
#if defined(MBEDTLS_SSL_SESSION_TICKETS)
static void ssl_write_session_ticket_ext( mbedtls_ssl_context *ssl,
unsigned char *buf, size_t *olen )
{
unsigned char *p = buf;
const unsigned char *end = ssl->out_msg + MBEDTLS_SSL_MAX_CONTENT_LEN;
size_t tlen = ssl->session_negotiate->ticket_len;
*olen = 0;
if( ssl->conf->session_tickets == MBEDTLS_SSL_SESSION_TICKETS_DISABLED )
{
return;
}
MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, adding session ticket extension" ) );
if( end < p || (size_t)( end - p ) < 4 + tlen )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "buffer too small" ) );
return;
}
*p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_SESSION_TICKET >> 8 ) & 0xFF );
*p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_SESSION_TICKET ) & 0xFF );
*p++ = (unsigned char)( ( tlen >> 8 ) & 0xFF );
*p++ = (unsigned char)( ( tlen ) & 0xFF );
*olen = 4;
if( ssl->session_negotiate->ticket == NULL || tlen == 0 )
{
return;
}
MBEDTLS_SSL_DEBUG_MSG( 3, ( "sending session ticket of length %d", tlen ) );
memcpy( p, ssl->session_negotiate->ticket, tlen );
*olen += tlen;
}
#endif /* MBEDTLS_SSL_SESSION_TICKETS */
#if defined(MBEDTLS_SSL_ALPN)
static void ssl_write_alpn_ext( mbedtls_ssl_context *ssl,
unsigned char *buf, size_t *olen )
{
unsigned char *p = buf;
const unsigned char *end = ssl->out_msg + MBEDTLS_SSL_MAX_CONTENT_LEN;
size_t alpnlen = 0;
const char **cur;
*olen = 0;
if( ssl->conf->alpn_list == NULL )
{
return;
}
MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, adding alpn extension" ) );
for( cur = ssl->conf->alpn_list; *cur != NULL; cur++ )
alpnlen += (unsigned char)( strlen( *cur ) & 0xFF ) + 1;
if( end < p || (size_t)( end - p ) < 6 + alpnlen )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "buffer too small" ) );
return;
}
*p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_ALPN >> 8 ) & 0xFF );
*p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_ALPN ) & 0xFF );
/*
* opaque ProtocolName<1..2^8-1>;
*
* struct {
* ProtocolName protocol_name_list<2..2^16-1>
* } ProtocolNameList;
*/
/* Skip writing extension and list length for now */
p += 4;
for( cur = ssl->conf->alpn_list; *cur != NULL; cur++ )
{
*p = (unsigned char)( strlen( *cur ) & 0xFF );
memcpy( p + 1, *cur, *p );
p += 1 + *p;
}
*olen = p - buf;
/* List length = olen - 2 (ext_type) - 2 (ext_len) - 2 (list_len) */
buf[4] = (unsigned char)( ( ( *olen - 6 ) >> 8 ) & 0xFF );
buf[5] = (unsigned char)( ( ( *olen - 6 ) ) & 0xFF );
/* Extension length = olen - 2 (ext_type) - 2 (ext_len) */
buf[2] = (unsigned char)( ( ( *olen - 4 ) >> 8 ) & 0xFF );
buf[3] = (unsigned char)( ( ( *olen - 4 ) ) & 0xFF );
}
#endif /* MBEDTLS_SSL_ALPN */
/*
* Generate random bytes for ClientHello
*/
static int ssl_generate_random( mbedtls_ssl_context *ssl )
{
int ret;
unsigned char *p = ssl->handshake->randbytes;
#if defined(MBEDTLS_HAVE_TIME)
mbedtls_time_t t;
#endif
/*
* When responding to a verify request, MUST reuse random (RFC 6347 4.2.1)
*/
#if defined(MBEDTLS_SSL_PROTO_DTLS)
if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
ssl->handshake->verify_cookie != NULL )
{
return( 0 );
}
#endif
#if defined(MBEDTLS_HAVE_TIME)
t = mbedtls_time( NULL );
*p++ = (unsigned char)( t >> 24 );
*p++ = (unsigned char)( t >> 16 );
*p++ = (unsigned char)( t >> 8 );
*p++ = (unsigned char)( t );
MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, current time: %lu", t ) );
#else
if( ( ret = ssl->conf->f_rng( ssl->conf->p_rng, p, 4 ) ) != 0 )
return( ret );
p += 4;
#endif /* MBEDTLS_HAVE_TIME */
if( ( ret = ssl->conf->f_rng( ssl->conf->p_rng, p, 28 ) ) != 0 )
return( ret );
return( 0 );
}
static int ssl_write_client_hello( mbedtls_ssl_context *ssl )
{
int ret;
size_t i, n, olen, ext_len = 0;
unsigned char *buf;
unsigned char *p, *q;
unsigned char offer_compress;
const int *ciphersuites;
const mbedtls_ssl_ciphersuite_t *ciphersuite_info;
MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write client hello" ) );
if( ssl->conf->f_rng == NULL )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "no RNG provided") );
return( MBEDTLS_ERR_SSL_NO_RNG );
}
#if defined(MBEDTLS_SSL_RENEGOTIATION)
if( ssl->renego_status == MBEDTLS_SSL_INITIAL_HANDSHAKE )
#endif
{
ssl->major_ver = ssl->conf->min_major_ver;
ssl->minor_ver = ssl->conf->min_minor_ver;
}
if( ssl->conf->max_major_ver == 0 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "configured max major version is invalid, "
"consider using mbedtls_ssl_config_defaults()" ) );
return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
}
/*
* 0 . 0 handshake type
* 1 . 3 handshake length
* 4 . 5 highest version supported
* 6 . 9 current UNIX time
* 10 . 37 random bytes
*/
buf = ssl->out_msg;
p = buf + 4;
mbedtls_ssl_write_version( ssl->conf->max_major_ver, ssl->conf->max_minor_ver,
ssl->conf->transport, p );
p += 2;
MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, max version: [%d:%d]",
buf[4], buf[5] ) );
if( ( ret = ssl_generate_random( ssl ) ) != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, "ssl_generate_random", ret );
return( ret );
}
memcpy( p, ssl->handshake->randbytes, 32 );
MBEDTLS_SSL_DEBUG_BUF( 3, "client hello, random bytes", p, 32 );
p += 32;
/*
* 38 . 38 session id length
* 39 . 39+n session id
* 39+n . 39+n DTLS only: cookie length (1 byte)
* 40+n . .. DTSL only: cookie
* .. . .. ciphersuitelist length (2 bytes)
* .. . .. ciphersuitelist
* .. . .. compression methods length (1 byte)
* .. . .. compression methods
* .. . .. extensions length (2 bytes)
* .. . .. extensions
*/
n = ssl->session_negotiate->id_len;
if( n < 16 || n > 32 ||
#if defined(MBEDTLS_SSL_RENEGOTIATION)
ssl->renego_status != MBEDTLS_SSL_INITIAL_HANDSHAKE ||
#endif
ssl->handshake->resume == 0 )
{
n = 0;
}
#if defined(MBEDTLS_SSL_SESSION_TICKETS)
/*
* RFC 5077 section 3.4: "When presenting a ticket, the client MAY
* generate and include a Session ID in the TLS ClientHello."
*/
#if defined(MBEDTLS_SSL_RENEGOTIATION)
if( ssl->renego_status == MBEDTLS_SSL_INITIAL_HANDSHAKE )
#endif
{
if( ssl->session_negotiate->ticket != NULL &&
ssl->session_negotiate->ticket_len != 0 )
{
ret = ssl->conf->f_rng( ssl->conf->p_rng, ssl->session_negotiate->id, 32 );
if( ret != 0 )
return( ret );
ssl->session_negotiate->id_len = n = 32;
}
}
#endif /* MBEDTLS_SSL_SESSION_TICKETS */
*p++ = (unsigned char) n;
for( i = 0; i < n; i++ )
*p++ = ssl->session_negotiate->id[i];
MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, session id len.: %d", n ) );
MBEDTLS_SSL_DEBUG_BUF( 3, "client hello, session id", buf + 39, n );
/*
* DTLS cookie
*/
#if defined(MBEDTLS_SSL_PROTO_DTLS)
if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
{
if( ssl->handshake->verify_cookie == NULL )
{
MBEDTLS_SSL_DEBUG_MSG( 3, ( "no verify cookie to send" ) );
*p++ = 0;
}
else
{
MBEDTLS_SSL_DEBUG_BUF( 3, "client hello, cookie",
ssl->handshake->verify_cookie,
ssl->handshake->verify_cookie_len );
*p++ = ssl->handshake->verify_cookie_len;
memcpy( p, ssl->handshake->verify_cookie,
ssl->handshake->verify_cookie_len );
p += ssl->handshake->verify_cookie_len;
}
}
#endif
/*
* Ciphersuite list
*/
ciphersuites = ssl->conf->ciphersuite_list[ssl->minor_ver];
/* Skip writing ciphersuite length for now */
n = 0;
q = p;
p += 2;
for( i = 0; ciphersuites[i] != 0; i++ )
{
ciphersuite_info = mbedtls_ssl_ciphersuite_from_id( ciphersuites[i] );
if( ciphersuite_info == NULL )
continue;
if( ciphersuite_info->min_minor_ver > ssl->conf->max_minor_ver ||
ciphersuite_info->max_minor_ver < ssl->conf->min_minor_ver )
continue;
#if defined(MBEDTLS_SSL_PROTO_DTLS)
if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
( ciphersuite_info->flags & MBEDTLS_CIPHERSUITE_NODTLS ) )
continue;
#endif
#if defined(MBEDTLS_ARC4_C)
if( ssl->conf->arc4_disabled == MBEDTLS_SSL_ARC4_DISABLED &&
ciphersuite_info->cipher == MBEDTLS_CIPHER_ARC4_128 )
continue;
#endif
#if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECJPAKE &&
mbedtls_ecjpake_check( &ssl->handshake->ecjpake_ctx ) != 0 )
continue;
#endif
MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, add ciphersuite: %04x",
ciphersuites[i] ) );
n++;
*p++ = (unsigned char)( ciphersuites[i] >> 8 );
*p++ = (unsigned char)( ciphersuites[i] );
}
/*
* Add TLS_EMPTY_RENEGOTIATION_INFO_SCSV
*/
#if defined(MBEDTLS_SSL_RENEGOTIATION)
if( ssl->renego_status == MBEDTLS_SSL_INITIAL_HANDSHAKE )
#endif
{
*p++ = (unsigned char)( MBEDTLS_SSL_EMPTY_RENEGOTIATION_INFO >> 8 );
*p++ = (unsigned char)( MBEDTLS_SSL_EMPTY_RENEGOTIATION_INFO );
n++;
}
/* Some versions of OpenSSL don't handle it correctly if not at end */
#if defined(MBEDTLS_SSL_FALLBACK_SCSV)
if( ssl->conf->fallback == MBEDTLS_SSL_IS_FALLBACK )
{
MBEDTLS_SSL_DEBUG_MSG( 3, ( "adding FALLBACK_SCSV" ) );
*p++ = (unsigned char)( MBEDTLS_SSL_FALLBACK_SCSV_VALUE >> 8 );
*p++ = (unsigned char)( MBEDTLS_SSL_FALLBACK_SCSV_VALUE );
n++;
}
#endif
*q++ = (unsigned char)( n >> 7 );
*q++ = (unsigned char)( n << 1 );
MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, got %d ciphersuites", n ) );
#if defined(MBEDTLS_ZLIB_SUPPORT)
offer_compress = 1;
#else
offer_compress = 0;
#endif
/*
* We don't support compression with DTLS right now: is many records come
* in the same datagram, uncompressing one could overwrite the next one.
* We don't want to add complexity for handling that case unless there is
* an actual need for it.
*/
#if defined(MBEDTLS_SSL_PROTO_DTLS)
if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
offer_compress = 0;
#endif
if( offer_compress )
{
MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, compress len.: %d", 2 ) );
MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, compress alg.: %d %d",
MBEDTLS_SSL_COMPRESS_DEFLATE, MBEDTLS_SSL_COMPRESS_NULL ) );
*p++ = 2;
*p++ = MBEDTLS_SSL_COMPRESS_DEFLATE;
*p++ = MBEDTLS_SSL_COMPRESS_NULL;
}
else
{
MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, compress len.: %d", 1 ) );
MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, compress alg.: %d",
MBEDTLS_SSL_COMPRESS_NULL ) );
*p++ = 1;
*p++ = MBEDTLS_SSL_COMPRESS_NULL;
}
// First write extensions, then the total length
//
#if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION)
ssl_write_hostname_ext( ssl, p + 2 + ext_len, &olen );
ext_len += olen;
#endif
/* Note that TLS_EMPTY_RENEGOTIATION_INFO_SCSV is always added
* even if MBEDTLS_SSL_RENEGOTIATION is not defined. */
#if defined(MBEDTLS_SSL_RENEGOTIATION)
ssl_write_renegotiation_ext( ssl, p + 2 + ext_len, &olen );
ext_len += olen;
#endif
#if defined(MBEDTLS_SSL_PROTO_TLS1_2) && \
defined(MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED)
ssl_write_signature_algorithms_ext( ssl, p + 2 + ext_len, &olen );
ext_len += olen;
#endif
#if defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_ECDSA_C) || \
defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
ssl_write_supported_elliptic_curves_ext( ssl, p + 2 + ext_len, &olen );
ext_len += olen;
ssl_write_supported_point_formats_ext( ssl, p + 2 + ext_len, &olen );
ext_len += olen;
#endif
#if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
ssl_write_ecjpake_kkpp_ext( ssl, p + 2 + ext_len, &olen );
ext_len += olen;
#endif
#if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)
ssl_write_max_fragment_length_ext( ssl, p + 2 + ext_len, &olen );
ext_len += olen;
#endif
#if defined(MBEDTLS_SSL_TRUNCATED_HMAC)
ssl_write_truncated_hmac_ext( ssl, p + 2 + ext_len, &olen );
ext_len += olen;
#endif
#if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
ssl_write_encrypt_then_mac_ext( ssl, p + 2 + ext_len, &olen );
ext_len += olen;
#endif
#if defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET)
ssl_write_extended_ms_ext( ssl, p + 2 + ext_len, &olen );
ext_len += olen;
#endif
#if defined(MBEDTLS_SSL_ALPN)
ssl_write_alpn_ext( ssl, p + 2 + ext_len, &olen );
ext_len += olen;
#endif
#if defined(MBEDTLS_SSL_SESSION_TICKETS)
ssl_write_session_ticket_ext( ssl, p + 2 + ext_len, &olen );
ext_len += olen;
#endif
/* olen unused if all extensions are disabled */
((void) olen);
MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, total extension length: %d",
ext_len ) );
if( ext_len > 0 )
{
*p++ = (unsigned char)( ( ext_len >> 8 ) & 0xFF );
*p++ = (unsigned char)( ( ext_len ) & 0xFF );
p += ext_len;
}
ssl->out_msglen = p - buf;
ssl->out_msgtype = MBEDTLS_SSL_MSG_HANDSHAKE;
ssl->out_msg[0] = MBEDTLS_SSL_HS_CLIENT_HELLO;
ssl->state++;
#if defined(MBEDTLS_SSL_PROTO_DTLS)
if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
mbedtls_ssl_send_flight_completed( ssl );
#endif
if( ( ret = mbedtls_ssl_write_record( ssl ) ) != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_write_record", ret );
return( ret );
}
MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write client hello" ) );
return( 0 );
}
static int ssl_parse_renegotiation_info( mbedtls_ssl_context *ssl,
const unsigned char *buf,
size_t len )
{
#if defined(MBEDTLS_SSL_RENEGOTIATION)
if( ssl->renego_status != MBEDTLS_SSL_INITIAL_HANDSHAKE )
{
/* Check verify-data in constant-time. The length OTOH is no secret */
if( len != 1 + ssl->verify_data_len * 2 ||
buf[0] != ssl->verify_data_len * 2 ||
mbedtls_ssl_safer_memcmp( buf + 1,
ssl->own_verify_data, ssl->verify_data_len ) != 0 ||
mbedtls_ssl_safer_memcmp( buf + 1 + ssl->verify_data_len,
ssl->peer_verify_data, ssl->verify_data_len ) != 0 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "non-matching renegotiation info" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
}
}
else
#endif /* MBEDTLS_SSL_RENEGOTIATION */
{
if( len != 1 || buf[0] != 0x00 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "non-zero length renegotiation info" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
}
ssl->secure_renegotiation = MBEDTLS_SSL_SECURE_RENEGOTIATION;
}
return( 0 );
}
#if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)
static int ssl_parse_max_fragment_length_ext( mbedtls_ssl_context *ssl,
const unsigned char *buf,
size_t len )
{
/*
* server should use the extension only if we did,
* and if so the server's value should match ours (and len is always 1)
*/
if( ssl->conf->mfl_code == MBEDTLS_SSL_MAX_FRAG_LEN_NONE ||
len != 1 ||
buf[0] != ssl->conf->mfl_code )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "non-matching max fragment length extension" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
}
return( 0 );
}
#endif /* MBEDTLS_SSL_MAX_FRAGMENT_LENGTH */
#if defined(MBEDTLS_SSL_TRUNCATED_HMAC)
static int ssl_parse_truncated_hmac_ext( mbedtls_ssl_context *ssl,
const unsigned char *buf,
size_t len )
{
if( ssl->conf->trunc_hmac == MBEDTLS_SSL_TRUNC_HMAC_DISABLED ||
len != 0 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "non-matching truncated HMAC extension" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
}
((void) buf);
ssl->session_negotiate->trunc_hmac = MBEDTLS_SSL_TRUNC_HMAC_ENABLED;
return( 0 );
}
#endif /* MBEDTLS_SSL_TRUNCATED_HMAC */
#if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
static int ssl_parse_encrypt_then_mac_ext( mbedtls_ssl_context *ssl,
const unsigned char *buf,
size_t len )
{
if( ssl->conf->encrypt_then_mac == MBEDTLS_SSL_ETM_DISABLED ||
ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 ||
len != 0 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "non-matching encrypt-then-MAC extension" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
}
((void) buf);
ssl->session_negotiate->encrypt_then_mac = MBEDTLS_SSL_ETM_ENABLED;
return( 0 );
}
#endif /* MBEDTLS_SSL_ENCRYPT_THEN_MAC */
#if defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET)
static int ssl_parse_extended_ms_ext( mbedtls_ssl_context *ssl,
const unsigned char *buf,
size_t len )
{
if( ssl->conf->extended_ms == MBEDTLS_SSL_EXTENDED_MS_DISABLED ||
ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 ||
len != 0 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "non-matching extended master secret extension" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
}
((void) buf);
ssl->handshake->extended_ms = MBEDTLS_SSL_EXTENDED_MS_ENABLED;
return( 0 );
}
#endif /* MBEDTLS_SSL_EXTENDED_MASTER_SECRET */
#if defined(MBEDTLS_SSL_SESSION_TICKETS)
static int ssl_parse_session_ticket_ext( mbedtls_ssl_context *ssl,
const unsigned char *buf,
size_t len )
{
if( ssl->conf->session_tickets == MBEDTLS_SSL_SESSION_TICKETS_DISABLED ||
len != 0 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "non-matching session ticket extension" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
}
((void) buf);
ssl->handshake->new_session_ticket = 1;
return( 0 );
}
#endif /* MBEDTLS_SSL_SESSION_TICKETS */
#if defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_ECDSA_C) || \
defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
static int ssl_parse_supported_point_formats_ext( mbedtls_ssl_context *ssl,
const unsigned char *buf,
size_t len )
{
size_t list_size;
const unsigned char *p;
list_size = buf[0];
if( list_size + 1 != len )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server hello message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
}
p = buf + 1;
while( list_size > 0 )
{
if( p[0] == MBEDTLS_ECP_PF_UNCOMPRESSED ||
p[0] == MBEDTLS_ECP_PF_COMPRESSED )
{
#if defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_ECDSA_C)
ssl->handshake->ecdh_ctx.point_format = p[0];
#endif
#if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
ssl->handshake->ecjpake_ctx.point_format = p[0];
#endif
MBEDTLS_SSL_DEBUG_MSG( 4, ( "point format selected: %d", p[0] ) );
return( 0 );
}
list_size--;
p++;
}
MBEDTLS_SSL_DEBUG_MSG( 1, ( "no point format in common" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
}
#endif /* MBEDTLS_ECDH_C || MBEDTLS_ECDSA_C ||
MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
#if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
static int ssl_parse_ecjpake_kkpp( mbedtls_ssl_context *ssl,
const unsigned char *buf,
size_t len )
{
int ret;
if( ssl->transform_negotiate->ciphersuite_info->key_exchange !=
MBEDTLS_KEY_EXCHANGE_ECJPAKE )
{
MBEDTLS_SSL_DEBUG_MSG( 3, ( "skip ecjpake kkpp extension" ) );
return( 0 );
}
/* If we got here, we no longer need our cached extension */
mbedtls_free( ssl->handshake->ecjpake_cache );
ssl->handshake->ecjpake_cache = NULL;
ssl->handshake->ecjpake_cache_len = 0;
if( ( ret = mbedtls_ecjpake_read_round_one( &ssl->handshake->ecjpake_ctx,
buf, len ) ) != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ecjpake_read_round_one", ret );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );
return( ret );
}
return( 0 );
}
#endif /* MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
#if defined(MBEDTLS_SSL_ALPN)
static int ssl_parse_alpn_ext( mbedtls_ssl_context *ssl,
const unsigned char *buf, size_t len )
{
size_t list_len, name_len;
const char **p;
/* If we didn't send it, the server shouldn't send it */
if( ssl->conf->alpn_list == NULL )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "non-matching ALPN extension" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
}
/*
* opaque ProtocolName<1..2^8-1>;
*
* struct {
* ProtocolName protocol_name_list<2..2^16-1>
* } ProtocolNameList;
*
* the "ProtocolNameList" MUST contain exactly one "ProtocolName"
*/
/* Min length is 2 (list_len) + 1 (name_len) + 1 (name) */
if( len < 4 )
{
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
}
list_len = ( buf[0] << 8 ) | buf[1];
if( list_len != len - 2 )
{
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
}
name_len = buf[2];
if( name_len != list_len - 1 )
{
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
}
/* Check that the server chosen protocol was in our list and save it */
for( p = ssl->conf->alpn_list; *p != NULL; p++ )
{
if( name_len == strlen( *p ) &&
memcmp( buf + 3, *p, name_len ) == 0 )
{
ssl->alpn_chosen = *p;
return( 0 );
}
}
MBEDTLS_SSL_DEBUG_MSG( 1, ( "ALPN extension: no matching protocol" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
}
#endif /* MBEDTLS_SSL_ALPN */
/*
* Parse HelloVerifyRequest. Only called after verifying the HS type.
*/
#if defined(MBEDTLS_SSL_PROTO_DTLS)
static int ssl_parse_hello_verify_request( mbedtls_ssl_context *ssl )
{
const unsigned char *p = ssl->in_msg + mbedtls_ssl_hs_hdr_len( ssl );
int major_ver, minor_ver;
unsigned char cookie_len;
MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse hello verify request" ) );
/*
* struct {
* ProtocolVersion server_version;
* opaque cookie<0..2^8-1>;
* } HelloVerifyRequest;
*/
MBEDTLS_SSL_DEBUG_BUF( 3, "server version", p, 2 );
mbedtls_ssl_read_version( &major_ver, &minor_ver, ssl->conf->transport, p );
p += 2;
/*
* Since the RFC is not clear on this point, accept DTLS 1.0 (TLS 1.1)
* even is lower than our min version.
*/
if( major_ver < MBEDTLS_SSL_MAJOR_VERSION_3 ||
minor_ver < MBEDTLS_SSL_MINOR_VERSION_2 ||
major_ver > ssl->conf->max_major_ver ||
minor_ver > ssl->conf->max_minor_ver )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server version" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_PROTOCOL_VERSION );
return( MBEDTLS_ERR_SSL_BAD_HS_PROTOCOL_VERSION );
}
cookie_len = *p++;
MBEDTLS_SSL_DEBUG_BUF( 3, "cookie", p, cookie_len );
if( ( ssl->in_msg + ssl->in_msglen ) - p < cookie_len )
{
MBEDTLS_SSL_DEBUG_MSG( 1,
( "cookie length does not match incoming message size" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
}
mbedtls_free( ssl->handshake->verify_cookie );
ssl->handshake->verify_cookie = mbedtls_calloc( 1, cookie_len );
if( ssl->handshake->verify_cookie == NULL )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "alloc failed (%d bytes)", cookie_len ) );
return( MBEDTLS_ERR_SSL_ALLOC_FAILED );
}
memcpy( ssl->handshake->verify_cookie, p, cookie_len );
ssl->handshake->verify_cookie_len = cookie_len;
/* Start over at ClientHello */
ssl->state = MBEDTLS_SSL_CLIENT_HELLO;
mbedtls_ssl_reset_checksum( ssl );
mbedtls_ssl_recv_flight_completed( ssl );
MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= parse hello verify request" ) );
return( 0 );
}
#endif /* MBEDTLS_SSL_PROTO_DTLS */
static int ssl_parse_server_hello( mbedtls_ssl_context *ssl )
{
int ret, i;
size_t n;
size_t ext_len;
unsigned char *buf, *ext;
unsigned char comp;
#if defined(MBEDTLS_ZLIB_SUPPORT)
int accept_comp;
#endif
#if defined(MBEDTLS_SSL_RENEGOTIATION)
int renegotiation_info_seen = 0;
#endif
int handshake_failure = 0;
const mbedtls_ssl_ciphersuite_t *suite_info;
MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse server hello" ) );
buf = ssl->in_msg;
if( ( ret = mbedtls_ssl_read_record( ssl ) ) != 0 )
{
/* No alert on a read error. */
MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_read_record", ret );
return( ret );
}
if( ssl->in_msgtype != MBEDTLS_SSL_MSG_HANDSHAKE )
{
#if defined(MBEDTLS_SSL_RENEGOTIATION)
if( ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS )
{
ssl->renego_records_seen++;
if( ssl->conf->renego_max_records >= 0 &&
ssl->renego_records_seen > ssl->conf->renego_max_records )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "renegotiation requested, "
"but not honored by server" ) );
return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );
}
MBEDTLS_SSL_DEBUG_MSG( 1, ( "non-handshake message during renego" ) );
ssl->keep_current_message = 1;
return( MBEDTLS_ERR_SSL_WAITING_SERVER_HELLO_RENEGO );
}
#endif /* MBEDTLS_SSL_RENEGOTIATION */
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server hello message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_UNEXPECTED_MESSAGE );
return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );
}
#if defined(MBEDTLS_SSL_PROTO_DTLS)
if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
{
if( buf[0] == MBEDTLS_SSL_HS_HELLO_VERIFY_REQUEST )
{
MBEDTLS_SSL_DEBUG_MSG( 2, ( "received hello verify request" ) );
MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= parse server hello" ) );
return( ssl_parse_hello_verify_request( ssl ) );
}
else
{
/* We made it through the verification process */
mbedtls_free( ssl->handshake->verify_cookie );
ssl->handshake->verify_cookie = NULL;
ssl->handshake->verify_cookie_len = 0;
}
}
#endif /* MBEDTLS_SSL_PROTO_DTLS */
if( ssl->in_hslen < 38 + mbedtls_ssl_hs_hdr_len( ssl ) ||
buf[0] != MBEDTLS_SSL_HS_SERVER_HELLO )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server hello message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
}
/*
* 0 . 1 server_version
* 2 . 33 random (maybe including 4 bytes of Unix time)
* 34 . 34 session_id length = n
* 35 . 34+n session_id
* 35+n . 36+n cipher_suite
* 37+n . 37+n compression_method
*
* 38+n . 39+n extensions length (optional)
* 40+n . .. extensions
*/
buf += mbedtls_ssl_hs_hdr_len( ssl );
MBEDTLS_SSL_DEBUG_BUF( 3, "server hello, version", buf + 0, 2 );
mbedtls_ssl_read_version( &ssl->major_ver, &ssl->minor_ver,
ssl->conf->transport, buf + 0 );
if( ssl->major_ver < ssl->conf->min_major_ver ||
ssl->minor_ver < ssl->conf->min_minor_ver ||
ssl->major_ver > ssl->conf->max_major_ver ||
ssl->minor_ver > ssl->conf->max_minor_ver )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "server version out of bounds - "
" min: [%d:%d], server: [%d:%d], max: [%d:%d]",
ssl->conf->min_major_ver, ssl->conf->min_minor_ver,
ssl->major_ver, ssl->minor_ver,
ssl->conf->max_major_ver, ssl->conf->max_minor_ver ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_PROTOCOL_VERSION );
return( MBEDTLS_ERR_SSL_BAD_HS_PROTOCOL_VERSION );
}
MBEDTLS_SSL_DEBUG_MSG( 3, ( "server hello, current time: %lu",
( (uint32_t) buf[2] << 24 ) |
( (uint32_t) buf[3] << 16 ) |
( (uint32_t) buf[4] << 8 ) |
( (uint32_t) buf[5] ) ) );
memcpy( ssl->handshake->randbytes + 32, buf + 2, 32 );
n = buf[34];
MBEDTLS_SSL_DEBUG_BUF( 3, "server hello, random bytes", buf + 2, 32 );
if( n > 32 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server hello message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
}
if( ssl->in_hslen > mbedtls_ssl_hs_hdr_len( ssl ) + 39 + n )
{
ext_len = ( ( buf[38 + n] << 8 )
| ( buf[39 + n] ) );
if( ( ext_len > 0 && ext_len < 4 ) ||
ssl->in_hslen != mbedtls_ssl_hs_hdr_len( ssl ) + 40 + n + ext_len )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server hello message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
}
}
else if( ssl->in_hslen == mbedtls_ssl_hs_hdr_len( ssl ) + 38 + n )
{
ext_len = 0;
}
else
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server hello message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
}
/* ciphersuite (used later) */
i = ( buf[35 + n] << 8 ) | buf[36 + n];
/*
* Read and check compression
*/
comp = buf[37 + n];
#if defined(MBEDTLS_ZLIB_SUPPORT)
/* See comments in ssl_write_client_hello() */
#if defined(MBEDTLS_SSL_PROTO_DTLS)
if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
accept_comp = 0;
else
#endif
accept_comp = 1;
if( comp != MBEDTLS_SSL_COMPRESS_NULL &&
( comp != MBEDTLS_SSL_COMPRESS_DEFLATE || accept_comp == 0 ) )
#else /* MBEDTLS_ZLIB_SUPPORT */
if( comp != MBEDTLS_SSL_COMPRESS_NULL )
#endif/* MBEDTLS_ZLIB_SUPPORT */
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "server hello, bad compression: %d", comp ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER );
return( MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE );
}
/*
* Initialize update checksum functions
*/
ssl->transform_negotiate->ciphersuite_info = mbedtls_ssl_ciphersuite_from_id( i );
if( ssl->transform_negotiate->ciphersuite_info == NULL )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "ciphersuite info for %04x not found", i ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_INTERNAL_ERROR );
return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
}
mbedtls_ssl_optimize_checksum( ssl, ssl->transform_negotiate->ciphersuite_info );
MBEDTLS_SSL_DEBUG_MSG( 3, ( "server hello, session id len.: %d", n ) );
MBEDTLS_SSL_DEBUG_BUF( 3, "server hello, session id", buf + 35, n );
/*
* Check if the session can be resumed
*/
if( ssl->handshake->resume == 0 || n == 0 ||
#if defined(MBEDTLS_SSL_RENEGOTIATION)
ssl->renego_status != MBEDTLS_SSL_INITIAL_HANDSHAKE ||
#endif
ssl->session_negotiate->ciphersuite != i ||
ssl->session_negotiate->compression != comp ||
ssl->session_negotiate->id_len != n ||
memcmp( ssl->session_negotiate->id, buf + 35, n ) != 0 )
{
ssl->state++;
ssl->handshake->resume = 0;
#if defined(MBEDTLS_HAVE_TIME)
ssl->session_negotiate->start = mbedtls_time( NULL );
#endif
ssl->session_negotiate->ciphersuite = i;
ssl->session_negotiate->compression = comp;
ssl->session_negotiate->id_len = n;
memcpy( ssl->session_negotiate->id, buf + 35, n );
}
else
{
ssl->state = MBEDTLS_SSL_SERVER_CHANGE_CIPHER_SPEC;
if( ( ret = mbedtls_ssl_derive_keys( ssl ) ) != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_derive_keys", ret );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_INTERNAL_ERROR );
return( ret );
}
}
MBEDTLS_SSL_DEBUG_MSG( 3, ( "%s session has been resumed",
ssl->handshake->resume ? "a" : "no" ) );
MBEDTLS_SSL_DEBUG_MSG( 3, ( "server hello, chosen ciphersuite: %04x", i ) );
MBEDTLS_SSL_DEBUG_MSG( 3, ( "server hello, compress alg.: %d", buf[37 + n] ) );
suite_info = mbedtls_ssl_ciphersuite_from_id( ssl->session_negotiate->ciphersuite );
if( suite_info == NULL
#if defined(MBEDTLS_ARC4_C)
|| ( ssl->conf->arc4_disabled &&
suite_info->cipher == MBEDTLS_CIPHER_ARC4_128 )
#endif
)
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server hello message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
}
MBEDTLS_SSL_DEBUG_MSG( 3, ( "server hello, chosen ciphersuite: %s", suite_info->name ) );
i = 0;
while( 1 )
{
if( ssl->conf->ciphersuite_list[ssl->minor_ver][i] == 0 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server hello message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
}
if( ssl->conf->ciphersuite_list[ssl->minor_ver][i++] ==
ssl->session_negotiate->ciphersuite )
{
break;
}
}
if( comp != MBEDTLS_SSL_COMPRESS_NULL
#if defined(MBEDTLS_ZLIB_SUPPORT)
&& comp != MBEDTLS_SSL_COMPRESS_DEFLATE
#endif
)
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server hello message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
}
ssl->session_negotiate->compression = comp;
ext = buf + 40 + n;
MBEDTLS_SSL_DEBUG_MSG( 2, ( "server hello, total extension length: %d", ext_len ) );
while( ext_len )
{
unsigned int ext_id = ( ( ext[0] << 8 )
| ( ext[1] ) );
unsigned int ext_size = ( ( ext[2] << 8 )
| ( ext[3] ) );
if( ext_size + 4 > ext_len )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server hello message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
}
switch( ext_id )
{
case MBEDTLS_TLS_EXT_RENEGOTIATION_INFO:
MBEDTLS_SSL_DEBUG_MSG( 3, ( "found renegotiation extension" ) );
#if defined(MBEDTLS_SSL_RENEGOTIATION)
renegotiation_info_seen = 1;
#endif
if( ( ret = ssl_parse_renegotiation_info( ssl, ext + 4,
ext_size ) ) != 0 )
return( ret );
break;
#if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)
case MBEDTLS_TLS_EXT_MAX_FRAGMENT_LENGTH:
MBEDTLS_SSL_DEBUG_MSG( 3, ( "found max_fragment_length extension" ) );
if( ( ret = ssl_parse_max_fragment_length_ext( ssl,
ext + 4, ext_size ) ) != 0 )
{
return( ret );
}
break;
#endif /* MBEDTLS_SSL_MAX_FRAGMENT_LENGTH */
#if defined(MBEDTLS_SSL_TRUNCATED_HMAC)
case MBEDTLS_TLS_EXT_TRUNCATED_HMAC:
MBEDTLS_SSL_DEBUG_MSG( 3, ( "found truncated_hmac extension" ) );
if( ( ret = ssl_parse_truncated_hmac_ext( ssl,
ext + 4, ext_size ) ) != 0 )
{
return( ret );
}
break;
#endif /* MBEDTLS_SSL_TRUNCATED_HMAC */
#if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
case MBEDTLS_TLS_EXT_ENCRYPT_THEN_MAC:
MBEDTLS_SSL_DEBUG_MSG( 3, ( "found encrypt_then_mac extension" ) );
if( ( ret = ssl_parse_encrypt_then_mac_ext( ssl,
ext + 4, ext_size ) ) != 0 )
{
return( ret );
}
break;
#endif /* MBEDTLS_SSL_ENCRYPT_THEN_MAC */
#if defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET)
case MBEDTLS_TLS_EXT_EXTENDED_MASTER_SECRET:
MBEDTLS_SSL_DEBUG_MSG( 3, ( "found extended_master_secret extension" ) );
if( ( ret = ssl_parse_extended_ms_ext( ssl,
ext + 4, ext_size ) ) != 0 )
{
return( ret );
}
break;
#endif /* MBEDTLS_SSL_EXTENDED_MASTER_SECRET */
#if defined(MBEDTLS_SSL_SESSION_TICKETS)
case MBEDTLS_TLS_EXT_SESSION_TICKET:
MBEDTLS_SSL_DEBUG_MSG( 3, ( "found session_ticket extension" ) );
if( ( ret = ssl_parse_session_ticket_ext( ssl,
ext + 4, ext_size ) ) != 0 )
{
return( ret );
}
break;
#endif /* MBEDTLS_SSL_SESSION_TICKETS */
#if defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_ECDSA_C) || \
defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
case MBEDTLS_TLS_EXT_SUPPORTED_POINT_FORMATS:
MBEDTLS_SSL_DEBUG_MSG( 3, ( "found supported_point_formats extension" ) );
if( ( ret = ssl_parse_supported_point_formats_ext( ssl,
ext + 4, ext_size ) ) != 0 )
{
return( ret );
}
break;
#endif /* MBEDTLS_ECDH_C || MBEDTLS_ECDSA_C ||
MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
#if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
case MBEDTLS_TLS_EXT_ECJPAKE_KKPP:
MBEDTLS_SSL_DEBUG_MSG( 3, ( "found ecjpake_kkpp extension" ) );
if( ( ret = ssl_parse_ecjpake_kkpp( ssl,
ext + 4, ext_size ) ) != 0 )
{
return( ret );
}
break;
#endif /* MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
#if defined(MBEDTLS_SSL_ALPN)
case MBEDTLS_TLS_EXT_ALPN:
MBEDTLS_SSL_DEBUG_MSG( 3, ( "found alpn extension" ) );
if( ( ret = ssl_parse_alpn_ext( ssl, ext + 4, ext_size ) ) != 0 )
return( ret );
break;
#endif /* MBEDTLS_SSL_ALPN */
default:
MBEDTLS_SSL_DEBUG_MSG( 3, ( "unknown extension found: %d (ignoring)",
ext_id ) );
}
ext_len -= 4 + ext_size;
ext += 4 + ext_size;
if( ext_len > 0 && ext_len < 4 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server hello message" ) );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
}
}
/*
* Renegotiation security checks
*/
if( ssl->secure_renegotiation == MBEDTLS_SSL_LEGACY_RENEGOTIATION &&
ssl->conf->allow_legacy_renegotiation == MBEDTLS_SSL_LEGACY_BREAK_HANDSHAKE )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "legacy renegotiation, breaking off handshake" ) );
handshake_failure = 1;
}
#if defined(MBEDTLS_SSL_RENEGOTIATION)
else if( ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS &&
ssl->secure_renegotiation == MBEDTLS_SSL_SECURE_RENEGOTIATION &&
renegotiation_info_seen == 0 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "renegotiation_info extension missing (secure)" ) );
handshake_failure = 1;
}
else if( ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS &&
ssl->secure_renegotiation == MBEDTLS_SSL_LEGACY_RENEGOTIATION &&
ssl->conf->allow_legacy_renegotiation == MBEDTLS_SSL_LEGACY_NO_RENEGOTIATION )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "legacy renegotiation not allowed" ) );
handshake_failure = 1;
}
else if( ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS &&
ssl->secure_renegotiation == MBEDTLS_SSL_LEGACY_RENEGOTIATION &&
renegotiation_info_seen == 1 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "renegotiation_info extension present (legacy)" ) );
handshake_failure = 1;
}
#endif /* MBEDTLS_SSL_RENEGOTIATION */
if( handshake_failure == 1 )
{
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
}
MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= parse server hello" ) );
return( 0 );
}
#if defined(MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED)
static int ssl_parse_server_dh_params( mbedtls_ssl_context *ssl, unsigned char **p,
unsigned char *end )
{
int ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE;
/*
* Ephemeral DH parameters:
*
* struct {
* opaque dh_p<1..2^16-1>;
* opaque dh_g<1..2^16-1>;
* opaque dh_Ys<1..2^16-1>;
* } ServerDHParams;
*/
if( ( ret = mbedtls_dhm_read_params( &ssl->handshake->dhm_ctx, p, end ) ) != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 2, ( "mbedtls_dhm_read_params" ), ret );
return( ret );
}
if( ssl->handshake->dhm_ctx.len * 8 < ssl->conf->dhm_min_bitlen )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "DHM prime too short: %d < %d",
ssl->handshake->dhm_ctx.len * 8,
ssl->conf->dhm_min_bitlen ) );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
}
MBEDTLS_SSL_DEBUG_MPI( 3, "DHM: P ", &ssl->handshake->dhm_ctx.P );
MBEDTLS_SSL_DEBUG_MPI( 3, "DHM: G ", &ssl->handshake->dhm_ctx.G );
MBEDTLS_SSL_DEBUG_MPI( 3, "DHM: GY", &ssl->handshake->dhm_ctx.GY );
return( ret );
}
#endif /* MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED ||
MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED */
#if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED)
static int ssl_check_server_ecdh_params( const mbedtls_ssl_context *ssl )
{
const mbedtls_ecp_curve_info *curve_info;
curve_info = mbedtls_ecp_curve_info_from_grp_id( ssl->handshake->ecdh_ctx.grp.id );
if( curve_info == NULL )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
}
MBEDTLS_SSL_DEBUG_MSG( 2, ( "ECDH curve: %s", curve_info->name ) );
#if defined(MBEDTLS_ECP_C)
if( mbedtls_ssl_check_curve( ssl, ssl->handshake->ecdh_ctx.grp.id ) != 0 )
#else
if( ssl->handshake->ecdh_ctx.grp.nbits < 163 ||
ssl->handshake->ecdh_ctx.grp.nbits > 521 )
#endif
return( -1 );
MBEDTLS_SSL_DEBUG_ECP( 3, "ECDH: Qp", &ssl->handshake->ecdh_ctx.Qp );
return( 0 );
}
#endif /* MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED ||
MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED ||
MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED ||
MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED ||
MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED */
#if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED)
static int ssl_parse_server_ecdh_params( mbedtls_ssl_context *ssl,
unsigned char **p,
unsigned char *end )
{
int ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE;
/*
* Ephemeral ECDH parameters:
*
* struct {
* ECParameters curve_params;
* ECPoint public;
* } ServerECDHParams;
*/
if( ( ret = mbedtls_ecdh_read_params( &ssl->handshake->ecdh_ctx,
(const unsigned char **) p, end ) ) != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, ( "mbedtls_ecdh_read_params" ), ret );
return( ret );
}
if( ssl_check_server_ecdh_params( ssl ) != 0 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message (ECDHE curve)" ) );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
}
return( ret );
}
#endif /* MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED ||
MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED ||
MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED */
#if defined(MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED)
static int ssl_parse_server_psk_hint( mbedtls_ssl_context *ssl,
unsigned char **p,
unsigned char *end )
{
int ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE;
size_t len;
((void) ssl);
/*
* PSK parameters:
*
* opaque psk_identity_hint<0..2^16-1>;
*/
len = (*p)[0] << 8 | (*p)[1];
*p += 2;
if( (*p) + len > end )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message "
"(psk_identity_hint length)" ) );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
}
/*
* Note: we currently ignore the PKS identity hint, as we only allow one
* PSK to be provisionned on the client. This could be changed later if
* someone needs that feature.
*/
*p += len;
ret = 0;
return( ret );
}
#endif /* MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED */
#if defined(MBEDTLS_KEY_EXCHANGE_RSA_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED)
/*
* Generate a pre-master secret and encrypt it with the server's RSA key
*/
static int ssl_write_encrypted_pms( mbedtls_ssl_context *ssl,
size_t offset, size_t *olen,
size_t pms_offset )
{
int ret;
size_t len_bytes = ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 ? 0 : 2;
unsigned char *p = ssl->handshake->premaster + pms_offset;
if( offset + len_bytes > MBEDTLS_SSL_MAX_CONTENT_LEN )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "buffer too small for encrypted pms" ) );
return( MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL );
}
/*
* Generate (part of) the pre-master as
* struct {
* ProtocolVersion client_version;
* opaque random[46];
* } PreMasterSecret;
*/
mbedtls_ssl_write_version( ssl->conf->max_major_ver, ssl->conf->max_minor_ver,
ssl->conf->transport, p );
if( ( ret = ssl->conf->f_rng( ssl->conf->p_rng, p + 2, 46 ) ) != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, "f_rng", ret );
return( ret );
}
ssl->handshake->pmslen = 48;
if( ssl->session_negotiate->peer_cert == NULL )
{
MBEDTLS_SSL_DEBUG_MSG( 2, ( "certificate required" ) );
return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );
}
/*
* Now write it out, encrypted
*/
if( ! mbedtls_pk_can_do( &ssl->session_negotiate->peer_cert->pk,
MBEDTLS_PK_RSA ) )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "certificate key type mismatch" ) );
return( MBEDTLS_ERR_SSL_PK_TYPE_MISMATCH );
}
if( ( ret = mbedtls_pk_encrypt( &ssl->session_negotiate->peer_cert->pk,
p, ssl->handshake->pmslen,
ssl->out_msg + offset + len_bytes, olen,
MBEDTLS_SSL_MAX_CONTENT_LEN - offset - len_bytes,
ssl->conf->f_rng, ssl->conf->p_rng ) ) != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_rsa_pkcs1_encrypt", ret );
return( ret );
}
#if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) || \
defined(MBEDTLS_SSL_PROTO_TLS1_2)
if( len_bytes == 2 )
{
ssl->out_msg[offset+0] = (unsigned char)( *olen >> 8 );
ssl->out_msg[offset+1] = (unsigned char)( *olen );
*olen += 2;
}
#endif
return( 0 );
}
#endif /* MBEDTLS_KEY_EXCHANGE_RSA_ENABLED ||
MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED */
#if defined(MBEDTLS_SSL_PROTO_TLS1_2)
#if defined(MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED)
static int ssl_parse_signature_algorithm( mbedtls_ssl_context *ssl,
unsigned char **p,
unsigned char *end,
mbedtls_md_type_t *md_alg,
mbedtls_pk_type_t *pk_alg )
{
((void) ssl);
*md_alg = MBEDTLS_MD_NONE;
*pk_alg = MBEDTLS_PK_NONE;
/* Only in TLS 1.2 */
if( ssl->minor_ver != MBEDTLS_SSL_MINOR_VERSION_3 )
{
return( 0 );
}
if( (*p) + 2 > end )
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
/*
* Get hash algorithm
*/
if( ( *md_alg = mbedtls_ssl_md_alg_from_hash( (*p)[0] ) ) == MBEDTLS_MD_NONE )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "Server used unsupported "
"HashAlgorithm %d", *(p)[0] ) );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
}
/*
* Get signature algorithm
*/
if( ( *pk_alg = mbedtls_ssl_pk_alg_from_sig( (*p)[1] ) ) == MBEDTLS_PK_NONE )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "server used unsupported "
"SignatureAlgorithm %d", (*p)[1] ) );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
}
/*
* Check if the hash is acceptable
*/
if( mbedtls_ssl_check_sig_hash( ssl, *md_alg ) != 0 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "server used HashAlgorithm %d that was not offered",
*(p)[0] ) );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
}
MBEDTLS_SSL_DEBUG_MSG( 2, ( "Server used SignatureAlgorithm %d", (*p)[1] ) );
MBEDTLS_SSL_DEBUG_MSG( 2, ( "Server used HashAlgorithm %d", (*p)[0] ) );
*p += 2;
return( 0 );
}
#endif /* MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED ||
MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED ||
MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED */
#endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
#if defined(MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED)
static int ssl_get_ecdh_params_from_cert( mbedtls_ssl_context *ssl )
{
int ret;
const mbedtls_ecp_keypair *peer_key;
if( ssl->session_negotiate->peer_cert == NULL )
{
MBEDTLS_SSL_DEBUG_MSG( 2, ( "certificate required" ) );
return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );
}
if( ! mbedtls_pk_can_do( &ssl->session_negotiate->peer_cert->pk,
MBEDTLS_PK_ECKEY ) )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "server key not ECDH capable" ) );
return( MBEDTLS_ERR_SSL_PK_TYPE_MISMATCH );
}
peer_key = mbedtls_pk_ec( ssl->session_negotiate->peer_cert->pk );
if( ( ret = mbedtls_ecdh_get_params( &ssl->handshake->ecdh_ctx, peer_key,
MBEDTLS_ECDH_THEIRS ) ) != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, ( "mbedtls_ecdh_get_params" ), ret );
return( ret );
}
if( ssl_check_server_ecdh_params( ssl ) != 0 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server certificate (ECDH curve)" ) );
return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE );
}
return( ret );
}
#endif /* MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED) ||
MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED */
static int ssl_parse_server_key_exchange( mbedtls_ssl_context *ssl )
{
int ret;
const mbedtls_ssl_ciphersuite_t *ciphersuite_info =
ssl->transform_negotiate->ciphersuite_info;
unsigned char *p = NULL, *end = NULL;
MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse server key exchange" ) );
#if defined(MBEDTLS_KEY_EXCHANGE_RSA_ENABLED)
if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA )
{
MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip parse server key exchange" ) );
ssl->state++;
return( 0 );
}
((void) p);
((void) end);
#endif
#if defined(MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED)
if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDH_RSA ||
ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA )
{
if( ( ret = ssl_get_ecdh_params_from_cert( ssl ) ) != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, "ssl_get_ecdh_params_from_cert", ret );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );
return( ret );
}
MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip parse server key exchange" ) );
ssl->state++;
return( 0 );
}
((void) p);
((void) end);
#endif /* MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED ||
MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED */
if( ( ret = mbedtls_ssl_read_record( ssl ) ) != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_read_record", ret );
return( ret );
}
if( ssl->in_msgtype != MBEDTLS_SSL_MSG_HANDSHAKE )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_UNEXPECTED_MESSAGE );
return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );
}
/*
* ServerKeyExchange may be skipped with PSK and RSA-PSK when the server
* doesn't use a psk_identity_hint
*/
if( ssl->in_msg[0] != MBEDTLS_SSL_HS_SERVER_KEY_EXCHANGE )
{
if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_PSK ||
ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA_PSK )
{
/* Current message is probably either
* CertificateRequest or ServerHelloDone */
ssl->keep_current_message = 1;
goto exit;
}
MBEDTLS_SSL_DEBUG_MSG( 1, ( "server key exchange message must "
"not be skipped" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_UNEXPECTED_MESSAGE );
return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );
}
p = ssl->in_msg + mbedtls_ssl_hs_hdr_len( ssl );
end = ssl->in_msg + ssl->in_hslen;
MBEDTLS_SSL_DEBUG_BUF( 3, "server key exchange", p, end - p );
#if defined(MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED)
if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_PSK ||
ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA_PSK ||
ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_PSK ||
ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK )
{
if( ssl_parse_server_psk_hint( ssl, &p, end ) != 0 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
}
} /* FALLTROUGH */
#endif /* MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED */
#if defined(MBEDTLS_KEY_EXCHANGE_PSK_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED)
if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_PSK ||
ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA_PSK )
; /* nothing more to do */
else
#endif /* MBEDTLS_KEY_EXCHANGE_PSK_ENABLED ||
MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED */
#if defined(MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED)
if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_RSA ||
ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_PSK )
{
if( ssl_parse_server_dh_params( ssl, &p, end ) != 0 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
}
}
else
#endif /* MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED ||
MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED */
#if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED)
if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_RSA ||
ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK ||
ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA )
{
if( ssl_parse_server_ecdh_params( ssl, &p, end ) != 0 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
}
}
else
#endif /* MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED ||
MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED ||
MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED */
#if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECJPAKE )
{
ret = mbedtls_ecjpake_read_round_two( &ssl->handshake->ecjpake_ctx,
p, end - p );
if( ret != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ecjpake_read_round_two", ret );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
}
}
else
#endif /* MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
}
#if defined(MBEDTLS_KEY_EXCHANGE__WITH_SERVER_SIGNATURE__ENABLED)
if( mbedtls_ssl_ciphersuite_uses_server_signature( ciphersuite_info ) )
{
size_t sig_len, hashlen;
unsigned char hash[64];
mbedtls_md_type_t md_alg = MBEDTLS_MD_NONE;
mbedtls_pk_type_t pk_alg = MBEDTLS_PK_NONE;
unsigned char *params = ssl->in_msg + mbedtls_ssl_hs_hdr_len( ssl );
size_t params_len = p - params;
/*
* Handle the digitally-signed structure
*/
#if defined(MBEDTLS_SSL_PROTO_TLS1_2)
if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_3 )
{
if( ssl_parse_signature_algorithm( ssl, &p, end,
&md_alg, &pk_alg ) != 0 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
}
if( pk_alg != mbedtls_ssl_get_ciphersuite_sig_pk_alg( ciphersuite_info ) )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
}
}
else
#endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
#if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \
defined(MBEDTLS_SSL_PROTO_TLS1_1)
if( ssl->minor_ver < MBEDTLS_SSL_MINOR_VERSION_3 )
{
pk_alg = mbedtls_ssl_get_ciphersuite_sig_pk_alg( ciphersuite_info );
/* Default hash for ECDSA is SHA-1 */
if( pk_alg == MBEDTLS_PK_ECDSA && md_alg == MBEDTLS_MD_NONE )
md_alg = MBEDTLS_MD_SHA1;
}
else
#endif
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
}
/*
* Read signature
*/
if( p > end - 2 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
}
sig_len = ( p[0] << 8 ) | p[1];
p += 2;
if( p != end - sig_len )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
}
MBEDTLS_SSL_DEBUG_BUF( 3, "signature", p, sig_len );
/*
* Compute the hash that has been signed
*/
#if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \
defined(MBEDTLS_SSL_PROTO_TLS1_1)
if( md_alg == MBEDTLS_MD_NONE )
{
hashlen = 36;
ret = mbedtls_ssl_get_key_exchange_md_ssl_tls( ssl, hash, params,
params_len );
if( ret != 0 )
return( ret );
}
else
#endif /* MBEDTLS_SSL_PROTO_SSL3 || MBEDTLS_SSL_PROTO_TLS1 || \
MBEDTLS_SSL_PROTO_TLS1_1 */
#if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) || \
defined(MBEDTLS_SSL_PROTO_TLS1_2)
if( md_alg != MBEDTLS_MD_NONE )
{
/* Info from md_alg will be used instead */
hashlen = 0;
ret = mbedtls_ssl_get_key_exchange_md_tls1_2( ssl, hash, params,
params_len, md_alg );
if( ret != 0 )
return( ret );
}
else
#endif /* MBEDTLS_SSL_PROTO_TLS1 || MBEDTLS_SSL_PROTO_TLS1_1 || \
MBEDTLS_SSL_PROTO_TLS1_2 */
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
}
MBEDTLS_SSL_DEBUG_BUF( 3, "parameters hash", hash, hashlen != 0 ? hashlen :
(unsigned int) ( mbedtls_md_get_size( mbedtls_md_info_from_type( md_alg ) ) ) );
if( ssl->session_negotiate->peer_cert == NULL )
{
MBEDTLS_SSL_DEBUG_MSG( 2, ( "certificate required" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );
return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );
}
/*
* Verify signature
*/
if( ! mbedtls_pk_can_do( &ssl->session_negotiate->peer_cert->pk, pk_alg ) )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );
return( MBEDTLS_ERR_SSL_PK_TYPE_MISMATCH );
}
if( ( ret = mbedtls_pk_verify( &ssl->session_negotiate->peer_cert->pk,
md_alg, hash, hashlen, p, sig_len ) ) != 0 )
{
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_DECRYPT_ERROR );
MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_pk_verify", ret );
return( ret );
}
}
#endif /* MBEDTLS_KEY_EXCHANGE__WITH_SERVER_SIGNATURE__ENABLED */
exit:
ssl->state++;
MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= parse server key exchange" ) );
return( 0 );
}
#if ! defined(MBEDTLS_KEY_EXCHANGE__CERT_REQ_ALLOWED__ENABLED)
static int ssl_parse_certificate_request( mbedtls_ssl_context *ssl )
{
const mbedtls_ssl_ciphersuite_t *ciphersuite_info =
ssl->transform_negotiate->ciphersuite_info;
MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse certificate request" ) );
if( ! mbedtls_ssl_ciphersuite_cert_req_allowed( ciphersuite_info ) )
{
MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip parse certificate request" ) );
ssl->state++;
return( 0 );
}
MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
}
#else /* MBEDTLS_KEY_EXCHANGE__CERT_REQ_ALLOWED__ENABLED */
static int ssl_parse_certificate_request( mbedtls_ssl_context *ssl )
{
int ret;
unsigned char *buf;
size_t n = 0;
size_t cert_type_len = 0, dn_len = 0;
const mbedtls_ssl_ciphersuite_t *ciphersuite_info =
ssl->transform_negotiate->ciphersuite_info;
MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse certificate request" ) );
if( ! mbedtls_ssl_ciphersuite_cert_req_allowed( ciphersuite_info ) )
{
MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip parse certificate request" ) );
ssl->state++;
return( 0 );
}
if( ( ret = mbedtls_ssl_read_record( ssl ) ) != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_read_record", ret );
return( ret );
}
if( ssl->in_msgtype != MBEDTLS_SSL_MSG_HANDSHAKE )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate request message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_UNEXPECTED_MESSAGE );
return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );
}
ssl->state++;
ssl->client_auth = ( ssl->in_msg[0] == MBEDTLS_SSL_HS_CERTIFICATE_REQUEST );
MBEDTLS_SSL_DEBUG_MSG( 3, ( "got %s certificate request",
ssl->client_auth ? "a" : "no" ) );
if( ssl->client_auth == 0 )
{
/* Current message is probably the ServerHelloDone */
ssl->keep_current_message = 1;
goto exit;
}
/*
* struct {
* ClientCertificateType certificate_types<1..2^8-1>;
* SignatureAndHashAlgorithm
* supported_signature_algorithms<2^16-1>; -- TLS 1.2 only
* DistinguishedName certificate_authorities<0..2^16-1>;
* } CertificateRequest;
*
* Since we only support a single certificate on clients, let's just
* ignore all the information that's supposed to help us pick a
* certificate.
*
* We could check that our certificate matches the request, and bail out
* if it doesn't, but it's simpler to just send the certificate anyway,
* and give the server the opportunity to decide if it should terminate
* the connection when it doesn't like our certificate.
*
* Same goes for the hash in TLS 1.2's signature_algorithms: at this
* point we only have one hash available (see comments in
* write_certificate_verify), so let's just use what we have.
*
* However, we still minimally parse the message to check it is at least
* superficially sane.
*/
buf = ssl->in_msg;
/* certificate_types */
cert_type_len = buf[mbedtls_ssl_hs_hdr_len( ssl )];
n = cert_type_len;
if( ssl->in_hslen < mbedtls_ssl_hs_hdr_len( ssl ) + 2 + n )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate request message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE_REQUEST );
}
/* supported_signature_algorithms */
#if defined(MBEDTLS_SSL_PROTO_TLS1_2)
if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_3 )
{
size_t sig_alg_len = ( ( buf[mbedtls_ssl_hs_hdr_len( ssl ) + 1 + n] << 8 )
| ( buf[mbedtls_ssl_hs_hdr_len( ssl ) + 2 + n] ) );
#if defined(MBEDTLS_DEBUG_C)
unsigned char* sig_alg = buf + mbedtls_ssl_hs_hdr_len( ssl ) + 3 + n;
size_t i;
for( i = 0; i < sig_alg_len; i += 2 )
{
MBEDTLS_SSL_DEBUG_MSG( 3, ( "Supported Signature Algorithm found: %d"
",%d", sig_alg[i], sig_alg[i + 1] ) );
}
#endif
n += 2 + sig_alg_len;
if( ssl->in_hslen < mbedtls_ssl_hs_hdr_len( ssl ) + 2 + n )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate request message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE_REQUEST );
}
}
#endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
/* certificate_authorities */
dn_len = ( ( buf[mbedtls_ssl_hs_hdr_len( ssl ) + 1 + n] << 8 )
| ( buf[mbedtls_ssl_hs_hdr_len( ssl ) + 2 + n] ) );
n += dn_len;
if( ssl->in_hslen != mbedtls_ssl_hs_hdr_len( ssl ) + 3 + n )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate request message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE_REQUEST );
}
exit:
MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= parse certificate request" ) );
return( 0 );
}
#endif /* MBEDTLS_KEY_EXCHANGE__CERT_REQ_ALLOWED__ENABLED */
static int ssl_parse_server_hello_done( mbedtls_ssl_context *ssl )
{
int ret;
MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse server hello done" ) );
if( ( ret = mbedtls_ssl_read_record( ssl ) ) != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_read_record", ret );
return( ret );
}
if( ssl->in_msgtype != MBEDTLS_SSL_MSG_HANDSHAKE )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server hello done message" ) );
return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );
}
if( ssl->in_hslen != mbedtls_ssl_hs_hdr_len( ssl ) ||
ssl->in_msg[0] != MBEDTLS_SSL_HS_SERVER_HELLO_DONE )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server hello done message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO_DONE );
}
ssl->state++;
#if defined(MBEDTLS_SSL_PROTO_DTLS)
if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
mbedtls_ssl_recv_flight_completed( ssl );
#endif
MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= parse server hello done" ) );
return( 0 );
}
static int ssl_write_client_key_exchange( mbedtls_ssl_context *ssl )
{
int ret;
size_t i, n;
const mbedtls_ssl_ciphersuite_t *ciphersuite_info =
ssl->transform_negotiate->ciphersuite_info;
MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write client key exchange" ) );
#if defined(MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED)
if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_RSA )
{
/*
* DHM key exchange -- send G^X mod P
*/
n = ssl->handshake->dhm_ctx.len;
ssl->out_msg[4] = (unsigned char)( n >> 8 );
ssl->out_msg[5] = (unsigned char)( n );
i = 6;
ret = mbedtls_dhm_make_public( &ssl->handshake->dhm_ctx,
(int) mbedtls_mpi_size( &ssl->handshake->dhm_ctx.P ),
&ssl->out_msg[i], n,
ssl->conf->f_rng, ssl->conf->p_rng );
if( ret != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_dhm_make_public", ret );
return( ret );
}
MBEDTLS_SSL_DEBUG_MPI( 3, "DHM: X ", &ssl->handshake->dhm_ctx.X );
MBEDTLS_SSL_DEBUG_MPI( 3, "DHM: GX", &ssl->handshake->dhm_ctx.GX );
if( ( ret = mbedtls_dhm_calc_secret( &ssl->handshake->dhm_ctx,
ssl->handshake->premaster,
MBEDTLS_PREMASTER_SIZE,
&ssl->handshake->pmslen,
ssl->conf->f_rng, ssl->conf->p_rng ) ) != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_dhm_calc_secret", ret );
return( ret );
}
MBEDTLS_SSL_DEBUG_MPI( 3, "DHM: K ", &ssl->handshake->dhm_ctx.K );
}
else
#endif /* MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED */
#if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED)
if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_RSA ||
ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA ||
ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDH_RSA ||
ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA )
{
/*
* ECDH key exchange -- send client public value
*/
i = 4;
ret = mbedtls_ecdh_make_public( &ssl->handshake->ecdh_ctx,
&n,
&ssl->out_msg[i], 1000,
ssl->conf->f_rng, ssl->conf->p_rng );
if( ret != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ecdh_make_public", ret );
return( ret );
}
MBEDTLS_SSL_DEBUG_ECP( 3, "ECDH: Q", &ssl->handshake->ecdh_ctx.Q );
if( ( ret = mbedtls_ecdh_calc_secret( &ssl->handshake->ecdh_ctx,
&ssl->handshake->pmslen,
ssl->handshake->premaster,
MBEDTLS_MPI_MAX_SIZE,
ssl->conf->f_rng, ssl->conf->p_rng ) ) != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ecdh_calc_secret", ret );
return( ret );
}
MBEDTLS_SSL_DEBUG_MPI( 3, "ECDH: z", &ssl->handshake->ecdh_ctx.z );
}
else
#endif /* MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED ||
MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED ||
MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED ||
MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED */
#if defined(MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED)
if( mbedtls_ssl_ciphersuite_uses_psk( ciphersuite_info ) )
{
/*
* opaque psk_identity<0..2^16-1>;
*/
if( ssl->conf->psk == NULL || ssl->conf->psk_identity == NULL )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "got no private key for PSK" ) );
return( MBEDTLS_ERR_SSL_PRIVATE_KEY_REQUIRED );
}
i = 4;
n = ssl->conf->psk_identity_len;
if( i + 2 + n > MBEDTLS_SSL_MAX_CONTENT_LEN )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "psk identity too long or "
"SSL buffer too short" ) );
return( MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL );
}
ssl->out_msg[i++] = (unsigned char)( n >> 8 );
ssl->out_msg[i++] = (unsigned char)( n );
memcpy( ssl->out_msg + i, ssl->conf->psk_identity, ssl->conf->psk_identity_len );
i += ssl->conf->psk_identity_len;
#if defined(MBEDTLS_KEY_EXCHANGE_PSK_ENABLED)
if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_PSK )
{
n = 0;
}
else
#endif
#if defined(MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED)
if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA_PSK )
{
if( ( ret = ssl_write_encrypted_pms( ssl, i, &n, 2 ) ) != 0 )
return( ret );
}
else
#endif
#if defined(MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED)
if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_PSK )
{
/*
* ClientDiffieHellmanPublic public (DHM send G^X mod P)
*/
n = ssl->handshake->dhm_ctx.len;
if( i + 2 + n > MBEDTLS_SSL_MAX_CONTENT_LEN )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "psk identity or DHM size too long"
" or SSL buffer too short" ) );
return( MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL );
}
ssl->out_msg[i++] = (unsigned char)( n >> 8 );
ssl->out_msg[i++] = (unsigned char)( n );
ret = mbedtls_dhm_make_public( &ssl->handshake->dhm_ctx,
(int) mbedtls_mpi_size( &ssl->handshake->dhm_ctx.P ),
&ssl->out_msg[i], n,
ssl->conf->f_rng, ssl->conf->p_rng );
if( ret != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_dhm_make_public", ret );
return( ret );
}
}
else
#endif /* MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED */
#if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED)
if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK )
{
/*
* ClientECDiffieHellmanPublic public;
*/
ret = mbedtls_ecdh_make_public( &ssl->handshake->ecdh_ctx, &n,
&ssl->out_msg[i], MBEDTLS_SSL_MAX_CONTENT_LEN - i,
ssl->conf->f_rng, ssl->conf->p_rng );
if( ret != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ecdh_make_public", ret );
return( ret );
}
MBEDTLS_SSL_DEBUG_ECP( 3, "ECDH: Q", &ssl->handshake->ecdh_ctx.Q );
}
else
#endif /* MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED */
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
}
if( ( ret = mbedtls_ssl_psk_derive_premaster( ssl,
ciphersuite_info->key_exchange ) ) != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_psk_derive_premaster", ret );
return( ret );
}
}
else
#endif /* MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED */
#if defined(MBEDTLS_KEY_EXCHANGE_RSA_ENABLED)
if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA )
{
i = 4;
if( ( ret = ssl_write_encrypted_pms( ssl, i, &n, 0 ) ) != 0 )
return( ret );
}
else
#endif /* MBEDTLS_KEY_EXCHANGE_RSA_ENABLED */
#if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECJPAKE )
{
i = 4;
ret = mbedtls_ecjpake_write_round_two( &ssl->handshake->ecjpake_ctx,
ssl->out_msg + i, MBEDTLS_SSL_MAX_CONTENT_LEN - i, &n,
ssl->conf->f_rng, ssl->conf->p_rng );
if( ret != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ecjpake_write_round_two", ret );
return( ret );
}
ret = mbedtls_ecjpake_derive_secret( &ssl->handshake->ecjpake_ctx,
ssl->handshake->premaster, 32, &ssl->handshake->pmslen,
ssl->conf->f_rng, ssl->conf->p_rng );
if( ret != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ecjpake_derive_secret", ret );
return( ret );
}
}
else
#endif /* MBEDTLS_KEY_EXCHANGE_RSA_ENABLED */
{
((void) ciphersuite_info);
MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
}
ssl->out_msglen = i + n;
ssl->out_msgtype = MBEDTLS_SSL_MSG_HANDSHAKE;
ssl->out_msg[0] = MBEDTLS_SSL_HS_CLIENT_KEY_EXCHANGE;
ssl->state++;
if( ( ret = mbedtls_ssl_write_record( ssl ) ) != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_write_record", ret );
return( ret );
}
MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write client key exchange" ) );
return( 0 );
}
#if !defined(MBEDTLS_KEY_EXCHANGE_RSA_ENABLED) && \
!defined(MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED) && \
!defined(MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED) && \
!defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED) && \
!defined(MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED)&& \
!defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED)
static int ssl_write_certificate_verify( mbedtls_ssl_context *ssl )
{
const mbedtls_ssl_ciphersuite_t *ciphersuite_info =
ssl->transform_negotiate->ciphersuite_info;
int ret;
MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write certificate verify" ) );
if( ( ret = mbedtls_ssl_derive_keys( ssl ) ) != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_derive_keys", ret );
return( ret );
}
if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_PSK ||
ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA_PSK ||
ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK ||
ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_PSK ||
ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECJPAKE )
{
MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip write certificate verify" ) );
ssl->state++;
return( 0 );
}
MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
}
#else
static int ssl_write_certificate_verify( mbedtls_ssl_context *ssl )
{
int ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE;
const mbedtls_ssl_ciphersuite_t *ciphersuite_info =
ssl->transform_negotiate->ciphersuite_info;
size_t n = 0, offset = 0;
unsigned char hash[48];
unsigned char *hash_start = hash;
mbedtls_md_type_t md_alg = MBEDTLS_MD_NONE;
unsigned int hashlen;
MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write certificate verify" ) );
if( ( ret = mbedtls_ssl_derive_keys( ssl ) ) != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_derive_keys", ret );
return( ret );
}
if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_PSK ||
ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA_PSK ||
ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK ||
ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_PSK ||
ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECJPAKE )
{
MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip write certificate verify" ) );
ssl->state++;
return( 0 );
}
if( ssl->client_auth == 0 || mbedtls_ssl_own_cert( ssl ) == NULL )
{
MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip write certificate verify" ) );
ssl->state++;
return( 0 );
}
if( mbedtls_ssl_own_key( ssl ) == NULL )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "got no private key for certificate" ) );
return( MBEDTLS_ERR_SSL_PRIVATE_KEY_REQUIRED );
}
/*
* Make an RSA signature of the handshake digests
*/
ssl->handshake->calc_verify( ssl, hash );
#if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \
defined(MBEDTLS_SSL_PROTO_TLS1_1)
if( ssl->minor_ver != MBEDTLS_SSL_MINOR_VERSION_3 )
{
/*
* digitally-signed struct {
* opaque md5_hash[16];
* opaque sha_hash[20];
* };
*
* md5_hash
* MD5(handshake_messages);
*
* sha_hash
* SHA(handshake_messages);
*/
hashlen = 36;
md_alg = MBEDTLS_MD_NONE;
/*
* For ECDSA, default hash is SHA-1 only
*/
if( mbedtls_pk_can_do( mbedtls_ssl_own_key( ssl ), MBEDTLS_PK_ECDSA ) )
{
hash_start += 16;
hashlen -= 16;
md_alg = MBEDTLS_MD_SHA1;
}
}
else
#endif /* MBEDTLS_SSL_PROTO_SSL3 || MBEDTLS_SSL_PROTO_TLS1 || \
MBEDTLS_SSL_PROTO_TLS1_1 */
#if defined(MBEDTLS_SSL_PROTO_TLS1_2)
if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_3 )
{
/*
* digitally-signed struct {
* opaque handshake_messages[handshake_messages_length];
* };
*
* Taking shortcut here. We assume that the server always allows the
* PRF Hash function and has sent it in the allowed signature
* algorithms list received in the Certificate Request message.
*
* Until we encounter a server that does not, we will take this
* shortcut.
*
* Reason: Otherwise we should have running hashes for SHA512 and SHA224
* in order to satisfy 'weird' needs from the server side.
*/
if( ssl->transform_negotiate->ciphersuite_info->mac ==
MBEDTLS_MD_SHA384 )
{
md_alg = MBEDTLS_MD_SHA384;
ssl->out_msg[4] = MBEDTLS_SSL_HASH_SHA384;
}
else
{
md_alg = MBEDTLS_MD_SHA256;
ssl->out_msg[4] = MBEDTLS_SSL_HASH_SHA256;
}
ssl->out_msg[5] = mbedtls_ssl_sig_from_pk( mbedtls_ssl_own_key( ssl ) );
/* Info from md_alg will be used instead */
hashlen = 0;
offset = 2;
}
else
#endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
}
if( ( ret = mbedtls_pk_sign( mbedtls_ssl_own_key( ssl ), md_alg, hash_start, hashlen,
ssl->out_msg + 6 + offset, &n,
ssl->conf->f_rng, ssl->conf->p_rng ) ) != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_pk_sign", ret );
return( ret );
}
ssl->out_msg[4 + offset] = (unsigned char)( n >> 8 );
ssl->out_msg[5 + offset] = (unsigned char)( n );
ssl->out_msglen = 6 + n + offset;
ssl->out_msgtype = MBEDTLS_SSL_MSG_HANDSHAKE;
ssl->out_msg[0] = MBEDTLS_SSL_HS_CERTIFICATE_VERIFY;
ssl->state++;
if( ( ret = mbedtls_ssl_write_record( ssl ) ) != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_write_record", ret );
return( ret );
}
MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write certificate verify" ) );
return( ret );
}
#endif /* !MBEDTLS_KEY_EXCHANGE_RSA_ENABLED &&
!MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED &&
!MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED &&
!MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED &&
!MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED &&
!MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED */
#if defined(MBEDTLS_SSL_SESSION_TICKETS)
static int ssl_parse_new_session_ticket( mbedtls_ssl_context *ssl )
{
int ret;
uint32_t lifetime;
size_t ticket_len;
unsigned char *ticket;
const unsigned char *msg;
MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse new session ticket" ) );
if( ( ret = mbedtls_ssl_read_record( ssl ) ) != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_read_record", ret );
return( ret );
}
if( ssl->in_msgtype != MBEDTLS_SSL_MSG_HANDSHAKE )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad new session ticket message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_UNEXPECTED_MESSAGE );
return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );
}
/*
* struct {
* uint32 ticket_lifetime_hint;
* opaque ticket<0..2^16-1>;
* } NewSessionTicket;
*
* 0 . 3 ticket_lifetime_hint
* 4 . 5 ticket_len (n)
* 6 . 5+n ticket content
*/
if( ssl->in_msg[0] != MBEDTLS_SSL_HS_NEW_SESSION_TICKET ||
ssl->in_hslen < 6 + mbedtls_ssl_hs_hdr_len( ssl ) )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad new session ticket message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
return( MBEDTLS_ERR_SSL_BAD_HS_NEW_SESSION_TICKET );
}
msg = ssl->in_msg + mbedtls_ssl_hs_hdr_len( ssl );
lifetime = ( msg[0] << 24 ) | ( msg[1] << 16 ) |
( msg[2] << 8 ) | ( msg[3] );
ticket_len = ( msg[4] << 8 ) | ( msg[5] );
if( ticket_len + 6 + mbedtls_ssl_hs_hdr_len( ssl ) != ssl->in_hslen )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad new session ticket message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
return( MBEDTLS_ERR_SSL_BAD_HS_NEW_SESSION_TICKET );
}
MBEDTLS_SSL_DEBUG_MSG( 3, ( "ticket length: %d", ticket_len ) );
/* We're not waiting for a NewSessionTicket message any more */
ssl->handshake->new_session_ticket = 0;
ssl->state = MBEDTLS_SSL_SERVER_CHANGE_CIPHER_SPEC;
/*
* Zero-length ticket means the server changed his mind and doesn't want
* to send a ticket after all, so just forget it
*/
if( ticket_len == 0 )
return( 0 );
mbedtls_zeroize( ssl->session_negotiate->ticket,
ssl->session_negotiate->ticket_len );
mbedtls_free( ssl->session_negotiate->ticket );
ssl->session_negotiate->ticket = NULL;
ssl->session_negotiate->ticket_len = 0;
if( ( ticket = mbedtls_calloc( 1, ticket_len ) ) == NULL )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "ticket alloc failed" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_INTERNAL_ERROR );
return( MBEDTLS_ERR_SSL_ALLOC_FAILED );
}
memcpy( ticket, msg + 6, ticket_len );
ssl->session_negotiate->ticket = ticket;
ssl->session_negotiate->ticket_len = ticket_len;
ssl->session_negotiate->ticket_lifetime = lifetime;
/*
* RFC 5077 section 3.4:
* "If the client receives a session ticket from the server, then it
* discards any Session ID that was sent in the ServerHello."
*/
MBEDTLS_SSL_DEBUG_MSG( 3, ( "ticket in use, discarding session id" ) );
ssl->session_negotiate->id_len = 0;
MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= parse new session ticket" ) );
return( 0 );
}
#endif /* MBEDTLS_SSL_SESSION_TICKETS */
/*
* SSL handshake -- client side -- single step
*/
int mbedtls_ssl_handshake_client_step( mbedtls_ssl_context *ssl )
{
int ret = 0;
if( ssl->state == MBEDTLS_SSL_HANDSHAKE_OVER || ssl->handshake == NULL )
return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
MBEDTLS_SSL_DEBUG_MSG( 2, ( "client state: %d", ssl->state ) );
if( ( ret = mbedtls_ssl_flush_output( ssl ) ) != 0 )
return( ret );
#if defined(MBEDTLS_SSL_PROTO_DTLS)
if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
ssl->handshake->retransmit_state == MBEDTLS_SSL_RETRANS_SENDING )
{
if( ( ret = mbedtls_ssl_resend( ssl ) ) != 0 )
return( ret );
}
#endif
/* Change state now, so that it is right in mbedtls_ssl_read_record(), used
* by DTLS for dropping out-of-sequence ChangeCipherSpec records */
#if defined(MBEDTLS_SSL_SESSION_TICKETS)
if( ssl->state == MBEDTLS_SSL_SERVER_CHANGE_CIPHER_SPEC &&
ssl->handshake->new_session_ticket != 0 )
{
ssl->state = MBEDTLS_SSL_SERVER_NEW_SESSION_TICKET;
}
#endif
switch( ssl->state )
{
case MBEDTLS_SSL_HELLO_REQUEST:
ssl->state = MBEDTLS_SSL_CLIENT_HELLO;
break;
/*
* ==> ClientHello
*/
case MBEDTLS_SSL_CLIENT_HELLO:
ret = ssl_write_client_hello( ssl );
break;
/*
* <== ServerHello
* Certificate
* ( ServerKeyExchange )
* ( CertificateRequest )
* ServerHelloDone
*/
case MBEDTLS_SSL_SERVER_HELLO:
ret = ssl_parse_server_hello( ssl );
break;
case MBEDTLS_SSL_SERVER_CERTIFICATE:
ret = mbedtls_ssl_parse_certificate( ssl );
break;
case MBEDTLS_SSL_SERVER_KEY_EXCHANGE:
ret = ssl_parse_server_key_exchange( ssl );
break;
case MBEDTLS_SSL_CERTIFICATE_REQUEST:
ret = ssl_parse_certificate_request( ssl );
break;
case MBEDTLS_SSL_SERVER_HELLO_DONE:
ret = ssl_parse_server_hello_done( ssl );
break;
/*
* ==> ( Certificate/Alert )
* ClientKeyExchange
* ( CertificateVerify )
* ChangeCipherSpec
* Finished
*/
case MBEDTLS_SSL_CLIENT_CERTIFICATE:
ret = mbedtls_ssl_write_certificate( ssl );
break;
case MBEDTLS_SSL_CLIENT_KEY_EXCHANGE:
ret = ssl_write_client_key_exchange( ssl );
break;
case MBEDTLS_SSL_CERTIFICATE_VERIFY:
ret = ssl_write_certificate_verify( ssl );
break;
case MBEDTLS_SSL_CLIENT_CHANGE_CIPHER_SPEC:
ret = mbedtls_ssl_write_change_cipher_spec( ssl );
break;
case MBEDTLS_SSL_CLIENT_FINISHED:
ret = mbedtls_ssl_write_finished( ssl );
break;
/*
* <== ( NewSessionTicket )
* ChangeCipherSpec
* Finished
*/
#if defined(MBEDTLS_SSL_SESSION_TICKETS)
case MBEDTLS_SSL_SERVER_NEW_SESSION_TICKET:
ret = ssl_parse_new_session_ticket( ssl );
break;
#endif
case MBEDTLS_SSL_SERVER_CHANGE_CIPHER_SPEC:
ret = mbedtls_ssl_parse_change_cipher_spec( ssl );
break;
case MBEDTLS_SSL_SERVER_FINISHED:
ret = mbedtls_ssl_parse_finished( ssl );
break;
case MBEDTLS_SSL_FLUSH_BUFFERS:
MBEDTLS_SSL_DEBUG_MSG( 2, ( "handshake: done" ) );
ssl->state = MBEDTLS_SSL_HANDSHAKE_WRAPUP;
break;
case MBEDTLS_SSL_HANDSHAKE_WRAPUP:
mbedtls_ssl_handshake_wrapup( ssl );
break;
default:
MBEDTLS_SSL_DEBUG_MSG( 1, ( "invalid state %d", ssl->state ) );
return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
}
return( ret );
}
#endif /* MBEDTLS_SSL_CLI_C */
| ./CrossVul/dataset_final_sorted/CWE-125/c/good_699_0 |
crossvul-cpp_data_good_1370_1 | /*-
* SPDX-License-Identifier: BSD-3-Clause
*
* Copyright (c) 2001-2008, by Cisco Systems, Inc. All rights reserved.
* Copyright (c) 2008-2012, by Randall Stewart. All rights reserved.
* Copyright (c) 2008-2012, by Michael Tuexen. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* a) Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* b) 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.
*
* c) Neither the name of Cisco Systems, Inc. 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.
*/
#ifdef __FreeBSD__
#include <sys/cdefs.h>
__FBSDID("$FreeBSD: head/sys/netinet/sctp_pcb.c 355931 2019-12-20 15:25:08Z tuexen $");
#endif
#include <netinet/sctp_os.h>
#ifdef __FreeBSD__
#include <sys/proc.h>
#endif
#include <netinet/sctp_var.h>
#include <netinet/sctp_sysctl.h>
#include <netinet/sctp_pcb.h>
#include <netinet/sctputil.h>
#include <netinet/sctp.h>
#include <netinet/sctp_header.h>
#include <netinet/sctp_asconf.h>
#include <netinet/sctp_output.h>
#include <netinet/sctp_timer.h>
#include <netinet/sctp_bsd_addr.h>
#if defined(INET) || defined(INET6)
#if !defined(__Userspace_os_Windows)
#include <netinet/udp.h>
#endif
#endif
#ifdef INET6
#if defined(__Userspace__)
#include "user_ip6_var.h"
#else
#include <netinet6/ip6_var.h>
#endif
#endif
#if defined(__FreeBSD__)
#include <sys/sched.h>
#include <sys/smp.h>
#include <sys/unistd.h>
#endif
#if defined(__Userspace__)
#include <user_socketvar.h>
#include <user_atomic.h>
#if !defined(__Userspace_os_Windows)
#include <netdb.h>
#endif
#endif
#if defined(__APPLE__)
#define APPLE_FILE_NO 4
#endif
#if defined(__FreeBSD__) && __FreeBSD_version >= 801000
VNET_DEFINE(struct sctp_base_info, system_base_info);
#else
struct sctp_base_info system_base_info;
#endif
/* FIX: we don't handle multiple link local scopes */
/* "scopeless" replacement IN6_ARE_ADDR_EQUAL */
#ifdef INET6
int
SCTP6_ARE_ADDR_EQUAL(struct sockaddr_in6 *a, struct sockaddr_in6 *b)
{
#ifdef SCTP_EMBEDDED_V6_SCOPE
#if defined(__APPLE__)
struct in6_addr tmp_a, tmp_b;
tmp_a = a->sin6_addr;
#if defined(APPLE_LEOPARD) || defined(APPLE_SNOWLEOPARD)
if (in6_embedscope(&tmp_a, a, NULL, NULL) != 0) {
#else
if (in6_embedscope(&tmp_a, a, NULL, NULL, NULL) != 0) {
#endif
return (0);
}
tmp_b = b->sin6_addr;
#if defined(APPLE_LEOPARD) || defined(APPLE_SNOWLEOPARD)
if (in6_embedscope(&tmp_b, b, NULL, NULL) != 0) {
#else
if (in6_embedscope(&tmp_b, b, NULL, NULL, NULL) != 0) {
#endif
return (0);
}
return (IN6_ARE_ADDR_EQUAL(&tmp_a, &tmp_b));
#elif defined(SCTP_KAME)
struct sockaddr_in6 tmp_a, tmp_b;
memcpy(&tmp_a, a, sizeof(struct sockaddr_in6));
if (sa6_embedscope(&tmp_a, MODULE_GLOBAL(ip6_use_defzone)) != 0) {
return (0);
}
memcpy(&tmp_b, b, sizeof(struct sockaddr_in6));
if (sa6_embedscope(&tmp_b, MODULE_GLOBAL(ip6_use_defzone)) != 0) {
return (0);
}
return (IN6_ARE_ADDR_EQUAL(&tmp_a.sin6_addr, &tmp_b.sin6_addr));
#else
struct in6_addr tmp_a, tmp_b;
tmp_a = a->sin6_addr;
if (in6_embedscope(&tmp_a, a) != 0) {
return (0);
}
tmp_b = b->sin6_addr;
if (in6_embedscope(&tmp_b, b) != 0) {
return (0);
}
return (IN6_ARE_ADDR_EQUAL(&tmp_a, &tmp_b));
#endif
#else
return (IN6_ARE_ADDR_EQUAL(&(a->sin6_addr), &(b->sin6_addr)));
#endif /* SCTP_EMBEDDED_V6_SCOPE */
}
#endif
void
sctp_fill_pcbinfo(struct sctp_pcbinfo *spcb)
{
/*
* We really don't need to lock this, but I will just because it
* does not hurt.
*/
SCTP_INP_INFO_RLOCK();
spcb->ep_count = SCTP_BASE_INFO(ipi_count_ep);
spcb->asoc_count = SCTP_BASE_INFO(ipi_count_asoc);
spcb->laddr_count = SCTP_BASE_INFO(ipi_count_laddr);
spcb->raddr_count = SCTP_BASE_INFO(ipi_count_raddr);
spcb->chk_count = SCTP_BASE_INFO(ipi_count_chunk);
spcb->readq_count = SCTP_BASE_INFO(ipi_count_readq);
spcb->stream_oque = SCTP_BASE_INFO(ipi_count_strmoq);
spcb->free_chunks = SCTP_BASE_INFO(ipi_free_chunks);
SCTP_INP_INFO_RUNLOCK();
}
/*-
* Addresses are added to VRF's (Virtual Router's). For BSD we
* have only the default VRF 0. We maintain a hash list of
* VRF's. Each VRF has its own list of sctp_ifn's. Each of
* these has a list of addresses. When we add a new address
* to a VRF we lookup the ifn/ifn_index, if the ifn does
* not exist we create it and add it to the list of IFN's
* within the VRF. Once we have the sctp_ifn, we add the
* address to the list. So we look something like:
*
* hash-vrf-table
* vrf-> ifn-> ifn -> ifn
* vrf |
* ... +--ifa-> ifa -> ifa
* vrf
*
* We keep these separate lists since the SCTP subsystem will
* point to these from its source address selection nets structure.
* When an address is deleted it does not happen right away on
* the SCTP side, it gets scheduled. What we do when a
* delete happens is immediately remove the address from
* the master list and decrement the refcount. As our
* addip iterator works through and frees the src address
* selection pointing to the sctp_ifa, eventually the refcount
* will reach 0 and we will delete it. Note that it is assumed
* that any locking on system level ifn/ifa is done at the
* caller of these functions and these routines will only
* lock the SCTP structures as they add or delete things.
*
* Other notes on VRF concepts.
* - An endpoint can be in multiple VRF's
* - An association lives within a VRF and only one VRF.
* - Any incoming packet we can deduce the VRF for by
* looking at the mbuf/pak inbound (for BSD its VRF=0 :D)
* - Any downward send call or connect call must supply the
* VRF via ancillary data or via some sort of set default
* VRF socket option call (again for BSD no brainer since
* the VRF is always 0).
* - An endpoint may add multiple VRF's to it.
* - Listening sockets can accept associations in any
* of the VRF's they are in but the assoc will end up
* in only one VRF (gotten from the packet or connect/send).
*
*/
struct sctp_vrf *
sctp_allocate_vrf(int vrf_id)
{
struct sctp_vrf *vrf = NULL;
struct sctp_vrflist *bucket;
/* First allocate the VRF structure */
vrf = sctp_find_vrf(vrf_id);
if (vrf) {
/* Already allocated */
return (vrf);
}
SCTP_MALLOC(vrf, struct sctp_vrf *, sizeof(struct sctp_vrf),
SCTP_M_VRF);
if (vrf == NULL) {
/* No memory */
#ifdef INVARIANTS
panic("No memory for VRF:%d", vrf_id);
#endif
return (NULL);
}
/* setup the VRF */
memset(vrf, 0, sizeof(struct sctp_vrf));
vrf->vrf_id = vrf_id;
LIST_INIT(&vrf->ifnlist);
vrf->total_ifa_count = 0;
vrf->refcount = 0;
/* now also setup table ids */
SCTP_INIT_VRF_TABLEID(vrf);
/* Init the HASH of addresses */
vrf->vrf_addr_hash = SCTP_HASH_INIT(SCTP_VRF_ADDR_HASH_SIZE,
&vrf->vrf_addr_hashmark);
if (vrf->vrf_addr_hash == NULL) {
/* No memory */
#ifdef INVARIANTS
panic("No memory for VRF:%d", vrf_id);
#endif
SCTP_FREE(vrf, SCTP_M_VRF);
return (NULL);
}
/* Add it to the hash table */
bucket = &SCTP_BASE_INFO(sctp_vrfhash)[(vrf_id & SCTP_BASE_INFO(hashvrfmark))];
LIST_INSERT_HEAD(bucket, vrf, next_vrf);
atomic_add_int(&SCTP_BASE_INFO(ipi_count_vrfs), 1);
return (vrf);
}
struct sctp_ifn *
sctp_find_ifn(void *ifn, uint32_t ifn_index)
{
struct sctp_ifn *sctp_ifnp;
struct sctp_ifnlist *hash_ifn_head;
/* We assume the lock is held for the addresses
* if that's wrong problems could occur :-)
*/
hash_ifn_head = &SCTP_BASE_INFO(vrf_ifn_hash)[(ifn_index & SCTP_BASE_INFO(vrf_ifn_hashmark))];
LIST_FOREACH(sctp_ifnp, hash_ifn_head, next_bucket) {
if (sctp_ifnp->ifn_index == ifn_index) {
return (sctp_ifnp);
}
if (sctp_ifnp->ifn_p && ifn && (sctp_ifnp->ifn_p == ifn)) {
return (sctp_ifnp);
}
}
return (NULL);
}
struct sctp_vrf *
sctp_find_vrf(uint32_t vrf_id)
{
struct sctp_vrflist *bucket;
struct sctp_vrf *liste;
bucket = &SCTP_BASE_INFO(sctp_vrfhash)[(vrf_id & SCTP_BASE_INFO(hashvrfmark))];
LIST_FOREACH(liste, bucket, next_vrf) {
if (vrf_id == liste->vrf_id) {
return (liste);
}
}
return (NULL);
}
void
sctp_free_vrf(struct sctp_vrf *vrf)
{
if (SCTP_DECREMENT_AND_CHECK_REFCOUNT(&vrf->refcount)) {
if (vrf->vrf_addr_hash) {
SCTP_HASH_FREE(vrf->vrf_addr_hash, vrf->vrf_addr_hashmark);
vrf->vrf_addr_hash = NULL;
}
/* We zero'd the count */
LIST_REMOVE(vrf, next_vrf);
SCTP_FREE(vrf, SCTP_M_VRF);
atomic_subtract_int(&SCTP_BASE_INFO(ipi_count_vrfs), 1);
}
}
void
sctp_free_ifn(struct sctp_ifn *sctp_ifnp)
{
if (SCTP_DECREMENT_AND_CHECK_REFCOUNT(&sctp_ifnp->refcount)) {
/* We zero'd the count */
if (sctp_ifnp->vrf) {
sctp_free_vrf(sctp_ifnp->vrf);
}
SCTP_FREE(sctp_ifnp, SCTP_M_IFN);
atomic_subtract_int(&SCTP_BASE_INFO(ipi_count_ifns), 1);
}
}
void
sctp_update_ifn_mtu(uint32_t ifn_index, uint32_t mtu)
{
struct sctp_ifn *sctp_ifnp;
sctp_ifnp = sctp_find_ifn((void *)NULL, ifn_index);
if (sctp_ifnp != NULL) {
sctp_ifnp->ifn_mtu = mtu;
}
}
void
sctp_free_ifa(struct sctp_ifa *sctp_ifap)
{
if (SCTP_DECREMENT_AND_CHECK_REFCOUNT(&sctp_ifap->refcount)) {
/* We zero'd the count */
if (sctp_ifap->ifn_p) {
sctp_free_ifn(sctp_ifap->ifn_p);
}
SCTP_FREE(sctp_ifap, SCTP_M_IFA);
atomic_subtract_int(&SCTP_BASE_INFO(ipi_count_ifas), 1);
}
}
static void
sctp_delete_ifn(struct sctp_ifn *sctp_ifnp, int hold_addr_lock)
{
struct sctp_ifn *found;
found = sctp_find_ifn(sctp_ifnp->ifn_p, sctp_ifnp->ifn_index);
if (found == NULL) {
/* Not in the list.. sorry */
return;
}
if (hold_addr_lock == 0)
SCTP_IPI_ADDR_WLOCK();
LIST_REMOVE(sctp_ifnp, next_bucket);
LIST_REMOVE(sctp_ifnp, next_ifn);
SCTP_DEREGISTER_INTERFACE(sctp_ifnp->ifn_index,
sctp_ifnp->registered_af);
if (hold_addr_lock == 0)
SCTP_IPI_ADDR_WUNLOCK();
/* Take away the reference, and possibly free it */
sctp_free_ifn(sctp_ifnp);
}
void
sctp_mark_ifa_addr_down(uint32_t vrf_id, struct sockaddr *addr,
const char *if_name, uint32_t ifn_index)
{
struct sctp_vrf *vrf;
struct sctp_ifa *sctp_ifap;
SCTP_IPI_ADDR_RLOCK();
vrf = sctp_find_vrf(vrf_id);
if (vrf == NULL) {
SCTPDBG(SCTP_DEBUG_PCB4, "Can't find vrf_id 0x%x\n", vrf_id);
goto out;
}
sctp_ifap = sctp_find_ifa_by_addr(addr, vrf->vrf_id, SCTP_ADDR_LOCKED);
if (sctp_ifap == NULL) {
SCTPDBG(SCTP_DEBUG_PCB4, "Can't find sctp_ifap for address\n");
goto out;
}
if (sctp_ifap->ifn_p == NULL) {
SCTPDBG(SCTP_DEBUG_PCB4, "IFA has no IFN - can't mark unusable\n");
goto out;
}
if (if_name) {
if (strncmp(if_name, sctp_ifap->ifn_p->ifn_name, SCTP_IFNAMSIZ) != 0) {
SCTPDBG(SCTP_DEBUG_PCB4, "IFN %s of IFA not the same as %s\n",
sctp_ifap->ifn_p->ifn_name, if_name);
goto out;
}
} else {
if (sctp_ifap->ifn_p->ifn_index != ifn_index) {
SCTPDBG(SCTP_DEBUG_PCB4, "IFA owned by ifn_index:%d down command for ifn_index:%d - ignored\n",
sctp_ifap->ifn_p->ifn_index, ifn_index);
goto out;
}
}
sctp_ifap->localifa_flags &= (~SCTP_ADDR_VALID);
sctp_ifap->localifa_flags |= SCTP_ADDR_IFA_UNUSEABLE;
out:
SCTP_IPI_ADDR_RUNLOCK();
}
void
sctp_mark_ifa_addr_up(uint32_t vrf_id, struct sockaddr *addr,
const char *if_name, uint32_t ifn_index)
{
struct sctp_vrf *vrf;
struct sctp_ifa *sctp_ifap;
SCTP_IPI_ADDR_RLOCK();
vrf = sctp_find_vrf(vrf_id);
if (vrf == NULL) {
SCTPDBG(SCTP_DEBUG_PCB4, "Can't find vrf_id 0x%x\n", vrf_id);
goto out;
}
sctp_ifap = sctp_find_ifa_by_addr(addr, vrf->vrf_id, SCTP_ADDR_LOCKED);
if (sctp_ifap == NULL) {
SCTPDBG(SCTP_DEBUG_PCB4, "Can't find sctp_ifap for address\n");
goto out;
}
if (sctp_ifap->ifn_p == NULL) {
SCTPDBG(SCTP_DEBUG_PCB4, "IFA has no IFN - can't mark unusable\n");
goto out;
}
if (if_name) {
if (strncmp(if_name, sctp_ifap->ifn_p->ifn_name, SCTP_IFNAMSIZ) != 0) {
SCTPDBG(SCTP_DEBUG_PCB4, "IFN %s of IFA not the same as %s\n",
sctp_ifap->ifn_p->ifn_name, if_name);
goto out;
}
} else {
if (sctp_ifap->ifn_p->ifn_index != ifn_index) {
SCTPDBG(SCTP_DEBUG_PCB4, "IFA owned by ifn_index:%d down command for ifn_index:%d - ignored\n",
sctp_ifap->ifn_p->ifn_index, ifn_index);
goto out;
}
}
sctp_ifap->localifa_flags &= (~SCTP_ADDR_IFA_UNUSEABLE);
sctp_ifap->localifa_flags |= SCTP_ADDR_VALID;
out:
SCTP_IPI_ADDR_RUNLOCK();
}
/*-
* Add an ifa to an ifn.
* Register the interface as necessary.
* NOTE: ADDR write lock MUST be held.
*/
static void
sctp_add_ifa_to_ifn(struct sctp_ifn *sctp_ifnp, struct sctp_ifa *sctp_ifap)
{
int ifa_af;
LIST_INSERT_HEAD(&sctp_ifnp->ifalist, sctp_ifap, next_ifa);
sctp_ifap->ifn_p = sctp_ifnp;
atomic_add_int(&sctp_ifap->ifn_p->refcount, 1);
/* update address counts */
sctp_ifnp->ifa_count++;
ifa_af = sctp_ifap->address.sa.sa_family;
switch (ifa_af) {
#ifdef INET
case AF_INET:
sctp_ifnp->num_v4++;
break;
#endif
#ifdef INET6
case AF_INET6:
sctp_ifnp->num_v6++;
break;
#endif
default:
break;
}
if (sctp_ifnp->ifa_count == 1) {
/* register the new interface */
SCTP_REGISTER_INTERFACE(sctp_ifnp->ifn_index, ifa_af);
sctp_ifnp->registered_af = ifa_af;
}
}
/*-
* Remove an ifa from its ifn.
* If no more addresses exist, remove the ifn too. Otherwise, re-register
* the interface based on the remaining address families left.
* NOTE: ADDR write lock MUST be held.
*/
static void
sctp_remove_ifa_from_ifn(struct sctp_ifa *sctp_ifap)
{
LIST_REMOVE(sctp_ifap, next_ifa);
if (sctp_ifap->ifn_p) {
/* update address counts */
sctp_ifap->ifn_p->ifa_count--;
switch (sctp_ifap->address.sa.sa_family) {
#ifdef INET
case AF_INET:
sctp_ifap->ifn_p->num_v4--;
break;
#endif
#ifdef INET6
case AF_INET6:
sctp_ifap->ifn_p->num_v6--;
break;
#endif
default:
break;
}
if (LIST_EMPTY(&sctp_ifap->ifn_p->ifalist)) {
/* remove the ifn, possibly freeing it */
sctp_delete_ifn(sctp_ifap->ifn_p, SCTP_ADDR_LOCKED);
} else {
/* re-register address family type, if needed */
if ((sctp_ifap->ifn_p->num_v6 == 0) &&
(sctp_ifap->ifn_p->registered_af == AF_INET6)) {
SCTP_DEREGISTER_INTERFACE(sctp_ifap->ifn_p->ifn_index, AF_INET6);
SCTP_REGISTER_INTERFACE(sctp_ifap->ifn_p->ifn_index, AF_INET);
sctp_ifap->ifn_p->registered_af = AF_INET;
} else if ((sctp_ifap->ifn_p->num_v4 == 0) &&
(sctp_ifap->ifn_p->registered_af == AF_INET)) {
SCTP_DEREGISTER_INTERFACE(sctp_ifap->ifn_p->ifn_index, AF_INET);
SCTP_REGISTER_INTERFACE(sctp_ifap->ifn_p->ifn_index, AF_INET6);
sctp_ifap->ifn_p->registered_af = AF_INET6;
}
/* free the ifn refcount */
sctp_free_ifn(sctp_ifap->ifn_p);
}
sctp_ifap->ifn_p = NULL;
}
}
struct sctp_ifa *
sctp_add_addr_to_vrf(uint32_t vrf_id, void *ifn, uint32_t ifn_index,
uint32_t ifn_type, const char *if_name, void *ifa,
struct sockaddr *addr, uint32_t ifa_flags,
int dynamic_add)
{
struct sctp_vrf *vrf;
struct sctp_ifn *sctp_ifnp = NULL;
struct sctp_ifa *sctp_ifap = NULL;
struct sctp_ifalist *hash_addr_head;
struct sctp_ifnlist *hash_ifn_head;
uint32_t hash_of_addr;
int new_ifn_af = 0;
#ifdef SCTP_DEBUG
SCTPDBG(SCTP_DEBUG_PCB4, "vrf_id 0x%x: adding address: ", vrf_id);
SCTPDBG_ADDR(SCTP_DEBUG_PCB4, addr);
#endif
SCTP_IPI_ADDR_WLOCK();
sctp_ifnp = sctp_find_ifn(ifn, ifn_index);
if (sctp_ifnp) {
vrf = sctp_ifnp->vrf;
} else {
vrf = sctp_find_vrf(vrf_id);
if (vrf == NULL) {
vrf = sctp_allocate_vrf(vrf_id);
if (vrf == NULL) {
SCTP_IPI_ADDR_WUNLOCK();
return (NULL);
}
}
}
if (sctp_ifnp == NULL) {
/* build one and add it, can't hold lock
* until after malloc done though.
*/
SCTP_IPI_ADDR_WUNLOCK();
SCTP_MALLOC(sctp_ifnp, struct sctp_ifn *,
sizeof(struct sctp_ifn), SCTP_M_IFN);
if (sctp_ifnp == NULL) {
#ifdef INVARIANTS
panic("No memory for IFN");
#endif
return (NULL);
}
memset(sctp_ifnp, 0, sizeof(struct sctp_ifn));
sctp_ifnp->ifn_index = ifn_index;
sctp_ifnp->ifn_p = ifn;
sctp_ifnp->ifn_type = ifn_type;
sctp_ifnp->refcount = 0;
sctp_ifnp->vrf = vrf;
atomic_add_int(&vrf->refcount, 1);
sctp_ifnp->ifn_mtu = SCTP_GATHER_MTU_FROM_IFN_INFO(ifn, ifn_index, addr->sa_family);
if (if_name != NULL) {
snprintf(sctp_ifnp->ifn_name, SCTP_IFNAMSIZ, "%s", if_name);
} else {
snprintf(sctp_ifnp->ifn_name, SCTP_IFNAMSIZ, "%s", "unknown");
}
hash_ifn_head = &SCTP_BASE_INFO(vrf_ifn_hash)[(ifn_index & SCTP_BASE_INFO(vrf_ifn_hashmark))];
LIST_INIT(&sctp_ifnp->ifalist);
SCTP_IPI_ADDR_WLOCK();
LIST_INSERT_HEAD(hash_ifn_head, sctp_ifnp, next_bucket);
LIST_INSERT_HEAD(&vrf->ifnlist, sctp_ifnp, next_ifn);
atomic_add_int(&SCTP_BASE_INFO(ipi_count_ifns), 1);
new_ifn_af = 1;
}
sctp_ifap = sctp_find_ifa_by_addr(addr, vrf->vrf_id, SCTP_ADDR_LOCKED);
if (sctp_ifap) {
/* Hmm, it already exists? */
if ((sctp_ifap->ifn_p) &&
(sctp_ifap->ifn_p->ifn_index == ifn_index)) {
SCTPDBG(SCTP_DEBUG_PCB4, "Using existing ifn %s (0x%x) for ifa %p\n",
sctp_ifap->ifn_p->ifn_name, ifn_index,
(void *)sctp_ifap);
if (new_ifn_af) {
/* Remove the created one that we don't want */
sctp_delete_ifn(sctp_ifnp, SCTP_ADDR_LOCKED);
}
if (sctp_ifap->localifa_flags & SCTP_BEING_DELETED) {
/* easy to solve, just switch back to active */
SCTPDBG(SCTP_DEBUG_PCB4, "Clearing deleted ifa flag\n");
sctp_ifap->localifa_flags = SCTP_ADDR_VALID;
sctp_ifap->ifn_p = sctp_ifnp;
atomic_add_int(&sctp_ifap->ifn_p->refcount, 1);
}
exit_stage_left:
SCTP_IPI_ADDR_WUNLOCK();
return (sctp_ifap);
} else {
if (sctp_ifap->ifn_p) {
/*
* The last IFN gets the address, remove the
* old one
*/
SCTPDBG(SCTP_DEBUG_PCB4, "Moving ifa %p from %s (0x%x) to %s (0x%x)\n",
(void *)sctp_ifap, sctp_ifap->ifn_p->ifn_name,
sctp_ifap->ifn_p->ifn_index, if_name,
ifn_index);
/* remove the address from the old ifn */
sctp_remove_ifa_from_ifn(sctp_ifap);
/* move the address over to the new ifn */
sctp_add_ifa_to_ifn(sctp_ifnp, sctp_ifap);
goto exit_stage_left;
} else {
/* repair ifnp which was NULL ? */
sctp_ifap->localifa_flags = SCTP_ADDR_VALID;
SCTPDBG(SCTP_DEBUG_PCB4, "Repairing ifn %p for ifa %p\n",
(void *)sctp_ifnp, (void *)sctp_ifap);
sctp_add_ifa_to_ifn(sctp_ifnp, sctp_ifap);
}
goto exit_stage_left;
}
}
SCTP_IPI_ADDR_WUNLOCK();
SCTP_MALLOC(sctp_ifap, struct sctp_ifa *, sizeof(struct sctp_ifa), SCTP_M_IFA);
if (sctp_ifap == NULL) {
#ifdef INVARIANTS
panic("No memory for IFA");
#endif
return (NULL);
}
memset(sctp_ifap, 0, sizeof(struct sctp_ifa));
sctp_ifap->ifn_p = sctp_ifnp;
atomic_add_int(&sctp_ifnp->refcount, 1);
sctp_ifap->vrf_id = vrf_id;
sctp_ifap->ifa = ifa;
#ifdef HAVE_SA_LEN
memcpy(&sctp_ifap->address, addr, addr->sa_len);
#else
switch (addr->sa_family) {
#ifdef INET
case AF_INET:
memcpy(&sctp_ifap->address, addr, sizeof(struct sockaddr_in));
break;
#endif
#ifdef INET6
case AF_INET6:
memcpy(&sctp_ifap->address, addr, sizeof(struct sockaddr_in6));
break;
#endif
#if defined(__Userspace__)
case AF_CONN:
memcpy(&sctp_ifap->address, addr, sizeof(struct sockaddr_conn));
break;
#endif
default:
/* TSNH */
break;
}
#endif
sctp_ifap->localifa_flags = SCTP_ADDR_VALID | SCTP_ADDR_DEFER_USE;
sctp_ifap->flags = ifa_flags;
/* Set scope */
switch (sctp_ifap->address.sa.sa_family) {
#ifdef INET
case AF_INET:
{
struct sockaddr_in *sin;
sin = &sctp_ifap->address.sin;
if (SCTP_IFN_IS_IFT_LOOP(sctp_ifap->ifn_p) ||
(IN4_ISLOOPBACK_ADDRESS(&sin->sin_addr))) {
sctp_ifap->src_is_loop = 1;
}
if ((IN4_ISPRIVATE_ADDRESS(&sin->sin_addr))) {
sctp_ifap->src_is_priv = 1;
}
sctp_ifnp->num_v4++;
if (new_ifn_af)
new_ifn_af = AF_INET;
break;
}
#endif
#ifdef INET6
case AF_INET6:
{
/* ok to use deprecated addresses? */
struct sockaddr_in6 *sin6;
sin6 = &sctp_ifap->address.sin6;
if (SCTP_IFN_IS_IFT_LOOP(sctp_ifap->ifn_p) ||
(IN6_IS_ADDR_LOOPBACK(&sin6->sin6_addr))) {
sctp_ifap->src_is_loop = 1;
}
if (IN6_IS_ADDR_LINKLOCAL(&sin6->sin6_addr)) {
sctp_ifap->src_is_priv = 1;
}
sctp_ifnp->num_v6++;
if (new_ifn_af)
new_ifn_af = AF_INET6;
break;
}
#endif
#if defined(__Userspace__)
case AF_CONN:
if (new_ifn_af)
new_ifn_af = AF_CONN;
break;
#endif
default:
new_ifn_af = 0;
break;
}
hash_of_addr = sctp_get_ifa_hash_val(&sctp_ifap->address.sa);
if ((sctp_ifap->src_is_priv == 0) &&
(sctp_ifap->src_is_loop == 0)) {
sctp_ifap->src_is_glob = 1;
}
SCTP_IPI_ADDR_WLOCK();
hash_addr_head = &vrf->vrf_addr_hash[(hash_of_addr & vrf->vrf_addr_hashmark)];
LIST_INSERT_HEAD(hash_addr_head, sctp_ifap, next_bucket);
sctp_ifap->refcount = 1;
LIST_INSERT_HEAD(&sctp_ifnp->ifalist, sctp_ifap, next_ifa);
sctp_ifnp->ifa_count++;
vrf->total_ifa_count++;
atomic_add_int(&SCTP_BASE_INFO(ipi_count_ifas), 1);
if (new_ifn_af) {
SCTP_REGISTER_INTERFACE(ifn_index, new_ifn_af);
sctp_ifnp->registered_af = new_ifn_af;
}
SCTP_IPI_ADDR_WUNLOCK();
if (dynamic_add) {
/* Bump up the refcount so that when the timer
* completes it will drop back down.
*/
struct sctp_laddr *wi;
atomic_add_int(&sctp_ifap->refcount, 1);
wi = SCTP_ZONE_GET(SCTP_BASE_INFO(ipi_zone_laddr), struct sctp_laddr);
if (wi == NULL) {
/*
* Gak, what can we do? We have lost an address
* change can you say HOSED?
*/
SCTPDBG(SCTP_DEBUG_PCB4, "Lost an address change?\n");
/* Opps, must decrement the count */
sctp_del_addr_from_vrf(vrf_id, addr, ifn_index,
if_name);
return (NULL);
}
SCTP_INCR_LADDR_COUNT();
memset(wi, 0, sizeof(*wi));
(void)SCTP_GETTIME_TIMEVAL(&wi->start_time);
wi->ifa = sctp_ifap;
wi->action = SCTP_ADD_IP_ADDRESS;
SCTP_WQ_ADDR_LOCK();
LIST_INSERT_HEAD(&SCTP_BASE_INFO(addr_wq), wi, sctp_nxt_addr);
sctp_timer_start(SCTP_TIMER_TYPE_ADDR_WQ,
(struct sctp_inpcb *)NULL,
(struct sctp_tcb *)NULL,
(struct sctp_nets *)NULL);
SCTP_WQ_ADDR_UNLOCK();
} else {
/* it's ready for use */
sctp_ifap->localifa_flags &= ~SCTP_ADDR_DEFER_USE;
}
return (sctp_ifap);
}
void
sctp_del_addr_from_vrf(uint32_t vrf_id, struct sockaddr *addr,
uint32_t ifn_index, const char *if_name)
{
struct sctp_vrf *vrf;
struct sctp_ifa *sctp_ifap = NULL;
SCTP_IPI_ADDR_WLOCK();
vrf = sctp_find_vrf(vrf_id);
if (vrf == NULL) {
SCTPDBG(SCTP_DEBUG_PCB4, "Can't find vrf_id 0x%x\n", vrf_id);
goto out_now;
}
#ifdef SCTP_DEBUG
SCTPDBG(SCTP_DEBUG_PCB4, "vrf_id 0x%x: deleting address:", vrf_id);
SCTPDBG_ADDR(SCTP_DEBUG_PCB4, addr);
#endif
sctp_ifap = sctp_find_ifa_by_addr(addr, vrf->vrf_id, SCTP_ADDR_LOCKED);
if (sctp_ifap) {
/* Validate the delete */
if (sctp_ifap->ifn_p) {
int valid = 0;
/*-
* The name has priority over the ifn_index
* if its given. We do this especially for
* panda who might recycle indexes fast.
*/
if (if_name) {
if (strncmp(if_name, sctp_ifap->ifn_p->ifn_name, SCTP_IFNAMSIZ) == 0) {
/* They match its a correct delete */
valid = 1;
}
}
if (!valid) {
/* last ditch check ifn_index */
if (ifn_index == sctp_ifap->ifn_p->ifn_index) {
valid = 1;
}
}
if (!valid) {
SCTPDBG(SCTP_DEBUG_PCB4, "ifn:%d ifname:%s does not match addresses\n",
ifn_index, ((if_name == NULL) ? "NULL" : if_name));
SCTPDBG(SCTP_DEBUG_PCB4, "ifn:%d ifname:%s - ignoring delete\n",
sctp_ifap->ifn_p->ifn_index, sctp_ifap->ifn_p->ifn_name);
SCTP_IPI_ADDR_WUNLOCK();
return;
}
}
SCTPDBG(SCTP_DEBUG_PCB4, "Deleting ifa %p\n", (void *)sctp_ifap);
sctp_ifap->localifa_flags &= SCTP_ADDR_VALID;
/*
* We don't set the flag. This means that the structure will
* hang around in EP's that have bound specific to it until
* they close. This gives us TCP like behavior if someone
* removes an address (or for that matter adds it right back).
*/
/* sctp_ifap->localifa_flags |= SCTP_BEING_DELETED; */
vrf->total_ifa_count--;
LIST_REMOVE(sctp_ifap, next_bucket);
sctp_remove_ifa_from_ifn(sctp_ifap);
}
#ifdef SCTP_DEBUG
else {
SCTPDBG(SCTP_DEBUG_PCB4, "Del Addr-ifn:%d Could not find address:",
ifn_index);
SCTPDBG_ADDR(SCTP_DEBUG_PCB1, addr);
}
#endif
out_now:
SCTP_IPI_ADDR_WUNLOCK();
if (sctp_ifap) {
struct sctp_laddr *wi;
wi = SCTP_ZONE_GET(SCTP_BASE_INFO(ipi_zone_laddr), struct sctp_laddr);
if (wi == NULL) {
/*
* Gak, what can we do? We have lost an address
* change can you say HOSED?
*/
SCTPDBG(SCTP_DEBUG_PCB4, "Lost an address change?\n");
/* Oops, must decrement the count */
sctp_free_ifa(sctp_ifap);
return;
}
SCTP_INCR_LADDR_COUNT();
memset(wi, 0, sizeof(*wi));
(void)SCTP_GETTIME_TIMEVAL(&wi->start_time);
wi->ifa = sctp_ifap;
wi->action = SCTP_DEL_IP_ADDRESS;
SCTP_WQ_ADDR_LOCK();
/*
* Should this really be a tailq? As it is we will process the
* newest first :-0
*/
LIST_INSERT_HEAD(&SCTP_BASE_INFO(addr_wq), wi, sctp_nxt_addr);
sctp_timer_start(SCTP_TIMER_TYPE_ADDR_WQ,
(struct sctp_inpcb *)NULL,
(struct sctp_tcb *)NULL,
(struct sctp_nets *)NULL);
SCTP_WQ_ADDR_UNLOCK();
}
return;
}
static int
sctp_does_stcb_own_this_addr(struct sctp_tcb *stcb, struct sockaddr *to)
{
int loopback_scope;
#if defined(INET)
int ipv4_local_scope, ipv4_addr_legal;
#endif
#if defined(INET6)
int local_scope, site_scope, ipv6_addr_legal;
#endif
#if defined(__Userspace__)
int conn_addr_legal;
#endif
struct sctp_vrf *vrf;
struct sctp_ifn *sctp_ifn;
struct sctp_ifa *sctp_ifa;
loopback_scope = stcb->asoc.scope.loopback_scope;
#if defined(INET)
ipv4_local_scope = stcb->asoc.scope.ipv4_local_scope;
ipv4_addr_legal = stcb->asoc.scope.ipv4_addr_legal;
#endif
#if defined(INET6)
local_scope = stcb->asoc.scope.local_scope;
site_scope = stcb->asoc.scope.site_scope;
ipv6_addr_legal = stcb->asoc.scope.ipv6_addr_legal;
#endif
#if defined(__Userspace__)
conn_addr_legal = stcb->asoc.scope.conn_addr_legal;
#endif
SCTP_IPI_ADDR_RLOCK();
vrf = sctp_find_vrf(stcb->asoc.vrf_id);
if (vrf == NULL) {
/* no vrf, no addresses */
SCTP_IPI_ADDR_RUNLOCK();
return (0);
}
if (stcb->sctp_ep->sctp_flags & SCTP_PCB_FLAGS_BOUNDALL) {
LIST_FOREACH(sctp_ifn, &vrf->ifnlist, next_ifn) {
if ((loopback_scope == 0) &&
SCTP_IFN_IS_IFT_LOOP(sctp_ifn)) {
continue;
}
LIST_FOREACH(sctp_ifa, &sctp_ifn->ifalist, next_ifa) {
if (sctp_is_addr_restricted(stcb, sctp_ifa) &&
(!sctp_is_addr_pending(stcb, sctp_ifa))) {
/* We allow pending addresses, where we
* have sent an asconf-add to be considered
* valid.
*/
continue;
}
if (sctp_ifa->address.sa.sa_family != to->sa_family) {
continue;
}
switch (sctp_ifa->address.sa.sa_family) {
#ifdef INET
case AF_INET:
if (ipv4_addr_legal) {
struct sockaddr_in *sin, *rsin;
sin = &sctp_ifa->address.sin;
rsin = (struct sockaddr_in *)to;
if ((ipv4_local_scope == 0) &&
IN4_ISPRIVATE_ADDRESS(&sin->sin_addr)) {
continue;
}
#if defined(__FreeBSD__)
if (prison_check_ip4(stcb->sctp_ep->ip_inp.inp.inp_cred,
&sin->sin_addr) != 0) {
continue;
}
#endif
if (sin->sin_addr.s_addr == rsin->sin_addr.s_addr) {
SCTP_IPI_ADDR_RUNLOCK();
return (1);
}
}
break;
#endif
#ifdef INET6
case AF_INET6:
if (ipv6_addr_legal) {
struct sockaddr_in6 *sin6, *rsin6;
#if defined(SCTP_EMBEDDED_V6_SCOPE) && !defined(SCTP_KAME)
struct sockaddr_in6 lsa6;
#endif
sin6 = &sctp_ifa->address.sin6;
rsin6 = (struct sockaddr_in6 *)to;
#if defined(__FreeBSD__)
if (prison_check_ip6(stcb->sctp_ep->ip_inp.inp.inp_cred,
&sin6->sin6_addr) != 0) {
continue;
}
#endif
if (IN6_IS_ADDR_LINKLOCAL(&sin6->sin6_addr)) {
if (local_scope == 0)
continue;
#if defined(SCTP_EMBEDDED_V6_SCOPE)
if (sin6->sin6_scope_id == 0) {
#ifdef SCTP_KAME
if (sa6_recoverscope(sin6) != 0)
continue;
#else
lsa6 = *sin6;
if (in6_recoverscope(&lsa6,
&lsa6.sin6_addr,
NULL))
continue;
sin6 = &lsa6;
#endif /* SCTP_KAME */
}
#endif /* SCTP_EMBEDDED_V6_SCOPE */
}
if ((site_scope == 0) &&
(IN6_IS_ADDR_SITELOCAL(&sin6->sin6_addr))) {
continue;
}
if (SCTP6_ARE_ADDR_EQUAL(sin6, rsin6)) {
SCTP_IPI_ADDR_RUNLOCK();
return (1);
}
}
break;
#endif
#if defined(__Userspace__)
case AF_CONN:
if (conn_addr_legal) {
struct sockaddr_conn *sconn, *rsconn;
sconn = &sctp_ifa->address.sconn;
rsconn = (struct sockaddr_conn *)to;
if (sconn->sconn_addr == rsconn->sconn_addr) {
SCTP_IPI_ADDR_RUNLOCK();
return (1);
}
}
break;
#endif
default:
/* TSNH */
break;
}
}
}
} else {
struct sctp_laddr *laddr;
LIST_FOREACH(laddr, &stcb->sctp_ep->sctp_addr_list, sctp_nxt_addr) {
if (laddr->ifa->localifa_flags & SCTP_BEING_DELETED) {
SCTPDBG(SCTP_DEBUG_PCB1, "ifa being deleted\n");
continue;
}
if (sctp_is_addr_restricted(stcb, laddr->ifa) &&
(!sctp_is_addr_pending(stcb, laddr->ifa))) {
/* We allow pending addresses, where we
* have sent an asconf-add to be considered
* valid.
*/
continue;
}
if (laddr->ifa->address.sa.sa_family != to->sa_family) {
continue;
}
switch (to->sa_family) {
#ifdef INET
case AF_INET:
{
struct sockaddr_in *sin, *rsin;
sin = &laddr->ifa->address.sin;
rsin = (struct sockaddr_in *)to;
if (sin->sin_addr.s_addr == rsin->sin_addr.s_addr) {
SCTP_IPI_ADDR_RUNLOCK();
return (1);
}
break;
}
#endif
#ifdef INET6
case AF_INET6:
{
struct sockaddr_in6 *sin6, *rsin6;
sin6 = &laddr->ifa->address.sin6;
rsin6 = (struct sockaddr_in6 *)to;
if (SCTP6_ARE_ADDR_EQUAL(sin6, rsin6)) {
SCTP_IPI_ADDR_RUNLOCK();
return (1);
}
break;
}
#endif
#if defined(__Userspace__)
case AF_CONN:
{
struct sockaddr_conn *sconn, *rsconn;
sconn = &laddr->ifa->address.sconn;
rsconn = (struct sockaddr_conn *)to;
if (sconn->sconn_addr == rsconn->sconn_addr) {
SCTP_IPI_ADDR_RUNLOCK();
return (1);
}
break;
}
#endif
default:
/* TSNH */
break;
}
}
}
SCTP_IPI_ADDR_RUNLOCK();
return (0);
}
static struct sctp_tcb *
sctp_tcb_special_locate(struct sctp_inpcb **inp_p, struct sockaddr *from,
struct sockaddr *to, struct sctp_nets **netp, uint32_t vrf_id)
{
/**** ASSUMES THE CALLER holds the INP_INFO_RLOCK */
/*
* If we support the TCP model, then we must now dig through to see
* if we can find our endpoint in the list of tcp ep's.
*/
uint16_t lport, rport;
struct sctppcbhead *ephead;
struct sctp_inpcb *inp;
struct sctp_laddr *laddr;
struct sctp_tcb *stcb;
struct sctp_nets *net;
#ifdef SCTP_MVRF
int fnd, i;
#endif
if ((to == NULL) || (from == NULL)) {
return (NULL);
}
switch (to->sa_family) {
#ifdef INET
case AF_INET:
if (from->sa_family == AF_INET) {
lport = ((struct sockaddr_in *)to)->sin_port;
rport = ((struct sockaddr_in *)from)->sin_port;
} else {
return (NULL);
}
break;
#endif
#ifdef INET6
case AF_INET6:
if (from->sa_family == AF_INET6) {
lport = ((struct sockaddr_in6 *)to)->sin6_port;
rport = ((struct sockaddr_in6 *)from)->sin6_port;
} else {
return (NULL);
}
break;
#endif
#if defined(__Userspace__)
case AF_CONN:
if (from->sa_family == AF_CONN) {
lport = ((struct sockaddr_conn *)to)->sconn_port;
rport = ((struct sockaddr_conn *)from)->sconn_port;
} else {
return (NULL);
}
break;
#endif
default:
return (NULL);
}
ephead = &SCTP_BASE_INFO(sctp_tcpephash)[SCTP_PCBHASH_ALLADDR((lport | rport), SCTP_BASE_INFO(hashtcpmark))];
/*
* Ok now for each of the guys in this bucket we must look and see:
* - Does the remote port match. - Does there single association's
* addresses match this address (to). If so we update p_ep to point
* to this ep and return the tcb from it.
*/
LIST_FOREACH(inp, ephead, sctp_hash) {
SCTP_INP_RLOCK(inp);
if (inp->sctp_flags & SCTP_PCB_FLAGS_SOCKET_ALLGONE) {
SCTP_INP_RUNLOCK(inp);
continue;
}
if (lport != inp->sctp_lport) {
SCTP_INP_RUNLOCK(inp);
continue;
}
#if defined(__FreeBSD__)
switch (to->sa_family) {
#ifdef INET
case AF_INET:
{
struct sockaddr_in *sin;
sin = (struct sockaddr_in *)to;
if (prison_check_ip4(inp->ip_inp.inp.inp_cred,
&sin->sin_addr) != 0) {
SCTP_INP_RUNLOCK(inp);
continue;
}
break;
}
#endif
#ifdef INET6
case AF_INET6:
{
struct sockaddr_in6 *sin6;
sin6 = (struct sockaddr_in6 *)to;
if (prison_check_ip6(inp->ip_inp.inp.inp_cred,
&sin6->sin6_addr) != 0) {
SCTP_INP_RUNLOCK(inp);
continue;
}
break;
}
#endif
default:
SCTP_INP_RUNLOCK(inp);
continue;
}
#endif
#ifdef SCTP_MVRF
fnd = 0;
for (i = 0; i < inp->num_vrfs; i++) {
if (inp->m_vrf_ids[i] == vrf_id) {
fnd = 1;
break;
}
}
if (fnd == 0) {
SCTP_INP_RUNLOCK(inp);
continue;
}
#else
if (inp->def_vrf_id != vrf_id) {
SCTP_INP_RUNLOCK(inp);
continue;
}
#endif
/* check to see if the ep has one of the addresses */
if ((inp->sctp_flags & SCTP_PCB_FLAGS_BOUNDALL) == 0) {
/* We are NOT bound all, so look further */
int match = 0;
LIST_FOREACH(laddr, &inp->sctp_addr_list, sctp_nxt_addr) {
if (laddr->ifa == NULL) {
SCTPDBG(SCTP_DEBUG_PCB1, "%s: NULL ifa\n", __func__);
continue;
}
if (laddr->ifa->localifa_flags & SCTP_BEING_DELETED) {
SCTPDBG(SCTP_DEBUG_PCB1, "ifa being deleted\n");
continue;
}
if (laddr->ifa->address.sa.sa_family ==
to->sa_family) {
/* see if it matches */
#ifdef INET
if (from->sa_family == AF_INET) {
struct sockaddr_in *intf_addr, *sin;
intf_addr = &laddr->ifa->address.sin;
sin = (struct sockaddr_in *)to;
if (sin->sin_addr.s_addr ==
intf_addr->sin_addr.s_addr) {
match = 1;
break;
}
}
#endif
#ifdef INET6
if (from->sa_family == AF_INET6) {
struct sockaddr_in6 *intf_addr6;
struct sockaddr_in6 *sin6;
sin6 = (struct sockaddr_in6 *)
to;
intf_addr6 = &laddr->ifa->address.sin6;
if (SCTP6_ARE_ADDR_EQUAL(sin6,
intf_addr6)) {
match = 1;
break;
}
}
#endif
#if defined(__Userspace__)
if (from->sa_family == AF_CONN) {
struct sockaddr_conn *intf_addr, *sconn;
intf_addr = &laddr->ifa->address.sconn;
sconn = (struct sockaddr_conn *)to;
if (sconn->sconn_addr ==
intf_addr->sconn_addr) {
match = 1;
break;
}
}
#endif
}
}
if (match == 0) {
/* This endpoint does not have this address */
SCTP_INP_RUNLOCK(inp);
continue;
}
}
/*
* Ok if we hit here the ep has the address, does it hold
* the tcb?
*/
/* XXX: Why don't we TAILQ_FOREACH through sctp_asoc_list? */
stcb = LIST_FIRST(&inp->sctp_asoc_list);
if (stcb == NULL) {
SCTP_INP_RUNLOCK(inp);
continue;
}
SCTP_TCB_LOCK(stcb);
if (!sctp_does_stcb_own_this_addr(stcb, to)) {
SCTP_TCB_UNLOCK(stcb);
SCTP_INP_RUNLOCK(inp);
continue;
}
if (stcb->rport != rport) {
/* remote port does not match. */
SCTP_TCB_UNLOCK(stcb);
SCTP_INP_RUNLOCK(inp);
continue;
}
if (stcb->asoc.state & SCTP_STATE_ABOUT_TO_BE_FREED) {
SCTP_TCB_UNLOCK(stcb);
SCTP_INP_RUNLOCK(inp);
continue;
}
if (!sctp_does_stcb_own_this_addr(stcb, to)) {
SCTP_TCB_UNLOCK(stcb);
SCTP_INP_RUNLOCK(inp);
continue;
}
/* Does this TCB have a matching address? */
TAILQ_FOREACH(net, &stcb->asoc.nets, sctp_next) {
if (net->ro._l_addr.sa.sa_family != from->sa_family) {
/* not the same family, can't be a match */
continue;
}
switch (from->sa_family) {
#ifdef INET
case AF_INET:
{
struct sockaddr_in *sin, *rsin;
sin = (struct sockaddr_in *)&net->ro._l_addr;
rsin = (struct sockaddr_in *)from;
if (sin->sin_addr.s_addr ==
rsin->sin_addr.s_addr) {
/* found it */
if (netp != NULL) {
*netp = net;
}
/* Update the endpoint pointer */
*inp_p = inp;
SCTP_INP_RUNLOCK(inp);
return (stcb);
}
break;
}
#endif
#ifdef INET6
case AF_INET6:
{
struct sockaddr_in6 *sin6, *rsin6;
sin6 = (struct sockaddr_in6 *)&net->ro._l_addr;
rsin6 = (struct sockaddr_in6 *)from;
if (SCTP6_ARE_ADDR_EQUAL(sin6,
rsin6)) {
/* found it */
if (netp != NULL) {
*netp = net;
}
/* Update the endpoint pointer */
*inp_p = inp;
SCTP_INP_RUNLOCK(inp);
return (stcb);
}
break;
}
#endif
#if defined(__Userspace__)
case AF_CONN:
{
struct sockaddr_conn *sconn, *rsconn;
sconn = (struct sockaddr_conn *)&net->ro._l_addr;
rsconn = (struct sockaddr_conn *)from;
if (sconn->sconn_addr == rsconn->sconn_addr) {
/* found it */
if (netp != NULL) {
*netp = net;
}
/* Update the endpoint pointer */
*inp_p = inp;
SCTP_INP_RUNLOCK(inp);
return (stcb);
}
break;
}
#endif
default:
/* TSNH */
break;
}
}
SCTP_TCB_UNLOCK(stcb);
SCTP_INP_RUNLOCK(inp);
}
return (NULL);
}
/*
* rules for use
*
* 1) If I return a NULL you must decrement any INP ref cnt. 2) If I find an
* stcb, both will be locked (locked_tcb and stcb) but decrement will be done
* (if locked == NULL). 3) Decrement happens on return ONLY if locked ==
* NULL.
*/
struct sctp_tcb *
sctp_findassociation_ep_addr(struct sctp_inpcb **inp_p, struct sockaddr *remote,
struct sctp_nets **netp, struct sockaddr *local, struct sctp_tcb *locked_tcb)
{
struct sctpasochead *head;
struct sctp_inpcb *inp;
struct sctp_tcb *stcb = NULL;
struct sctp_nets *net;
uint16_t rport;
inp = *inp_p;
switch (remote->sa_family) {
#ifdef INET
case AF_INET:
rport = (((struct sockaddr_in *)remote)->sin_port);
break;
#endif
#ifdef INET6
case AF_INET6:
rport = (((struct sockaddr_in6 *)remote)->sin6_port);
break;
#endif
#if defined(__Userspace__)
case AF_CONN:
rport = (((struct sockaddr_conn *)remote)->sconn_port);
break;
#endif
default:
return (NULL);
}
if (locked_tcb) {
/*
* UN-lock so we can do proper locking here this occurs when
* called from load_addresses_from_init.
*/
atomic_add_int(&locked_tcb->asoc.refcnt, 1);
SCTP_TCB_UNLOCK(locked_tcb);
}
SCTP_INP_INFO_RLOCK();
if ((inp->sctp_flags & SCTP_PCB_FLAGS_TCPTYPE) ||
(inp->sctp_flags & SCTP_PCB_FLAGS_IN_TCPPOOL)) {
/*-
* Now either this guy is our listener or it's the
* connector. If it is the one that issued the connect, then
* it's only chance is to be the first TCB in the list. If
* it is the acceptor, then do the special_lookup to hash
* and find the real inp.
*/
if ((inp->sctp_socket) && SCTP_IS_LISTENING(inp)) {
/* to is peer addr, from is my addr */
#ifndef SCTP_MVRF
stcb = sctp_tcb_special_locate(inp_p, remote, local,
netp, inp->def_vrf_id);
if ((stcb != NULL) && (locked_tcb == NULL)) {
/* we have a locked tcb, lower refcount */
SCTP_INP_DECR_REF(inp);
}
if ((locked_tcb != NULL) && (locked_tcb != stcb)) {
SCTP_INP_RLOCK(locked_tcb->sctp_ep);
SCTP_TCB_LOCK(locked_tcb);
atomic_subtract_int(&locked_tcb->asoc.refcnt, 1);
SCTP_INP_RUNLOCK(locked_tcb->sctp_ep);
}
#else
/*-
* MVRF is tricky, we must look in every VRF
* the endpoint has.
*/
int i;
for (i = 0; i < inp->num_vrfs; i++) {
stcb = sctp_tcb_special_locate(inp_p, remote, local,
netp, inp->m_vrf_ids[i]);
if ((stcb != NULL) && (locked_tcb == NULL)) {
/* we have a locked tcb, lower refcount */
SCTP_INP_DECR_REF(inp);
break;
}
if ((locked_tcb != NULL) && (locked_tcb != stcb)) {
SCTP_INP_RLOCK(locked_tcb->sctp_ep);
SCTP_TCB_LOCK(locked_tcb);
atomic_subtract_int(&locked_tcb->asoc.refcnt, 1);
SCTP_INP_RUNLOCK(locked_tcb->sctp_ep);
break;
}
}
#endif
SCTP_INP_INFO_RUNLOCK();
return (stcb);
} else {
SCTP_INP_WLOCK(inp);
if (inp->sctp_flags & SCTP_PCB_FLAGS_SOCKET_ALLGONE) {
goto null_return;
}
stcb = LIST_FIRST(&inp->sctp_asoc_list);
if (stcb == NULL) {
goto null_return;
}
SCTP_TCB_LOCK(stcb);
if (stcb->rport != rport) {
/* remote port does not match. */
SCTP_TCB_UNLOCK(stcb);
goto null_return;
}
if (stcb->asoc.state & SCTP_STATE_ABOUT_TO_BE_FREED) {
SCTP_TCB_UNLOCK(stcb);
goto null_return;
}
if (local && !sctp_does_stcb_own_this_addr(stcb, local)) {
SCTP_TCB_UNLOCK(stcb);
goto null_return;
}
/* now look at the list of remote addresses */
TAILQ_FOREACH(net, &stcb->asoc.nets, sctp_next) {
#ifdef INVARIANTS
if (net == (TAILQ_NEXT(net, sctp_next))) {
panic("Corrupt net list");
}
#endif
if (net->ro._l_addr.sa.sa_family !=
remote->sa_family) {
/* not the same family */
continue;
}
switch (remote->sa_family) {
#ifdef INET
case AF_INET:
{
struct sockaddr_in *sin, *rsin;
sin = (struct sockaddr_in *)
&net->ro._l_addr;
rsin = (struct sockaddr_in *)remote;
if (sin->sin_addr.s_addr ==
rsin->sin_addr.s_addr) {
/* found it */
if (netp != NULL) {
*netp = net;
}
if (locked_tcb == NULL) {
SCTP_INP_DECR_REF(inp);
} else if (locked_tcb != stcb) {
SCTP_TCB_LOCK(locked_tcb);
}
if (locked_tcb) {
atomic_subtract_int(&locked_tcb->asoc.refcnt, 1);
}
SCTP_INP_WUNLOCK(inp);
SCTP_INP_INFO_RUNLOCK();
return (stcb);
}
break;
}
#endif
#ifdef INET6
case AF_INET6:
{
struct sockaddr_in6 *sin6, *rsin6;
sin6 = (struct sockaddr_in6 *)&net->ro._l_addr;
rsin6 = (struct sockaddr_in6 *)remote;
if (SCTP6_ARE_ADDR_EQUAL(sin6,
rsin6)) {
/* found it */
if (netp != NULL) {
*netp = net;
}
if (locked_tcb == NULL) {
SCTP_INP_DECR_REF(inp);
} else if (locked_tcb != stcb) {
SCTP_TCB_LOCK(locked_tcb);
}
if (locked_tcb) {
atomic_subtract_int(&locked_tcb->asoc.refcnt, 1);
}
SCTP_INP_WUNLOCK(inp);
SCTP_INP_INFO_RUNLOCK();
return (stcb);
}
break;
}
#endif
#if defined(__Userspace__)
case AF_CONN:
{
struct sockaddr_conn *sconn, *rsconn;
sconn = (struct sockaddr_conn *)&net->ro._l_addr;
rsconn = (struct sockaddr_conn *)remote;
if (sconn->sconn_addr == rsconn->sconn_addr) {
/* found it */
if (netp != NULL) {
*netp = net;
}
if (locked_tcb == NULL) {
SCTP_INP_DECR_REF(inp);
} else if (locked_tcb != stcb) {
SCTP_TCB_LOCK(locked_tcb);
}
if (locked_tcb) {
atomic_subtract_int(&locked_tcb->asoc.refcnt, 1);
}
SCTP_INP_WUNLOCK(inp);
SCTP_INP_INFO_RUNLOCK();
return (stcb);
}
break;
}
#endif
default:
/* TSNH */
break;
}
}
SCTP_TCB_UNLOCK(stcb);
}
} else {
SCTP_INP_WLOCK(inp);
if (inp->sctp_flags & SCTP_PCB_FLAGS_SOCKET_ALLGONE) {
goto null_return;
}
head = &inp->sctp_tcbhash[SCTP_PCBHASH_ALLADDR(rport,
inp->sctp_hashmark)];
LIST_FOREACH(stcb, head, sctp_tcbhash) {
if (stcb->rport != rport) {
/* remote port does not match */
continue;
}
SCTP_TCB_LOCK(stcb);
if (stcb->asoc.state & SCTP_STATE_ABOUT_TO_BE_FREED) {
SCTP_TCB_UNLOCK(stcb);
continue;
}
if (local && !sctp_does_stcb_own_this_addr(stcb, local)) {
SCTP_TCB_UNLOCK(stcb);
continue;
}
/* now look at the list of remote addresses */
TAILQ_FOREACH(net, &stcb->asoc.nets, sctp_next) {
#ifdef INVARIANTS
if (net == (TAILQ_NEXT(net, sctp_next))) {
panic("Corrupt net list");
}
#endif
if (net->ro._l_addr.sa.sa_family !=
remote->sa_family) {
/* not the same family */
continue;
}
switch (remote->sa_family) {
#ifdef INET
case AF_INET:
{
struct sockaddr_in *sin, *rsin;
sin = (struct sockaddr_in *)
&net->ro._l_addr;
rsin = (struct sockaddr_in *)remote;
if (sin->sin_addr.s_addr ==
rsin->sin_addr.s_addr) {
/* found it */
if (netp != NULL) {
*netp = net;
}
if (locked_tcb == NULL) {
SCTP_INP_DECR_REF(inp);
} else if (locked_tcb != stcb) {
SCTP_TCB_LOCK(locked_tcb);
}
if (locked_tcb) {
atomic_subtract_int(&locked_tcb->asoc.refcnt, 1);
}
SCTP_INP_WUNLOCK(inp);
SCTP_INP_INFO_RUNLOCK();
return (stcb);
}
break;
}
#endif
#ifdef INET6
case AF_INET6:
{
struct sockaddr_in6 *sin6, *rsin6;
sin6 = (struct sockaddr_in6 *)
&net->ro._l_addr;
rsin6 = (struct sockaddr_in6 *)remote;
if (SCTP6_ARE_ADDR_EQUAL(sin6,
rsin6)) {
/* found it */
if (netp != NULL) {
*netp = net;
}
if (locked_tcb == NULL) {
SCTP_INP_DECR_REF(inp);
} else if (locked_tcb != stcb) {
SCTP_TCB_LOCK(locked_tcb);
}
if (locked_tcb) {
atomic_subtract_int(&locked_tcb->asoc.refcnt, 1);
}
SCTP_INP_WUNLOCK(inp);
SCTP_INP_INFO_RUNLOCK();
return (stcb);
}
break;
}
#endif
#if defined(__Userspace__)
case AF_CONN:
{
struct sockaddr_conn *sconn, *rsconn;
sconn = (struct sockaddr_conn *)&net->ro._l_addr;
rsconn = (struct sockaddr_conn *)remote;
if (sconn->sconn_addr == rsconn->sconn_addr) {
/* found it */
if (netp != NULL) {
*netp = net;
}
if (locked_tcb == NULL) {
SCTP_INP_DECR_REF(inp);
} else if (locked_tcb != stcb) {
SCTP_TCB_LOCK(locked_tcb);
}
if (locked_tcb) {
atomic_subtract_int(&locked_tcb->asoc.refcnt, 1);
}
SCTP_INP_WUNLOCK(inp);
SCTP_INP_INFO_RUNLOCK();
return (stcb);
}
break;
}
#endif
default:
/* TSNH */
break;
}
}
SCTP_TCB_UNLOCK(stcb);
}
}
null_return:
/* clean up for returning null */
if (locked_tcb) {
SCTP_TCB_LOCK(locked_tcb);
atomic_subtract_int(&locked_tcb->asoc.refcnt, 1);
}
SCTP_INP_WUNLOCK(inp);
SCTP_INP_INFO_RUNLOCK();
/* not found */
return (NULL);
}
/*
* Find an association for a specific endpoint using the association id given
* out in the COMM_UP notification
*/
struct sctp_tcb *
sctp_findasoc_ep_asocid_locked(struct sctp_inpcb *inp, sctp_assoc_t asoc_id, int want_lock)
{
/*
* Use my the assoc_id to find a endpoint
*/
struct sctpasochead *head;
struct sctp_tcb *stcb;
uint32_t id;
if (inp == NULL) {
SCTP_PRINTF("TSNH ep_associd\n");
return (NULL);
}
if (inp->sctp_flags & SCTP_PCB_FLAGS_SOCKET_ALLGONE) {
SCTP_PRINTF("TSNH ep_associd0\n");
return (NULL);
}
id = (uint32_t)asoc_id;
head = &inp->sctp_asocidhash[SCTP_PCBHASH_ASOC(id, inp->hashasocidmark)];
if (head == NULL) {
/* invalid id TSNH */
SCTP_PRINTF("TSNH ep_associd1\n");
return (NULL);
}
LIST_FOREACH(stcb, head, sctp_tcbasocidhash) {
if (stcb->asoc.assoc_id == id) {
if (inp != stcb->sctp_ep) {
/*
* some other guy has the same id active (id
* collision ??).
*/
SCTP_PRINTF("TSNH ep_associd2\n");
continue;
}
if (stcb->asoc.state & SCTP_STATE_ABOUT_TO_BE_FREED) {
continue;
}
if (want_lock) {
SCTP_TCB_LOCK(stcb);
}
return (stcb);
}
}
return (NULL);
}
struct sctp_tcb *
sctp_findassociation_ep_asocid(struct sctp_inpcb *inp, sctp_assoc_t asoc_id, int want_lock)
{
struct sctp_tcb *stcb;
SCTP_INP_RLOCK(inp);
stcb = sctp_findasoc_ep_asocid_locked(inp, asoc_id, want_lock);
SCTP_INP_RUNLOCK(inp);
return (stcb);
}
/*
* Endpoint probe expects that the INP_INFO is locked.
*/
static struct sctp_inpcb *
sctp_endpoint_probe(struct sockaddr *nam, struct sctppcbhead *head,
uint16_t lport, uint32_t vrf_id)
{
struct sctp_inpcb *inp;
struct sctp_laddr *laddr;
#ifdef INET
struct sockaddr_in *sin;
#endif
#ifdef INET6
struct sockaddr_in6 *sin6;
struct sockaddr_in6 *intf_addr6;
#endif
#if defined(__Userspace__)
struct sockaddr_conn *sconn;
#endif
#ifdef SCTP_MVRF
int i;
#endif
int fnd;
#ifdef INET
sin = NULL;
#endif
#ifdef INET6
sin6 = NULL;
#endif
#if defined(__Userspace__)
sconn = NULL;
#endif
switch (nam->sa_family) {
#ifdef INET
case AF_INET:
sin = (struct sockaddr_in *)nam;
break;
#endif
#ifdef INET6
case AF_INET6:
sin6 = (struct sockaddr_in6 *)nam;
break;
#endif
#if defined(__Userspace__)
case AF_CONN:
sconn = (struct sockaddr_conn *)nam;
break;
#endif
default:
/* unsupported family */
return (NULL);
}
if (head == NULL)
return (NULL);
LIST_FOREACH(inp, head, sctp_hash) {
SCTP_INP_RLOCK(inp);
if (inp->sctp_flags & SCTP_PCB_FLAGS_SOCKET_ALLGONE) {
SCTP_INP_RUNLOCK(inp);
continue;
}
if ((inp->sctp_flags & SCTP_PCB_FLAGS_BOUNDALL) &&
(inp->sctp_lport == lport)) {
/* got it */
switch (nam->sa_family) {
#ifdef INET
case AF_INET:
if ((inp->sctp_flags & SCTP_PCB_FLAGS_BOUND_V6) &&
SCTP_IPV6_V6ONLY(inp)) {
/* IPv4 on a IPv6 socket with ONLY IPv6 set */
SCTP_INP_RUNLOCK(inp);
continue;
}
#if defined(__FreeBSD__)
if (prison_check_ip4(inp->ip_inp.inp.inp_cred,
&sin->sin_addr) != 0) {
SCTP_INP_RUNLOCK(inp);
continue;
}
#endif
break;
#endif
#ifdef INET6
case AF_INET6:
/* A V6 address and the endpoint is NOT bound V6 */
if ((inp->sctp_flags & SCTP_PCB_FLAGS_BOUND_V6) == 0) {
SCTP_INP_RUNLOCK(inp);
continue;
}
#if defined(__FreeBSD__)
if (prison_check_ip6(inp->ip_inp.inp.inp_cred,
&sin6->sin6_addr) != 0) {
SCTP_INP_RUNLOCK(inp);
continue;
}
#endif
break;
#endif
default:
break;
}
/* does a VRF id match? */
fnd = 0;
#ifdef SCTP_MVRF
for (i = 0; i < inp->num_vrfs; i++) {
if (inp->m_vrf_ids[i] == vrf_id) {
fnd = 1;
break;
}
}
#else
if (inp->def_vrf_id == vrf_id)
fnd = 1;
#endif
SCTP_INP_RUNLOCK(inp);
if (!fnd)
continue;
return (inp);
}
SCTP_INP_RUNLOCK(inp);
}
switch (nam->sa_family) {
#ifdef INET
case AF_INET:
if (sin->sin_addr.s_addr == INADDR_ANY) {
/* Can't hunt for one that has no address specified */
return (NULL);
}
break;
#endif
#ifdef INET6
case AF_INET6:
if (IN6_IS_ADDR_UNSPECIFIED(&sin6->sin6_addr)) {
/* Can't hunt for one that has no address specified */
return (NULL);
}
break;
#endif
#if defined(__Userspace__)
case AF_CONN:
if (sconn->sconn_addr == NULL) {
return (NULL);
}
break;
#endif
default:
break;
}
/*
* ok, not bound to all so see if we can find a EP bound to this
* address.
*/
LIST_FOREACH(inp, head, sctp_hash) {
SCTP_INP_RLOCK(inp);
if (inp->sctp_flags & SCTP_PCB_FLAGS_SOCKET_ALLGONE) {
SCTP_INP_RUNLOCK(inp);
continue;
}
if ((inp->sctp_flags & SCTP_PCB_FLAGS_BOUNDALL)) {
SCTP_INP_RUNLOCK(inp);
continue;
}
/*
* Ok this could be a likely candidate, look at all of its
* addresses
*/
if (inp->sctp_lport != lport) {
SCTP_INP_RUNLOCK(inp);
continue;
}
/* does a VRF id match? */
fnd = 0;
#ifdef SCTP_MVRF
for (i = 0; i < inp->num_vrfs; i++) {
if (inp->m_vrf_ids[i] == vrf_id) {
fnd = 1;
break;
}
}
#else
if (inp->def_vrf_id == vrf_id)
fnd = 1;
#endif
if (!fnd) {
SCTP_INP_RUNLOCK(inp);
continue;
}
LIST_FOREACH(laddr, &inp->sctp_addr_list, sctp_nxt_addr) {
if (laddr->ifa == NULL) {
SCTPDBG(SCTP_DEBUG_PCB1, "%s: NULL ifa\n",
__func__);
continue;
}
SCTPDBG(SCTP_DEBUG_PCB1, "Ok laddr->ifa:%p is possible, ",
(void *)laddr->ifa);
if (laddr->ifa->localifa_flags & SCTP_BEING_DELETED) {
SCTPDBG(SCTP_DEBUG_PCB1, "Huh IFA being deleted\n");
continue;
}
if (laddr->ifa->address.sa.sa_family == nam->sa_family) {
/* possible, see if it matches */
switch (nam->sa_family) {
#ifdef INET
case AF_INET:
#if defined(__APPLE__)
if (sin == NULL) {
/* TSNH */
break;
}
#endif
if (sin->sin_addr.s_addr ==
laddr->ifa->address.sin.sin_addr.s_addr) {
SCTP_INP_RUNLOCK(inp);
return (inp);
}
break;
#endif
#ifdef INET6
case AF_INET6:
intf_addr6 = &laddr->ifa->address.sin6;
if (SCTP6_ARE_ADDR_EQUAL(sin6,
intf_addr6)) {
SCTP_INP_RUNLOCK(inp);
return (inp);
}
break;
#endif
#if defined(__Userspace__)
case AF_CONN:
if (sconn->sconn_addr == laddr->ifa->address.sconn.sconn_addr) {
SCTP_INP_RUNLOCK(inp);
return (inp);
}
break;
#endif
}
}
}
SCTP_INP_RUNLOCK(inp);
}
return (NULL);
}
static struct sctp_inpcb *
sctp_isport_inuse(struct sctp_inpcb *inp, uint16_t lport, uint32_t vrf_id)
{
struct sctppcbhead *head;
struct sctp_inpcb *t_inp;
#ifdef SCTP_MVRF
int i;
#endif
int fnd;
head = &SCTP_BASE_INFO(sctp_ephash)[SCTP_PCBHASH_ALLADDR(lport,
SCTP_BASE_INFO(hashmark))];
LIST_FOREACH(t_inp, head, sctp_hash) {
if (t_inp->sctp_lport != lport) {
continue;
}
/* is it in the VRF in question */
fnd = 0;
#ifdef SCTP_MVRF
for (i = 0; i < inp->num_vrfs; i++) {
if (t_inp->m_vrf_ids[i] == vrf_id) {
fnd = 1;
break;
}
}
#else
if (t_inp->def_vrf_id == vrf_id)
fnd = 1;
#endif
if (!fnd)
continue;
/* This one is in use. */
/* check the v6/v4 binding issue */
if ((t_inp->sctp_flags & SCTP_PCB_FLAGS_BOUND_V6) &&
SCTP_IPV6_V6ONLY(t_inp)) {
if (inp->sctp_flags & SCTP_PCB_FLAGS_BOUND_V6) {
/* collision in V6 space */
return (t_inp);
} else {
/* inp is BOUND_V4 no conflict */
continue;
}
} else if (t_inp->sctp_flags & SCTP_PCB_FLAGS_BOUND_V6) {
/* t_inp is bound v4 and v6, conflict always */
return (t_inp);
} else {
/* t_inp is bound only V4 */
if ((inp->sctp_flags & SCTP_PCB_FLAGS_BOUND_V6) &&
SCTP_IPV6_V6ONLY(inp)) {
/* no conflict */
continue;
}
/* else fall through to conflict */
}
return (t_inp);
}
return (NULL);
}
int
sctp_swap_inpcb_for_listen(struct sctp_inpcb *inp)
{
/* For 1-2-1 with port reuse */
struct sctppcbhead *head;
struct sctp_inpcb *tinp, *ninp;
if (sctp_is_feature_off(inp, SCTP_PCB_FLAGS_PORTREUSE)) {
/* only works with port reuse on */
return (-1);
}
if ((inp->sctp_flags & SCTP_PCB_FLAGS_IN_TCPPOOL) == 0) {
return (0);
}
SCTP_INP_RUNLOCK(inp);
SCTP_INP_INFO_WLOCK();
head = &SCTP_BASE_INFO(sctp_ephash)[SCTP_PCBHASH_ALLADDR(inp->sctp_lport,
SCTP_BASE_INFO(hashmark))];
/* Kick out all non-listeners to the TCP hash */
LIST_FOREACH_SAFE(tinp, head, sctp_hash, ninp) {
if (tinp->sctp_lport != inp->sctp_lport) {
continue;
}
if (tinp->sctp_flags & SCTP_PCB_FLAGS_SOCKET_ALLGONE) {
continue;
}
if (tinp->sctp_flags & SCTP_PCB_FLAGS_SOCKET_GONE) {
continue;
}
if (SCTP_IS_LISTENING(tinp)) {
continue;
}
SCTP_INP_WLOCK(tinp);
LIST_REMOVE(tinp, sctp_hash);
head = &SCTP_BASE_INFO(sctp_tcpephash)[SCTP_PCBHASH_ALLADDR(tinp->sctp_lport, SCTP_BASE_INFO(hashtcpmark))];
tinp->sctp_flags |= SCTP_PCB_FLAGS_IN_TCPPOOL;
LIST_INSERT_HEAD(head, tinp, sctp_hash);
SCTP_INP_WUNLOCK(tinp);
}
SCTP_INP_WLOCK(inp);
/* Pull from where he was */
LIST_REMOVE(inp, sctp_hash);
inp->sctp_flags &= ~SCTP_PCB_FLAGS_IN_TCPPOOL;
head = &SCTP_BASE_INFO(sctp_ephash)[SCTP_PCBHASH_ALLADDR(inp->sctp_lport, SCTP_BASE_INFO(hashmark))];
LIST_INSERT_HEAD(head, inp, sctp_hash);
SCTP_INP_WUNLOCK(inp);
SCTP_INP_RLOCK(inp);
SCTP_INP_INFO_WUNLOCK();
return (0);
}
struct sctp_inpcb *
sctp_pcb_findep(struct sockaddr *nam, int find_tcp_pool, int have_lock,
uint32_t vrf_id)
{
/*
* First we check the hash table to see if someone has this port
* bound with just the port.
*/
struct sctp_inpcb *inp;
struct sctppcbhead *head;
int lport;
unsigned int i;
#ifdef INET
struct sockaddr_in *sin;
#endif
#ifdef INET6
struct sockaddr_in6 *sin6;
#endif
#if defined(__Userspace__)
struct sockaddr_conn *sconn;
#endif
switch (nam->sa_family) {
#ifdef INET
case AF_INET:
sin = (struct sockaddr_in *)nam;
lport = sin->sin_port;
break;
#endif
#ifdef INET6
case AF_INET6:
sin6 = (struct sockaddr_in6 *)nam;
lport = sin6->sin6_port;
break;
#endif
#if defined(__Userspace__)
case AF_CONN:
sconn = (struct sockaddr_conn *)nam;
lport = sconn->sconn_port;
break;
#endif
default:
return (NULL);
}
/*
* I could cheat here and just cast to one of the types but we will
* do it right. It also provides the check against an Unsupported
* type too.
*/
/* Find the head of the ALLADDR chain */
if (have_lock == 0) {
SCTP_INP_INFO_RLOCK();
}
head = &SCTP_BASE_INFO(sctp_ephash)[SCTP_PCBHASH_ALLADDR(lport,
SCTP_BASE_INFO(hashmark))];
inp = sctp_endpoint_probe(nam, head, lport, vrf_id);
/*
* If the TCP model exists it could be that the main listening
* endpoint is gone but there still exists a connected socket for this
* guy. If so we can return the first one that we find. This may NOT
* be the correct one so the caller should be wary on the returned INP.
* Currently the only caller that sets find_tcp_pool is in bindx where
* we are verifying that a user CAN bind the address. He either
* has bound it already, or someone else has, or its open to bind,
* so this is good enough.
*/
if (inp == NULL && find_tcp_pool) {
for (i = 0; i < SCTP_BASE_INFO(hashtcpmark) + 1; i++) {
head = &SCTP_BASE_INFO(sctp_tcpephash)[i];
inp = sctp_endpoint_probe(nam, head, lport, vrf_id);
if (inp) {
break;
}
}
}
if (inp) {
SCTP_INP_INCR_REF(inp);
}
if (have_lock == 0) {
SCTP_INP_INFO_RUNLOCK();
}
return (inp);
}
/*
* Find an association for an endpoint with the pointer to whom you want to
* send to and the endpoint pointer. The address can be IPv4 or IPv6. We may
* need to change the *to to some other struct like a mbuf...
*/
struct sctp_tcb *
sctp_findassociation_addr_sa(struct sockaddr *from, struct sockaddr *to,
struct sctp_inpcb **inp_p, struct sctp_nets **netp, int find_tcp_pool,
uint32_t vrf_id)
{
struct sctp_inpcb *inp = NULL;
struct sctp_tcb *stcb;
SCTP_INP_INFO_RLOCK();
if (find_tcp_pool) {
if (inp_p != NULL) {
stcb = sctp_tcb_special_locate(inp_p, from, to, netp,
vrf_id);
} else {
stcb = sctp_tcb_special_locate(&inp, from, to, netp,
vrf_id);
}
if (stcb != NULL) {
SCTP_INP_INFO_RUNLOCK();
return (stcb);
}
}
inp = sctp_pcb_findep(to, 0, 1, vrf_id);
if (inp_p != NULL) {
*inp_p = inp;
}
SCTP_INP_INFO_RUNLOCK();
if (inp == NULL) {
return (NULL);
}
/*
* ok, we have an endpoint, now lets find the assoc for it (if any)
* we now place the source address or from in the to of the find
* endpoint call. Since in reality this chain is used from the
* inbound packet side.
*/
if (inp_p != NULL) {
stcb = sctp_findassociation_ep_addr(inp_p, from, netp, to,
NULL);
} else {
stcb = sctp_findassociation_ep_addr(&inp, from, netp, to,
NULL);
}
return (stcb);
}
/*
* This routine will grub through the mbuf that is a INIT or INIT-ACK and
* find all addresses that the sender has specified in any address list. Each
* address will be used to lookup the TCB and see if one exits.
*/
static struct sctp_tcb *
sctp_findassociation_special_addr(struct mbuf *m, int offset,
struct sctphdr *sh, struct sctp_inpcb **inp_p, struct sctp_nets **netp,
struct sockaddr *dst)
{
struct sctp_paramhdr *phdr, param_buf;
#if defined(INET) || defined(INET6)
struct sctp_tcb *stcb;
uint16_t ptype;
#endif
uint16_t plen;
#ifdef INET
struct sockaddr_in sin4;
#endif
#ifdef INET6
struct sockaddr_in6 sin6;
#endif
#ifdef INET
memset(&sin4, 0, sizeof(sin4));
#ifdef HAVE_SIN_LEN
sin4.sin_len = sizeof(sin4);
#endif
sin4.sin_family = AF_INET;
sin4.sin_port = sh->src_port;
#endif
#ifdef INET6
memset(&sin6, 0, sizeof(sin6));
#ifdef HAVE_SIN6_LEN
sin6.sin6_len = sizeof(sin6);
#endif
sin6.sin6_family = AF_INET6;
sin6.sin6_port = sh->src_port;
#endif
offset += sizeof(struct sctp_init_chunk);
phdr = sctp_get_next_param(m, offset, ¶m_buf, sizeof(param_buf));
while (phdr != NULL) {
/* now we must see if we want the parameter */
#if defined(INET) || defined(INET6)
ptype = ntohs(phdr->param_type);
#endif
plen = ntohs(phdr->param_length);
if (plen == 0) {
break;
}
#ifdef INET
if (ptype == SCTP_IPV4_ADDRESS &&
plen == sizeof(struct sctp_ipv4addr_param)) {
/* Get the rest of the address */
struct sctp_ipv4addr_param ip4_param, *p4;
phdr = sctp_get_next_param(m, offset,
(struct sctp_paramhdr *)&ip4_param, sizeof(ip4_param));
if (phdr == NULL) {
return (NULL);
}
p4 = (struct sctp_ipv4addr_param *)phdr;
memcpy(&sin4.sin_addr, &p4->addr, sizeof(p4->addr));
/* look it up */
stcb = sctp_findassociation_ep_addr(inp_p,
(struct sockaddr *)&sin4, netp, dst, NULL);
if (stcb != NULL) {
return (stcb);
}
}
#endif
#ifdef INET6
if (ptype == SCTP_IPV6_ADDRESS &&
plen == sizeof(struct sctp_ipv6addr_param)) {
/* Get the rest of the address */
struct sctp_ipv6addr_param ip6_param, *p6;
phdr = sctp_get_next_param(m, offset,
(struct sctp_paramhdr *)&ip6_param, sizeof(ip6_param));
if (phdr == NULL) {
return (NULL);
}
p6 = (struct sctp_ipv6addr_param *)phdr;
memcpy(&sin6.sin6_addr, &p6->addr, sizeof(p6->addr));
/* look it up */
stcb = sctp_findassociation_ep_addr(inp_p,
(struct sockaddr *)&sin6, netp, dst, NULL);
if (stcb != NULL) {
return (stcb);
}
}
#endif
offset += SCTP_SIZE32(plen);
phdr = sctp_get_next_param(m, offset, ¶m_buf,
sizeof(param_buf));
}
return (NULL);
}
static struct sctp_tcb *
sctp_findassoc_by_vtag(struct sockaddr *from, struct sockaddr *to, uint32_t vtag,
struct sctp_inpcb **inp_p, struct sctp_nets **netp, uint16_t rport,
uint16_t lport, int skip_src_check, uint32_t vrf_id, uint32_t remote_tag)
{
/*
* Use my vtag to hash. If we find it we then verify the source addr
* is in the assoc. If all goes well we save a bit on rec of a
* packet.
*/
struct sctpasochead *head;
struct sctp_nets *net;
struct sctp_tcb *stcb;
#ifdef SCTP_MVRF
unsigned int i;
#endif
SCTP_INP_INFO_RLOCK();
head = &SCTP_BASE_INFO(sctp_asochash)[SCTP_PCBHASH_ASOC(vtag,
SCTP_BASE_INFO(hashasocmark))];
LIST_FOREACH(stcb, head, sctp_asocs) {
SCTP_INP_RLOCK(stcb->sctp_ep);
if (stcb->sctp_ep->sctp_flags & SCTP_PCB_FLAGS_SOCKET_ALLGONE) {
SCTP_INP_RUNLOCK(stcb->sctp_ep);
continue;
}
#ifdef SCTP_MVRF
for (i = 0; i < stcb->sctp_ep->num_vrfs; i++) {
if (stcb->sctp_ep->m_vrf_ids[i] == vrf_id) {
break;
}
}
if (i == stcb->sctp_ep->num_vrfs) {
SCTP_INP_RUNLOCK(inp);
continue;
}
#else
if (stcb->sctp_ep->def_vrf_id != vrf_id) {
SCTP_INP_RUNLOCK(stcb->sctp_ep);
continue;
}
#endif
SCTP_TCB_LOCK(stcb);
SCTP_INP_RUNLOCK(stcb->sctp_ep);
if (stcb->asoc.my_vtag == vtag) {
/* candidate */
if (stcb->rport != rport) {
SCTP_TCB_UNLOCK(stcb);
continue;
}
if (stcb->sctp_ep->sctp_lport != lport) {
SCTP_TCB_UNLOCK(stcb);
continue;
}
if (stcb->asoc.state & SCTP_STATE_ABOUT_TO_BE_FREED) {
SCTP_TCB_UNLOCK(stcb);
continue;
}
/* RRS:Need toaddr check here */
if (sctp_does_stcb_own_this_addr(stcb, to) == 0) {
/* Endpoint does not own this address */
SCTP_TCB_UNLOCK(stcb);
continue;
}
if (remote_tag) {
/* If we have both vtags that's all we match on */
if (stcb->asoc.peer_vtag == remote_tag) {
/* If both tags match we consider it conclusive
* and check NO source/destination addresses
*/
goto conclusive;
}
}
if (skip_src_check) {
conclusive:
if (from) {
*netp = sctp_findnet(stcb, from);
} else {
*netp = NULL; /* unknown */
}
if (inp_p)
*inp_p = stcb->sctp_ep;
SCTP_INP_INFO_RUNLOCK();
return (stcb);
}
net = sctp_findnet(stcb, from);
if (net) {
/* yep its him. */
*netp = net;
SCTP_STAT_INCR(sctps_vtagexpress);
*inp_p = stcb->sctp_ep;
SCTP_INP_INFO_RUNLOCK();
return (stcb);
} else {
/*
* not him, this should only happen in rare
* cases so I peg it.
*/
SCTP_STAT_INCR(sctps_vtagbogus);
}
}
SCTP_TCB_UNLOCK(stcb);
}
SCTP_INP_INFO_RUNLOCK();
return (NULL);
}
/*
* Find an association with the pointer to the inbound IP packet. This can be
* a IPv4 or IPv6 packet.
*/
struct sctp_tcb *
sctp_findassociation_addr(struct mbuf *m, int offset,
struct sockaddr *src, struct sockaddr *dst,
struct sctphdr *sh, struct sctp_chunkhdr *ch,
struct sctp_inpcb **inp_p, struct sctp_nets **netp, uint32_t vrf_id)
{
struct sctp_tcb *stcb;
struct sctp_inpcb *inp;
if (sh->v_tag) {
/* we only go down this path if vtag is non-zero */
stcb = sctp_findassoc_by_vtag(src, dst, ntohl(sh->v_tag),
inp_p, netp, sh->src_port, sh->dest_port, 0, vrf_id, 0);
if (stcb) {
return (stcb);
}
}
if (inp_p) {
stcb = sctp_findassociation_addr_sa(src, dst, inp_p, netp,
1, vrf_id);
inp = *inp_p;
} else {
stcb = sctp_findassociation_addr_sa(src, dst, &inp, netp,
1, vrf_id);
}
SCTPDBG(SCTP_DEBUG_PCB1, "stcb:%p inp:%p\n", (void *)stcb, (void *)inp);
if (stcb == NULL && inp) {
/* Found a EP but not this address */
if ((ch->chunk_type == SCTP_INITIATION) ||
(ch->chunk_type == SCTP_INITIATION_ACK)) {
/*-
* special hook, we do NOT return linp or an
* association that is linked to an existing
* association that is under the TCP pool (i.e. no
* listener exists). The endpoint finding routine
* will always find a listener before examining the
* TCP pool.
*/
if (inp->sctp_flags & SCTP_PCB_FLAGS_IN_TCPPOOL) {
if (inp_p) {
*inp_p = NULL;
}
return (NULL);
}
stcb = sctp_findassociation_special_addr(m,
offset, sh, &inp, netp, dst);
if (inp_p != NULL) {
*inp_p = inp;
}
}
}
SCTPDBG(SCTP_DEBUG_PCB1, "stcb is %p\n", (void *)stcb);
return (stcb);
}
/*
* lookup an association by an ASCONF lookup address.
* if the lookup address is 0.0.0.0 or ::0, use the vtag to do the lookup
*/
struct sctp_tcb *
sctp_findassociation_ep_asconf(struct mbuf *m, int offset,
struct sockaddr *dst, struct sctphdr *sh,
struct sctp_inpcb **inp_p, struct sctp_nets **netp, uint32_t vrf_id)
{
struct sctp_tcb *stcb;
union sctp_sockstore remote_store;
struct sctp_paramhdr param_buf, *phdr;
int ptype;
int zero_address = 0;
#ifdef INET
struct sockaddr_in *sin;
#endif
#ifdef INET6
struct sockaddr_in6 *sin6;
#endif
memset(&remote_store, 0, sizeof(remote_store));
phdr = sctp_get_next_param(m, offset + sizeof(struct sctp_asconf_chunk),
¶m_buf, sizeof(struct sctp_paramhdr));
if (phdr == NULL) {
SCTPDBG(SCTP_DEBUG_INPUT3, "%s: failed to get asconf lookup addr\n",
__func__);
return NULL;
}
ptype = (int)((uint32_t) ntohs(phdr->param_type));
/* get the correlation address */
switch (ptype) {
#ifdef INET6
case SCTP_IPV6_ADDRESS:
{
/* ipv6 address param */
struct sctp_ipv6addr_param *p6, p6_buf;
if (ntohs(phdr->param_length) != sizeof(struct sctp_ipv6addr_param)) {
return NULL;
}
p6 = (struct sctp_ipv6addr_param *)sctp_get_next_param(m,
offset + sizeof(struct sctp_asconf_chunk),
&p6_buf.ph, sizeof(p6_buf));
if (p6 == NULL) {
SCTPDBG(SCTP_DEBUG_INPUT3, "%s: failed to get asconf v6 lookup addr\n",
__func__);
return (NULL);
}
sin6 = &remote_store.sin6;
sin6->sin6_family = AF_INET6;
#ifdef HAVE_SIN6_LEN
sin6->sin6_len = sizeof(*sin6);
#endif
sin6->sin6_port = sh->src_port;
memcpy(&sin6->sin6_addr, &p6->addr, sizeof(struct in6_addr));
if (IN6_IS_ADDR_UNSPECIFIED(&sin6->sin6_addr))
zero_address = 1;
break;
}
#endif
#ifdef INET
case SCTP_IPV4_ADDRESS:
{
/* ipv4 address param */
struct sctp_ipv4addr_param *p4, p4_buf;
if (ntohs(phdr->param_length) != sizeof(struct sctp_ipv4addr_param)) {
return NULL;
}
p4 = (struct sctp_ipv4addr_param *)sctp_get_next_param(m,
offset + sizeof(struct sctp_asconf_chunk),
&p4_buf.ph, sizeof(p4_buf));
if (p4 == NULL) {
SCTPDBG(SCTP_DEBUG_INPUT3, "%s: failed to get asconf v4 lookup addr\n",
__func__);
return (NULL);
}
sin = &remote_store.sin;
sin->sin_family = AF_INET;
#ifdef HAVE_SIN_LEN
sin->sin_len = sizeof(*sin);
#endif
sin->sin_port = sh->src_port;
memcpy(&sin->sin_addr, &p4->addr, sizeof(struct in_addr));
if (sin->sin_addr.s_addr == INADDR_ANY)
zero_address = 1;
break;
}
#endif
default:
/* invalid address param type */
return NULL;
}
if (zero_address) {
stcb = sctp_findassoc_by_vtag(NULL, dst, ntohl(sh->v_tag), inp_p,
netp, sh->src_port, sh->dest_port, 1, vrf_id, 0);
if (stcb != NULL) {
SCTP_INP_DECR_REF(*inp_p);
}
} else {
stcb = sctp_findassociation_ep_addr(inp_p,
&remote_store.sa, netp,
dst, NULL);
}
return (stcb);
}
/*
* allocate a sctp_inpcb and setup a temporary binding to a port/all
* addresses. This way if we don't get a bind we by default pick a ephemeral
* port with all addresses bound.
*/
int
sctp_inpcb_alloc(struct socket *so, uint32_t vrf_id)
{
/*
* we get called when a new endpoint starts up. We need to allocate
* the sctp_inpcb structure from the zone and init it. Mark it as
* unbound and find a port that we can use as an ephemeral with
* INADDR_ANY. If the user binds later no problem we can then add in
* the specific addresses. And setup the default parameters for the
* EP.
*/
int i, error;
struct sctp_inpcb *inp;
struct sctp_pcb *m;
struct timeval time;
sctp_sharedkey_t *null_key;
error = 0;
SCTP_INP_INFO_WLOCK();
inp = SCTP_ZONE_GET(SCTP_BASE_INFO(ipi_zone_ep), struct sctp_inpcb);
if (inp == NULL) {
SCTP_PRINTF("Out of SCTP-INPCB structures - no resources\n");
SCTP_INP_INFO_WUNLOCK();
SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, ENOBUFS);
return (ENOBUFS);
}
/* zap it */
memset(inp, 0, sizeof(*inp));
/* bump generations */
#if defined(__APPLE__)
inp->ip_inp.inp.inp_state = INPCB_STATE_INUSE;
#endif
/* setup socket pointers */
inp->sctp_socket = so;
inp->ip_inp.inp.inp_socket = so;
#if defined(__FreeBSD__)
inp->ip_inp.inp.inp_cred = crhold(so->so_cred);
#endif
#ifdef INET6
#if !defined(__Userspace__) && !defined(__Windows__)
if (INP_SOCKAF(so) == AF_INET6) {
if (MODULE_GLOBAL(ip6_auto_flowlabel)) {
inp->ip_inp.inp.inp_flags |= IN6P_AUTOFLOWLABEL;
}
if (MODULE_GLOBAL(ip6_v6only)) {
inp->ip_inp.inp.inp_flags |= IN6P_IPV6_V6ONLY;
}
}
#endif
#endif
inp->sctp_associd_counter = 1;
inp->partial_delivery_point = SCTP_SB_LIMIT_RCV(so) >> SCTP_PARTIAL_DELIVERY_SHIFT;
inp->sctp_frag_point = SCTP_DEFAULT_MAXSEGMENT;
inp->max_cwnd = 0;
inp->sctp_cmt_on_off = SCTP_BASE_SYSCTL(sctp_cmt_on_off);
inp->ecn_supported = (uint8_t)SCTP_BASE_SYSCTL(sctp_ecn_enable);
inp->prsctp_supported = (uint8_t)SCTP_BASE_SYSCTL(sctp_pr_enable);
inp->auth_supported = (uint8_t)SCTP_BASE_SYSCTL(sctp_auth_enable);
inp->asconf_supported = (uint8_t)SCTP_BASE_SYSCTL(sctp_asconf_enable);
inp->reconfig_supported = (uint8_t)SCTP_BASE_SYSCTL(sctp_reconfig_enable);
inp->nrsack_supported = (uint8_t)SCTP_BASE_SYSCTL(sctp_nrsack_enable);
inp->pktdrop_supported = (uint8_t)SCTP_BASE_SYSCTL(sctp_pktdrop_enable);
inp->idata_supported = 0;
#if defined(__FreeBSD__)
inp->fibnum = so->so_fibnum;
#else
inp->fibnum = 0;
#endif
#if defined(__Userspace__)
inp->ulp_info = NULL;
inp->recv_callback = NULL;
inp->send_callback = NULL;
inp->send_sb_threshold = 0;
#endif
/* init the small hash table we use to track asocid <-> tcb */
inp->sctp_asocidhash = SCTP_HASH_INIT(SCTP_STACK_VTAG_HASH_SIZE, &inp->hashasocidmark);
if (inp->sctp_asocidhash == NULL) {
#if defined(__FreeBSD__)
crfree(inp->ip_inp.inp.inp_cred);
#endif
SCTP_ZONE_FREE(SCTP_BASE_INFO(ipi_zone_ep), inp);
SCTP_INP_INFO_WUNLOCK();
return (ENOBUFS);
}
SCTP_INCR_EP_COUNT();
inp->ip_inp.inp.inp_ip_ttl = MODULE_GLOBAL(ip_defttl);
SCTP_INP_INFO_WUNLOCK();
so->so_pcb = (caddr_t)inp;
#if defined(__FreeBSD__) && __FreeBSD_version < 803000
if ((SCTP_SO_TYPE(so) == SOCK_DGRAM) ||
(SCTP_SO_TYPE(so) == SOCK_SEQPACKET)) {
#else
if (SCTP_SO_TYPE(so) == SOCK_SEQPACKET) {
#endif
/* UDP style socket */
inp->sctp_flags = (SCTP_PCB_FLAGS_UDPTYPE |
SCTP_PCB_FLAGS_UNBOUND);
/* Be sure it is NON-BLOCKING IO for UDP */
/* SCTP_SET_SO_NBIO(so); */
} else if (SCTP_SO_TYPE(so) == SOCK_STREAM) {
/* TCP style socket */
inp->sctp_flags = (SCTP_PCB_FLAGS_TCPTYPE |
SCTP_PCB_FLAGS_UNBOUND);
/* Be sure we have blocking IO by default */
SOCK_LOCK(so);
SCTP_CLEAR_SO_NBIO(so);
SOCK_UNLOCK(so);
#if defined(__Panda__)
} else if (SCTP_SO_TYPE(so) == SOCK_FASTSEQPACKET) {
inp->sctp_flags = (SCTP_PCB_FLAGS_UDPTYPE |
SCTP_PCB_FLAGS_UNBOUND);
} else if (SCTP_SO_TYPE(so) == SOCK_FASTSTREAM) {
inp->sctp_flags = (SCTP_PCB_FLAGS_TCPTYPE |
SCTP_PCB_FLAGS_UNBOUND);
#endif
} else {
/*
* unsupported socket type (RAW, etc)- in case we missed it
* in protosw
*/
SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, EOPNOTSUPP);
so->so_pcb = NULL;
#if defined(__FreeBSD__)
crfree(inp->ip_inp.inp.inp_cred);
#endif
SCTP_ZONE_FREE(SCTP_BASE_INFO(ipi_zone_ep), inp);
return (EOPNOTSUPP);
}
if (SCTP_BASE_SYSCTL(sctp_default_frag_interleave) == SCTP_FRAG_LEVEL_1) {
sctp_feature_on(inp, SCTP_PCB_FLAGS_FRAG_INTERLEAVE);
sctp_feature_off(inp, SCTP_PCB_FLAGS_INTERLEAVE_STRMS);
} else if (SCTP_BASE_SYSCTL(sctp_default_frag_interleave) == SCTP_FRAG_LEVEL_2) {
sctp_feature_on(inp, SCTP_PCB_FLAGS_FRAG_INTERLEAVE);
sctp_feature_on(inp, SCTP_PCB_FLAGS_INTERLEAVE_STRMS);
} else if (SCTP_BASE_SYSCTL(sctp_default_frag_interleave) == SCTP_FRAG_LEVEL_0) {
sctp_feature_off(inp, SCTP_PCB_FLAGS_FRAG_INTERLEAVE);
sctp_feature_off(inp, SCTP_PCB_FLAGS_INTERLEAVE_STRMS);
}
inp->sctp_tcbhash = SCTP_HASH_INIT(SCTP_BASE_SYSCTL(sctp_pcbtblsize),
&inp->sctp_hashmark);
if (inp->sctp_tcbhash == NULL) {
SCTP_PRINTF("Out of SCTP-INPCB->hashinit - no resources\n");
SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, ENOBUFS);
so->so_pcb = NULL;
#if defined(__FreeBSD__)
crfree(inp->ip_inp.inp.inp_cred);
#endif
SCTP_ZONE_FREE(SCTP_BASE_INFO(ipi_zone_ep), inp);
return (ENOBUFS);
}
#ifdef SCTP_MVRF
inp->vrf_size = SCTP_DEFAULT_VRF_SIZE;
SCTP_MALLOC(inp->m_vrf_ids, uint32_t *,
(sizeof(uint32_t) * inp->vrf_size), SCTP_M_MVRF);
if (inp->m_vrf_ids == NULL) {
SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, ENOBUFS);
so->so_pcb = NULL;
SCTP_HASH_FREE(inp->sctp_tcbhash, inp->sctp_hashmark);
#if defined(__FreeBSD__)
crfree(inp->ip_inp.inp.inp_cred);
#endif
SCTP_ZONE_FREE(SCTP_BASE_INFO(ipi_zone_ep), inp);
return (ENOBUFS);
}
inp->m_vrf_ids[0] = vrf_id;
inp->num_vrfs = 1;
#endif
inp->def_vrf_id = vrf_id;
#if defined(__APPLE__)
#if defined(APPLE_LEOPARD) || defined(APPLE_SNOWLEOPARD)
inp->ip_inp.inp.inpcb_mtx = lck_mtx_alloc_init(SCTP_BASE_INFO(sctbinfo).mtx_grp, SCTP_BASE_INFO(sctbinfo).mtx_attr);
if (inp->ip_inp.inp.inpcb_mtx == NULL) {
SCTP_PRINTF("in_pcballoc: can't alloc mutex! so=%p\n", (void *)so);
#ifdef SCTP_MVRF
SCTP_FREE(inp->m_vrf_ids, SCTP_M_MVRF);
#endif
SCTP_HASH_FREE(inp->sctp_tcbhash, inp->sctp_hashmark);
so->so_pcb = NULL;
SCTP_ZONE_FREE(SCTP_BASE_INFO(ipi_zone_ep), inp);
SCTP_UNLOCK_EXC(SCTP_BASE_INFO(sctbinfo).ipi_lock);
SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, ENOMEM);
return (ENOMEM);
}
#elif defined(APPLE_LION) || defined(APPLE_MOUNTAINLION)
lck_mtx_init(&inp->ip_inp.inp.inpcb_mtx, SCTP_BASE_INFO(sctbinfo).mtx_grp, SCTP_BASE_INFO(sctbinfo).mtx_attr);
#else
lck_mtx_init(&inp->ip_inp.inp.inpcb_mtx, SCTP_BASE_INFO(sctbinfo).ipi_lock_grp, SCTP_BASE_INFO(sctbinfo).ipi_lock_attr);
#endif
#endif
SCTP_INP_INFO_WLOCK();
SCTP_INP_LOCK_INIT(inp);
#if defined(__FreeBSD__)
INP_LOCK_INIT(&inp->ip_inp.inp, "inp", "sctpinp");
#endif
SCTP_INP_READ_INIT(inp);
SCTP_ASOC_CREATE_LOCK_INIT(inp);
/* lock the new ep */
SCTP_INP_WLOCK(inp);
/* add it to the info area */
LIST_INSERT_HEAD(&SCTP_BASE_INFO(listhead), inp, sctp_list);
#if defined(__APPLE__)
inp->ip_inp.inp.inp_pcbinfo = &SCTP_BASE_INFO(sctbinfo);
#if defined(APPLE_LEOPARD) || defined(APPLE_SNOWLEOPARD) || defined(APPLE_LION) || defined(APPLE_MOUNTAINLION)
LIST_INSERT_HEAD(SCTP_BASE_INFO(sctbinfo).listhead, &inp->ip_inp.inp, inp_list);
#else
LIST_INSERT_HEAD(SCTP_BASE_INFO(sctbinfo).ipi_listhead, &inp->ip_inp.inp, inp_list);
#endif
#endif
SCTP_INP_INFO_WUNLOCK();
TAILQ_INIT(&inp->read_queue);
LIST_INIT(&inp->sctp_addr_list);
LIST_INIT(&inp->sctp_asoc_list);
#ifdef SCTP_TRACK_FREED_ASOCS
/* TEMP CODE */
LIST_INIT(&inp->sctp_asoc_free_list);
#endif
/* Init the timer structure for signature change */
SCTP_OS_TIMER_INIT(&inp->sctp_ep.signature_change.timer);
inp->sctp_ep.signature_change.type = SCTP_TIMER_TYPE_NEWCOOKIE;
/* now init the actual endpoint default data */
m = &inp->sctp_ep;
/* setup the base timeout information */
m->sctp_timeoutticks[SCTP_TIMER_SEND] = SEC_TO_TICKS(SCTP_SEND_SEC); /* needed ? */
m->sctp_timeoutticks[SCTP_TIMER_INIT] = SEC_TO_TICKS(SCTP_INIT_SEC); /* needed ? */
m->sctp_timeoutticks[SCTP_TIMER_RECV] = MSEC_TO_TICKS(SCTP_BASE_SYSCTL(sctp_delayed_sack_time_default));
m->sctp_timeoutticks[SCTP_TIMER_HEARTBEAT] = MSEC_TO_TICKS(SCTP_BASE_SYSCTL(sctp_heartbeat_interval_default));
m->sctp_timeoutticks[SCTP_TIMER_PMTU] = SEC_TO_TICKS(SCTP_BASE_SYSCTL(sctp_pmtu_raise_time_default));
m->sctp_timeoutticks[SCTP_TIMER_MAXSHUTDOWN] = SEC_TO_TICKS(SCTP_BASE_SYSCTL(sctp_shutdown_guard_time_default));
m->sctp_timeoutticks[SCTP_TIMER_SIGNATURE] = SEC_TO_TICKS(SCTP_BASE_SYSCTL(sctp_secret_lifetime_default));
/* all max/min max are in ms */
m->sctp_maxrto = SCTP_BASE_SYSCTL(sctp_rto_max_default);
m->sctp_minrto = SCTP_BASE_SYSCTL(sctp_rto_min_default);
m->initial_rto = SCTP_BASE_SYSCTL(sctp_rto_initial_default);
m->initial_init_rto_max = SCTP_BASE_SYSCTL(sctp_init_rto_max_default);
m->sctp_sack_freq = SCTP_BASE_SYSCTL(sctp_sack_freq_default);
m->max_init_times = SCTP_BASE_SYSCTL(sctp_init_rtx_max_default);
m->max_send_times = SCTP_BASE_SYSCTL(sctp_assoc_rtx_max_default);
m->def_net_failure = SCTP_BASE_SYSCTL(sctp_path_rtx_max_default);
m->def_net_pf_threshold = SCTP_BASE_SYSCTL(sctp_path_pf_threshold);
m->sctp_sws_sender = SCTP_SWS_SENDER_DEF;
m->sctp_sws_receiver = SCTP_SWS_RECEIVER_DEF;
m->max_burst = SCTP_BASE_SYSCTL(sctp_max_burst_default);
m->fr_max_burst = SCTP_BASE_SYSCTL(sctp_fr_max_burst_default);
m->sctp_default_cc_module = SCTP_BASE_SYSCTL(sctp_default_cc_module);
m->sctp_default_ss_module = SCTP_BASE_SYSCTL(sctp_default_ss_module);
m->max_open_streams_intome = SCTP_BASE_SYSCTL(sctp_nr_incoming_streams_default);
/* number of streams to pre-open on a association */
m->pre_open_stream_count = SCTP_BASE_SYSCTL(sctp_nr_outgoing_streams_default);
m->default_mtu = 0;
/* Add adaptation cookie */
m->adaptation_layer_indicator = 0;
m->adaptation_layer_indicator_provided = 0;
/* seed random number generator */
m->random_counter = 1;
m->store_at = SCTP_SIGNATURE_SIZE;
SCTP_READ_RANDOM(m->random_numbers, sizeof(m->random_numbers));
sctp_fill_random_store(m);
/* Minimum cookie size */
m->size_of_a_cookie = (sizeof(struct sctp_init_msg) * 2) +
sizeof(struct sctp_state_cookie);
m->size_of_a_cookie += SCTP_SIGNATURE_SIZE;
/* Setup the initial secret */
(void)SCTP_GETTIME_TIMEVAL(&time);
m->time_of_secret_change = time.tv_sec;
for (i = 0; i < SCTP_NUMBER_OF_SECRETS; i++) {
m->secret_key[0][i] = sctp_select_initial_TSN(m);
}
sctp_timer_start(SCTP_TIMER_TYPE_NEWCOOKIE, inp, NULL, NULL);
/* How long is a cookie good for ? */
m->def_cookie_life = MSEC_TO_TICKS(SCTP_BASE_SYSCTL(sctp_valid_cookie_life_default));
/*
* Initialize authentication parameters
*/
m->local_hmacs = sctp_default_supported_hmaclist();
m->local_auth_chunks = sctp_alloc_chunklist();
if (inp->asconf_supported) {
sctp_auth_add_chunk(SCTP_ASCONF, m->local_auth_chunks);
sctp_auth_add_chunk(SCTP_ASCONF_ACK, m->local_auth_chunks);
}
m->default_dscp = 0;
#ifdef INET6
m->default_flowlabel = 0;
#endif
m->port = 0; /* encapsulation disabled by default */
LIST_INIT(&m->shared_keys);
/* add default NULL key as key id 0 */
null_key = sctp_alloc_sharedkey();
sctp_insert_sharedkey(&m->shared_keys, null_key);
SCTP_INP_WUNLOCK(inp);
#ifdef SCTP_LOG_CLOSING
sctp_log_closing(inp, NULL, 12);
#endif
return (error);
}
void
sctp_move_pcb_and_assoc(struct sctp_inpcb *old_inp, struct sctp_inpcb *new_inp,
struct sctp_tcb *stcb)
{
struct sctp_nets *net;
uint16_t lport, rport;
struct sctppcbhead *head;
struct sctp_laddr *laddr, *oladdr;
atomic_add_int(&stcb->asoc.refcnt, 1);
SCTP_TCB_UNLOCK(stcb);
SCTP_INP_INFO_WLOCK();
SCTP_INP_WLOCK(old_inp);
SCTP_INP_WLOCK(new_inp);
SCTP_TCB_LOCK(stcb);
atomic_subtract_int(&stcb->asoc.refcnt, 1);
new_inp->sctp_ep.time_of_secret_change =
old_inp->sctp_ep.time_of_secret_change;
memcpy(new_inp->sctp_ep.secret_key, old_inp->sctp_ep.secret_key,
sizeof(old_inp->sctp_ep.secret_key));
new_inp->sctp_ep.current_secret_number =
old_inp->sctp_ep.current_secret_number;
new_inp->sctp_ep.last_secret_number =
old_inp->sctp_ep.last_secret_number;
new_inp->sctp_ep.size_of_a_cookie = old_inp->sctp_ep.size_of_a_cookie;
/* make it so new data pours into the new socket */
stcb->sctp_socket = new_inp->sctp_socket;
stcb->sctp_ep = new_inp;
/* Copy the port across */
lport = new_inp->sctp_lport = old_inp->sctp_lport;
rport = stcb->rport;
/* Pull the tcb from the old association */
LIST_REMOVE(stcb, sctp_tcbhash);
LIST_REMOVE(stcb, sctp_tcblist);
if (stcb->asoc.in_asocid_hash) {
LIST_REMOVE(stcb, sctp_tcbasocidhash);
}
/* Now insert the new_inp into the TCP connected hash */
head = &SCTP_BASE_INFO(sctp_tcpephash)[SCTP_PCBHASH_ALLADDR((lport | rport), SCTP_BASE_INFO(hashtcpmark))];
LIST_INSERT_HEAD(head, new_inp, sctp_hash);
/* Its safe to access */
new_inp->sctp_flags &= ~SCTP_PCB_FLAGS_UNBOUND;
/* Now move the tcb into the endpoint list */
LIST_INSERT_HEAD(&new_inp->sctp_asoc_list, stcb, sctp_tcblist);
/*
* Question, do we even need to worry about the ep-hash since we
* only have one connection? Probably not :> so lets get rid of it
* and not suck up any kernel memory in that.
*/
if (stcb->asoc.in_asocid_hash) {
struct sctpasochead *lhd;
lhd = &new_inp->sctp_asocidhash[SCTP_PCBHASH_ASOC(stcb->asoc.assoc_id,
new_inp->hashasocidmark)];
LIST_INSERT_HEAD(lhd, stcb, sctp_tcbasocidhash);
}
/* Ok. Let's restart timer. */
TAILQ_FOREACH(net, &stcb->asoc.nets, sctp_next) {
sctp_timer_start(SCTP_TIMER_TYPE_PATHMTURAISE, new_inp,
stcb, net);
}
SCTP_INP_INFO_WUNLOCK();
if (new_inp->sctp_tcbhash != NULL) {
SCTP_HASH_FREE(new_inp->sctp_tcbhash, new_inp->sctp_hashmark);
new_inp->sctp_tcbhash = NULL;
}
if ((new_inp->sctp_flags & SCTP_PCB_FLAGS_BOUNDALL) == 0) {
/* Subset bound, so copy in the laddr list from the old_inp */
LIST_FOREACH(oladdr, &old_inp->sctp_addr_list, sctp_nxt_addr) {
laddr = SCTP_ZONE_GET(SCTP_BASE_INFO(ipi_zone_laddr), struct sctp_laddr);
if (laddr == NULL) {
/*
* Gak, what can we do? This assoc is really
* HOSED. We probably should send an abort
* here.
*/
SCTPDBG(SCTP_DEBUG_PCB1, "Association hosed in TCP model, out of laddr memory\n");
continue;
}
SCTP_INCR_LADDR_COUNT();
memset(laddr, 0, sizeof(*laddr));
(void)SCTP_GETTIME_TIMEVAL(&laddr->start_time);
laddr->ifa = oladdr->ifa;
atomic_add_int(&laddr->ifa->refcount, 1);
LIST_INSERT_HEAD(&new_inp->sctp_addr_list, laddr,
sctp_nxt_addr);
new_inp->laddr_count++;
if (oladdr == stcb->asoc.last_used_address) {
stcb->asoc.last_used_address = laddr;
}
}
}
/* Now any running timers need to be adjusted
* since we really don't care if they are running
* or not just blast in the new_inp into all of
* them.
*/
stcb->asoc.dack_timer.ep = (void *)new_inp;
stcb->asoc.asconf_timer.ep = (void *)new_inp;
stcb->asoc.strreset_timer.ep = (void *)new_inp;
stcb->asoc.shut_guard_timer.ep = (void *)new_inp;
stcb->asoc.autoclose_timer.ep = (void *)new_inp;
stcb->asoc.delayed_event_timer.ep = (void *)new_inp;
stcb->asoc.delete_prim_timer.ep = (void *)new_inp;
/* now what about the nets? */
TAILQ_FOREACH(net, &stcb->asoc.nets, sctp_next) {
net->pmtu_timer.ep = (void *)new_inp;
net->hb_timer.ep = (void *)new_inp;
net->rxt_timer.ep = (void *)new_inp;
}
SCTP_INP_WUNLOCK(new_inp);
SCTP_INP_WUNLOCK(old_inp);
}
/*
* insert an laddr entry with the given ifa for the desired list
*/
static int
sctp_insert_laddr(struct sctpladdr *list, struct sctp_ifa *ifa, uint32_t act)
{
struct sctp_laddr *laddr;
laddr = SCTP_ZONE_GET(SCTP_BASE_INFO(ipi_zone_laddr), struct sctp_laddr);
if (laddr == NULL) {
/* out of memory? */
SCTP_LTRACE_ERR_RET(NULL, NULL, NULL, SCTP_FROM_SCTP_PCB, EINVAL);
return (EINVAL);
}
SCTP_INCR_LADDR_COUNT();
memset(laddr, 0, sizeof(*laddr));
(void)SCTP_GETTIME_TIMEVAL(&laddr->start_time);
laddr->ifa = ifa;
laddr->action = act;
atomic_add_int(&ifa->refcount, 1);
/* insert it */
LIST_INSERT_HEAD(list, laddr, sctp_nxt_addr);
return (0);
}
/*
* Remove an laddr entry from the local address list (on an assoc)
*/
static void
sctp_remove_laddr(struct sctp_laddr *laddr)
{
/* remove from the list */
LIST_REMOVE(laddr, sctp_nxt_addr);
sctp_free_ifa(laddr->ifa);
SCTP_ZONE_FREE(SCTP_BASE_INFO(ipi_zone_laddr), laddr);
SCTP_DECR_LADDR_COUNT();
}
#if !(defined(__FreeBSD__) || defined(__APPLE__) || defined(__Userspace__))
/*
* Don't know why, but without this there is an unknown reference when
* compiling NetBSD... hmm
*/
extern void in6_sin6_2_sin(struct sockaddr_in *, struct sockaddr_in6 *sin6);
#endif
/* sctp_ifap is used to bypass normal local address validation checks */
int
#if defined(__FreeBSD__) && __FreeBSD_version >= 500000
sctp_inpcb_bind(struct socket *so, struct sockaddr *addr,
struct sctp_ifa *sctp_ifap, struct thread *p)
#elif defined(__Windows__)
sctp_inpcb_bind(struct socket *so, struct sockaddr *addr,
struct sctp_ifa *sctp_ifap, PKTHREAD p)
#else
sctp_inpcb_bind(struct socket *so, struct sockaddr *addr,
struct sctp_ifa *sctp_ifap, struct proc *p)
#endif
{
/* bind a ep to a socket address */
struct sctppcbhead *head;
struct sctp_inpcb *inp, *inp_tmp;
#if defined(__FreeBSD__) || defined(__APPLE__)
struct inpcb *ip_inp;
#endif
int port_reuse_active = 0;
int bindall;
#ifdef SCTP_MVRF
int i;
#endif
uint16_t lport;
int error;
uint32_t vrf_id;
lport = 0;
bindall = 1;
inp = (struct sctp_inpcb *)so->so_pcb;
#if defined(__FreeBSD__) || defined(__APPLE__)
ip_inp = (struct inpcb *)so->so_pcb;
#endif
#ifdef SCTP_DEBUG
if (addr) {
SCTPDBG(SCTP_DEBUG_PCB1, "Bind called port: %d\n",
ntohs(((struct sockaddr_in *)addr)->sin_port));
SCTPDBG(SCTP_DEBUG_PCB1, "Addr: ");
SCTPDBG_ADDR(SCTP_DEBUG_PCB1, addr);
}
#endif
if ((inp->sctp_flags & SCTP_PCB_FLAGS_UNBOUND) == 0) {
/* already did a bind, subsequent binds NOT allowed ! */
SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, EINVAL);
return (EINVAL);
}
#if defined(__FreeBSD__) && __FreeBSD_version >= 500000
#ifdef INVARIANTS
if (p == NULL)
panic("null proc/thread");
#endif
#endif
if (addr != NULL) {
switch (addr->sa_family) {
#ifdef INET
case AF_INET:
{
struct sockaddr_in *sin;
/* IPV6_V6ONLY socket? */
if (SCTP_IPV6_V6ONLY(inp)) {
SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, EINVAL);
return (EINVAL);
}
#ifdef HAVE_SA_LEN
if (addr->sa_len != sizeof(*sin)) {
SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, EINVAL);
return (EINVAL);
}
#endif
sin = (struct sockaddr_in *)addr;
lport = sin->sin_port;
#if defined(__FreeBSD__) && __FreeBSD_version >= 800000
/*
* For LOOPBACK the prison_local_ip4() call will transmute the ip address
* to the proper value.
*/
if (p && (error = prison_local_ip4(p->td_ucred, &sin->sin_addr)) != 0) {
SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, error);
return (error);
}
#endif
if (sin->sin_addr.s_addr != INADDR_ANY) {
bindall = 0;
}
break;
}
#endif
#ifdef INET6
case AF_INET6:
{
/* Only for pure IPv6 Address. (No IPv4 Mapped!) */
struct sockaddr_in6 *sin6;
sin6 = (struct sockaddr_in6 *)addr;
#ifdef HAVE_SA_LEN
if (addr->sa_len != sizeof(*sin6)) {
SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, EINVAL);
return (EINVAL);
}
#endif
lport = sin6->sin6_port;
#if defined(__FreeBSD__) && __FreeBSD_version >= 800000
/*
* For LOOPBACK the prison_local_ip6() call will transmute the ipv6 address
* to the proper value.
*/
if (p && (error = prison_local_ip6(p->td_ucred, &sin6->sin6_addr,
(SCTP_IPV6_V6ONLY(inp) != 0))) != 0) {
SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, error);
return (error);
}
#endif
if (!IN6_IS_ADDR_UNSPECIFIED(&sin6->sin6_addr)) {
bindall = 0;
#ifdef SCTP_EMBEDDED_V6_SCOPE
/* KAME hack: embed scopeid */
#if defined(SCTP_KAME)
if (sa6_embedscope(sin6, MODULE_GLOBAL(ip6_use_defzone)) != 0) {
SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, EINVAL);
return (EINVAL);
}
#elif defined(__APPLE__)
#if defined(APPLE_LEOPARD) || defined(APPLE_SNOWLEOPARD)
if (in6_embedscope(&sin6->sin6_addr, sin6, ip_inp, NULL) != 0) {
#else
if (in6_embedscope(&sin6->sin6_addr, sin6, ip_inp, NULL, NULL) != 0) {
#endif
SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, EINVAL);
return (EINVAL);
}
#elif defined(__FreeBSD__)
error = scope6_check_id(sin6, MODULE_GLOBAL(ip6_use_defzone));
if (error != 0) {
SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, error);
return (error);
}
#else
if (in6_embedscope(&sin6->sin6_addr, sin6) != 0) {
SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, EINVAL);
return (EINVAL);
}
#endif
#endif /* SCTP_EMBEDDED_V6_SCOPE */
}
#ifndef SCOPEDROUTING
/* this must be cleared for ifa_ifwithaddr() */
sin6->sin6_scope_id = 0;
#endif /* SCOPEDROUTING */
break;
}
#endif
#if defined(__Userspace__)
case AF_CONN:
{
struct sockaddr_conn *sconn;
#ifdef HAVE_SA_LEN
if (addr->sa_len != sizeof(struct sockaddr_conn)) {
SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, EINVAL);
return (EINVAL);
}
#endif
sconn = (struct sockaddr_conn *)addr;
lport = sconn->sconn_port;
if (sconn->sconn_addr != NULL) {
bindall = 0;
}
break;
}
#endif
default:
SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, EAFNOSUPPORT);
return (EAFNOSUPPORT);
}
}
SCTP_INP_INFO_WLOCK();
SCTP_INP_WLOCK(inp);
/* Setup a vrf_id to be the default for the non-bind-all case. */
vrf_id = inp->def_vrf_id;
/* increase our count due to the unlock we do */
SCTP_INP_INCR_REF(inp);
if (lport) {
/*
* Did the caller specify a port? if so we must see if an ep
* already has this one bound.
*/
/* got to be root to get at low ports */
#if !defined(__Windows__)
if (ntohs(lport) < IPPORT_RESERVED) {
if ((p != NULL) && ((error =
#ifdef __FreeBSD__
#if __FreeBSD_version > 602000
priv_check(p, PRIV_NETINET_RESERVEDPORT)
#elif __FreeBSD_version >= 500000
suser_cred(p->td_ucred, 0)
#else
suser(p)
#endif
#elif defined(__APPLE__)
suser(p->p_ucred, &p->p_acflag)
#elif defined(__Userspace__) /* must be true to use raw socket */
1
#else
suser(p, 0)
#endif
) != 0)) {
SCTP_INP_DECR_REF(inp);
SCTP_INP_WUNLOCK(inp);
SCTP_INP_INFO_WUNLOCK();
return (error);
}
#if defined(__Panda__)
if (!SCTP_IS_PRIVILEDGED(so)) {
SCTP_INP_DECR_REF(inp);
SCTP_INP_WUNLOCK(inp);
SCTP_INP_INFO_WUNLOCK();
SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, EACCES);
return (EACCES);
}
#endif
}
#endif /* __Windows__ */
SCTP_INP_WUNLOCK(inp);
if (bindall) {
#ifdef SCTP_MVRF
for (i = 0; i < inp->num_vrfs; i++) {
vrf_id = inp->m_vrf_ids[i];
#else
vrf_id = inp->def_vrf_id;
#endif
inp_tmp = sctp_pcb_findep(addr, 0, 1, vrf_id);
if (inp_tmp != NULL) {
/*
* lock guy returned and lower count
* note that we are not bound so
* inp_tmp should NEVER be inp. And
* it is this inp (inp_tmp) that gets
* the reference bump, so we must
* lower it.
*/
SCTP_INP_DECR_REF(inp_tmp);
/* unlock info */
if ((sctp_is_feature_on(inp, SCTP_PCB_FLAGS_PORTREUSE)) &&
(sctp_is_feature_on(inp_tmp, SCTP_PCB_FLAGS_PORTREUSE))) {
/* Ok, must be one-2-one and allowing port re-use */
port_reuse_active = 1;
goto continue_anyway;
}
SCTP_INP_DECR_REF(inp);
SCTP_INP_INFO_WUNLOCK();
SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, EADDRINUSE);
return (EADDRINUSE);
}
#ifdef SCTP_MVRF
}
#endif
} else {
inp_tmp = sctp_pcb_findep(addr, 0, 1, vrf_id);
if (inp_tmp != NULL) {
/*
* lock guy returned and lower count note
* that we are not bound so inp_tmp should
* NEVER be inp. And it is this inp (inp_tmp)
* that gets the reference bump, so we must
* lower it.
*/
SCTP_INP_DECR_REF(inp_tmp);
/* unlock info */
if ((sctp_is_feature_on(inp, SCTP_PCB_FLAGS_PORTREUSE)) &&
(sctp_is_feature_on(inp_tmp, SCTP_PCB_FLAGS_PORTREUSE))) {
/* Ok, must be one-2-one and allowing port re-use */
port_reuse_active = 1;
goto continue_anyway;
}
SCTP_INP_DECR_REF(inp);
SCTP_INP_INFO_WUNLOCK();
SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, EADDRINUSE);
return (EADDRINUSE);
}
}
continue_anyway:
SCTP_INP_WLOCK(inp);
if (bindall) {
/* verify that no lport is not used by a singleton */
if ((port_reuse_active == 0) &&
(inp_tmp = sctp_isport_inuse(inp, lport, vrf_id))) {
/* Sorry someone already has this one bound */
if ((sctp_is_feature_on(inp, SCTP_PCB_FLAGS_PORTREUSE)) &&
(sctp_is_feature_on(inp_tmp, SCTP_PCB_FLAGS_PORTREUSE))) {
port_reuse_active = 1;
} else {
SCTP_INP_DECR_REF(inp);
SCTP_INP_WUNLOCK(inp);
SCTP_INP_INFO_WUNLOCK();
SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, EADDRINUSE);
return (EADDRINUSE);
}
}
}
} else {
uint16_t first, last, candidate;
uint16_t count;
int done;
#if defined(__Windows__)
first = 1;
last = 0xffff;
#else
#if defined(__Userspace__)
/* TODO ensure uid is 0, etc... */
#elif defined(__FreeBSD__) || defined(__APPLE__)
if (ip_inp->inp_flags & INP_HIGHPORT) {
first = MODULE_GLOBAL(ipport_hifirstauto);
last = MODULE_GLOBAL(ipport_hilastauto);
} else if (ip_inp->inp_flags & INP_LOWPORT) {
if (p && (error =
#ifdef __FreeBSD__
#if __FreeBSD_version > 602000
priv_check(p, PRIV_NETINET_RESERVEDPORT)
#elif __FreeBSD_version >= 500000
suser_cred(p->td_ucred, 0)
#else
suser(p)
#endif
#elif defined(__APPLE__)
suser(p->p_ucred, &p->p_acflag)
#else
suser(p, 0)
#endif
)) {
SCTP_INP_DECR_REF(inp);
SCTP_INP_WUNLOCK(inp);
SCTP_INP_INFO_WUNLOCK();
SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, error);
return (error);
}
first = MODULE_GLOBAL(ipport_lowfirstauto);
last = MODULE_GLOBAL(ipport_lowlastauto);
} else {
#endif
first = MODULE_GLOBAL(ipport_firstauto);
last = MODULE_GLOBAL(ipport_lastauto);
#if defined(__FreeBSD__) || defined(__APPLE__)
}
#endif
#endif /* __Windows__ */
if (first > last) {
uint16_t temp;
temp = first;
first = last;
last = temp;
}
count = last - first + 1; /* number of candidates */
candidate = first + sctp_select_initial_TSN(&inp->sctp_ep) % (count);
done = 0;
while (!done) {
#ifdef SCTP_MVRF
for (i = 0; i < inp->num_vrfs; i++) {
if (sctp_isport_inuse(inp, htons(candidate), inp->m_vrf_ids[i]) != NULL) {
break;
}
}
if (i == inp->num_vrfs) {
done = 1;
}
#else
if (sctp_isport_inuse(inp, htons(candidate), inp->def_vrf_id) == NULL) {
done = 1;
}
#endif
if (!done) {
if (--count == 0) {
SCTP_INP_DECR_REF(inp);
SCTP_INP_WUNLOCK(inp);
SCTP_INP_INFO_WUNLOCK();
SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, EADDRINUSE);
return (EADDRINUSE);
}
if (candidate == last)
candidate = first;
else
candidate = candidate + 1;
}
}
lport = htons(candidate);
}
SCTP_INP_DECR_REF(inp);
if (inp->sctp_flags & (SCTP_PCB_FLAGS_SOCKET_GONE |
SCTP_PCB_FLAGS_SOCKET_ALLGONE)) {
/*
* this really should not happen. The guy did a non-blocking
* bind and then did a close at the same time.
*/
SCTP_INP_WUNLOCK(inp);
SCTP_INP_INFO_WUNLOCK();
SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, EINVAL);
return (EINVAL);
}
/* ok we look clear to give out this port, so lets setup the binding */
if (bindall) {
/* binding to all addresses, so just set in the proper flags */
inp->sctp_flags |= SCTP_PCB_FLAGS_BOUNDALL;
/* set the automatic addr changes from kernel flag */
if (SCTP_BASE_SYSCTL(sctp_auto_asconf) == 0) {
sctp_feature_off(inp, SCTP_PCB_FLAGS_DO_ASCONF);
sctp_feature_off(inp, SCTP_PCB_FLAGS_AUTO_ASCONF);
} else {
sctp_feature_on(inp, SCTP_PCB_FLAGS_DO_ASCONF);
sctp_feature_on(inp, SCTP_PCB_FLAGS_AUTO_ASCONF);
}
if (SCTP_BASE_SYSCTL(sctp_multiple_asconfs) == 0) {
sctp_feature_off(inp, SCTP_PCB_FLAGS_MULTIPLE_ASCONFS);
} else {
sctp_feature_on(inp, SCTP_PCB_FLAGS_MULTIPLE_ASCONFS);
}
/* set the automatic mobility_base from kernel
flag (by micchie)
*/
if (SCTP_BASE_SYSCTL(sctp_mobility_base) == 0) {
sctp_mobility_feature_off(inp, SCTP_MOBILITY_BASE);
sctp_mobility_feature_off(inp, SCTP_MOBILITY_PRIM_DELETED);
} else {
sctp_mobility_feature_on(inp, SCTP_MOBILITY_BASE);
sctp_mobility_feature_off(inp, SCTP_MOBILITY_PRIM_DELETED);
}
/* set the automatic mobility_fasthandoff from kernel
flag (by micchie)
*/
if (SCTP_BASE_SYSCTL(sctp_mobility_fasthandoff) == 0) {
sctp_mobility_feature_off(inp, SCTP_MOBILITY_FASTHANDOFF);
sctp_mobility_feature_off(inp, SCTP_MOBILITY_PRIM_DELETED);
} else {
sctp_mobility_feature_on(inp, SCTP_MOBILITY_FASTHANDOFF);
sctp_mobility_feature_off(inp, SCTP_MOBILITY_PRIM_DELETED);
}
} else {
/*
* bind specific, make sure flags is off and add a new
* address structure to the sctp_addr_list inside the ep
* structure.
*
* We will need to allocate one and insert it at the head. The
* socketopt call can just insert new addresses in there as
* well. It will also have to do the embed scope kame hack
* too (before adding).
*/
struct sctp_ifa *ifa;
union sctp_sockstore store;
memset(&store, 0, sizeof(store));
switch (addr->sa_family) {
#ifdef INET
case AF_INET:
memcpy(&store.sin, addr, sizeof(struct sockaddr_in));
store.sin.sin_port = 0;
break;
#endif
#ifdef INET6
case AF_INET6:
memcpy(&store.sin6, addr, sizeof(struct sockaddr_in6));
store.sin6.sin6_port = 0;
break;
#endif
#if defined(__Userspace__)
case AF_CONN:
memcpy(&store.sconn, addr, sizeof(struct sockaddr_conn));
store.sconn.sconn_port = 0;
break;
#endif
default:
break;
}
/*
* first find the interface with the bound address need to
* zero out the port to find the address! yuck! can't do
* this earlier since need port for sctp_pcb_findep()
*/
if (sctp_ifap != NULL) {
ifa = sctp_ifap;
} else {
/* Note for BSD we hit here always other
* O/S's will pass things in via the
* sctp_ifap argument (Panda).
*/
ifa = sctp_find_ifa_by_addr(&store.sa,
vrf_id, SCTP_ADDR_NOT_LOCKED);
}
if (ifa == NULL) {
/* Can't find an interface with that address */
SCTP_INP_WUNLOCK(inp);
SCTP_INP_INFO_WUNLOCK();
SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, EADDRNOTAVAIL);
return (EADDRNOTAVAIL);
}
#ifdef INET6
if (addr->sa_family == AF_INET6) {
/* GAK, more FIXME IFA lock? */
if (ifa->localifa_flags & SCTP_ADDR_IFA_UNUSEABLE) {
/* Can't bind a non-existent addr. */
SCTP_INP_WUNLOCK(inp);
SCTP_INP_INFO_WUNLOCK();
SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, EINVAL);
return (EINVAL);
}
}
#endif
/* we're not bound all */
inp->sctp_flags &= ~SCTP_PCB_FLAGS_BOUNDALL;
/* allow bindx() to send ASCONF's for binding changes */
sctp_feature_on(inp, SCTP_PCB_FLAGS_DO_ASCONF);
/* clear automatic addr changes from kernel flag */
sctp_feature_off(inp, SCTP_PCB_FLAGS_AUTO_ASCONF);
/* add this address to the endpoint list */
error = sctp_insert_laddr(&inp->sctp_addr_list, ifa, 0);
if (error != 0) {
SCTP_INP_WUNLOCK(inp);
SCTP_INP_INFO_WUNLOCK();
return (error);
}
inp->laddr_count++;
}
/* find the bucket */
if (port_reuse_active) {
/* Put it into tcp 1-2-1 hash */
head = &SCTP_BASE_INFO(sctp_tcpephash)[SCTP_PCBHASH_ALLADDR(lport, SCTP_BASE_INFO(hashtcpmark))];
inp->sctp_flags |= SCTP_PCB_FLAGS_IN_TCPPOOL;
} else {
head = &SCTP_BASE_INFO(sctp_ephash)[SCTP_PCBHASH_ALLADDR(lport, SCTP_BASE_INFO(hashmark))];
}
/* put it in the bucket */
LIST_INSERT_HEAD(head, inp, sctp_hash);
SCTPDBG(SCTP_DEBUG_PCB1, "Main hash to bind at head:%p, bound port:%d - in tcp_pool=%d\n",
(void *)head, ntohs(lport), port_reuse_active);
/* set in the port */
inp->sctp_lport = lport;
/* turn off just the unbound flag */
inp->sctp_flags &= ~SCTP_PCB_FLAGS_UNBOUND;
SCTP_INP_WUNLOCK(inp);
SCTP_INP_INFO_WUNLOCK();
return (0);
}
static void
sctp_iterator_inp_being_freed(struct sctp_inpcb *inp)
{
struct sctp_iterator *it, *nit;
/*
* We enter with the only the ITERATOR_LOCK in place and a write
* lock on the inp_info stuff.
*/
it = sctp_it_ctl.cur_it;
#if defined(__FreeBSD__) && __FreeBSD_version >= 801000
if (it && (it->vn != curvnet)) {
/* Its not looking at our VNET */
return;
}
#endif
if (it && (it->inp == inp)) {
/*
* This is tricky and we hold the iterator lock,
* but when it returns and gets the lock (when we
* release it) the iterator will try to operate on
* inp. We need to stop that from happening. But
* of course the iterator has a reference on the
* stcb and inp. We can mark it and it will stop.
*
* If its a single iterator situation, we
* set the end iterator flag. Otherwise
* we set the iterator to go to the next inp.
*
*/
if (it->iterator_flags & SCTP_ITERATOR_DO_SINGLE_INP) {
sctp_it_ctl.iterator_flags |= SCTP_ITERATOR_STOP_CUR_IT;
} else {
sctp_it_ctl.iterator_flags |= SCTP_ITERATOR_STOP_CUR_INP;
}
}
/* Now go through and remove any single reference to
* our inp that may be still pending on the list
*/
SCTP_IPI_ITERATOR_WQ_LOCK();
TAILQ_FOREACH_SAFE(it, &sctp_it_ctl.iteratorhead, sctp_nxt_itr, nit) {
#if defined(__FreeBSD__) && __FreeBSD_version >= 801000
if (it->vn != curvnet) {
continue;
}
#endif
if (it->inp == inp) {
/* This one points to me is it inp specific? */
if (it->iterator_flags & SCTP_ITERATOR_DO_SINGLE_INP) {
/* Remove and free this one */
TAILQ_REMOVE(&sctp_it_ctl.iteratorhead,
it, sctp_nxt_itr);
if (it->function_atend != NULL) {
(*it->function_atend) (it->pointer, it->val);
}
SCTP_FREE(it, SCTP_M_ITER);
} else {
it->inp = LIST_NEXT(it->inp, sctp_list);
if (it->inp) {
SCTP_INP_INCR_REF(it->inp);
}
}
/* When its put in the refcnt is incremented so decr it */
SCTP_INP_DECR_REF(inp);
}
}
SCTP_IPI_ITERATOR_WQ_UNLOCK();
}
/* release sctp_inpcb unbind the port */
void
sctp_inpcb_free(struct sctp_inpcb *inp, int immediate, int from)
{
/*
* Here we free a endpoint. We must find it (if it is in the Hash
* table) and remove it from there. Then we must also find it in the
* overall list and remove it from there. After all removals are
* complete then any timer has to be stopped. Then start the actual
* freeing. a) Any local lists. b) Any associations. c) The hash of
* all associations. d) finally the ep itself.
*/
struct sctp_tcb *asoc, *nasoc;
struct sctp_laddr *laddr, *nladdr;
struct inpcb *ip_pcb;
struct socket *so;
int being_refed = 0;
struct sctp_queued_to_read *sq, *nsq;
#if !defined(__Panda__) && !defined(__Userspace__)
#if !defined(__FreeBSD__) || __FreeBSD_version < 500000
sctp_rtentry_t *rt;
#endif
#endif
int cnt;
sctp_sharedkey_t *shared_key, *nshared_key;
#if defined(__APPLE__)
sctp_lock_assert(SCTP_INP_SO(inp));
#endif
#ifdef SCTP_LOG_CLOSING
sctp_log_closing(inp, NULL, 0);
#endif
SCTP_ITERATOR_LOCK();
/* mark any iterators on the list or being processed */
sctp_iterator_inp_being_freed(inp);
SCTP_ITERATOR_UNLOCK();
so = inp->sctp_socket;
if (inp->sctp_flags & SCTP_PCB_FLAGS_SOCKET_ALLGONE) {
/* been here before.. eeks.. get out of here */
SCTP_PRINTF("This conflict in free SHOULD not be happening! from %d, imm %d\n", from, immediate);
#ifdef SCTP_LOG_CLOSING
sctp_log_closing(inp, NULL, 1);
#endif
return;
}
SCTP_ASOC_CREATE_LOCK(inp);
SCTP_INP_INFO_WLOCK();
SCTP_INP_WLOCK(inp);
if (from == SCTP_CALLED_AFTER_CMPSET_OFCLOSE) {
inp->sctp_flags &= ~SCTP_PCB_FLAGS_CLOSE_IP;
/* socket is gone, so no more wakeups allowed */
inp->sctp_flags |= SCTP_PCB_FLAGS_DONT_WAKE;
inp->sctp_flags &= ~SCTP_PCB_FLAGS_WAKEINPUT;
inp->sctp_flags &= ~SCTP_PCB_FLAGS_WAKEOUTPUT;
}
/* First time through we have the socket lock, after that no more. */
sctp_timer_stop(SCTP_TIMER_TYPE_NEWCOOKIE, inp, NULL, NULL,
SCTP_FROM_SCTP_PCB + SCTP_LOC_1);
if (inp->control) {
sctp_m_freem(inp->control);
inp->control = NULL;
}
if (inp->pkt) {
sctp_m_freem(inp->pkt);
inp->pkt = NULL;
}
ip_pcb = &inp->ip_inp.inp; /* we could just cast the main pointer
* here but I will be nice :> (i.e.
* ip_pcb = ep;) */
if (immediate == SCTP_FREE_SHOULD_USE_GRACEFUL_CLOSE) {
int cnt_in_sd;
cnt_in_sd = 0;
LIST_FOREACH_SAFE(asoc, &inp->sctp_asoc_list, sctp_tcblist, nasoc) {
SCTP_TCB_LOCK(asoc);
if (asoc->asoc.state & SCTP_STATE_ABOUT_TO_BE_FREED) {
/* Skip guys being freed */
cnt_in_sd++;
if (asoc->asoc.state & SCTP_STATE_IN_ACCEPT_QUEUE) {
/*
* Special case - we did not start a kill
* timer on the asoc due to it was not
* closed. So go ahead and start it now.
*/
SCTP_CLEAR_SUBSTATE(asoc, SCTP_STATE_IN_ACCEPT_QUEUE);
sctp_timer_start(SCTP_TIMER_TYPE_ASOCKILL, inp, asoc, NULL);
}
SCTP_TCB_UNLOCK(asoc);
continue;
}
if (((SCTP_GET_STATE(asoc) == SCTP_STATE_COOKIE_WAIT) ||
(SCTP_GET_STATE(asoc) == SCTP_STATE_COOKIE_ECHOED)) &&
(asoc->asoc.total_output_queue_size == 0)) {
/* If we have data in queue, we don't want to just
* free since the app may have done, send()/close
* or connect/send/close. And it wants the data
* to get across first.
*/
/* Just abandon things in the front states */
if (sctp_free_assoc(inp, asoc, SCTP_PCBFREE_NOFORCE,
SCTP_FROM_SCTP_PCB + SCTP_LOC_2) == 0) {
cnt_in_sd++;
}
continue;
}
/* Disconnect the socket please */
asoc->sctp_socket = NULL;
SCTP_ADD_SUBSTATE(asoc, SCTP_STATE_CLOSED_SOCKET);
if ((asoc->asoc.size_on_reasm_queue > 0) ||
(asoc->asoc.control_pdapi) ||
(asoc->asoc.size_on_all_streams > 0) ||
(so && (so->so_rcv.sb_cc > 0))) {
/* Left with Data unread */
struct mbuf *op_err;
op_err = sctp_generate_cause(SCTP_CAUSE_USER_INITIATED_ABT, "");
asoc->sctp_ep->last_abort_code = SCTP_FROM_SCTP_PCB + SCTP_LOC_3;
sctp_send_abort_tcb(asoc, op_err, SCTP_SO_LOCKED);
SCTP_STAT_INCR_COUNTER32(sctps_aborted);
if ((SCTP_GET_STATE(asoc) == SCTP_STATE_OPEN) ||
(SCTP_GET_STATE(asoc) == SCTP_STATE_SHUTDOWN_RECEIVED)) {
SCTP_STAT_DECR_GAUGE32(sctps_currestab);
}
if (sctp_free_assoc(inp, asoc,
SCTP_PCBFREE_NOFORCE, SCTP_FROM_SCTP_PCB + SCTP_LOC_4) == 0) {
cnt_in_sd++;
}
continue;
} else if (TAILQ_EMPTY(&asoc->asoc.send_queue) &&
TAILQ_EMPTY(&asoc->asoc.sent_queue) &&
(asoc->asoc.stream_queue_cnt == 0)) {
if ((*asoc->asoc.ss_functions.sctp_ss_is_user_msgs_incomplete)(asoc, &asoc->asoc)) {
goto abort_anyway;
}
if ((SCTP_GET_STATE(asoc) != SCTP_STATE_SHUTDOWN_SENT) &&
(SCTP_GET_STATE(asoc) != SCTP_STATE_SHUTDOWN_ACK_SENT)) {
struct sctp_nets *netp;
/*
* there is nothing queued to send,
* so I send shutdown
*/
if ((SCTP_GET_STATE(asoc) == SCTP_STATE_OPEN) ||
(SCTP_GET_STATE(asoc) == SCTP_STATE_SHUTDOWN_RECEIVED)) {
SCTP_STAT_DECR_GAUGE32(sctps_currestab);
}
SCTP_SET_STATE(asoc, SCTP_STATE_SHUTDOWN_SENT);
sctp_stop_timers_for_shutdown(asoc);
if (asoc->asoc.alternate) {
netp = asoc->asoc.alternate;
} else {
netp = asoc->asoc.primary_destination;
}
sctp_send_shutdown(asoc, netp);
sctp_timer_start(SCTP_TIMER_TYPE_SHUTDOWN, asoc->sctp_ep, asoc,
netp);
sctp_timer_start(SCTP_TIMER_TYPE_SHUTDOWNGUARD, asoc->sctp_ep, asoc,
asoc->asoc.primary_destination);
sctp_chunk_output(inp, asoc, SCTP_OUTPUT_FROM_SHUT_TMR, SCTP_SO_LOCKED);
}
} else {
/* mark into shutdown pending */
SCTP_ADD_SUBSTATE(asoc, SCTP_STATE_SHUTDOWN_PENDING);
sctp_timer_start(SCTP_TIMER_TYPE_SHUTDOWNGUARD, asoc->sctp_ep, asoc,
asoc->asoc.primary_destination);
if ((*asoc->asoc.ss_functions.sctp_ss_is_user_msgs_incomplete)(asoc, &asoc->asoc)) {
SCTP_ADD_SUBSTATE(asoc, SCTP_STATE_PARTIAL_MSG_LEFT);
}
if (TAILQ_EMPTY(&asoc->asoc.send_queue) &&
TAILQ_EMPTY(&asoc->asoc.sent_queue) &&
(asoc->asoc.state & SCTP_STATE_PARTIAL_MSG_LEFT)) {
struct mbuf *op_err;
abort_anyway:
op_err = sctp_generate_cause(SCTP_CAUSE_USER_INITIATED_ABT, "");
asoc->sctp_ep->last_abort_code = SCTP_FROM_SCTP_PCB + SCTP_LOC_5;
sctp_send_abort_tcb(asoc, op_err, SCTP_SO_LOCKED);
SCTP_STAT_INCR_COUNTER32(sctps_aborted);
if ((SCTP_GET_STATE(asoc) == SCTP_STATE_OPEN) ||
(SCTP_GET_STATE(asoc) == SCTP_STATE_SHUTDOWN_RECEIVED)) {
SCTP_STAT_DECR_GAUGE32(sctps_currestab);
}
if (sctp_free_assoc(inp, asoc,
SCTP_PCBFREE_NOFORCE,
SCTP_FROM_SCTP_PCB + SCTP_LOC_6) == 0) {
cnt_in_sd++;
}
continue;
} else {
sctp_chunk_output(inp, asoc, SCTP_OUTPUT_FROM_CLOSING, SCTP_SO_LOCKED);
}
}
cnt_in_sd++;
SCTP_TCB_UNLOCK(asoc);
}
/* now is there some left in our SHUTDOWN state? */
if (cnt_in_sd) {
#ifdef SCTP_LOG_CLOSING
sctp_log_closing(inp, NULL, 2);
#endif
inp->sctp_socket = NULL;
SCTP_INP_WUNLOCK(inp);
SCTP_ASOC_CREATE_UNLOCK(inp);
SCTP_INP_INFO_WUNLOCK();
return;
}
}
inp->sctp_socket = NULL;
if ((inp->sctp_flags & SCTP_PCB_FLAGS_UNBOUND) !=
SCTP_PCB_FLAGS_UNBOUND) {
/*
* ok, this guy has been bound. It's port is
* somewhere in the SCTP_BASE_INFO(hash table). Remove
* it!
*/
LIST_REMOVE(inp, sctp_hash);
inp->sctp_flags |= SCTP_PCB_FLAGS_UNBOUND;
}
/* If there is a timer running to kill us,
* forget it, since it may have a contest
* on the INP lock.. which would cause us
* to die ...
*/
cnt = 0;
LIST_FOREACH_SAFE(asoc, &inp->sctp_asoc_list, sctp_tcblist, nasoc) {
SCTP_TCB_LOCK(asoc);
if (asoc->asoc.state & SCTP_STATE_ABOUT_TO_BE_FREED) {
if (asoc->asoc.state & SCTP_STATE_IN_ACCEPT_QUEUE) {
SCTP_CLEAR_SUBSTATE(asoc, SCTP_STATE_IN_ACCEPT_QUEUE);
sctp_timer_start(SCTP_TIMER_TYPE_ASOCKILL, inp, asoc, NULL);
}
cnt++;
SCTP_TCB_UNLOCK(asoc);
continue;
}
/* Free associations that are NOT killing us */
if ((SCTP_GET_STATE(asoc) != SCTP_STATE_COOKIE_WAIT) &&
((asoc->asoc.state & SCTP_STATE_ABOUT_TO_BE_FREED) == 0)) {
struct mbuf *op_err;
op_err = sctp_generate_cause(SCTP_CAUSE_USER_INITIATED_ABT, "");
asoc->sctp_ep->last_abort_code = SCTP_FROM_SCTP_PCB + SCTP_LOC_7;
sctp_send_abort_tcb(asoc, op_err, SCTP_SO_LOCKED);
SCTP_STAT_INCR_COUNTER32(sctps_aborted);
} else if (asoc->asoc.state & SCTP_STATE_ABOUT_TO_BE_FREED) {
cnt++;
SCTP_TCB_UNLOCK(asoc);
continue;
}
if ((SCTP_GET_STATE(asoc) == SCTP_STATE_OPEN) ||
(SCTP_GET_STATE(asoc) == SCTP_STATE_SHUTDOWN_RECEIVED)) {
SCTP_STAT_DECR_GAUGE32(sctps_currestab);
}
if (sctp_free_assoc(inp, asoc, SCTP_PCBFREE_FORCE,
SCTP_FROM_SCTP_PCB + SCTP_LOC_8) == 0) {
cnt++;
}
}
if (cnt) {
/* Ok we have someone out there that will kill us */
(void)SCTP_OS_TIMER_STOP(&inp->sctp_ep.signature_change.timer);
#ifdef SCTP_LOG_CLOSING
sctp_log_closing(inp, NULL, 3);
#endif
SCTP_INP_WUNLOCK(inp);
SCTP_ASOC_CREATE_UNLOCK(inp);
SCTP_INP_INFO_WUNLOCK();
return;
}
if (SCTP_INP_LOCK_CONTENDED(inp))
being_refed++;
if (SCTP_INP_READ_CONTENDED(inp))
being_refed++;
if (SCTP_ASOC_CREATE_LOCK_CONTENDED(inp))
being_refed++;
if ((inp->refcount) ||
(being_refed) ||
(inp->sctp_flags & SCTP_PCB_FLAGS_CLOSE_IP)) {
(void)SCTP_OS_TIMER_STOP(&inp->sctp_ep.signature_change.timer);
#ifdef SCTP_LOG_CLOSING
sctp_log_closing(inp, NULL, 4);
#endif
sctp_timer_start(SCTP_TIMER_TYPE_INPKILL, inp, NULL, NULL);
SCTP_INP_WUNLOCK(inp);
SCTP_ASOC_CREATE_UNLOCK(inp);
SCTP_INP_INFO_WUNLOCK();
return;
}
inp->sctp_ep.signature_change.type = 0;
inp->sctp_flags |= SCTP_PCB_FLAGS_SOCKET_ALLGONE;
/* Remove it from the list .. last thing we need a
* lock for.
*/
LIST_REMOVE(inp, sctp_list);
SCTP_INP_WUNLOCK(inp);
SCTP_ASOC_CREATE_UNLOCK(inp);
SCTP_INP_INFO_WUNLOCK();
/* Now we release all locks. Since this INP
* cannot be found anymore except possibly by the
* kill timer that might be running. We call
* the drain function here. It should hit the case
* were it sees the ACTIVE flag cleared and exit
* out freeing us to proceed and destroy everything.
*/
if (from != SCTP_CALLED_FROM_INPKILL_TIMER) {
(void)SCTP_OS_TIMER_STOP_DRAIN(&inp->sctp_ep.signature_change.timer);
} else {
/* Probably un-needed */
(void)SCTP_OS_TIMER_STOP(&inp->sctp_ep.signature_change.timer);
}
#ifdef SCTP_LOG_CLOSING
sctp_log_closing(inp, NULL, 5);
#endif
#if !(defined(__Panda__) || defined(__Windows__) || defined(__Userspace__))
#if !defined(__FreeBSD__) || __FreeBSD_version < 500000
rt = ip_pcb->inp_route.ro_rt;
#endif
#endif
if ((inp->sctp_asocidhash) != NULL) {
SCTP_HASH_FREE(inp->sctp_asocidhash, inp->hashasocidmark);
inp->sctp_asocidhash = NULL;
}
/*sa_ignore FREED_MEMORY*/
TAILQ_FOREACH_SAFE(sq, &inp->read_queue, next, nsq) {
/* Its only abandoned if it had data left */
if (sq->length)
SCTP_STAT_INCR(sctps_left_abandon);
TAILQ_REMOVE(&inp->read_queue, sq, next);
sctp_free_remote_addr(sq->whoFrom);
if (so)
so->so_rcv.sb_cc -= sq->length;
if (sq->data) {
sctp_m_freem(sq->data);
sq->data = NULL;
}
/*
* no need to free the net count, since at this point all
* assoc's are gone.
*/
sctp_free_a_readq(NULL, sq);
}
/* Now the sctp_pcb things */
/*
* free each asoc if it is not already closed/free. we can't use the
* macro here since le_next will get freed as part of the
* sctp_free_assoc() call.
*/
#ifndef __Panda__
if (ip_pcb->inp_options) {
(void)sctp_m_free(ip_pcb->inp_options);
ip_pcb->inp_options = 0;
}
#endif
#if !(defined(__Panda__) || defined(__Windows__) || defined(__Userspace__))
#if !defined(__FreeBSD__) || __FreeBSD_version < 500000
if (rt) {
RTFREE(rt);
ip_pcb->inp_route.ro_rt = 0;
}
#endif
#if defined(__FreeBSD__) && __FreeBSD_version < 803000
#ifdef INET
if (ip_pcb->inp_moptions) {
inp_freemoptions(ip_pcb->inp_moptions);
ip_pcb->inp_moptions = 0;
}
#endif
#endif
#endif
#ifdef INET6
#if !(defined(__Panda__) || defined(__Windows__) || defined(__Userspace__))
#if defined(__FreeBSD__) || defined(__APPLE__)
if (ip_pcb->inp_vflag & INP_IPV6) {
#else
if (inp->inp_vflag & INP_IPV6) {
#endif
ip6_freepcbopts(ip_pcb->in6p_outputopts);
}
#endif
#endif /* INET6 */
#if !(defined(__FreeBSD__) || defined(__APPLE__) || defined(__Windows__) || defined(__Userspace__))
inp->inp_vflag = 0;
#else
ip_pcb->inp_vflag = 0;
#endif
/* free up authentication fields */
if (inp->sctp_ep.local_auth_chunks != NULL)
sctp_free_chunklist(inp->sctp_ep.local_auth_chunks);
if (inp->sctp_ep.local_hmacs != NULL)
sctp_free_hmaclist(inp->sctp_ep.local_hmacs);
LIST_FOREACH_SAFE(shared_key, &inp->sctp_ep.shared_keys, next, nshared_key) {
LIST_REMOVE(shared_key, next);
sctp_free_sharedkey(shared_key);
/*sa_ignore FREED_MEMORY*/
}
#if defined(__APPLE__)
inp->ip_inp.inp.inp_state = INPCB_STATE_DEAD;
if (in_pcb_checkstate(&inp->ip_inp.inp, WNT_STOPUSING, 1) != WNT_STOPUSING) {
#ifdef INVARIANTS
panic("sctp_inpcb_free inp = %p couldn't set to STOPUSING\n", (void *)inp);
#else
SCTP_PRINTF("sctp_inpcb_free inp = %p couldn't set to STOPUSING\n", (void *)inp);
#endif
}
inp->ip_inp.inp.inp_socket->so_flags |= SOF_PCBCLEARING;
#endif
/*
* if we have an address list the following will free the list of
* ifaddr's that are set into this ep. Again macro limitations here,
* since the LIST_FOREACH could be a bad idea.
*/
LIST_FOREACH_SAFE(laddr, &inp->sctp_addr_list, sctp_nxt_addr, nladdr) {
sctp_remove_laddr(laddr);
}
#ifdef SCTP_TRACK_FREED_ASOCS
/* TEMP CODE */
LIST_FOREACH_SAFE(asoc, &inp->sctp_asoc_free_list, sctp_tcblist, nasoc) {
LIST_REMOVE(asoc, sctp_tcblist);
SCTP_ZONE_FREE(SCTP_BASE_INFO(ipi_zone_asoc), asoc);
SCTP_DECR_ASOC_COUNT();
}
/* *** END TEMP CODE ****/
#endif
#ifdef SCTP_MVRF
SCTP_FREE(inp->m_vrf_ids, SCTP_M_MVRF);
#endif
/* Now lets see about freeing the EP hash table. */
if (inp->sctp_tcbhash != NULL) {
SCTP_HASH_FREE(inp->sctp_tcbhash, inp->sctp_hashmark);
inp->sctp_tcbhash = NULL;
}
/* Now we must put the ep memory back into the zone pool */
#if defined(__FreeBSD__)
crfree(inp->ip_inp.inp.inp_cred);
INP_LOCK_DESTROY(&inp->ip_inp.inp);
#endif
SCTP_INP_LOCK_DESTROY(inp);
SCTP_INP_READ_DESTROY(inp);
SCTP_ASOC_CREATE_LOCK_DESTROY(inp);
#if !defined(__APPLE__)
SCTP_ZONE_FREE(SCTP_BASE_INFO(ipi_zone_ep), inp);
SCTP_DECR_EP_COUNT();
#else
/* For Tiger, we will do this later... */
#endif
}
struct sctp_nets *
sctp_findnet(struct sctp_tcb *stcb, struct sockaddr *addr)
{
struct sctp_nets *net;
/* locate the address */
TAILQ_FOREACH(net, &stcb->asoc.nets, sctp_next) {
if (sctp_cmpaddr(addr, (struct sockaddr *)&net->ro._l_addr))
return (net);
}
return (NULL);
}
int
sctp_is_address_on_local_host(struct sockaddr *addr, uint32_t vrf_id)
{
#ifdef __Panda__
return (0);
#else
struct sctp_ifa *sctp_ifa;
sctp_ifa = sctp_find_ifa_by_addr(addr, vrf_id, SCTP_ADDR_NOT_LOCKED);
if (sctp_ifa) {
return (1);
} else {
return (0);
}
#endif
}
/*
* add's a remote endpoint address, done with the INIT/INIT-ACK as well as
* when a ASCONF arrives that adds it. It will also initialize all the cwnd
* stats of stuff.
*/
int
sctp_add_remote_addr(struct sctp_tcb *stcb, struct sockaddr *newaddr,
struct sctp_nets **netp, uint16_t port, int set_scope, int from)
{
/*
* The following is redundant to the same lines in the
* sctp_aloc_assoc() but is needed since others call the add
* address function
*/
struct sctp_nets *net, *netfirst;
int addr_inscope;
SCTPDBG(SCTP_DEBUG_PCB1, "Adding an address (from:%d) to the peer: ",
from);
SCTPDBG_ADDR(SCTP_DEBUG_PCB1, newaddr);
netfirst = sctp_findnet(stcb, newaddr);
if (netfirst) {
/*
* Lie and return ok, we don't want to make the association
* go away for this behavior. It will happen in the TCP
* model in a connected socket. It does not reach the hash
* table until after the association is built so it can't be
* found. Mark as reachable, since the initial creation will
* have been cleared and the NOT_IN_ASSOC flag will have
* been added... and we don't want to end up removing it
* back out.
*/
if (netfirst->dest_state & SCTP_ADDR_UNCONFIRMED) {
netfirst->dest_state = (SCTP_ADDR_REACHABLE |
SCTP_ADDR_UNCONFIRMED);
} else {
netfirst->dest_state = SCTP_ADDR_REACHABLE;
}
return (0);
}
addr_inscope = 1;
switch (newaddr->sa_family) {
#ifdef INET
case AF_INET:
{
struct sockaddr_in *sin;
sin = (struct sockaddr_in *)newaddr;
if (sin->sin_addr.s_addr == 0) {
/* Invalid address */
return (-1);
}
/* zero out the zero area */
memset(&sin->sin_zero, 0, sizeof(sin->sin_zero));
/* assure len is set */
#ifdef HAVE_SIN_LEN
sin->sin_len = sizeof(struct sockaddr_in);
#endif
if (set_scope) {
if (IN4_ISPRIVATE_ADDRESS(&sin->sin_addr)) {
stcb->asoc.scope.ipv4_local_scope = 1;
}
} else {
/* Validate the address is in scope */
if ((IN4_ISPRIVATE_ADDRESS(&sin->sin_addr)) &&
(stcb->asoc.scope.ipv4_local_scope == 0)) {
addr_inscope = 0;
}
}
break;
}
#endif
#ifdef INET6
case AF_INET6:
{
struct sockaddr_in6 *sin6;
sin6 = (struct sockaddr_in6 *)newaddr;
if (IN6_IS_ADDR_UNSPECIFIED(&sin6->sin6_addr)) {
/* Invalid address */
return (-1);
}
/* assure len is set */
#ifdef HAVE_SIN6_LEN
sin6->sin6_len = sizeof(struct sockaddr_in6);
#endif
if (set_scope) {
if (sctp_is_address_on_local_host(newaddr, stcb->asoc.vrf_id)) {
stcb->asoc.scope.loopback_scope = 1;
stcb->asoc.scope.local_scope = 0;
stcb->asoc.scope.ipv4_local_scope = 1;
stcb->asoc.scope.site_scope = 1;
} else if (IN6_IS_ADDR_LINKLOCAL(&sin6->sin6_addr)) {
/*
* If the new destination is a LINK_LOCAL we
* must have common site scope. Don't set
* the local scope since we may not share
* all links, only loopback can do this.
* Links on the local network would also be
* on our private network for v4 too.
*/
stcb->asoc.scope.ipv4_local_scope = 1;
stcb->asoc.scope.site_scope = 1;
} else if (IN6_IS_ADDR_SITELOCAL(&sin6->sin6_addr)) {
/*
* If the new destination is SITE_LOCAL then
* we must have site scope in common.
*/
stcb->asoc.scope.site_scope = 1;
}
} else {
/* Validate the address is in scope */
if (IN6_IS_ADDR_LOOPBACK(&sin6->sin6_addr) &&
(stcb->asoc.scope.loopback_scope == 0)) {
addr_inscope = 0;
} else if (IN6_IS_ADDR_LINKLOCAL(&sin6->sin6_addr) &&
(stcb->asoc.scope.local_scope == 0)) {
addr_inscope = 0;
} else if (IN6_IS_ADDR_SITELOCAL(&sin6->sin6_addr) &&
(stcb->asoc.scope.site_scope == 0)) {
addr_inscope = 0;
}
}
break;
}
#endif
#if defined(__Userspace__)
case AF_CONN:
{
struct sockaddr_conn *sconn;
sconn = (struct sockaddr_conn *)newaddr;
if (sconn->sconn_addr == NULL) {
/* Invalid address */
return (-1);
}
#ifdef HAVE_SCONN_LEN
sconn->sconn_len = sizeof(struct sockaddr_conn);
#endif
break;
}
#endif
default:
/* not supported family type */
return (-1);
}
net = SCTP_ZONE_GET(SCTP_BASE_INFO(ipi_zone_net), struct sctp_nets);
if (net == NULL) {
return (-1);
}
SCTP_INCR_RADDR_COUNT();
memset(net, 0, sizeof(struct sctp_nets));
(void)SCTP_GETTIME_TIMEVAL(&net->start_time);
#ifdef HAVE_SA_LEN
memcpy(&net->ro._l_addr, newaddr, newaddr->sa_len);
#endif
switch (newaddr->sa_family) {
#ifdef INET
case AF_INET:
#ifndef HAVE_SA_LEN
memcpy(&net->ro._l_addr, newaddr, sizeof(struct sockaddr_in));
#endif
((struct sockaddr_in *)&net->ro._l_addr)->sin_port = stcb->rport;
break;
#endif
#ifdef INET6
case AF_INET6:
#ifndef HAVE_SA_LEN
memcpy(&net->ro._l_addr, newaddr, sizeof(struct sockaddr_in6));
#endif
((struct sockaddr_in6 *)&net->ro._l_addr)->sin6_port = stcb->rport;
break;
#endif
#if defined(__Userspace__)
case AF_CONN:
#ifndef HAVE_SA_LEN
memcpy(&net->ro._l_addr, newaddr, sizeof(struct sockaddr_conn));
#endif
((struct sockaddr_conn *)&net->ro._l_addr)->sconn_port = stcb->rport;
break;
#endif
default:
break;
}
net->addr_is_local = sctp_is_address_on_local_host(newaddr, stcb->asoc.vrf_id);
if (net->addr_is_local && ((set_scope || (from == SCTP_ADDR_IS_CONFIRMED)))) {
stcb->asoc.scope.loopback_scope = 1;
stcb->asoc.scope.ipv4_local_scope = 1;
stcb->asoc.scope.local_scope = 0;
stcb->asoc.scope.site_scope = 1;
addr_inscope = 1;
}
net->failure_threshold = stcb->asoc.def_net_failure;
net->pf_threshold = stcb->asoc.def_net_pf_threshold;
if (addr_inscope == 0) {
net->dest_state = (SCTP_ADDR_REACHABLE |
SCTP_ADDR_OUT_OF_SCOPE);
} else {
if (from == SCTP_ADDR_IS_CONFIRMED)
/* SCTP_ADDR_IS_CONFIRMED is passed by connect_x */
net->dest_state = SCTP_ADDR_REACHABLE;
else
net->dest_state = SCTP_ADDR_REACHABLE |
SCTP_ADDR_UNCONFIRMED;
}
/* We set this to 0, the timer code knows that
* this means its an initial value
*/
net->rto_needed = 1;
net->RTO = 0;
net->RTO_measured = 0;
stcb->asoc.numnets++;
net->ref_count = 1;
net->cwr_window_tsn = net->last_cwr_tsn = stcb->asoc.sending_seq - 1;
net->port = port;
net->dscp = stcb->asoc.default_dscp;
#ifdef INET6
net->flowlabel = stcb->asoc.default_flowlabel;
#endif
if (sctp_stcb_is_feature_on(stcb->sctp_ep, stcb, SCTP_PCB_FLAGS_DONOT_HEARTBEAT)) {
net->dest_state |= SCTP_ADDR_NOHB;
} else {
net->dest_state &= ~SCTP_ADDR_NOHB;
}
if (sctp_stcb_is_feature_on(stcb->sctp_ep, stcb, SCTP_PCB_FLAGS_DO_NOT_PMTUD)) {
net->dest_state |= SCTP_ADDR_NO_PMTUD;
} else {
net->dest_state &= ~SCTP_ADDR_NO_PMTUD;
}
net->heart_beat_delay = stcb->asoc.heart_beat_delay;
/* Init the timer structure */
SCTP_OS_TIMER_INIT(&net->rxt_timer.timer);
SCTP_OS_TIMER_INIT(&net->pmtu_timer.timer);
SCTP_OS_TIMER_INIT(&net->hb_timer.timer);
/* Now generate a route for this guy */
#ifdef INET6
#ifdef SCTP_EMBEDDED_V6_SCOPE
/* KAME hack: embed scopeid */
if (newaddr->sa_family == AF_INET6) {
struct sockaddr_in6 *sin6;
sin6 = (struct sockaddr_in6 *)&net->ro._l_addr;
#if defined(__APPLE__)
#if defined(APPLE_LEOPARD) || defined(APPLE_SNOWLEOPARD)
(void)in6_embedscope(&sin6->sin6_addr, sin6, &stcb->sctp_ep->ip_inp.inp, NULL);
#else
(void)in6_embedscope(&sin6->sin6_addr, sin6, &stcb->sctp_ep->ip_inp.inp, NULL, NULL);
#endif
#elif defined(SCTP_KAME)
(void)sa6_embedscope(sin6, MODULE_GLOBAL(ip6_use_defzone));
#else
(void)in6_embedscope(&sin6->sin6_addr, sin6);
#endif
#ifndef SCOPEDROUTING
sin6->sin6_scope_id = 0;
#endif
}
#endif /* SCTP_EMBEDDED_V6_SCOPE */
#endif
SCTP_RTALLOC((sctp_route_t *)&net->ro,
stcb->asoc.vrf_id,
stcb->sctp_ep->fibnum);
net->src_addr_selected = 0;
#if !defined(__Userspace__)
if (SCTP_ROUTE_HAS_VALID_IFN(&net->ro)) {
/* Get source address */
net->ro._s_addr = sctp_source_address_selection(stcb->sctp_ep,
stcb,
(sctp_route_t *)&net->ro,
net,
0,
stcb->asoc.vrf_id);
if (stcb->asoc.default_mtu > 0) {
net->mtu = stcb->asoc.default_mtu;
switch (net->ro._l_addr.sa.sa_family) {
#ifdef INET
case AF_INET:
net->mtu += SCTP_MIN_V4_OVERHEAD;
break;
#endif
#ifdef INET6
case AF_INET6:
net->mtu += SCTP_MIN_OVERHEAD;
break;
#endif
#if defined(__Userspace__)
case AF_CONN:
net->mtu += sizeof(struct sctphdr);
break;
#endif
default:
break;
}
#if defined(INET) || defined(INET6)
if (net->port) {
net->mtu += (uint32_t)sizeof(struct udphdr);
}
#endif
} else if (net->ro._s_addr != NULL) {
uint32_t imtu, rmtu, hcmtu;
net->src_addr_selected = 1;
/* Now get the interface MTU */
if (net->ro._s_addr->ifn_p != NULL) {
imtu = SCTP_GATHER_MTU_FROM_INTFC(net->ro._s_addr->ifn_p);
} else {
imtu = 0;
}
rmtu = SCTP_GATHER_MTU_FROM_ROUTE(net->ro._s_addr, &net->ro._l_addr.sa, net->ro.ro_rt);
#if defined(__FreeBSD__)
hcmtu = sctp_hc_get_mtu(&net->ro._l_addr, stcb->sctp_ep->fibnum);
#else
hcmtu = 0;
#endif
net->mtu = sctp_min_mtu(hcmtu, rmtu, imtu);
if (rmtu == 0) {
/* Start things off to match mtu of interface please. */
SCTP_SET_MTU_OF_ROUTE(&net->ro._l_addr.sa,
net->ro.ro_rt, net->mtu);
}
}
}
#endif
if (net->mtu == 0) {
if (stcb->asoc.default_mtu > 0) {
net->mtu = stcb->asoc.default_mtu;
switch (net->ro._l_addr.sa.sa_family) {
#ifdef INET
case AF_INET:
net->mtu += SCTP_MIN_V4_OVERHEAD;
break;
#endif
#ifdef INET6
case AF_INET6:
net->mtu += SCTP_MIN_OVERHEAD;
break;
#endif
#if defined(__Userspace__)
case AF_CONN:
net->mtu += sizeof(struct sctphdr);
break;
#endif
default:
break;
}
#if defined(INET) || defined(INET6)
if (net->port) {
net->mtu += (uint32_t)sizeof(struct udphdr);
}
#endif
} else {
switch (newaddr->sa_family) {
#ifdef INET
case AF_INET:
net->mtu = SCTP_DEFAULT_MTU;
break;
#endif
#ifdef INET6
case AF_INET6:
net->mtu = 1280;
break;
#endif
#if defined(__Userspace__)
case AF_CONN:
net->mtu = 1280;
break;
#endif
default:
break;
}
}
}
#if defined(INET) || defined(INET6)
if (net->port) {
net->mtu -= (uint32_t)sizeof(struct udphdr);
}
#endif
if (from == SCTP_ALLOC_ASOC) {
stcb->asoc.smallest_mtu = net->mtu;
}
if (stcb->asoc.smallest_mtu > net->mtu) {
sctp_pathmtu_adjustment(stcb, net->mtu);
}
#ifdef INET6
#ifdef SCTP_EMBEDDED_V6_SCOPE
if (newaddr->sa_family == AF_INET6) {
struct sockaddr_in6 *sin6;
sin6 = (struct sockaddr_in6 *)&net->ro._l_addr;
#ifdef SCTP_KAME
(void)sa6_recoverscope(sin6);
#else
(void)in6_recoverscope(sin6, &sin6->sin6_addr, NULL);
#endif /* SCTP_KAME */
}
#endif /* SCTP_EMBEDDED_V6_SCOPE */
#endif
/* JRS - Use the congestion control given in the CC module */
if (stcb->asoc.cc_functions.sctp_set_initial_cc_param != NULL)
(*stcb->asoc.cc_functions.sctp_set_initial_cc_param)(stcb, net);
/*
* CMT: CUC algo - set find_pseudo_cumack to TRUE (1) at beginning
* of assoc (2005/06/27, iyengar@cis.udel.edu)
*/
net->find_pseudo_cumack = 1;
net->find_rtx_pseudo_cumack = 1;
#if defined(__FreeBSD__)
/* Choose an initial flowid. */
net->flowid = stcb->asoc.my_vtag ^
ntohs(stcb->rport) ^
ntohs(stcb->sctp_ep->sctp_lport);
net->flowtype = M_HASHTYPE_OPAQUE_HASH;
#endif
if (netp) {
*netp = net;
}
netfirst = TAILQ_FIRST(&stcb->asoc.nets);
if (net->ro.ro_rt == NULL) {
/* Since we have no route put it at the back */
TAILQ_INSERT_TAIL(&stcb->asoc.nets, net, sctp_next);
} else if (netfirst == NULL) {
/* We are the first one in the pool. */
TAILQ_INSERT_HEAD(&stcb->asoc.nets, net, sctp_next);
} else if (netfirst->ro.ro_rt == NULL) {
/*
* First one has NO route. Place this one ahead of the first
* one.
*/
TAILQ_INSERT_HEAD(&stcb->asoc.nets, net, sctp_next);
#ifndef __Panda__
} else if (net->ro.ro_rt->rt_ifp != netfirst->ro.ro_rt->rt_ifp) {
/*
* This one has a different interface than the one at the
* top of the list. Place it ahead.
*/
TAILQ_INSERT_HEAD(&stcb->asoc.nets, net, sctp_next);
#endif
} else {
/*
* Ok we have the same interface as the first one. Move
* forward until we find either a) one with a NULL route...
* insert ahead of that b) one with a different ifp.. insert
* after that. c) end of the list.. insert at the tail.
*/
struct sctp_nets *netlook;
do {
netlook = TAILQ_NEXT(netfirst, sctp_next);
if (netlook == NULL) {
/* End of the list */
TAILQ_INSERT_TAIL(&stcb->asoc.nets, net, sctp_next);
break;
} else if (netlook->ro.ro_rt == NULL) {
/* next one has NO route */
TAILQ_INSERT_BEFORE(netfirst, net, sctp_next);
break;
}
#ifndef __Panda__
else if (netlook->ro.ro_rt->rt_ifp != net->ro.ro_rt->rt_ifp)
#else
else
#endif
{
TAILQ_INSERT_AFTER(&stcb->asoc.nets, netlook,
net, sctp_next);
break;
}
#ifndef __Panda__
/* Shift forward */
netfirst = netlook;
#endif
} while (netlook != NULL);
}
/* got to have a primary set */
if (stcb->asoc.primary_destination == 0) {
stcb->asoc.primary_destination = net;
} else if ((stcb->asoc.primary_destination->ro.ro_rt == NULL) &&
(net->ro.ro_rt) &&
((net->dest_state & SCTP_ADDR_UNCONFIRMED) == 0)) {
/* No route to current primary adopt new primary */
stcb->asoc.primary_destination = net;
}
/* Validate primary is first */
net = TAILQ_FIRST(&stcb->asoc.nets);
if ((net != stcb->asoc.primary_destination) &&
(stcb->asoc.primary_destination)) {
/* first one on the list is NOT the primary
* sctp_cmpaddr() is much more efficient if
* the primary is the first on the list, make it
* so.
*/
TAILQ_REMOVE(&stcb->asoc.nets,
stcb->asoc.primary_destination, sctp_next);
TAILQ_INSERT_HEAD(&stcb->asoc.nets,
stcb->asoc.primary_destination, sctp_next);
}
return (0);
}
static uint32_t
sctp_aloc_a_assoc_id(struct sctp_inpcb *inp, struct sctp_tcb *stcb)
{
uint32_t id;
struct sctpasochead *head;
struct sctp_tcb *lstcb;
try_again:
if (inp->sctp_flags & SCTP_PCB_FLAGS_SOCKET_ALLGONE) {
/* TSNH */
return (0);
}
/*
* We don't allow assoc id to be one of SCTP_FUTURE_ASSOC,
* SCTP_CURRENT_ASSOC and SCTP_ALL_ASSOC.
*/
if (inp->sctp_associd_counter <= SCTP_ALL_ASSOC) {
inp->sctp_associd_counter = SCTP_ALL_ASSOC + 1;
}
id = inp->sctp_associd_counter;
inp->sctp_associd_counter++;
lstcb = sctp_findasoc_ep_asocid_locked(inp, (sctp_assoc_t)id, 0);
if (lstcb) {
goto try_again;
}
head = &inp->sctp_asocidhash[SCTP_PCBHASH_ASOC(id, inp->hashasocidmark)];
LIST_INSERT_HEAD(head, stcb, sctp_tcbasocidhash);
stcb->asoc.in_asocid_hash = 1;
return (id);
}
/*
* allocate an association and add it to the endpoint. The caller must be
* careful to add all additional addresses once they are know right away or
* else the assoc will be may experience a blackout scenario.
*/
struct sctp_tcb *
sctp_aloc_assoc(struct sctp_inpcb *inp, struct sockaddr *firstaddr,
int *error, uint32_t override_tag, uint32_t vrf_id,
uint16_t o_streams, uint16_t port,
#if defined(__FreeBSD__) && __FreeBSD_version >= 500000
struct thread *p,
#elif defined(__Windows__)
PKTHREAD p,
#else
#if defined(__Userspace__)
/* __Userspace__ NULL proc is going to be passed here. See sctp_lower_sosend */
#endif
struct proc *p,
#endif
int initialize_auth_params)
{
/* note the p argument is only valid in unbound sockets */
struct sctp_tcb *stcb;
struct sctp_association *asoc;
struct sctpasochead *head;
uint16_t rport;
int err;
/*
* Assumption made here: Caller has done a
* sctp_findassociation_ep_addr(ep, addr's); to make sure the
* address does not exist already.
*/
if (SCTP_BASE_INFO(ipi_count_asoc) >= SCTP_MAX_NUM_OF_ASOC) {
/* Hit max assoc, sorry no more */
SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, ENOBUFS);
*error = ENOBUFS;
return (NULL);
}
if (firstaddr == NULL) {
SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, EINVAL);
*error = EINVAL;
return (NULL);
}
SCTP_INP_RLOCK(inp);
if ((inp->sctp_flags & SCTP_PCB_FLAGS_IN_TCPPOOL) &&
((sctp_is_feature_off(inp, SCTP_PCB_FLAGS_PORTREUSE)) ||
(inp->sctp_flags & SCTP_PCB_FLAGS_CONNECTED))) {
/*
* If its in the TCP pool, its NOT allowed to create an
* association. The parent listener needs to call
* sctp_aloc_assoc.. or the one-2-many socket. If a peeled
* off, or connected one does this.. its an error.
*/
SCTP_INP_RUNLOCK(inp);
SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, EINVAL);
*error = EINVAL;
return (NULL);
}
if ((inp->sctp_flags & SCTP_PCB_FLAGS_IN_TCPPOOL) ||
(inp->sctp_flags & SCTP_PCB_FLAGS_TCPTYPE)) {
if ((inp->sctp_flags & SCTP_PCB_FLAGS_WAS_CONNECTED) ||
(inp->sctp_flags & SCTP_PCB_FLAGS_WAS_ABORTED)) {
SCTP_INP_RUNLOCK(inp);
SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, EINVAL);
*error = EINVAL;
return (NULL);
}
}
SCTPDBG(SCTP_DEBUG_PCB3, "Allocate an association for peer:");
#ifdef SCTP_DEBUG
if (firstaddr) {
SCTPDBG_ADDR(SCTP_DEBUG_PCB3, firstaddr);
switch (firstaddr->sa_family) {
#ifdef INET
case AF_INET:
SCTPDBG(SCTP_DEBUG_PCB3, "Port:%d\n",
ntohs(((struct sockaddr_in *)firstaddr)->sin_port));
break;
#endif
#ifdef INET6
case AF_INET6:
SCTPDBG(SCTP_DEBUG_PCB3, "Port:%d\n",
ntohs(((struct sockaddr_in6 *)firstaddr)->sin6_port));
break;
#endif
#if defined(__Userspace__)
case AF_CONN:
SCTPDBG(SCTP_DEBUG_PCB3, "Port:%d\n",
ntohs(((struct sockaddr_conn *)firstaddr)->sconn_port));
break;
#endif
default:
break;
}
} else {
SCTPDBG(SCTP_DEBUG_PCB3,"None\n");
}
#endif /* SCTP_DEBUG */
switch (firstaddr->sa_family) {
#ifdef INET
case AF_INET:
{
struct sockaddr_in *sin;
sin = (struct sockaddr_in *)firstaddr;
if ((ntohs(sin->sin_port) == 0) ||
(sin->sin_addr.s_addr == INADDR_ANY) ||
(sin->sin_addr.s_addr == INADDR_BROADCAST) ||
IN_MULTICAST(ntohl(sin->sin_addr.s_addr))) {
/* Invalid address */
SCTP_INP_RUNLOCK(inp);
SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, EINVAL);
*error = EINVAL;
return (NULL);
}
rport = sin->sin_port;
break;
}
#endif
#ifdef INET6
case AF_INET6:
{
struct sockaddr_in6 *sin6;
sin6 = (struct sockaddr_in6 *)firstaddr;
if ((ntohs(sin6->sin6_port) == 0) ||
IN6_IS_ADDR_UNSPECIFIED(&sin6->sin6_addr) ||
IN6_IS_ADDR_MULTICAST(&sin6->sin6_addr)) {
/* Invalid address */
SCTP_INP_RUNLOCK(inp);
SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, EINVAL);
*error = EINVAL;
return (NULL);
}
rport = sin6->sin6_port;
break;
}
#endif
#if defined(__Userspace__)
case AF_CONN:
{
struct sockaddr_conn *sconn;
sconn = (struct sockaddr_conn *)firstaddr;
if ((ntohs(sconn->sconn_port) == 0) ||
(sconn->sconn_addr == NULL)) {
/* Invalid address */
SCTP_INP_RUNLOCK(inp);
SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, EINVAL);
*error = EINVAL;
return (NULL);
}
rport = sconn->sconn_port;
break;
}
#endif
default:
/* not supported family type */
SCTP_INP_RUNLOCK(inp);
SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, EINVAL);
*error = EINVAL;
return (NULL);
}
SCTP_INP_RUNLOCK(inp);
if (inp->sctp_flags & SCTP_PCB_FLAGS_UNBOUND) {
/*
* If you have not performed a bind, then we need to do the
* ephemeral bind for you.
*/
if ((err = sctp_inpcb_bind(inp->sctp_socket,
(struct sockaddr *)NULL,
(struct sctp_ifa *)NULL,
#ifndef __Panda__
p
#else
(struct proc *)NULL
#endif
))) {
/* bind error, probably perm */
*error = err;
return (NULL);
}
}
stcb = SCTP_ZONE_GET(SCTP_BASE_INFO(ipi_zone_asoc), struct sctp_tcb);
if (stcb == NULL) {
/* out of memory? */
SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, ENOMEM);
*error = ENOMEM;
return (NULL);
}
SCTP_INCR_ASOC_COUNT();
memset(stcb, 0, sizeof(*stcb));
asoc = &stcb->asoc;
SCTP_TCB_LOCK_INIT(stcb);
SCTP_TCB_SEND_LOCK_INIT(stcb);
stcb->rport = rport;
/* setup back pointer's */
stcb->sctp_ep = inp;
stcb->sctp_socket = inp->sctp_socket;
if ((err = sctp_init_asoc(inp, stcb, override_tag, vrf_id, o_streams))) {
/* failed */
SCTP_TCB_LOCK_DESTROY(stcb);
SCTP_TCB_SEND_LOCK_DESTROY(stcb);
SCTP_ZONE_FREE(SCTP_BASE_INFO(ipi_zone_asoc), stcb);
SCTP_DECR_ASOC_COUNT();
*error = err;
return (NULL);
}
/* and the port */
SCTP_INP_INFO_WLOCK();
SCTP_INP_WLOCK(inp);
if (inp->sctp_flags & (SCTP_PCB_FLAGS_SOCKET_GONE | SCTP_PCB_FLAGS_SOCKET_ALLGONE)) {
/* inpcb freed while alloc going on */
SCTP_TCB_LOCK_DESTROY(stcb);
SCTP_TCB_SEND_LOCK_DESTROY(stcb);
SCTP_ZONE_FREE(SCTP_BASE_INFO(ipi_zone_asoc), stcb);
SCTP_INP_WUNLOCK(inp);
SCTP_INP_INFO_WUNLOCK();
SCTP_DECR_ASOC_COUNT();
SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, EINVAL);
*error = EINVAL;
return (NULL);
}
SCTP_TCB_LOCK(stcb);
asoc->assoc_id = sctp_aloc_a_assoc_id(inp, stcb);
/* now that my_vtag is set, add it to the hash */
head = &SCTP_BASE_INFO(sctp_asochash)[SCTP_PCBHASH_ASOC(stcb->asoc.my_vtag, SCTP_BASE_INFO(hashasocmark))];
/* put it in the bucket in the vtag hash of assoc's for the system */
LIST_INSERT_HEAD(head, stcb, sctp_asocs);
SCTP_INP_INFO_WUNLOCK();
if ((err = sctp_add_remote_addr(stcb, firstaddr, NULL, port, SCTP_DO_SETSCOPE, SCTP_ALLOC_ASOC))) {
/* failure.. memory error? */
if (asoc->strmout) {
SCTP_FREE(asoc->strmout, SCTP_M_STRMO);
asoc->strmout = NULL;
}
if (asoc->mapping_array) {
SCTP_FREE(asoc->mapping_array, SCTP_M_MAP);
asoc->mapping_array = NULL;
}
if (asoc->nr_mapping_array) {
SCTP_FREE(asoc->nr_mapping_array, SCTP_M_MAP);
asoc->nr_mapping_array = NULL;
}
SCTP_DECR_ASOC_COUNT();
SCTP_TCB_UNLOCK(stcb);
SCTP_TCB_LOCK_DESTROY(stcb);
SCTP_TCB_SEND_LOCK_DESTROY(stcb);
LIST_REMOVE(stcb, sctp_tcbasocidhash);
SCTP_ZONE_FREE(SCTP_BASE_INFO(ipi_zone_asoc), stcb);
SCTP_INP_WUNLOCK(inp);
SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, ENOBUFS);
*error = ENOBUFS;
return (NULL);
}
/* Init all the timers */
SCTP_OS_TIMER_INIT(&asoc->dack_timer.timer);
SCTP_OS_TIMER_INIT(&asoc->strreset_timer.timer);
SCTP_OS_TIMER_INIT(&asoc->asconf_timer.timer);
SCTP_OS_TIMER_INIT(&asoc->shut_guard_timer.timer);
SCTP_OS_TIMER_INIT(&asoc->autoclose_timer.timer);
SCTP_OS_TIMER_INIT(&asoc->delayed_event_timer.timer);
SCTP_OS_TIMER_INIT(&asoc->delete_prim_timer.timer);
LIST_INSERT_HEAD(&inp->sctp_asoc_list, stcb, sctp_tcblist);
/* now file the port under the hash as well */
if (inp->sctp_tcbhash != NULL) {
head = &inp->sctp_tcbhash[SCTP_PCBHASH_ALLADDR(stcb->rport,
inp->sctp_hashmark)];
LIST_INSERT_HEAD(head, stcb, sctp_tcbhash);
}
if (initialize_auth_params == SCTP_INITIALIZE_AUTH_PARAMS) {
sctp_initialize_auth_params(inp, stcb);
}
SCTP_INP_WUNLOCK(inp);
SCTPDBG(SCTP_DEBUG_PCB1, "Association %p now allocated\n", (void *)stcb);
return (stcb);
}
void
sctp_remove_net(struct sctp_tcb *stcb, struct sctp_nets *net)
{
struct sctp_association *asoc;
asoc = &stcb->asoc;
asoc->numnets--;
TAILQ_REMOVE(&asoc->nets, net, sctp_next);
if (net == asoc->primary_destination) {
/* Reset primary */
struct sctp_nets *lnet;
lnet = TAILQ_FIRST(&asoc->nets);
/* Mobility adaptation
Ideally, if deleted destination is the primary, it becomes
a fast retransmission trigger by the subsequent SET PRIMARY.
(by micchie)
*/
if (sctp_is_mobility_feature_on(stcb->sctp_ep,
SCTP_MOBILITY_BASE) ||
sctp_is_mobility_feature_on(stcb->sctp_ep,
SCTP_MOBILITY_FASTHANDOFF)) {
SCTPDBG(SCTP_DEBUG_ASCONF1, "remove_net: primary dst is deleting\n");
if (asoc->deleted_primary != NULL) {
SCTPDBG(SCTP_DEBUG_ASCONF1, "remove_net: deleted primary may be already stored\n");
goto out;
}
asoc->deleted_primary = net;
atomic_add_int(&net->ref_count, 1);
memset(&net->lastsa, 0, sizeof(net->lastsa));
memset(&net->lastsv, 0, sizeof(net->lastsv));
sctp_mobility_feature_on(stcb->sctp_ep,
SCTP_MOBILITY_PRIM_DELETED);
sctp_timer_start(SCTP_TIMER_TYPE_PRIM_DELETED,
stcb->sctp_ep, stcb, NULL);
}
out:
/* Try to find a confirmed primary */
asoc->primary_destination = sctp_find_alternate_net(stcb, lnet, 0);
}
if (net == asoc->last_data_chunk_from) {
/* Reset primary */
asoc->last_data_chunk_from = TAILQ_FIRST(&asoc->nets);
}
if (net == asoc->last_control_chunk_from) {
/* Clear net */
asoc->last_control_chunk_from = NULL;
}
if (net == stcb->asoc.alternate) {
sctp_free_remote_addr(stcb->asoc.alternate);
stcb->asoc.alternate = NULL;
}
sctp_free_remote_addr(net);
}
/*
* remove a remote endpoint address from an association, it will fail if the
* address does not exist.
*/
int
sctp_del_remote_addr(struct sctp_tcb *stcb, struct sockaddr *remaddr)
{
/*
* Here we need to remove a remote address. This is quite simple, we
* first find it in the list of address for the association
* (tasoc->asoc.nets) and then if it is there, we do a LIST_REMOVE
* on that item. Note we do not allow it to be removed if there are
* no other addresses.
*/
struct sctp_association *asoc;
struct sctp_nets *net, *nnet;
asoc = &stcb->asoc;
/* locate the address */
TAILQ_FOREACH_SAFE(net, &asoc->nets, sctp_next, nnet) {
if (net->ro._l_addr.sa.sa_family != remaddr->sa_family) {
continue;
}
if (sctp_cmpaddr((struct sockaddr *)&net->ro._l_addr,
remaddr)) {
/* we found the guy */
if (asoc->numnets < 2) {
/* Must have at LEAST two remote addresses */
return (-1);
} else {
sctp_remove_net(stcb, net);
return (0);
}
}
}
/* not found. */
return (-2);
}
void
sctp_delete_from_timewait(uint32_t tag, uint16_t lport, uint16_t rport)
{
struct sctpvtaghead *chain;
struct sctp_tagblock *twait_block;
int found = 0;
int i;
chain = &SCTP_BASE_INFO(vtag_timewait)[(tag % SCTP_STACK_VTAG_HASH_SIZE)];
LIST_FOREACH(twait_block, chain, sctp_nxt_tagblock) {
for (i = 0; i < SCTP_NUMBER_IN_VTAG_BLOCK; i++) {
if ((twait_block->vtag_block[i].v_tag == tag) &&
(twait_block->vtag_block[i].lport == lport) &&
(twait_block->vtag_block[i].rport == rport)) {
twait_block->vtag_block[i].tv_sec_at_expire = 0;
twait_block->vtag_block[i].v_tag = 0;
twait_block->vtag_block[i].lport = 0;
twait_block->vtag_block[i].rport = 0;
found = 1;
break;
}
}
if (found)
break;
}
}
int
sctp_is_in_timewait(uint32_t tag, uint16_t lport, uint16_t rport)
{
struct sctpvtaghead *chain;
struct sctp_tagblock *twait_block;
int found = 0;
int i;
SCTP_INP_INFO_WLOCK();
chain = &SCTP_BASE_INFO(vtag_timewait)[(tag % SCTP_STACK_VTAG_HASH_SIZE)];
LIST_FOREACH(twait_block, chain, sctp_nxt_tagblock) {
for (i = 0; i < SCTP_NUMBER_IN_VTAG_BLOCK; i++) {
if ((twait_block->vtag_block[i].v_tag == tag) &&
(twait_block->vtag_block[i].lport == lport) &&
(twait_block->vtag_block[i].rport == rport)) {
found = 1;
break;
}
}
if (found)
break;
}
SCTP_INP_INFO_WUNLOCK();
return (found);
}
void
sctp_add_vtag_to_timewait(uint32_t tag, uint32_t time, uint16_t lport, uint16_t rport)
{
struct sctpvtaghead *chain;
struct sctp_tagblock *twait_block;
struct timeval now;
int set, i;
if (time == 0) {
/* Its disabled */
return;
}
(void)SCTP_GETTIME_TIMEVAL(&now);
chain = &SCTP_BASE_INFO(vtag_timewait)[(tag % SCTP_STACK_VTAG_HASH_SIZE)];
set = 0;
LIST_FOREACH(twait_block, chain, sctp_nxt_tagblock) {
/* Block(s) present, lets find space, and expire on the fly */
for (i = 0; i < SCTP_NUMBER_IN_VTAG_BLOCK; i++) {
if ((twait_block->vtag_block[i].v_tag == 0) &&
!set) {
twait_block->vtag_block[i].tv_sec_at_expire =
now.tv_sec + time;
twait_block->vtag_block[i].v_tag = tag;
twait_block->vtag_block[i].lport = lport;
twait_block->vtag_block[i].rport = rport;
set = 1;
} else if ((twait_block->vtag_block[i].v_tag) &&
((long)twait_block->vtag_block[i].tv_sec_at_expire < now.tv_sec)) {
/* Audit expires this guy */
twait_block->vtag_block[i].tv_sec_at_expire = 0;
twait_block->vtag_block[i].v_tag = 0;
twait_block->vtag_block[i].lport = 0;
twait_block->vtag_block[i].rport = 0;
if (set == 0) {
/* Reuse it for my new tag */
twait_block->vtag_block[i].tv_sec_at_expire = now.tv_sec + time;
twait_block->vtag_block[i].v_tag = tag;
twait_block->vtag_block[i].lport = lport;
twait_block->vtag_block[i].rport = rport;
set = 1;
}
}
}
if (set) {
/*
* We only do up to the block where we can
* place our tag for audits
*/
break;
}
}
/* Need to add a new block to chain */
if (!set) {
SCTP_MALLOC(twait_block, struct sctp_tagblock *,
sizeof(struct sctp_tagblock), SCTP_M_TIMW);
if (twait_block == NULL) {
#ifdef INVARIANTS
panic("Can not alloc tagblock");
#endif
return;
}
memset(twait_block, 0, sizeof(struct sctp_tagblock));
LIST_INSERT_HEAD(chain, twait_block, sctp_nxt_tagblock);
twait_block->vtag_block[0].tv_sec_at_expire = now.tv_sec + time;
twait_block->vtag_block[0].v_tag = tag;
twait_block->vtag_block[0].lport = lport;
twait_block->vtag_block[0].rport = rport;
}
}
void
sctp_clean_up_stream(struct sctp_tcb *stcb, struct sctp_readhead *rh)
{
struct sctp_tmit_chunk *chk, *nchk;
struct sctp_queued_to_read *control, *ncontrol;
TAILQ_FOREACH_SAFE(control, rh, next_instrm, ncontrol) {
TAILQ_REMOVE(rh, control, next_instrm);
control->on_strm_q = 0;
if (control->on_read_q == 0) {
sctp_free_remote_addr(control->whoFrom);
if (control->data) {
sctp_m_freem(control->data);
control->data = NULL;
}
}
/* Reassembly free? */
TAILQ_FOREACH_SAFE(chk, &control->reasm, sctp_next, nchk) {
TAILQ_REMOVE(&control->reasm, chk, sctp_next);
if (chk->data) {
sctp_m_freem(chk->data);
chk->data = NULL;
}
if (chk->holds_key_ref)
sctp_auth_key_release(stcb, chk->auth_keyid, SCTP_SO_LOCKED);
sctp_free_remote_addr(chk->whoTo);
SCTP_ZONE_FREE(SCTP_BASE_INFO(ipi_zone_chunk), chk);
SCTP_DECR_CHK_COUNT();
/*sa_ignore FREED_MEMORY*/
}
/*
* We don't free the address here
* since all the net's were freed
* above.
*/
if (control->on_read_q == 0) {
sctp_free_a_readq(stcb, control);
}
}
}
#ifdef __Panda__
void panda_wakeup_socket(struct socket *so);
#endif
/*-
* Free the association after un-hashing the remote port. This
* function ALWAYS returns holding NO LOCK on the stcb. It DOES
* expect that the input to this function IS a locked TCB.
* It will return 0, if it did NOT destroy the association (instead
* it unlocks it. It will return NON-zero if it either destroyed the
* association OR the association is already destroyed.
*/
int
sctp_free_assoc(struct sctp_inpcb *inp, struct sctp_tcb *stcb, int from_inpcbfree, int from_location)
{
int i;
struct sctp_association *asoc;
struct sctp_nets *net, *nnet;
struct sctp_laddr *laddr, *naddr;
struct sctp_tmit_chunk *chk, *nchk;
struct sctp_asconf_addr *aparam, *naparam;
struct sctp_asconf_ack *aack, *naack;
struct sctp_stream_reset_list *strrst, *nstrrst;
struct sctp_queued_to_read *sq, *nsq;
struct sctp_stream_queue_pending *sp, *nsp;
sctp_sharedkey_t *shared_key, *nshared_key;
struct socket *so;
/* first, lets purge the entry from the hash table. */
#if defined(__APPLE__)
sctp_lock_assert(SCTP_INP_SO(inp));
#endif
#ifdef SCTP_LOG_CLOSING
sctp_log_closing(inp, stcb, 6);
#endif
if (stcb->asoc.state == 0) {
#ifdef SCTP_LOG_CLOSING
sctp_log_closing(inp, NULL, 7);
#endif
/* there is no asoc, really TSNH :-0 */
return (1);
}
if (stcb->asoc.alternate) {
sctp_free_remote_addr(stcb->asoc.alternate);
stcb->asoc.alternate = NULL;
}
#if !defined(__APPLE__) /* TEMP: moved to below */
/* TEMP CODE */
if (stcb->freed_from_where == 0) {
/* Only record the first place free happened from */
stcb->freed_from_where = from_location;
}
/* TEMP CODE */
#endif
asoc = &stcb->asoc;
if ((inp->sctp_flags & SCTP_PCB_FLAGS_SOCKET_ALLGONE) ||
(inp->sctp_flags & SCTP_PCB_FLAGS_SOCKET_GONE))
/* nothing around */
so = NULL;
else
so = inp->sctp_socket;
/*
* We used timer based freeing if a reader or writer is in the way.
* So we first check if we are actually being called from a timer,
* if so we abort early if a reader or writer is still in the way.
*/
if ((stcb->asoc.state & SCTP_STATE_ABOUT_TO_BE_FREED) &&
(from_inpcbfree == SCTP_NORMAL_PROC)) {
/*
* is it the timer driving us? if so are the reader/writers
* gone?
*/
if (stcb->asoc.refcnt) {
/* nope, reader or writer in the way */
sctp_timer_start(SCTP_TIMER_TYPE_ASOCKILL, inp, stcb, NULL);
/* no asoc destroyed */
SCTP_TCB_UNLOCK(stcb);
#ifdef SCTP_LOG_CLOSING
sctp_log_closing(inp, stcb, 8);
#endif
return (0);
}
}
/* now clean up any other timers */
(void)SCTP_OS_TIMER_STOP(&asoc->dack_timer.timer);
asoc->dack_timer.self = NULL;
(void)SCTP_OS_TIMER_STOP(&asoc->strreset_timer.timer);
/*-
* For stream reset we don't blast this unless
* it is a str-reset timer, it might be the
* free-asoc timer which we DON'T want to
* disturb.
*/
if (asoc->strreset_timer.type == SCTP_TIMER_TYPE_STRRESET)
asoc->strreset_timer.self = NULL;
(void)SCTP_OS_TIMER_STOP(&asoc->asconf_timer.timer);
asoc->asconf_timer.self = NULL;
(void)SCTP_OS_TIMER_STOP(&asoc->autoclose_timer.timer);
asoc->autoclose_timer.self = NULL;
(void)SCTP_OS_TIMER_STOP(&asoc->shut_guard_timer.timer);
asoc->shut_guard_timer.self = NULL;
(void)SCTP_OS_TIMER_STOP(&asoc->delayed_event_timer.timer);
asoc->delayed_event_timer.self = NULL;
/* Mobility adaptation */
(void)SCTP_OS_TIMER_STOP(&asoc->delete_prim_timer.timer);
asoc->delete_prim_timer.self = NULL;
TAILQ_FOREACH(net, &asoc->nets, sctp_next) {
(void)SCTP_OS_TIMER_STOP(&net->rxt_timer.timer);
net->rxt_timer.self = NULL;
(void)SCTP_OS_TIMER_STOP(&net->pmtu_timer.timer);
net->pmtu_timer.self = NULL;
(void)SCTP_OS_TIMER_STOP(&net->hb_timer.timer);
net->hb_timer.self = NULL;
}
/* Now the read queue needs to be cleaned up (only once) */
if ((stcb->asoc.state & SCTP_STATE_ABOUT_TO_BE_FREED) == 0) {
SCTP_ADD_SUBSTATE(stcb, SCTP_STATE_ABOUT_TO_BE_FREED);
SCTP_INP_READ_LOCK(inp);
TAILQ_FOREACH(sq, &inp->read_queue, next) {
if (sq->stcb == stcb) {
sq->do_not_ref_stcb = 1;
sq->sinfo_cumtsn = stcb->asoc.cumulative_tsn;
/* If there is no end, there never
* will be now.
*/
if (sq->end_added == 0) {
/* Held for PD-API clear that. */
sq->pdapi_aborted = 1;
sq->held_length = 0;
if (sctp_stcb_is_feature_on(inp, stcb, SCTP_PCB_FLAGS_PDAPIEVNT) && (so != NULL)) {
/*
* Need to add a PD-API aborted indication.
* Setting the control_pdapi assures that it will
* be added right after this msg.
*/
uint32_t strseq;
stcb->asoc.control_pdapi = sq;
strseq = (sq->sinfo_stream << 16) | (sq->mid & 0x0000ffff);
sctp_ulp_notify(SCTP_NOTIFY_PARTIAL_DELVIERY_INDICATION,
stcb,
SCTP_PARTIAL_DELIVERY_ABORTED,
(void *)&strseq,
SCTP_SO_LOCKED);
stcb->asoc.control_pdapi = NULL;
}
}
/* Add an end to wake them */
sq->end_added = 1;
}
}
SCTP_INP_READ_UNLOCK(inp);
if (stcb->block_entry) {
SCTP_LTRACE_ERR_RET(inp, stcb, NULL, SCTP_FROM_SCTP_PCB, ECONNRESET);
stcb->block_entry->error = ECONNRESET;
stcb->block_entry = NULL;
}
}
if ((stcb->asoc.refcnt) || (stcb->asoc.state & SCTP_STATE_IN_ACCEPT_QUEUE)) {
/* Someone holds a reference OR the socket is unaccepted yet.
*/
if ((stcb->asoc.refcnt) ||
(inp->sctp_flags & SCTP_PCB_FLAGS_SOCKET_ALLGONE) ||
(inp->sctp_flags & SCTP_PCB_FLAGS_SOCKET_GONE)) {
SCTP_CLEAR_SUBSTATE(stcb, SCTP_STATE_IN_ACCEPT_QUEUE);
sctp_timer_start(SCTP_TIMER_TYPE_ASOCKILL, inp, stcb, NULL);
}
SCTP_TCB_UNLOCK(stcb);
if ((inp->sctp_flags & SCTP_PCB_FLAGS_SOCKET_ALLGONE) ||
(inp->sctp_flags & SCTP_PCB_FLAGS_SOCKET_GONE))
/* nothing around */
so = NULL;
if (so) {
/* Wake any reader/writers */
sctp_sorwakeup(inp, so);
sctp_sowwakeup(inp, so);
}
#ifdef SCTP_LOG_CLOSING
sctp_log_closing(inp, stcb, 9);
#endif
/* no asoc destroyed */
return (0);
}
#ifdef SCTP_LOG_CLOSING
sctp_log_closing(inp, stcb, 10);
#endif
/* When I reach here, no others want
* to kill the assoc yet.. and I own
* the lock. Now its possible an abort
* comes in when I do the lock exchange
* below to grab all the locks to do
* the final take out. to prevent this
* we increment the count, which will
* start a timer and blow out above thus
* assuring us that we hold exclusive
* killing of the asoc. Note that
* after getting back the TCB lock
* we will go ahead and increment the
* counter back up and stop any timer
* a passing stranger may have started :-S
*/
if (from_inpcbfree == SCTP_NORMAL_PROC) {
atomic_add_int(&stcb->asoc.refcnt, 1);
SCTP_TCB_UNLOCK(stcb);
SCTP_INP_INFO_WLOCK();
SCTP_INP_WLOCK(inp);
SCTP_TCB_LOCK(stcb);
}
/* Double check the GONE flag */
if ((inp->sctp_flags & SCTP_PCB_FLAGS_SOCKET_ALLGONE) ||
(inp->sctp_flags & SCTP_PCB_FLAGS_SOCKET_GONE))
/* nothing around */
so = NULL;
if ((inp->sctp_flags & SCTP_PCB_FLAGS_TCPTYPE) ||
(inp->sctp_flags & SCTP_PCB_FLAGS_IN_TCPPOOL)) {
/*
* For TCP type we need special handling when we are
* connected. We also include the peel'ed off ones to.
*/
if (inp->sctp_flags & SCTP_PCB_FLAGS_CONNECTED) {
inp->sctp_flags &= ~SCTP_PCB_FLAGS_CONNECTED;
inp->sctp_flags |= SCTP_PCB_FLAGS_WAS_CONNECTED;
if (so) {
SOCKBUF_LOCK(&so->so_rcv);
so->so_state &= ~(SS_ISCONNECTING |
SS_ISDISCONNECTING |
SS_ISCONFIRMING |
SS_ISCONNECTED);
so->so_state |= SS_ISDISCONNECTED;
#if defined(__APPLE__)
socantrcvmore(so);
#else
socantrcvmore_locked(so);
#endif
socantsendmore(so);
sctp_sowwakeup(inp, so);
sctp_sorwakeup(inp, so);
SCTP_SOWAKEUP(so);
}
}
}
/* Make it invalid too, that way if its
* about to run it will abort and return.
*/
/* re-increment the lock */
if (from_inpcbfree == SCTP_NORMAL_PROC) {
atomic_add_int(&stcb->asoc.refcnt, -1);
}
if (stcb->asoc.refcnt) {
SCTP_CLEAR_SUBSTATE(stcb, SCTP_STATE_IN_ACCEPT_QUEUE);
sctp_timer_start(SCTP_TIMER_TYPE_ASOCKILL, inp, stcb, NULL);
if (from_inpcbfree == SCTP_NORMAL_PROC) {
SCTP_INP_INFO_WUNLOCK();
SCTP_INP_WUNLOCK(inp);
}
SCTP_TCB_UNLOCK(stcb);
return (0);
}
asoc->state = 0;
if (inp->sctp_tcbhash) {
LIST_REMOVE(stcb, sctp_tcbhash);
}
if (stcb->asoc.in_asocid_hash) {
LIST_REMOVE(stcb, sctp_tcbasocidhash);
}
/* Now lets remove it from the list of ALL associations in the EP */
LIST_REMOVE(stcb, sctp_tcblist);
if (from_inpcbfree == SCTP_NORMAL_PROC) {
SCTP_INP_INCR_REF(inp);
SCTP_INP_WUNLOCK(inp);
}
/* pull from vtag hash */
LIST_REMOVE(stcb, sctp_asocs);
sctp_add_vtag_to_timewait(asoc->my_vtag, SCTP_BASE_SYSCTL(sctp_vtag_time_wait),
inp->sctp_lport, stcb->rport);
/* Now restop the timers to be sure
* this is paranoia at is finest!
*/
(void)SCTP_OS_TIMER_STOP(&asoc->strreset_timer.timer);
(void)SCTP_OS_TIMER_STOP(&asoc->dack_timer.timer);
(void)SCTP_OS_TIMER_STOP(&asoc->strreset_timer.timer);
(void)SCTP_OS_TIMER_STOP(&asoc->asconf_timer.timer);
(void)SCTP_OS_TIMER_STOP(&asoc->shut_guard_timer.timer);
(void)SCTP_OS_TIMER_STOP(&asoc->autoclose_timer.timer);
(void)SCTP_OS_TIMER_STOP(&asoc->delayed_event_timer.timer);
TAILQ_FOREACH(net, &asoc->nets, sctp_next) {
(void)SCTP_OS_TIMER_STOP(&net->rxt_timer.timer);
(void)SCTP_OS_TIMER_STOP(&net->pmtu_timer.timer);
(void)SCTP_OS_TIMER_STOP(&net->hb_timer.timer);
}
asoc->strreset_timer.type = SCTP_TIMER_TYPE_NONE;
/*
* The chunk lists and such SHOULD be empty but we check them just
* in case.
*/
/* anything on the wheel needs to be removed */
SCTP_TCB_SEND_LOCK(stcb);
for (i = 0; i < asoc->streamoutcnt; i++) {
struct sctp_stream_out *outs;
outs = &asoc->strmout[i];
/* now clean up any chunks here */
TAILQ_FOREACH_SAFE(sp, &outs->outqueue, next, nsp) {
atomic_subtract_int(&asoc->stream_queue_cnt, 1);
TAILQ_REMOVE(&outs->outqueue, sp, next);
stcb->asoc.ss_functions.sctp_ss_remove_from_stream(stcb, asoc, outs, sp, 1);
sctp_free_spbufspace(stcb, asoc, sp);
if (sp->data) {
if (so) {
/* Still an open socket - report */
sctp_ulp_notify(SCTP_NOTIFY_SPECIAL_SP_FAIL, stcb,
0, (void *)sp, SCTP_SO_LOCKED);
}
if (sp->data) {
sctp_m_freem(sp->data);
sp->data = NULL;
sp->tail_mbuf = NULL;
sp->length = 0;
}
}
if (sp->net) {
sctp_free_remote_addr(sp->net);
sp->net = NULL;
}
sctp_free_a_strmoq(stcb, sp, SCTP_SO_LOCKED);
}
}
SCTP_TCB_SEND_UNLOCK(stcb);
/*sa_ignore FREED_MEMORY*/
TAILQ_FOREACH_SAFE(strrst, &asoc->resetHead, next_resp, nstrrst) {
TAILQ_REMOVE(&asoc->resetHead, strrst, next_resp);
SCTP_FREE(strrst, SCTP_M_STRESET);
}
TAILQ_FOREACH_SAFE(sq, &asoc->pending_reply_queue, next, nsq) {
TAILQ_REMOVE(&asoc->pending_reply_queue, sq, next);
if (sq->data) {
sctp_m_freem(sq->data);
sq->data = NULL;
}
sctp_free_remote_addr(sq->whoFrom);
sq->whoFrom = NULL;
sq->stcb = NULL;
/* Free the ctl entry */
sctp_free_a_readq(stcb, sq);
/*sa_ignore FREED_MEMORY*/
}
TAILQ_FOREACH_SAFE(chk, &asoc->free_chunks, sctp_next, nchk) {
TAILQ_REMOVE(&asoc->free_chunks, chk, sctp_next);
if (chk->data) {
sctp_m_freem(chk->data);
chk->data = NULL;
}
if (chk->holds_key_ref)
sctp_auth_key_release(stcb, chk->auth_keyid, SCTP_SO_LOCKED);
SCTP_ZONE_FREE(SCTP_BASE_INFO(ipi_zone_chunk), chk);
SCTP_DECR_CHK_COUNT();
atomic_subtract_int(&SCTP_BASE_INFO(ipi_free_chunks), 1);
asoc->free_chunk_cnt--;
/*sa_ignore FREED_MEMORY*/
}
/* pending send queue SHOULD be empty */
TAILQ_FOREACH_SAFE(chk, &asoc->send_queue, sctp_next, nchk) {
if (asoc->strmout[chk->rec.data.sid].chunks_on_queues > 0) {
asoc->strmout[chk->rec.data.sid].chunks_on_queues--;
#ifdef INVARIANTS
} else {
panic("No chunks on the queues for sid %u.", chk->rec.data.sid);
#endif
}
TAILQ_REMOVE(&asoc->send_queue, chk, sctp_next);
if (chk->data) {
if (so) {
/* Still a socket? */
sctp_ulp_notify(SCTP_NOTIFY_UNSENT_DG_FAIL, stcb,
0, chk, SCTP_SO_LOCKED);
}
if (chk->data) {
sctp_m_freem(chk->data);
chk->data = NULL;
}
}
if (chk->holds_key_ref)
sctp_auth_key_release(stcb, chk->auth_keyid, SCTP_SO_LOCKED);
if (chk->whoTo) {
sctp_free_remote_addr(chk->whoTo);
chk->whoTo = NULL;
}
SCTP_ZONE_FREE(SCTP_BASE_INFO(ipi_zone_chunk), chk);
SCTP_DECR_CHK_COUNT();
/*sa_ignore FREED_MEMORY*/
}
/* sent queue SHOULD be empty */
TAILQ_FOREACH_SAFE(chk, &asoc->sent_queue, sctp_next, nchk) {
if (chk->sent != SCTP_DATAGRAM_NR_ACKED) {
if (asoc->strmout[chk->rec.data.sid].chunks_on_queues > 0) {
asoc->strmout[chk->rec.data.sid].chunks_on_queues--;
#ifdef INVARIANTS
} else {
panic("No chunks on the queues for sid %u.", chk->rec.data.sid);
#endif
}
}
TAILQ_REMOVE(&asoc->sent_queue, chk, sctp_next);
if (chk->data) {
if (so) {
/* Still a socket? */
sctp_ulp_notify(SCTP_NOTIFY_SENT_DG_FAIL, stcb,
0, chk, SCTP_SO_LOCKED);
}
if (chk->data) {
sctp_m_freem(chk->data);
chk->data = NULL;
}
}
if (chk->holds_key_ref)
sctp_auth_key_release(stcb, chk->auth_keyid, SCTP_SO_LOCKED);
sctp_free_remote_addr(chk->whoTo);
SCTP_ZONE_FREE(SCTP_BASE_INFO(ipi_zone_chunk), chk);
SCTP_DECR_CHK_COUNT();
/*sa_ignore FREED_MEMORY*/
}
#ifdef INVARIANTS
for (i = 0; i < stcb->asoc.streamoutcnt; i++) {
if (stcb->asoc.strmout[i].chunks_on_queues > 0) {
panic("%u chunks left for stream %u.", stcb->asoc.strmout[i].chunks_on_queues, i);
}
}
#endif
/* control queue MAY not be empty */
TAILQ_FOREACH_SAFE(chk, &asoc->control_send_queue, sctp_next, nchk) {
TAILQ_REMOVE(&asoc->control_send_queue, chk, sctp_next);
if (chk->data) {
sctp_m_freem(chk->data);
chk->data = NULL;
}
if (chk->holds_key_ref)
sctp_auth_key_release(stcb, chk->auth_keyid, SCTP_SO_LOCKED);
sctp_free_remote_addr(chk->whoTo);
SCTP_ZONE_FREE(SCTP_BASE_INFO(ipi_zone_chunk), chk);
SCTP_DECR_CHK_COUNT();
/*sa_ignore FREED_MEMORY*/
}
/* ASCONF queue MAY not be empty */
TAILQ_FOREACH_SAFE(chk, &asoc->asconf_send_queue, sctp_next, nchk) {
TAILQ_REMOVE(&asoc->asconf_send_queue, chk, sctp_next);
if (chk->data) {
sctp_m_freem(chk->data);
chk->data = NULL;
}
if (chk->holds_key_ref)
sctp_auth_key_release(stcb, chk->auth_keyid, SCTP_SO_LOCKED);
sctp_free_remote_addr(chk->whoTo);
SCTP_ZONE_FREE(SCTP_BASE_INFO(ipi_zone_chunk), chk);
SCTP_DECR_CHK_COUNT();
/*sa_ignore FREED_MEMORY*/
}
if (asoc->mapping_array) {
SCTP_FREE(asoc->mapping_array, SCTP_M_MAP);
asoc->mapping_array = NULL;
}
if (asoc->nr_mapping_array) {
SCTP_FREE(asoc->nr_mapping_array, SCTP_M_MAP);
asoc->nr_mapping_array = NULL;
}
/* the stream outs */
if (asoc->strmout) {
SCTP_FREE(asoc->strmout, SCTP_M_STRMO);
asoc->strmout = NULL;
}
asoc->strm_realoutsize = asoc->streamoutcnt = 0;
if (asoc->strmin) {
for (i = 0; i < asoc->streamincnt; i++) {
sctp_clean_up_stream(stcb, &asoc->strmin[i].inqueue);
sctp_clean_up_stream(stcb, &asoc->strmin[i].uno_inqueue);
}
SCTP_FREE(asoc->strmin, SCTP_M_STRMI);
asoc->strmin = NULL;
}
asoc->streamincnt = 0;
TAILQ_FOREACH_SAFE(net, &asoc->nets, sctp_next, nnet) {
#ifdef INVARIANTS
if (SCTP_BASE_INFO(ipi_count_raddr) == 0) {
panic("no net's left alloc'ed, or list points to itself");
}
#endif
TAILQ_REMOVE(&asoc->nets, net, sctp_next);
sctp_free_remote_addr(net);
}
LIST_FOREACH_SAFE(laddr, &asoc->sctp_restricted_addrs, sctp_nxt_addr, naddr) {
/*sa_ignore FREED_MEMORY*/
sctp_remove_laddr(laddr);
}
/* pending asconf (address) parameters */
TAILQ_FOREACH_SAFE(aparam, &asoc->asconf_queue, next, naparam) {
/*sa_ignore FREED_MEMORY*/
TAILQ_REMOVE(&asoc->asconf_queue, aparam, next);
SCTP_FREE(aparam,SCTP_M_ASC_ADDR);
}
TAILQ_FOREACH_SAFE(aack, &asoc->asconf_ack_sent, next, naack) {
/*sa_ignore FREED_MEMORY*/
TAILQ_REMOVE(&asoc->asconf_ack_sent, aack, next);
if (aack->data != NULL) {
sctp_m_freem(aack->data);
}
SCTP_ZONE_FREE(SCTP_BASE_INFO(ipi_zone_asconf_ack), aack);
}
/* clean up auth stuff */
if (asoc->local_hmacs)
sctp_free_hmaclist(asoc->local_hmacs);
if (asoc->peer_hmacs)
sctp_free_hmaclist(asoc->peer_hmacs);
if (asoc->local_auth_chunks)
sctp_free_chunklist(asoc->local_auth_chunks);
if (asoc->peer_auth_chunks)
sctp_free_chunklist(asoc->peer_auth_chunks);
sctp_free_authinfo(&asoc->authinfo);
LIST_FOREACH_SAFE(shared_key, &asoc->shared_keys, next, nshared_key) {
LIST_REMOVE(shared_key, next);
sctp_free_sharedkey(shared_key);
/*sa_ignore FREED_MEMORY*/
}
/* Insert new items here :> */
/* Get rid of LOCK */
SCTP_TCB_UNLOCK(stcb);
SCTP_TCB_LOCK_DESTROY(stcb);
SCTP_TCB_SEND_LOCK_DESTROY(stcb);
if (from_inpcbfree == SCTP_NORMAL_PROC) {
SCTP_INP_INFO_WUNLOCK();
SCTP_INP_RLOCK(inp);
}
#if defined(__APPLE__) /* TEMP CODE */
stcb->freed_from_where = from_location;
#endif
#ifdef SCTP_TRACK_FREED_ASOCS
if (inp->sctp_flags & SCTP_PCB_FLAGS_SOCKET_GONE) {
/* now clean up the tasoc itself */
SCTP_ZONE_FREE(SCTP_BASE_INFO(ipi_zone_asoc), stcb);
SCTP_DECR_ASOC_COUNT();
} else {
LIST_INSERT_HEAD(&inp->sctp_asoc_free_list, stcb, sctp_tcblist);
}
#else
SCTP_ZONE_FREE(SCTP_BASE_INFO(ipi_zone_asoc), stcb);
SCTP_DECR_ASOC_COUNT();
#endif
if (from_inpcbfree == SCTP_NORMAL_PROC) {
if (inp->sctp_flags & SCTP_PCB_FLAGS_SOCKET_GONE) {
/* If its NOT the inp_free calling us AND
* sctp_close as been called, we
* call back...
*/
SCTP_INP_RUNLOCK(inp);
/* This will start the kill timer (if we are
* the last one) since we hold an increment yet. But
* this is the only safe way to do this
* since otherwise if the socket closes
* at the same time we are here we might
* collide in the cleanup.
*/
sctp_inpcb_free(inp,
SCTP_FREE_SHOULD_USE_GRACEFUL_CLOSE,
SCTP_CALLED_DIRECTLY_NOCMPSET);
SCTP_INP_DECR_REF(inp);
goto out_of;
} else {
/* The socket is still open. */
SCTP_INP_DECR_REF(inp);
}
}
if (from_inpcbfree == SCTP_NORMAL_PROC) {
SCTP_INP_RUNLOCK(inp);
}
out_of:
/* destroyed the asoc */
#ifdef SCTP_LOG_CLOSING
sctp_log_closing(inp, NULL, 11);
#endif
return (1);
}
/*
* determine if a destination is "reachable" based upon the addresses bound
* to the current endpoint (e.g. only v4 or v6 currently bound)
*/
/*
* FIX: if we allow assoc-level bindx(), then this needs to be fixed to use
* assoc level v4/v6 flags, as the assoc *may* not have the same address
* types bound as its endpoint
*/
int
sctp_destination_is_reachable(struct sctp_tcb *stcb, struct sockaddr *destaddr)
{
struct sctp_inpcb *inp;
int answer;
/*
* No locks here, the TCB, in all cases is already locked and an
* assoc is up. There is either a INP lock by the caller applied (in
* asconf case when deleting an address) or NOT in the HB case,
* however if HB then the INP increment is up and the INP will not
* be removed (on top of the fact that we have a TCB lock). So we
* only want to read the sctp_flags, which is either bound-all or
* not.. no protection needed since once an assoc is up you can't be
* changing your binding.
*/
inp = stcb->sctp_ep;
if (inp->sctp_flags & SCTP_PCB_FLAGS_BOUNDALL) {
/* if bound all, destination is not restricted */
/*
* RRS: Question during lock work: Is this correct? If you
* are bound-all you still might need to obey the V4--V6
* flags??? IMO this bound-all stuff needs to be removed!
*/
return (1);
}
/* NOTE: all "scope" checks are done when local addresses are added */
switch (destaddr->sa_family) {
#ifdef INET6
case AF_INET6:
#if !(defined(__FreeBSD__) || defined(__APPLE__) || defined(__Windows__) || defined(__Userspace__))
answer = inp->inp_vflag & INP_IPV6;
#else
answer = inp->ip_inp.inp.inp_vflag & INP_IPV6;
#endif
break;
#endif
#ifdef INET
case AF_INET:
#if !(defined(__FreeBSD__) || defined(__APPLE__) || defined(__Windows__) || defined(__Userspace__))
answer = inp->inp_vflag & INP_IPV4;
#else
answer = inp->ip_inp.inp.inp_vflag & INP_IPV4;
#endif
break;
#endif
#if defined(__Userspace__)
case AF_CONN:
answer = inp->ip_inp.inp.inp_vflag & INP_CONN;
break;
#endif
default:
/* invalid family, so it's unreachable */
answer = 0;
break;
}
return (answer);
}
/*
* update the inp_vflags on an endpoint
*/
static void
sctp_update_ep_vflag(struct sctp_inpcb *inp)
{
struct sctp_laddr *laddr;
/* first clear the flag */
#if !(defined(__FreeBSD__) || defined(__APPLE__) || defined(__Windows__) || defined(__Userspace__))
inp->inp_vflag = 0;
#else
inp->ip_inp.inp.inp_vflag = 0;
#endif
/* set the flag based on addresses on the ep list */
LIST_FOREACH(laddr, &inp->sctp_addr_list, sctp_nxt_addr) {
if (laddr->ifa == NULL) {
SCTPDBG(SCTP_DEBUG_PCB1, "%s: NULL ifa\n",
__func__);
continue;
}
if (laddr->ifa->localifa_flags & SCTP_BEING_DELETED) {
continue;
}
switch (laddr->ifa->address.sa.sa_family) {
#ifdef INET6
case AF_INET6:
#if !(defined(__FreeBSD__) || defined(__APPLE__) || defined(__Windows__) || defined(__Userspace__))
inp->inp_vflag |= INP_IPV6;
#else
inp->ip_inp.inp.inp_vflag |= INP_IPV6;
#endif
break;
#endif
#ifdef INET
case AF_INET:
#if !(defined(__FreeBSD__) || defined(__APPLE__) || defined(__Windows__) || defined(__Userspace__))
inp->inp_vflag |= INP_IPV4;
#else
inp->ip_inp.inp.inp_vflag |= INP_IPV4;
#endif
break;
#endif
#if defined(__Userspace__)
case AF_CONN:
inp->ip_inp.inp.inp_vflag |= INP_CONN;
break;
#endif
default:
break;
}
}
}
/*
* Add the address to the endpoint local address list There is nothing to be
* done if we are bound to all addresses
*/
void
sctp_add_local_addr_ep(struct sctp_inpcb *inp, struct sctp_ifa *ifa, uint32_t action)
{
struct sctp_laddr *laddr;
struct sctp_tcb *stcb;
int fnd, error = 0;
fnd = 0;
if (inp->sctp_flags & SCTP_PCB_FLAGS_BOUNDALL) {
/* You are already bound to all. You have it already */
return;
}
#ifdef INET6
if (ifa->address.sa.sa_family == AF_INET6) {
if (ifa->localifa_flags & SCTP_ADDR_IFA_UNUSEABLE) {
/* Can't bind a non-useable addr. */
return;
}
}
#endif
/* first, is it already present? */
LIST_FOREACH(laddr, &inp->sctp_addr_list, sctp_nxt_addr) {
if (laddr->ifa == ifa) {
fnd = 1;
break;
}
}
if (fnd == 0) {
/* Not in the ep list */
error = sctp_insert_laddr(&inp->sctp_addr_list, ifa, action);
if (error != 0)
return;
inp->laddr_count++;
/* update inp_vflag flags */
switch (ifa->address.sa.sa_family) {
#ifdef INET6
case AF_INET6:
#if !(defined(__FreeBSD__) || defined(__APPLE__) || defined(__Windows__) || defined(__Userspace__))
inp->inp_vflag |= INP_IPV6;
#else
inp->ip_inp.inp.inp_vflag |= INP_IPV6;
#endif
break;
#endif
#ifdef INET
case AF_INET:
#if !(defined(__FreeBSD__) || defined(__APPLE__) || defined(__Windows__) || defined(__Userspace__))
inp->inp_vflag |= INP_IPV4;
#else
inp->ip_inp.inp.inp_vflag |= INP_IPV4;
#endif
break;
#endif
#if defined(__Userspace__)
case AF_CONN:
inp->ip_inp.inp.inp_vflag |= INP_CONN;
break;
#endif
default:
break;
}
LIST_FOREACH(stcb, &inp->sctp_asoc_list, sctp_tcblist) {
sctp_add_local_addr_restricted(stcb, ifa);
}
}
return;
}
/*
* select a new (hopefully reachable) destination net (should only be used
* when we deleted an ep addr that is the only usable source address to reach
* the destination net)
*/
static void
sctp_select_primary_destination(struct sctp_tcb *stcb)
{
struct sctp_nets *net;
TAILQ_FOREACH(net, &stcb->asoc.nets, sctp_next) {
/* for now, we'll just pick the first reachable one we find */
if (net->dest_state & SCTP_ADDR_UNCONFIRMED)
continue;
if (sctp_destination_is_reachable(stcb,
(struct sockaddr *)&net->ro._l_addr)) {
/* found a reachable destination */
stcb->asoc.primary_destination = net;
}
}
/* I can't there from here! ...we're gonna die shortly... */
}
/*
* Delete the address from the endpoint local address list. There is nothing
* to be done if we are bound to all addresses
*/
void
sctp_del_local_addr_ep(struct sctp_inpcb *inp, struct sctp_ifa *ifa)
{
struct sctp_laddr *laddr;
int fnd;
fnd = 0;
if (inp->sctp_flags & SCTP_PCB_FLAGS_BOUNDALL) {
/* You are already bound to all. You have it already */
return;
}
LIST_FOREACH(laddr, &inp->sctp_addr_list, sctp_nxt_addr) {
if (laddr->ifa == ifa) {
fnd = 1;
break;
}
}
if (fnd && (inp->laddr_count < 2)) {
/* can't delete unless there are at LEAST 2 addresses */
return;
}
if (fnd) {
/*
* clean up any use of this address go through our
* associations and clear any last_used_address that match
* this one for each assoc, see if a new primary_destination
* is needed
*/
struct sctp_tcb *stcb;
/* clean up "next_addr_touse" */
if (inp->next_addr_touse == laddr)
/* delete this address */
inp->next_addr_touse = NULL;
/* clean up "last_used_address" */
LIST_FOREACH(stcb, &inp->sctp_asoc_list, sctp_tcblist) {
struct sctp_nets *net;
SCTP_TCB_LOCK(stcb);
if (stcb->asoc.last_used_address == laddr)
/* delete this address */
stcb->asoc.last_used_address = NULL;
/* Now spin through all the nets and purge any ref to laddr */
TAILQ_FOREACH(net, &stcb->asoc.nets, sctp_next) {
if (net->ro._s_addr == laddr->ifa) {
/* Yep, purge src address selected */
sctp_rtentry_t *rt;
/* delete this address if cached */
rt = net->ro.ro_rt;
if (rt != NULL) {
RTFREE(rt);
net->ro.ro_rt = NULL;
}
sctp_free_ifa(net->ro._s_addr);
net->ro._s_addr = NULL;
net->src_addr_selected = 0;
}
}
SCTP_TCB_UNLOCK(stcb);
} /* for each tcb */
/* remove it from the ep list */
sctp_remove_laddr(laddr);
inp->laddr_count--;
/* update inp_vflag flags */
sctp_update_ep_vflag(inp);
}
return;
}
/*
* Add the address to the TCB local address restricted list.
* This is a "pending" address list (eg. addresses waiting for an
* ASCONF-ACK response) and cannot be used as a valid source address.
*/
void
sctp_add_local_addr_restricted(struct sctp_tcb *stcb, struct sctp_ifa *ifa)
{
struct sctp_laddr *laddr;
struct sctpladdr *list;
/*
* Assumes TCB is locked.. and possibly the INP. May need to
* confirm/fix that if we need it and is not the case.
*/
list = &stcb->asoc.sctp_restricted_addrs;
#ifdef INET6
if (ifa->address.sa.sa_family == AF_INET6) {
if (ifa->localifa_flags & SCTP_ADDR_IFA_UNUSEABLE) {
/* Can't bind a non-existent addr. */
return;
}
}
#endif
/* does the address already exist? */
LIST_FOREACH(laddr, list, sctp_nxt_addr) {
if (laddr->ifa == ifa) {
return;
}
}
/* add to the list */
(void)sctp_insert_laddr(list, ifa, 0);
return;
}
/*
* Remove a local address from the TCB local address restricted list
*/
void
sctp_del_local_addr_restricted(struct sctp_tcb *stcb, struct sctp_ifa *ifa)
{
struct sctp_inpcb *inp;
struct sctp_laddr *laddr;
/*
* This is called by asconf work. It is assumed that a) The TCB is
* locked and b) The INP is locked. This is true in as much as I can
* trace through the entry asconf code where I did these locks.
* Again, the ASCONF code is a bit different in that it does lock
* the INP during its work often times. This must be since we don't
* want other proc's looking up things while what they are looking
* up is changing :-D
*/
inp = stcb->sctp_ep;
/* if subset bound and don't allow ASCONF's, can't delete last */
if (((inp->sctp_flags & SCTP_PCB_FLAGS_BOUNDALL) == 0) &&
sctp_is_feature_off(inp, SCTP_PCB_FLAGS_DO_ASCONF)) {
if (stcb->sctp_ep->laddr_count < 2) {
/* can't delete last address */
return;
}
}
LIST_FOREACH(laddr, &stcb->asoc.sctp_restricted_addrs, sctp_nxt_addr) {
/* remove the address if it exists */
if (laddr->ifa == NULL)
continue;
if (laddr->ifa == ifa) {
sctp_remove_laddr(laddr);
return;
}
}
/* address not found! */
return;
}
#if defined(__FreeBSD__)
/*
* Temporarily remove for __APPLE__ until we use the Tiger equivalents
*/
/* sysctl */
static int sctp_max_number_of_assoc = SCTP_MAX_NUM_OF_ASOC;
static int sctp_scale_up_for_address = SCTP_SCALE_FOR_ADDR;
#endif /* FreeBSD || APPLE */
#if defined(__FreeBSD__) && defined(SCTP_MCORE_INPUT) && defined(SMP)
struct sctp_mcore_ctrl *sctp_mcore_workers = NULL;
int *sctp_cpuarry = NULL;
void
sctp_queue_to_mcore(struct mbuf *m, int off, int cpu_to_use)
{
/* Queue a packet to a processor for the specified core */
struct sctp_mcore_queue *qent;
struct sctp_mcore_ctrl *wkq;
int need_wake = 0;
if (sctp_mcore_workers == NULL) {
/* Something went way bad during setup */
sctp_input_with_port(m, off, 0);
return;
}
SCTP_MALLOC(qent, struct sctp_mcore_queue *,
(sizeof(struct sctp_mcore_queue)),
SCTP_M_MCORE);
if (qent == NULL) {
/* This is trouble */
sctp_input_with_port(m, off, 0);
return;
}
#if defined(__FreeBSD__) && __FreeBSD_version >= 801000
qent->vn = curvnet;
#endif
qent->m = m;
qent->off = off;
qent->v6 = 0;
wkq = &sctp_mcore_workers[cpu_to_use];
SCTP_MCORE_QLOCK(wkq);
TAILQ_INSERT_TAIL(&wkq->que, qent, next);
if (wkq->running == 0) {
need_wake = 1;
}
SCTP_MCORE_QUNLOCK(wkq);
if (need_wake) {
wakeup(&wkq->running);
}
}
static void
sctp_mcore_thread(void *arg)
{
struct sctp_mcore_ctrl *wkq;
struct sctp_mcore_queue *qent;
wkq = (struct sctp_mcore_ctrl *)arg;
struct mbuf *m;
int off, v6;
/* Wait for first tickle */
SCTP_MCORE_LOCK(wkq);
wkq->running = 0;
msleep(&wkq->running,
&wkq->core_mtx,
0, "wait for pkt", 0);
SCTP_MCORE_UNLOCK(wkq);
/* Bind to our cpu */
thread_lock(curthread);
sched_bind(curthread, wkq->cpuid);
thread_unlock(curthread);
/* Now lets start working */
SCTP_MCORE_LOCK(wkq);
/* Now grab lock and go */
for (;;) {
SCTP_MCORE_QLOCK(wkq);
skip_sleep:
wkq->running = 1;
qent = TAILQ_FIRST(&wkq->que);
if (qent) {
TAILQ_REMOVE(&wkq->que, qent, next);
SCTP_MCORE_QUNLOCK(wkq);
#if defined(__FreeBSD__) && __FreeBSD_version >= 801000
CURVNET_SET(qent->vn);
#endif
m = qent->m;
off = qent->off;
v6 = qent->v6;
SCTP_FREE(qent, SCTP_M_MCORE);
if (v6 == 0) {
sctp_input_with_port(m, off, 0);
} else {
SCTP_PRINTF("V6 not yet supported\n");
sctp_m_freem(m);
}
#if defined(__FreeBSD__) && __FreeBSD_version >= 801000
CURVNET_RESTORE();
#endif
SCTP_MCORE_QLOCK(wkq);
}
wkq->running = 0;
if (!TAILQ_EMPTY(&wkq->que)) {
goto skip_sleep;
}
SCTP_MCORE_QUNLOCK(wkq);
msleep(&wkq->running,
&wkq->core_mtx,
0, "wait for pkt", 0);
}
}
static void
sctp_startup_mcore_threads(void)
{
int i, cpu;
if (mp_ncpus == 1)
return;
if (sctp_mcore_workers != NULL) {
/* Already been here in some previous
* vnet?
*/
return;
}
SCTP_MALLOC(sctp_mcore_workers, struct sctp_mcore_ctrl *,
((mp_maxid+1) * sizeof(struct sctp_mcore_ctrl)),
SCTP_M_MCORE);
if (sctp_mcore_workers == NULL) {
/* TSNH I hope */
return;
}
memset(sctp_mcore_workers, 0 , ((mp_maxid+1) *
sizeof(struct sctp_mcore_ctrl)));
/* Init the structures */
for (i = 0; i<=mp_maxid; i++) {
TAILQ_INIT(&sctp_mcore_workers[i].que);
SCTP_MCORE_LOCK_INIT(&sctp_mcore_workers[i]);
SCTP_MCORE_QLOCK_INIT(&sctp_mcore_workers[i]);
sctp_mcore_workers[i].cpuid = i;
}
if (sctp_cpuarry == NULL) {
SCTP_MALLOC(sctp_cpuarry, int *,
(mp_ncpus * sizeof(int)),
SCTP_M_MCORE);
i = 0;
CPU_FOREACH(cpu) {
sctp_cpuarry[i] = cpu;
i++;
}
}
/* Now start them all */
CPU_FOREACH(cpu) {
#if __FreeBSD_version <= 701000
(void)kthread_create(sctp_mcore_thread,
(void *)&sctp_mcore_workers[cpu],
&sctp_mcore_workers[cpu].thread_proc,
RFPROC,
SCTP_KTHREAD_PAGES,
SCTP_MCORE_NAME);
#else
(void)kproc_create(sctp_mcore_thread,
(void *)&sctp_mcore_workers[cpu],
&sctp_mcore_workers[cpu].thread_proc,
RFPROC,
SCTP_KTHREAD_PAGES,
SCTP_MCORE_NAME);
#endif
}
}
#endif
#if defined(__FreeBSD__) && __FreeBSD_cc_version >= 1400000
static struct mbuf *
sctp_netisr_hdlr(struct mbuf *m, uintptr_t source)
{
struct ip *ip;
struct sctphdr *sh;
int offset;
uint32_t flowid, tag;
/*
* No flow id built by lower layers fix it so we
* create one.
*/
ip = mtod(m, struct ip *);
offset = (ip->ip_hl << 2) + sizeof(struct sctphdr);
if (SCTP_BUF_LEN(m) < offset) {
if ((m = m_pullup(m, offset)) == NULL) {
SCTP_STAT_INCR(sctps_hdrops);
return (NULL);
}
ip = mtod(m, struct ip *);
}
sh = (struct sctphdr *)((caddr_t)ip + (ip->ip_hl << 2));
tag = htonl(sh->v_tag);
flowid = tag ^ ntohs(sh->dest_port) ^ ntohs(sh->src_port);
m->m_pkthdr.flowid = flowid;
/* FIX ME */
m->m_flags |= M_FLOWID;
return (m);
}
#endif
void
#if defined(__Userspace__)
sctp_pcb_init(int start_threads)
#else
sctp_pcb_init(void)
#endif
{
/*
* SCTP initialization for the PCB structures should be called by
* the sctp_init() function.
*/
int i;
struct timeval tv;
if (SCTP_BASE_VAR(sctp_pcb_initialized) != 0) {
/* error I was called twice */
return;
}
SCTP_BASE_VAR(sctp_pcb_initialized) = 1;
#if defined(SCTP_PROCESS_LEVEL_LOCKS)
#if !defined(__Userspace_os_Windows)
pthread_mutexattr_init(&SCTP_BASE_VAR(mtx_attr));
#ifdef INVARIANTS
pthread_mutexattr_settype(&SCTP_BASE_VAR(mtx_attr), PTHREAD_MUTEX_ERRORCHECK);
#endif
#endif
#endif
#if defined(SCTP_LOCAL_TRACE_BUF)
#if defined(__Windows__)
if (SCTP_BASE_SYSCTL(sctp_log) != NULL) {
memset(SCTP_BASE_SYSCTL(sctp_log), 0, sizeof(struct sctp_log));
}
#else
memset(&SCTP_BASE_SYSCTL(sctp_log), 0, sizeof(struct sctp_log));
#endif
#endif
#if defined(__FreeBSD__) && defined(SMP) && defined(SCTP_USE_PERCPU_STAT)
SCTP_MALLOC(SCTP_BASE_STATS, struct sctpstat *,
((mp_maxid+1) * sizeof(struct sctpstat)),
SCTP_M_MCORE);
#endif
(void)SCTP_GETTIME_TIMEVAL(&tv);
#if defined(__FreeBSD__) && defined(SMP) && defined(SCTP_USE_PERCPU_STAT)
memset(SCTP_BASE_STATS, 0, sizeof(struct sctpstat) * (mp_maxid+1));
SCTP_BASE_STATS[PCPU_GET(cpuid)].sctps_discontinuitytime.tv_sec = (uint32_t)tv.tv_sec;
SCTP_BASE_STATS[PCPU_GET(cpuid)].sctps_discontinuitytime.tv_usec = (uint32_t)tv.tv_usec;
#else
memset(&SCTP_BASE_STATS, 0, sizeof(struct sctpstat));
SCTP_BASE_STAT(sctps_discontinuitytime).tv_sec = (uint32_t)tv.tv_sec;
SCTP_BASE_STAT(sctps_discontinuitytime).tv_usec = (uint32_t)tv.tv_usec;
#endif
/* init the empty list of (All) Endpoints */
LIST_INIT(&SCTP_BASE_INFO(listhead));
#if defined(__APPLE__)
LIST_INIT(&SCTP_BASE_INFO(inplisthead));
#if defined(APPLE_LEOPARD) || defined(APPLE_SNOWLEOPARD) || defined(APPLE_LION) || defined(APPLE_MOUNTAINLION)
SCTP_BASE_INFO(sctbinfo).listhead = &SCTP_BASE_INFO(inplisthead);
SCTP_BASE_INFO(sctbinfo).mtx_grp_attr = lck_grp_attr_alloc_init();
lck_grp_attr_setdefault(SCTP_BASE_INFO(sctbinfo).mtx_grp_attr);
SCTP_BASE_INFO(sctbinfo).mtx_grp = lck_grp_alloc_init("sctppcb", SCTP_BASE_INFO(sctbinfo).mtx_grp_attr);
SCTP_BASE_INFO(sctbinfo).mtx_attr = lck_attr_alloc_init();
lck_attr_setdefault(SCTP_BASE_INFO(sctbinfo).mtx_attr);
#else
SCTP_BASE_INFO(sctbinfo).ipi_listhead = &SCTP_BASE_INFO(inplisthead);
SCTP_BASE_INFO(sctbinfo).ipi_lock_grp_attr = lck_grp_attr_alloc_init();
lck_grp_attr_setdefault(SCTP_BASE_INFO(sctbinfo).ipi_lock_grp_attr);
SCTP_BASE_INFO(sctbinfo).ipi_lock_grp = lck_grp_alloc_init("sctppcb", SCTP_BASE_INFO(sctbinfo).ipi_lock_grp_attr);
SCTP_BASE_INFO(sctbinfo).ipi_lock_attr = lck_attr_alloc_init();
lck_attr_setdefault(SCTP_BASE_INFO(sctbinfo).ipi_lock_attr);
#endif
#if !defined(APPLE_LEOPARD) && !defined(APPLE_SNOWLEOPARD) && !defined(APPLE_LION) && !defined(APPLE_MOUNTAINLION)
SCTP_BASE_INFO(sctbinfo).ipi_gc = sctp_gc;
in_pcbinfo_attach(&SCTP_BASE_INFO(sctbinfo));
#endif
#endif
/* init the hash table of endpoints */
#if defined(__FreeBSD__)
#if defined(__FreeBSD_cc_version) && __FreeBSD_cc_version >= 440000
TUNABLE_INT_FETCH("net.inet.sctp.tcbhashsize", &SCTP_BASE_SYSCTL(sctp_hashtblsize));
TUNABLE_INT_FETCH("net.inet.sctp.pcbhashsize", &SCTP_BASE_SYSCTL(sctp_pcbtblsize));
TUNABLE_INT_FETCH("net.inet.sctp.chunkscale", &SCTP_BASE_SYSCTL(sctp_chunkscale));
#else
TUNABLE_INT_FETCH("net.inet.sctp.tcbhashsize", SCTP_TCBHASHSIZE,
SCTP_BASE_SYSCTL(sctp_hashtblsize));
TUNABLE_INT_FETCH("net.inet.sctp.pcbhashsize", SCTP_PCBHASHSIZE,
SCTP_BASE_SYSCTL(sctp_pcbtblsize));
TUNABLE_INT_FETCH("net.inet.sctp.chunkscale", SCTP_CHUNKQUEUE_SCALE,
SCTP_BASE_SYSCTL(sctp_chunkscale));
#endif
#endif
SCTP_BASE_INFO(sctp_asochash) = SCTP_HASH_INIT((SCTP_BASE_SYSCTL(sctp_hashtblsize) * 31),
&SCTP_BASE_INFO(hashasocmark));
SCTP_BASE_INFO(sctp_ephash) = SCTP_HASH_INIT(SCTP_BASE_SYSCTL(sctp_hashtblsize),
&SCTP_BASE_INFO(hashmark));
SCTP_BASE_INFO(sctp_tcpephash) = SCTP_HASH_INIT(SCTP_BASE_SYSCTL(sctp_hashtblsize),
&SCTP_BASE_INFO(hashtcpmark));
SCTP_BASE_INFO(hashtblsize) = SCTP_BASE_SYSCTL(sctp_hashtblsize);
SCTP_BASE_INFO(sctp_vrfhash) = SCTP_HASH_INIT(SCTP_SIZE_OF_VRF_HASH,
&SCTP_BASE_INFO(hashvrfmark));
SCTP_BASE_INFO(vrf_ifn_hash) = SCTP_HASH_INIT(SCTP_VRF_IFN_HASH_SIZE,
&SCTP_BASE_INFO(vrf_ifn_hashmark));
/* init the zones */
/*
* FIX ME: Should check for NULL returns, but if it does fail we are
* doomed to panic anyways... add later maybe.
*/
SCTP_ZONE_INIT(SCTP_BASE_INFO(ipi_zone_ep), "sctp_ep",
sizeof(struct sctp_inpcb), maxsockets);
SCTP_ZONE_INIT(SCTP_BASE_INFO(ipi_zone_asoc), "sctp_asoc",
sizeof(struct sctp_tcb), sctp_max_number_of_assoc);
SCTP_ZONE_INIT(SCTP_BASE_INFO(ipi_zone_laddr), "sctp_laddr",
sizeof(struct sctp_laddr),
(sctp_max_number_of_assoc * sctp_scale_up_for_address));
SCTP_ZONE_INIT(SCTP_BASE_INFO(ipi_zone_net), "sctp_raddr",
sizeof(struct sctp_nets),
(sctp_max_number_of_assoc * sctp_scale_up_for_address));
SCTP_ZONE_INIT(SCTP_BASE_INFO(ipi_zone_chunk), "sctp_chunk",
sizeof(struct sctp_tmit_chunk),
(sctp_max_number_of_assoc * SCTP_BASE_SYSCTL(sctp_chunkscale)));
SCTP_ZONE_INIT(SCTP_BASE_INFO(ipi_zone_readq), "sctp_readq",
sizeof(struct sctp_queued_to_read),
(sctp_max_number_of_assoc * SCTP_BASE_SYSCTL(sctp_chunkscale)));
SCTP_ZONE_INIT(SCTP_BASE_INFO(ipi_zone_strmoq), "sctp_stream_msg_out",
sizeof(struct sctp_stream_queue_pending),
(sctp_max_number_of_assoc * SCTP_BASE_SYSCTL(sctp_chunkscale)));
SCTP_ZONE_INIT(SCTP_BASE_INFO(ipi_zone_asconf), "sctp_asconf",
sizeof(struct sctp_asconf),
(sctp_max_number_of_assoc * SCTP_BASE_SYSCTL(sctp_chunkscale)));
SCTP_ZONE_INIT(SCTP_BASE_INFO(ipi_zone_asconf_ack), "sctp_asconf_ack",
sizeof(struct sctp_asconf_ack),
(sctp_max_number_of_assoc * SCTP_BASE_SYSCTL(sctp_chunkscale)));
/* Master Lock INIT for info structure */
SCTP_INP_INFO_LOCK_INIT();
SCTP_STATLOG_INIT_LOCK();
SCTP_IPI_COUNT_INIT();
SCTP_IPI_ADDR_INIT();
#ifdef SCTP_PACKET_LOGGING
SCTP_IP_PKTLOG_INIT();
#endif
LIST_INIT(&SCTP_BASE_INFO(addr_wq));
SCTP_WQ_ADDR_INIT();
/* not sure if we need all the counts */
SCTP_BASE_INFO(ipi_count_ep) = 0;
/* assoc/tcb zone info */
SCTP_BASE_INFO(ipi_count_asoc) = 0;
/* local addrlist zone info */
SCTP_BASE_INFO(ipi_count_laddr) = 0;
/* remote addrlist zone info */
SCTP_BASE_INFO(ipi_count_raddr) = 0;
/* chunk info */
SCTP_BASE_INFO(ipi_count_chunk) = 0;
/* socket queue zone info */
SCTP_BASE_INFO(ipi_count_readq) = 0;
/* stream out queue cont */
SCTP_BASE_INFO(ipi_count_strmoq) = 0;
SCTP_BASE_INFO(ipi_free_strmoq) = 0;
SCTP_BASE_INFO(ipi_free_chunks) = 0;
SCTP_OS_TIMER_INIT(&SCTP_BASE_INFO(addr_wq_timer.timer));
/* Init the TIMEWAIT list */
for (i = 0; i < SCTP_STACK_VTAG_HASH_SIZE; i++) {
LIST_INIT(&SCTP_BASE_INFO(vtag_timewait)[i]);
}
#if defined(SCTP_PROCESS_LEVEL_LOCKS)
#if defined(__Userspace_os_Windows)
InitializeConditionVariable(&sctp_it_ctl.iterator_wakeup);
#else
(void)pthread_cond_init(&sctp_it_ctl.iterator_wakeup, NULL);
#endif
#endif
sctp_startup_iterator();
#if defined(__FreeBSD__) && defined(SCTP_MCORE_INPUT) && defined(SMP)
sctp_startup_mcore_threads();
#endif
#ifndef __Panda__
/*
* INIT the default VRF which for BSD is the only one, other O/S's
* may have more. But initially they must start with one and then
* add the VRF's as addresses are added.
*/
sctp_init_vrf_list(SCTP_DEFAULT_VRF);
#endif
#if defined(__FreeBSD__) && __FreeBSD_cc_version >= 1400000
if (ip_register_flow_handler(sctp_netisr_hdlr, IPPROTO_SCTP)) {
SCTP_PRINTF("***SCTP- Error can't register netisr handler***\n");
}
#endif
#if defined(_SCTP_NEEDS_CALLOUT_) || defined(_USER_SCTP_NEEDS_CALLOUT_)
/* allocate the lock for the callout/timer queue */
SCTP_TIMERQ_LOCK_INIT();
SCTP_TIMERWAIT_LOCK_INIT();
TAILQ_INIT(&SCTP_BASE_INFO(callqueue));
#endif
#if defined(__Userspace__)
mbuf_initialize(NULL);
atomic_init();
#if defined(INET) || defined(INET6)
if (start_threads)
recv_thread_init();
#endif
#endif
}
/*
* Assumes that the SCTP_BASE_INFO() lock is NOT held.
*/
void
sctp_pcb_finish(void)
{
struct sctp_vrflist *vrf_bucket;
struct sctp_vrf *vrf, *nvrf;
struct sctp_ifn *ifn, *nifn;
struct sctp_ifa *ifa, *nifa;
struct sctpvtaghead *chain;
struct sctp_tagblock *twait_block, *prev_twait_block;
struct sctp_laddr *wi, *nwi;
int i;
struct sctp_iterator *it, *nit;
if (SCTP_BASE_VAR(sctp_pcb_initialized) == 0) {
SCTP_PRINTF("%s: race condition on teardown.\n", __func__);
return;
}
SCTP_BASE_VAR(sctp_pcb_initialized) = 0;
#if !defined(__FreeBSD__)
/* Notify the iterator to exit. */
SCTP_IPI_ITERATOR_WQ_LOCK();
sctp_it_ctl.iterator_flags |= SCTP_ITERATOR_MUST_EXIT;
sctp_wakeup_iterator();
SCTP_IPI_ITERATOR_WQ_UNLOCK();
#endif
#if defined(__APPLE__)
#if !defined(APPLE_LEOPARD) && !defined(APPLE_SNOWLEOPARD) && !defined(APPLE_LION) && !defined(APPLE_MOUNTAINLION)
in_pcbinfo_detach(&SCTP_BASE_INFO(sctbinfo));
#endif
SCTP_IPI_ITERATOR_WQ_LOCK();
do {
msleep(&sctp_it_ctl.iterator_flags,
sctp_it_ctl.ipi_iterator_wq_mtx,
0, "waiting_for_work", 0);
} while ((sctp_it_ctl.iterator_flags & SCTP_ITERATOR_EXITED) == 0);
thread_deallocate(sctp_it_ctl.thread_proc);
SCTP_IPI_ITERATOR_WQ_UNLOCK();
#endif
#if defined(__Windows__)
if (sctp_it_ctl.iterator_thread_obj != NULL) {
NTSTATUS status = STATUS_SUCCESS;
KeSetEvent(&sctp_it_ctl.iterator_wakeup[1], IO_NO_INCREMENT, FALSE);
status = KeWaitForSingleObject(sctp_it_ctl.iterator_thread_obj,
Executive,
KernelMode,
FALSE,
NULL);
ObDereferenceObject(sctp_it_ctl.iterator_thread_obj);
}
#endif
#if defined(__Userspace__)
if (sctp_it_ctl.thread_proc) {
#if defined(__Userspace_os_Windows)
WaitForSingleObject(sctp_it_ctl.thread_proc, INFINITE);
CloseHandle(sctp_it_ctl.thread_proc);
sctp_it_ctl.thread_proc = NULL;
#else
pthread_join(sctp_it_ctl.thread_proc, NULL);
sctp_it_ctl.thread_proc = 0;
#endif
}
#endif
#if defined(SCTP_PROCESS_LEVEL_LOCKS)
#if defined(__Userspace_os_Windows)
DeleteConditionVariable(&sctp_it_ctl.iterator_wakeup);
#else
pthread_cond_destroy(&sctp_it_ctl.iterator_wakeup);
pthread_mutexattr_destroy(&SCTP_BASE_VAR(mtx_attr));
#endif
#endif
/* In FreeBSD the iterator thread never exits
* but we do clean up.
* The only way FreeBSD reaches here is if we have VRF's
* but we still add the ifdef to make it compile on old versions.
*/
#if defined(__FreeBSD__)
retry:
#endif
SCTP_IPI_ITERATOR_WQ_LOCK();
#if defined(__FreeBSD__)
/*
* sctp_iterator_worker() might be working on an it entry without
* holding the lock. We won't find it on the list either and
* continue and free/destroy it. While holding the lock, spin, to
* avoid the race condition as sctp_iterator_worker() will have to
* wait to re-aquire the lock.
*/
if (sctp_it_ctl.iterator_running != 0 || sctp_it_ctl.cur_it != NULL) {
SCTP_IPI_ITERATOR_WQ_UNLOCK();
SCTP_PRINTF("%s: Iterator running while we held the lock. Retry. "
"cur_it=%p\n", __func__, sctp_it_ctl.cur_it);
DELAY(10);
goto retry;
}
#endif
TAILQ_FOREACH_SAFE(it, &sctp_it_ctl.iteratorhead, sctp_nxt_itr, nit) {
#if defined(__FreeBSD__) && __FreeBSD_version >= 801000
if (it->vn != curvnet) {
continue;
}
#endif
TAILQ_REMOVE(&sctp_it_ctl.iteratorhead, it, sctp_nxt_itr);
if (it->function_atend != NULL) {
(*it->function_atend) (it->pointer, it->val);
}
SCTP_FREE(it,SCTP_M_ITER);
}
SCTP_IPI_ITERATOR_WQ_UNLOCK();
#if defined(__FreeBSD__) && __FreeBSD_version >= 801000
SCTP_ITERATOR_LOCK();
if ((sctp_it_ctl.cur_it) &&
(sctp_it_ctl.cur_it->vn == curvnet)) {
sctp_it_ctl.iterator_flags |= SCTP_ITERATOR_STOP_CUR_IT;
}
SCTP_ITERATOR_UNLOCK();
#endif
#if !defined(__FreeBSD__)
SCTP_IPI_ITERATOR_WQ_DESTROY();
SCTP_ITERATOR_LOCK_DESTROY();
#endif
SCTP_OS_TIMER_STOP_DRAIN(&SCTP_BASE_INFO(addr_wq_timer.timer));
SCTP_WQ_ADDR_LOCK();
LIST_FOREACH_SAFE(wi, &SCTP_BASE_INFO(addr_wq), sctp_nxt_addr, nwi) {
LIST_REMOVE(wi, sctp_nxt_addr);
SCTP_DECR_LADDR_COUNT();
if (wi->action == SCTP_DEL_IP_ADDRESS) {
SCTP_FREE(wi->ifa, SCTP_M_IFA);
}
SCTP_ZONE_FREE(SCTP_BASE_INFO(ipi_zone_laddr), wi);
}
SCTP_WQ_ADDR_UNLOCK();
/*
* free the vrf/ifn/ifa lists and hashes (be sure address monitor
* is destroyed first).
*/
vrf_bucket = &SCTP_BASE_INFO(sctp_vrfhash)[(SCTP_DEFAULT_VRFID & SCTP_BASE_INFO(hashvrfmark))];
LIST_FOREACH_SAFE(vrf, vrf_bucket, next_vrf, nvrf) {
LIST_FOREACH_SAFE(ifn, &vrf->ifnlist, next_ifn, nifn) {
LIST_FOREACH_SAFE(ifa, &ifn->ifalist, next_ifa, nifa) {
/* free the ifa */
LIST_REMOVE(ifa, next_bucket);
LIST_REMOVE(ifa, next_ifa);
SCTP_FREE(ifa, SCTP_M_IFA);
}
/* free the ifn */
LIST_REMOVE(ifn, next_bucket);
LIST_REMOVE(ifn, next_ifn);
SCTP_FREE(ifn, SCTP_M_IFN);
}
SCTP_HASH_FREE(vrf->vrf_addr_hash, vrf->vrf_addr_hashmark);
/* free the vrf */
LIST_REMOVE(vrf, next_vrf);
SCTP_FREE(vrf, SCTP_M_VRF);
}
/* free the vrf hashes */
SCTP_HASH_FREE(SCTP_BASE_INFO(sctp_vrfhash), SCTP_BASE_INFO(hashvrfmark));
SCTP_HASH_FREE(SCTP_BASE_INFO(vrf_ifn_hash), SCTP_BASE_INFO(vrf_ifn_hashmark));
/* free the TIMEWAIT list elements malloc'd in the function
* sctp_add_vtag_to_timewait()...
*/
for (i = 0; i < SCTP_STACK_VTAG_HASH_SIZE; i++) {
chain = &SCTP_BASE_INFO(vtag_timewait)[i];
if (!LIST_EMPTY(chain)) {
prev_twait_block = NULL;
LIST_FOREACH(twait_block, chain, sctp_nxt_tagblock) {
if (prev_twait_block) {
SCTP_FREE(prev_twait_block, SCTP_M_TIMW);
}
prev_twait_block = twait_block;
}
SCTP_FREE(prev_twait_block, SCTP_M_TIMW);
}
}
/* free the locks and mutexes */
#if defined(__APPLE__)
SCTP_TIMERQ_LOCK_DESTROY();
SCTP_TIMERWAIT_LOCK_DESTROY();
#endif
#ifdef SCTP_PACKET_LOGGING
SCTP_IP_PKTLOG_DESTROY();
#endif
SCTP_IPI_ADDR_DESTROY();
#if defined(__APPLE__)
SCTP_IPI_COUNT_DESTROY();
#endif
SCTP_STATLOG_DESTROY();
SCTP_INP_INFO_LOCK_DESTROY();
SCTP_WQ_ADDR_DESTROY();
#if defined(__APPLE__)
#if defined(APPLE_LEOPARD) || defined(APPLE_SNOWLEOPARD) || defined(APPLE_LION) || defined(APPLE_MOUNTAINLION)
lck_grp_attr_free(SCTP_BASE_INFO(sctbinfo).mtx_grp_attr);
lck_grp_free(SCTP_BASE_INFO(sctbinfo).mtx_grp);
lck_attr_free(SCTP_BASE_INFO(sctbinfo).mtx_attr);
#else
lck_grp_attr_free(SCTP_BASE_INFO(sctbinfo).ipi_lock_grp_attr);
lck_grp_free(SCTP_BASE_INFO(sctbinfo).ipi_lock_grp);
lck_attr_free(SCTP_BASE_INFO(sctbinfo).ipi_lock_attr);
#endif
#endif
#if defined(__Userspace__)
SCTP_TIMERQ_LOCK_DESTROY();
SCTP_TIMERWAIT_LOCK_DESTROY();
SCTP_ZONE_DESTROY(zone_mbuf);
SCTP_ZONE_DESTROY(zone_clust);
SCTP_ZONE_DESTROY(zone_ext_refcnt);
#endif
/* Get rid of other stuff too. */
if (SCTP_BASE_INFO(sctp_asochash) != NULL)
SCTP_HASH_FREE(SCTP_BASE_INFO(sctp_asochash), SCTP_BASE_INFO(hashasocmark));
if (SCTP_BASE_INFO(sctp_ephash) != NULL)
SCTP_HASH_FREE(SCTP_BASE_INFO(sctp_ephash), SCTP_BASE_INFO(hashmark));
if (SCTP_BASE_INFO(sctp_tcpephash) != NULL)
SCTP_HASH_FREE(SCTP_BASE_INFO(sctp_tcpephash), SCTP_BASE_INFO(hashtcpmark));
#if defined(__Windows__) || defined(__FreeBSD__) || defined(__Userspace__)
SCTP_ZONE_DESTROY(SCTP_BASE_INFO(ipi_zone_ep));
SCTP_ZONE_DESTROY(SCTP_BASE_INFO(ipi_zone_asoc));
SCTP_ZONE_DESTROY(SCTP_BASE_INFO(ipi_zone_laddr));
SCTP_ZONE_DESTROY(SCTP_BASE_INFO(ipi_zone_net));
SCTP_ZONE_DESTROY(SCTP_BASE_INFO(ipi_zone_chunk));
SCTP_ZONE_DESTROY(SCTP_BASE_INFO(ipi_zone_readq));
SCTP_ZONE_DESTROY(SCTP_BASE_INFO(ipi_zone_strmoq));
SCTP_ZONE_DESTROY(SCTP_BASE_INFO(ipi_zone_asconf));
SCTP_ZONE_DESTROY(SCTP_BASE_INFO(ipi_zone_asconf_ack));
#endif
#if defined(__FreeBSD__) && defined(SMP) && defined(SCTP_USE_PERCPU_STAT)
SCTP_FREE(SCTP_BASE_STATS, SCTP_M_MCORE);
#endif
}
int
sctp_load_addresses_from_init(struct sctp_tcb *stcb, struct mbuf *m,
int offset, int limit,
struct sockaddr *src, struct sockaddr *dst,
struct sockaddr *altsa, uint16_t port)
{
/*
* grub through the INIT pulling addresses and loading them to the
* nets structure in the asoc. The from address in the mbuf should
* also be loaded (if it is not already). This routine can be called
* with either INIT or INIT-ACK's as long as the m points to the IP
* packet and the offset points to the beginning of the parameters.
*/
struct sctp_inpcb *inp;
struct sctp_nets *net, *nnet, *net_tmp;
struct sctp_paramhdr *phdr, param_buf;
struct sctp_tcb *stcb_tmp;
uint16_t ptype, plen;
struct sockaddr *sa;
uint8_t random_store[SCTP_PARAM_BUFFER_SIZE];
struct sctp_auth_random *p_random = NULL;
uint16_t random_len = 0;
uint8_t hmacs_store[SCTP_PARAM_BUFFER_SIZE];
struct sctp_auth_hmac_algo *hmacs = NULL;
uint16_t hmacs_len = 0;
uint8_t saw_asconf = 0;
uint8_t saw_asconf_ack = 0;
uint8_t chunks_store[SCTP_PARAM_BUFFER_SIZE];
struct sctp_auth_chunk_list *chunks = NULL;
uint16_t num_chunks = 0;
sctp_key_t *new_key;
uint32_t keylen;
int got_random = 0, got_hmacs = 0, got_chklist = 0;
uint8_t peer_supports_ecn;
uint8_t peer_supports_prsctp;
uint8_t peer_supports_auth;
uint8_t peer_supports_asconf;
uint8_t peer_supports_asconf_ack;
uint8_t peer_supports_reconfig;
uint8_t peer_supports_nrsack;
uint8_t peer_supports_pktdrop;
uint8_t peer_supports_idata;
#ifdef INET
struct sockaddr_in sin;
#endif
#ifdef INET6
struct sockaddr_in6 sin6;
#endif
/* First get the destination address setup too. */
#ifdef INET
memset(&sin, 0, sizeof(sin));
sin.sin_family = AF_INET;
#ifdef HAVE_SIN_LEN
sin.sin_len = sizeof(sin);
#endif
sin.sin_port = stcb->rport;
#endif
#ifdef INET6
memset(&sin6, 0, sizeof(sin6));
sin6.sin6_family = AF_INET6;
#ifdef HAVE_SIN6_LEN
sin6.sin6_len = sizeof(struct sockaddr_in6);
#endif
sin6.sin6_port = stcb->rport;
#endif
if (altsa) {
sa = altsa;
} else {
sa = src;
}
peer_supports_idata = 0;
peer_supports_ecn = 0;
peer_supports_prsctp = 0;
peer_supports_auth = 0;
peer_supports_asconf = 0;
peer_supports_reconfig = 0;
peer_supports_nrsack = 0;
peer_supports_pktdrop = 0;
TAILQ_FOREACH(net, &stcb->asoc.nets, sctp_next) {
/* mark all addresses that we have currently on the list */
net->dest_state |= SCTP_ADDR_NOT_IN_ASSOC;
}
/* does the source address already exist? if so skip it */
inp = stcb->sctp_ep;
atomic_add_int(&stcb->asoc.refcnt, 1);
stcb_tmp = sctp_findassociation_ep_addr(&inp, sa, &net_tmp, dst, stcb);
atomic_add_int(&stcb->asoc.refcnt, -1);
if ((stcb_tmp == NULL && inp == stcb->sctp_ep) || inp == NULL) {
/* we must add the source address */
/* no scope set here since we have a tcb already. */
switch (sa->sa_family) {
#ifdef INET
case AF_INET:
if (stcb->asoc.scope.ipv4_addr_legal) {
if (sctp_add_remote_addr(stcb, sa, NULL, port, SCTP_DONOT_SETSCOPE, SCTP_LOAD_ADDR_2)) {
return (-1);
}
}
break;
#endif
#ifdef INET6
case AF_INET6:
if (stcb->asoc.scope.ipv6_addr_legal) {
if (sctp_add_remote_addr(stcb, sa, NULL, port, SCTP_DONOT_SETSCOPE, SCTP_LOAD_ADDR_3)) {
return (-2);
}
}
break;
#endif
#if defined(__Userspace__)
case AF_CONN:
if (stcb->asoc.scope.conn_addr_legal) {
if (sctp_add_remote_addr(stcb, sa, NULL, port, SCTP_DONOT_SETSCOPE, SCTP_LOAD_ADDR_3)) {
return (-2);
}
}
break;
#endif
default:
break;
}
} else {
if (net_tmp != NULL && stcb_tmp == stcb) {
net_tmp->dest_state &= ~SCTP_ADDR_NOT_IN_ASSOC;
} else if (stcb_tmp != stcb) {
/* It belongs to another association? */
if (stcb_tmp)
SCTP_TCB_UNLOCK(stcb_tmp);
return (-3);
}
}
if (stcb->asoc.state == 0) {
/* the assoc was freed? */
return (-4);
}
/* now we must go through each of the params. */
phdr = sctp_get_next_param(m, offset, ¶m_buf, sizeof(param_buf));
while (phdr) {
ptype = ntohs(phdr->param_type);
plen = ntohs(phdr->param_length);
/*
* SCTP_PRINTF("ptype => %0x, plen => %d\n", (uint32_t)ptype,
* (int)plen);
*/
if (offset + plen > limit) {
break;
}
if (plen < sizeof(struct sctp_paramhdr)) {
break;
}
#ifdef INET
if (ptype == SCTP_IPV4_ADDRESS) {
if (stcb->asoc.scope.ipv4_addr_legal) {
struct sctp_ipv4addr_param *p4, p4_buf;
/* ok get the v4 address and check/add */
phdr = sctp_get_next_param(m, offset,
(struct sctp_paramhdr *)&p4_buf,
sizeof(p4_buf));
if (plen != sizeof(struct sctp_ipv4addr_param) ||
phdr == NULL) {
return (-5);
}
p4 = (struct sctp_ipv4addr_param *)phdr;
sin.sin_addr.s_addr = p4->addr;
if (IN_MULTICAST(ntohl(sin.sin_addr.s_addr))) {
/* Skip multi-cast addresses */
goto next_param;
}
if ((sin.sin_addr.s_addr == INADDR_BROADCAST) ||
(sin.sin_addr.s_addr == INADDR_ANY)) {
goto next_param;
}
sa = (struct sockaddr *)&sin;
inp = stcb->sctp_ep;
atomic_add_int(&stcb->asoc.refcnt, 1);
stcb_tmp = sctp_findassociation_ep_addr(&inp, sa, &net,
dst, stcb);
atomic_add_int(&stcb->asoc.refcnt, -1);
if ((stcb_tmp == NULL && inp == stcb->sctp_ep) ||
inp == NULL) {
/* we must add the source address */
/*
* no scope set since we have a tcb
* already
*/
/*
* we must validate the state again
* here
*/
add_it_now:
if (stcb->asoc.state == 0) {
/* the assoc was freed? */
return (-7);
}
if (sctp_add_remote_addr(stcb, sa, NULL, port, SCTP_DONOT_SETSCOPE, SCTP_LOAD_ADDR_4)) {
return (-8);
}
} else if (stcb_tmp == stcb) {
if (stcb->asoc.state == 0) {
/* the assoc was freed? */
return (-10);
}
if (net != NULL) {
/* clear flag */
net->dest_state &=
~SCTP_ADDR_NOT_IN_ASSOC;
}
} else {
/*
* strange, address is in another
* assoc? straighten out locks.
*/
if (stcb_tmp) {
if (SCTP_GET_STATE(stcb_tmp) == SCTP_STATE_COOKIE_WAIT) {
struct mbuf *op_err;
char msg[SCTP_DIAG_INFO_LEN];
/* in setup state we abort this guy */
snprintf(msg, sizeof(msg),
"%s:%d at %s", __FILE__, __LINE__, __func__);
op_err = sctp_generate_cause(SCTP_BASE_SYSCTL(sctp_diag_info_code),
msg);
sctp_abort_an_association(stcb_tmp->sctp_ep,
stcb_tmp, op_err,
SCTP_SO_NOT_LOCKED);
goto add_it_now;
}
SCTP_TCB_UNLOCK(stcb_tmp);
}
if (stcb->asoc.state == 0) {
/* the assoc was freed? */
return (-12);
}
return (-13);
}
}
} else
#endif
#ifdef INET6
if (ptype == SCTP_IPV6_ADDRESS) {
if (stcb->asoc.scope.ipv6_addr_legal) {
/* ok get the v6 address and check/add */
struct sctp_ipv6addr_param *p6, p6_buf;
phdr = sctp_get_next_param(m, offset,
(struct sctp_paramhdr *)&p6_buf,
sizeof(p6_buf));
if (plen != sizeof(struct sctp_ipv6addr_param) ||
phdr == NULL) {
return (-14);
}
p6 = (struct sctp_ipv6addr_param *)phdr;
memcpy((caddr_t)&sin6.sin6_addr, p6->addr,
sizeof(p6->addr));
if (IN6_IS_ADDR_MULTICAST(&sin6.sin6_addr)) {
/* Skip multi-cast addresses */
goto next_param;
}
if (IN6_IS_ADDR_LINKLOCAL(&sin6.sin6_addr)) {
/* Link local make no sense without scope */
goto next_param;
}
sa = (struct sockaddr *)&sin6;
inp = stcb->sctp_ep;
atomic_add_int(&stcb->asoc.refcnt, 1);
stcb_tmp = sctp_findassociation_ep_addr(&inp, sa, &net,
dst, stcb);
atomic_add_int(&stcb->asoc.refcnt, -1);
if (stcb_tmp == NULL &&
(inp == stcb->sctp_ep || inp == NULL)) {
/*
* we must validate the state again
* here
*/
add_it_now6:
if (stcb->asoc.state == 0) {
/* the assoc was freed? */
return (-16);
}
/*
* we must add the address, no scope
* set
*/
if (sctp_add_remote_addr(stcb, sa, NULL, port, SCTP_DONOT_SETSCOPE, SCTP_LOAD_ADDR_5)) {
return (-17);
}
} else if (stcb_tmp == stcb) {
/*
* we must validate the state again
* here
*/
if (stcb->asoc.state == 0) {
/* the assoc was freed? */
return (-19);
}
if (net != NULL) {
/* clear flag */
net->dest_state &=
~SCTP_ADDR_NOT_IN_ASSOC;
}
} else {
/*
* strange, address is in another
* assoc? straighten out locks.
*/
if (stcb_tmp) {
if (SCTP_GET_STATE(stcb_tmp) == SCTP_STATE_COOKIE_WAIT) {
struct mbuf *op_err;
char msg[SCTP_DIAG_INFO_LEN];
/* in setup state we abort this guy */
snprintf(msg, sizeof(msg),
"%s:%d at %s", __FILE__, __LINE__, __func__);
op_err = sctp_generate_cause(SCTP_BASE_SYSCTL(sctp_diag_info_code),
msg);
sctp_abort_an_association(stcb_tmp->sctp_ep,
stcb_tmp, op_err,
SCTP_SO_NOT_LOCKED);
goto add_it_now6;
}
SCTP_TCB_UNLOCK(stcb_tmp);
}
if (stcb->asoc.state == 0) {
/* the assoc was freed? */
return (-21);
}
return (-22);
}
}
} else
#endif
if (ptype == SCTP_ECN_CAPABLE) {
peer_supports_ecn = 1;
} else if (ptype == SCTP_ULP_ADAPTATION) {
if (stcb->asoc.state != SCTP_STATE_OPEN) {
struct sctp_adaptation_layer_indication ai, *aip;
phdr = sctp_get_next_param(m, offset,
(struct sctp_paramhdr *)&ai, sizeof(ai));
aip = (struct sctp_adaptation_layer_indication *)phdr;
if (aip) {
stcb->asoc.peers_adaptation = ntohl(aip->indication);
stcb->asoc.adaptation_needed = 1;
}
}
} else if (ptype == SCTP_SET_PRIM_ADDR) {
struct sctp_asconf_addr_param lstore, *fee;
int lptype;
struct sockaddr *lsa = NULL;
#ifdef INET
struct sctp_asconf_addrv4_param *fii;
#endif
if (stcb->asoc.asconf_supported == 0) {
return (-100);
}
if (plen > sizeof(lstore)) {
return (-23);
}
if (plen < sizeof(struct sctp_asconf_addrv4_param)) {
return (-101);
}
phdr = sctp_get_next_param(m, offset,
(struct sctp_paramhdr *)&lstore,
plen);
if (phdr == NULL) {
return (-24);
}
fee = (struct sctp_asconf_addr_param *)phdr;
lptype = ntohs(fee->addrp.ph.param_type);
switch (lptype) {
#ifdef INET
case SCTP_IPV4_ADDRESS:
if (plen !=
sizeof(struct sctp_asconf_addrv4_param)) {
SCTP_PRINTF("Sizeof setprim in init/init ack not %d but %d - ignored\n",
(int)sizeof(struct sctp_asconf_addrv4_param),
plen);
} else {
fii = (struct sctp_asconf_addrv4_param *)fee;
sin.sin_addr.s_addr = fii->addrp.addr;
lsa = (struct sockaddr *)&sin;
}
break;
#endif
#ifdef INET6
case SCTP_IPV6_ADDRESS:
if (plen !=
sizeof(struct sctp_asconf_addr_param)) {
SCTP_PRINTF("Sizeof setprim (v6) in init/init ack not %d but %d - ignored\n",
(int)sizeof(struct sctp_asconf_addr_param),
plen);
} else {
memcpy(sin6.sin6_addr.s6_addr,
fee->addrp.addr,
sizeof(fee->addrp.addr));
lsa = (struct sockaddr *)&sin6;
}
break;
#endif
default:
break;
}
if (lsa) {
(void)sctp_set_primary_addr(stcb, sa, NULL);
}
} else if (ptype == SCTP_HAS_NAT_SUPPORT) {
stcb->asoc.peer_supports_nat = 1;
} else if (ptype == SCTP_PRSCTP_SUPPORTED) {
/* Peer supports pr-sctp */
peer_supports_prsctp = 1;
} else if (ptype == SCTP_SUPPORTED_CHUNK_EXT) {
/* A supported extension chunk */
struct sctp_supported_chunk_types_param *pr_supported;
uint8_t local_store[SCTP_PARAM_BUFFER_SIZE];
int num_ent, i;
if (plen > sizeof(local_store)) {
return (-35);
}
phdr = sctp_get_next_param(m, offset,
(struct sctp_paramhdr *)&local_store, plen);
if (phdr == NULL) {
return (-25);
}
pr_supported = (struct sctp_supported_chunk_types_param *)phdr;
num_ent = plen - sizeof(struct sctp_paramhdr);
for (i = 0; i < num_ent; i++) {
switch (pr_supported->chunk_types[i]) {
case SCTP_ASCONF:
peer_supports_asconf = 1;
break;
case SCTP_ASCONF_ACK:
peer_supports_asconf_ack = 1;
break;
case SCTP_FORWARD_CUM_TSN:
peer_supports_prsctp = 1;
break;
case SCTP_PACKET_DROPPED:
peer_supports_pktdrop = 1;
break;
case SCTP_NR_SELECTIVE_ACK:
peer_supports_nrsack = 1;
break;
case SCTP_STREAM_RESET:
peer_supports_reconfig = 1;
break;
case SCTP_AUTHENTICATION:
peer_supports_auth = 1;
break;
case SCTP_IDATA:
peer_supports_idata = 1;
break;
default:
/* one I have not learned yet */
break;
}
}
} else if (ptype == SCTP_RANDOM) {
if (plen > sizeof(random_store))
break;
if (got_random) {
/* already processed a RANDOM */
goto next_param;
}
phdr = sctp_get_next_param(m, offset,
(struct sctp_paramhdr *)random_store,
plen);
if (phdr == NULL)
return (-26);
p_random = (struct sctp_auth_random *)phdr;
random_len = plen - sizeof(*p_random);
/* enforce the random length */
if (random_len != SCTP_AUTH_RANDOM_SIZE_REQUIRED) {
SCTPDBG(SCTP_DEBUG_AUTH1, "SCTP: invalid RANDOM len\n");
return (-27);
}
got_random = 1;
} else if (ptype == SCTP_HMAC_LIST) {
uint16_t num_hmacs;
uint16_t i;
if (plen > sizeof(hmacs_store))
break;
if (got_hmacs) {
/* already processed a HMAC list */
goto next_param;
}
phdr = sctp_get_next_param(m, offset,
(struct sctp_paramhdr *)hmacs_store,
plen);
if (phdr == NULL)
return (-28);
hmacs = (struct sctp_auth_hmac_algo *)phdr;
hmacs_len = plen - sizeof(*hmacs);
num_hmacs = hmacs_len / sizeof(hmacs->hmac_ids[0]);
/* validate the hmac list */
if (sctp_verify_hmac_param(hmacs, num_hmacs)) {
return (-29);
}
if (stcb->asoc.peer_hmacs != NULL)
sctp_free_hmaclist(stcb->asoc.peer_hmacs);
stcb->asoc.peer_hmacs = sctp_alloc_hmaclist(num_hmacs);
if (stcb->asoc.peer_hmacs != NULL) {
for (i = 0; i < num_hmacs; i++) {
(void)sctp_auth_add_hmacid(stcb->asoc.peer_hmacs,
ntohs(hmacs->hmac_ids[i]));
}
}
got_hmacs = 1;
} else if (ptype == SCTP_CHUNK_LIST) {
int i;
if (plen > sizeof(chunks_store))
break;
if (got_chklist) {
/* already processed a Chunks list */
goto next_param;
}
phdr = sctp_get_next_param(m, offset,
(struct sctp_paramhdr *)chunks_store,
plen);
if (phdr == NULL)
return (-30);
chunks = (struct sctp_auth_chunk_list *)phdr;
num_chunks = plen - sizeof(*chunks);
if (stcb->asoc.peer_auth_chunks != NULL)
sctp_clear_chunklist(stcb->asoc.peer_auth_chunks);
else
stcb->asoc.peer_auth_chunks = sctp_alloc_chunklist();
for (i = 0; i < num_chunks; i++) {
(void)sctp_auth_add_chunk(chunks->chunk_types[i],
stcb->asoc.peer_auth_chunks);
/* record asconf/asconf-ack if listed */
if (chunks->chunk_types[i] == SCTP_ASCONF)
saw_asconf = 1;
if (chunks->chunk_types[i] == SCTP_ASCONF_ACK)
saw_asconf_ack = 1;
}
got_chklist = 1;
} else if ((ptype == SCTP_HEARTBEAT_INFO) ||
(ptype == SCTP_STATE_COOKIE) ||
(ptype == SCTP_UNRECOG_PARAM) ||
(ptype == SCTP_COOKIE_PRESERVE) ||
(ptype == SCTP_SUPPORTED_ADDRTYPE) ||
(ptype == SCTP_ADD_IP_ADDRESS) ||
(ptype == SCTP_DEL_IP_ADDRESS) ||
(ptype == SCTP_ERROR_CAUSE_IND) ||
(ptype == SCTP_SUCCESS_REPORT)) {
/* don't care */ ;
} else {
if ((ptype & 0x8000) == 0x0000) {
/*
* must stop processing the rest of the
* param's. Any report bits were handled
* with the call to
* sctp_arethere_unrecognized_parameters()
* when the INIT or INIT-ACK was first seen.
*/
break;
}
}
next_param:
offset += SCTP_SIZE32(plen);
if (offset >= limit) {
break;
}
phdr = sctp_get_next_param(m, offset, ¶m_buf,
sizeof(param_buf));
}
/* Now check to see if we need to purge any addresses */
TAILQ_FOREACH_SAFE(net, &stcb->asoc.nets, sctp_next, nnet) {
if ((net->dest_state & SCTP_ADDR_NOT_IN_ASSOC) ==
SCTP_ADDR_NOT_IN_ASSOC) {
/* This address has been removed from the asoc */
/* remove and free it */
stcb->asoc.numnets--;
TAILQ_REMOVE(&stcb->asoc.nets, net, sctp_next);
sctp_free_remote_addr(net);
if (net == stcb->asoc.primary_destination) {
stcb->asoc.primary_destination = NULL;
sctp_select_primary_destination(stcb);
}
}
}
if ((stcb->asoc.ecn_supported == 1) &&
(peer_supports_ecn == 0)) {
stcb->asoc.ecn_supported = 0;
}
if ((stcb->asoc.prsctp_supported == 1) &&
(peer_supports_prsctp == 0)) {
stcb->asoc.prsctp_supported = 0;
}
if ((stcb->asoc.auth_supported == 1) &&
((peer_supports_auth == 0) ||
(got_random == 0) || (got_hmacs == 0))) {
stcb->asoc.auth_supported = 0;
}
if ((stcb->asoc.asconf_supported == 1) &&
((peer_supports_asconf == 0) || (peer_supports_asconf_ack == 0) ||
(stcb->asoc.auth_supported == 0) ||
(saw_asconf == 0) || (saw_asconf_ack == 0))) {
stcb->asoc.asconf_supported = 0;
}
if ((stcb->asoc.reconfig_supported == 1) &&
(peer_supports_reconfig == 0)) {
stcb->asoc.reconfig_supported = 0;
}
if ((stcb->asoc.idata_supported == 1) &&
(peer_supports_idata == 0)) {
stcb->asoc.idata_supported = 0;
}
if ((stcb->asoc.nrsack_supported == 1) &&
(peer_supports_nrsack == 0)) {
stcb->asoc.nrsack_supported = 0;
}
if ((stcb->asoc.pktdrop_supported == 1) &&
(peer_supports_pktdrop == 0)){
stcb->asoc.pktdrop_supported = 0;
}
/* validate authentication required parameters */
if ((peer_supports_auth == 0) && (got_chklist == 1)) {
/* peer does not support auth but sent a chunks list? */
return (-31);
}
if ((peer_supports_asconf == 1) && (peer_supports_auth == 0)) {
/* peer supports asconf but not auth? */
return (-32);
} else if ((peer_supports_asconf == 1) &&
(peer_supports_auth == 1) &&
((saw_asconf == 0) || (saw_asconf_ack == 0))) {
return (-33);
}
/* concatenate the full random key */
keylen = sizeof(*p_random) + random_len + sizeof(*hmacs) + hmacs_len;
if (chunks != NULL) {
keylen += sizeof(*chunks) + num_chunks;
}
new_key = sctp_alloc_key(keylen);
if (new_key != NULL) {
/* copy in the RANDOM */
if (p_random != NULL) {
keylen = sizeof(*p_random) + random_len;
memcpy(new_key->key, p_random, keylen);
} else {
keylen = 0;
}
/* append in the AUTH chunks */
if (chunks != NULL) {
memcpy(new_key->key + keylen, chunks,
sizeof(*chunks) + num_chunks);
keylen += sizeof(*chunks) + num_chunks;
}
/* append in the HMACs */
if (hmacs != NULL) {
memcpy(new_key->key + keylen, hmacs,
sizeof(*hmacs) + hmacs_len);
}
} else {
/* failed to get memory for the key */
return (-34);
}
if (stcb->asoc.authinfo.peer_random != NULL)
sctp_free_key(stcb->asoc.authinfo.peer_random);
stcb->asoc.authinfo.peer_random = new_key;
sctp_clear_cachedkeys(stcb, stcb->asoc.authinfo.assoc_keyid);
sctp_clear_cachedkeys(stcb, stcb->asoc.authinfo.recv_keyid);
return (0);
}
int
sctp_set_primary_addr(struct sctp_tcb *stcb, struct sockaddr *sa,
struct sctp_nets *net)
{
/* make sure the requested primary address exists in the assoc */
if (net == NULL && sa)
net = sctp_findnet(stcb, sa);
if (net == NULL) {
/* didn't find the requested primary address! */
return (-1);
} else {
/* set the primary address */
if (net->dest_state & SCTP_ADDR_UNCONFIRMED) {
/* Must be confirmed, so queue to set */
net->dest_state |= SCTP_ADDR_REQ_PRIMARY;
return (0);
}
stcb->asoc.primary_destination = net;
if (!(net->dest_state & SCTP_ADDR_PF) && (stcb->asoc.alternate)) {
sctp_free_remote_addr(stcb->asoc.alternate);
stcb->asoc.alternate = NULL;
}
net = TAILQ_FIRST(&stcb->asoc.nets);
if (net != stcb->asoc.primary_destination) {
/* first one on the list is NOT the primary
* sctp_cmpaddr() is much more efficient if
* the primary is the first on the list, make it
* so.
*/
TAILQ_REMOVE(&stcb->asoc.nets, stcb->asoc.primary_destination, sctp_next);
TAILQ_INSERT_HEAD(&stcb->asoc.nets, stcb->asoc.primary_destination, sctp_next);
}
return (0);
}
}
int
sctp_is_vtag_good(uint32_t tag, uint16_t lport, uint16_t rport, struct timeval *now)
{
/*
* This function serves two purposes. It will see if a TAG can be
* re-used and return 1 for yes it is ok and 0 for don't use that
* tag. A secondary function it will do is purge out old tags that
* can be removed.
*/
struct sctpvtaghead *chain;
struct sctp_tagblock *twait_block;
struct sctpasochead *head;
struct sctp_tcb *stcb;
int i;
SCTP_INP_INFO_RLOCK();
head = &SCTP_BASE_INFO(sctp_asochash)[SCTP_PCBHASH_ASOC(tag,
SCTP_BASE_INFO(hashasocmark))];
LIST_FOREACH(stcb, head, sctp_asocs) {
/* We choose not to lock anything here. TCB's can't be
* removed since we have the read lock, so they can't
* be freed on us, same thing for the INP. I may
* be wrong with this assumption, but we will go
* with it for now :-)
*/
if (stcb->sctp_ep->sctp_flags & SCTP_PCB_FLAGS_SOCKET_ALLGONE) {
continue;
}
if (stcb->asoc.my_vtag == tag) {
/* candidate */
if (stcb->rport != rport) {
continue;
}
if (stcb->sctp_ep->sctp_lport != lport) {
continue;
}
/* Its a used tag set */
SCTP_INP_INFO_RUNLOCK();
return (0);
}
}
chain = &SCTP_BASE_INFO(vtag_timewait)[(tag % SCTP_STACK_VTAG_HASH_SIZE)];
/* Now what about timed wait ? */
LIST_FOREACH(twait_block, chain, sctp_nxt_tagblock) {
/*
* Block(s) are present, lets see if we have this tag in the
* list
*/
for (i = 0; i < SCTP_NUMBER_IN_VTAG_BLOCK; i++) {
if (twait_block->vtag_block[i].v_tag == 0) {
/* not used */
continue;
} else if ((long)twait_block->vtag_block[i].tv_sec_at_expire <
now->tv_sec) {
/* Audit expires this guy */
twait_block->vtag_block[i].tv_sec_at_expire = 0;
twait_block->vtag_block[i].v_tag = 0;
twait_block->vtag_block[i].lport = 0;
twait_block->vtag_block[i].rport = 0;
} else if ((twait_block->vtag_block[i].v_tag == tag) &&
(twait_block->vtag_block[i].lport == lport) &&
(twait_block->vtag_block[i].rport == rport)) {
/* Bad tag, sorry :< */
SCTP_INP_INFO_RUNLOCK();
return (0);
}
}
}
SCTP_INP_INFO_RUNLOCK();
return (1);
}
static void
sctp_drain_mbufs(struct sctp_tcb *stcb)
{
/*
* We must hunt this association for MBUF's past the cumack (i.e.
* out of order data that we can renege on).
*/
struct sctp_association *asoc;
struct sctp_tmit_chunk *chk, *nchk;
uint32_t cumulative_tsn_p1;
struct sctp_queued_to_read *control, *ncontrol;
int cnt, strmat;
uint32_t gap, i;
int fnd = 0;
/* We look for anything larger than the cum-ack + 1 */
asoc = &stcb->asoc;
if (asoc->cumulative_tsn == asoc->highest_tsn_inside_map) {
/* none we can reneg on. */
return;
}
SCTP_STAT_INCR(sctps_protocol_drains_done);
cumulative_tsn_p1 = asoc->cumulative_tsn + 1;
cnt = 0;
/* Ok that was fun, now we will drain all the inbound streams? */
for (strmat = 0; strmat < asoc->streamincnt; strmat++) {
TAILQ_FOREACH_SAFE(control, &asoc->strmin[strmat].inqueue, next_instrm, ncontrol) {
#ifdef INVARIANTS
if (control->on_strm_q != SCTP_ON_ORDERED ) {
panic("Huh control: %p on_q: %d -- not ordered?",
control, control->on_strm_q);
}
#endif
if (SCTP_TSN_GT(control->sinfo_tsn, cumulative_tsn_p1)) {
/* Yep it is above cum-ack */
cnt++;
SCTP_CALC_TSN_TO_GAP(gap, control->sinfo_tsn, asoc->mapping_array_base_tsn);
KASSERT(control->length > 0, ("control has zero length"));
if (asoc->size_on_all_streams >= control->length) {
asoc->size_on_all_streams -= control->length;
} else {
#ifdef INVARIANTS
panic("size_on_all_streams = %u smaller than control length %u", asoc->size_on_all_streams, control->length);
#else
asoc->size_on_all_streams = 0;
#endif
}
sctp_ucount_decr(asoc->cnt_on_all_streams);
SCTP_UNSET_TSN_PRESENT(asoc->mapping_array, gap);
if (control->on_read_q) {
TAILQ_REMOVE(&stcb->sctp_ep->read_queue, control, next);
control->on_read_q = 0;
}
TAILQ_REMOVE(&asoc->strmin[strmat].inqueue, control, next_instrm);
control->on_strm_q = 0;
if (control->data) {
sctp_m_freem(control->data);
control->data = NULL;
}
sctp_free_remote_addr(control->whoFrom);
/* Now its reasm? */
TAILQ_FOREACH_SAFE(chk, &control->reasm, sctp_next, nchk) {
cnt++;
SCTP_CALC_TSN_TO_GAP(gap, chk->rec.data.tsn, asoc->mapping_array_base_tsn);
KASSERT(chk->send_size > 0, ("chunk has zero length"));
if (asoc->size_on_reasm_queue >= chk->send_size) {
asoc->size_on_reasm_queue -= chk->send_size;
} else {
#ifdef INVARIANTS
panic("size_on_reasm_queue = %u smaller than chunk length %u", asoc->size_on_reasm_queue, chk->send_size);
#else
asoc->size_on_reasm_queue = 0;
#endif
}
sctp_ucount_decr(asoc->cnt_on_reasm_queue);
SCTP_UNSET_TSN_PRESENT(asoc->mapping_array, gap);
TAILQ_REMOVE(&control->reasm, chk, sctp_next);
if (chk->data) {
sctp_m_freem(chk->data);
chk->data = NULL;
}
sctp_free_a_chunk(stcb, chk, SCTP_SO_NOT_LOCKED);
}
sctp_free_a_readq(stcb, control);
}
}
TAILQ_FOREACH_SAFE(control, &asoc->strmin[strmat].uno_inqueue, next_instrm, ncontrol) {
#ifdef INVARIANTS
if (control->on_strm_q != SCTP_ON_UNORDERED ) {
panic("Huh control: %p on_q: %d -- not unordered?",
control, control->on_strm_q);
}
#endif
if (SCTP_TSN_GT(control->sinfo_tsn, cumulative_tsn_p1)) {
/* Yep it is above cum-ack */
cnt++;
SCTP_CALC_TSN_TO_GAP(gap, control->sinfo_tsn, asoc->mapping_array_base_tsn);
KASSERT(control->length > 0, ("control has zero length"));
if (asoc->size_on_all_streams >= control->length) {
asoc->size_on_all_streams -= control->length;
} else {
#ifdef INVARIANTS
panic("size_on_all_streams = %u smaller than control length %u", asoc->size_on_all_streams, control->length);
#else
asoc->size_on_all_streams = 0;
#endif
}
sctp_ucount_decr(asoc->cnt_on_all_streams);
SCTP_UNSET_TSN_PRESENT(asoc->mapping_array, gap);
if (control->on_read_q) {
TAILQ_REMOVE(&stcb->sctp_ep->read_queue, control, next);
control->on_read_q = 0;
}
TAILQ_REMOVE(&asoc->strmin[strmat].uno_inqueue, control, next_instrm);
control->on_strm_q = 0;
if (control->data) {
sctp_m_freem(control->data);
control->data = NULL;
}
sctp_free_remote_addr(control->whoFrom);
/* Now its reasm? */
TAILQ_FOREACH_SAFE(chk, &control->reasm, sctp_next, nchk) {
cnt++;
SCTP_CALC_TSN_TO_GAP(gap, chk->rec.data.tsn, asoc->mapping_array_base_tsn);
KASSERT(chk->send_size > 0, ("chunk has zero length"));
if (asoc->size_on_reasm_queue >= chk->send_size) {
asoc->size_on_reasm_queue -= chk->send_size;
} else {
#ifdef INVARIANTS
panic("size_on_reasm_queue = %u smaller than chunk length %u", asoc->size_on_reasm_queue, chk->send_size);
#else
asoc->size_on_reasm_queue = 0;
#endif
}
sctp_ucount_decr(asoc->cnt_on_reasm_queue);
SCTP_UNSET_TSN_PRESENT(asoc->mapping_array, gap);
TAILQ_REMOVE(&control->reasm, chk, sctp_next);
if (chk->data) {
sctp_m_freem(chk->data);
chk->data = NULL;
}
sctp_free_a_chunk(stcb, chk, SCTP_SO_NOT_LOCKED);
}
sctp_free_a_readq(stcb, control);
}
}
}
if (cnt) {
/* We must back down to see what the new highest is */
for (i = asoc->highest_tsn_inside_map; SCTP_TSN_GE(i, asoc->mapping_array_base_tsn); i--) {
SCTP_CALC_TSN_TO_GAP(gap, i, asoc->mapping_array_base_tsn);
if (SCTP_IS_TSN_PRESENT(asoc->mapping_array, gap)) {
asoc->highest_tsn_inside_map = i;
fnd = 1;
break;
}
}
if (!fnd) {
asoc->highest_tsn_inside_map = asoc->mapping_array_base_tsn - 1;
}
/*
* Question, should we go through the delivery queue? The only
* reason things are on here is the app not reading OR a p-d-api up.
* An attacker COULD send enough in to initiate the PD-API and then
* send a bunch of stuff to other streams... these would wind up on
* the delivery queue.. and then we would not get to them. But in
* order to do this I then have to back-track and un-deliver
* sequence numbers in streams.. el-yucko. I think for now we will
* NOT look at the delivery queue and leave it to be something to
* consider later. An alternative would be to abort the P-D-API with
* a notification and then deliver the data.... Or another method
* might be to keep track of how many times the situation occurs and
* if we see a possible attack underway just abort the association.
*/
#ifdef SCTP_DEBUG
SCTPDBG(SCTP_DEBUG_PCB1, "Freed %d chunks from reneg harvest\n", cnt);
#endif
/*
* Now do we need to find a new
* asoc->highest_tsn_inside_map?
*/
asoc->last_revoke_count = cnt;
(void)SCTP_OS_TIMER_STOP(&stcb->asoc.dack_timer.timer);
/*sa_ignore NO_NULL_CHK*/
sctp_send_sack(stcb, SCTP_SO_NOT_LOCKED);
sctp_chunk_output(stcb->sctp_ep, stcb, SCTP_OUTPUT_FROM_DRAIN, SCTP_SO_NOT_LOCKED);
}
/*
* Another issue, in un-setting the TSN's in the mapping array we
* DID NOT adjust the highest_tsn marker. This will cause one of two
* things to occur. It may cause us to do extra work in checking for
* our mapping array movement. More importantly it may cause us to
* SACK every datagram. This may not be a bad thing though since we
* will recover once we get our cum-ack above and all this stuff we
* dumped recovered.
*/
}
void
sctp_drain()
{
/*
* We must walk the PCB lists for ALL associations here. The system
* is LOW on MBUF's and needs help. This is where reneging will
* occur. We really hope this does NOT happen!
*/
#if defined(__FreeBSD__) && __FreeBSD_version >= 801000
VNET_ITERATOR_DECL(vnet_iter);
#else
struct sctp_inpcb *inp;
struct sctp_tcb *stcb;
SCTP_STAT_INCR(sctps_protocol_drain_calls);
if (SCTP_BASE_SYSCTL(sctp_do_drain) == 0) {
return;
}
#endif
#if defined(__FreeBSD__) && __FreeBSD_version >= 801000
VNET_LIST_RLOCK_NOSLEEP();
VNET_FOREACH(vnet_iter) {
CURVNET_SET(vnet_iter);
struct sctp_inpcb *inp;
struct sctp_tcb *stcb;
#endif
#if defined(__FreeBSD__) && __FreeBSD_version >= 801000
SCTP_STAT_INCR(sctps_protocol_drain_calls);
if (SCTP_BASE_SYSCTL(sctp_do_drain) == 0) {
#ifdef VIMAGE
continue;
#else
return;
#endif
}
#endif
SCTP_INP_INFO_RLOCK();
LIST_FOREACH(inp, &SCTP_BASE_INFO(listhead), sctp_list) {
/* For each endpoint */
SCTP_INP_RLOCK(inp);
LIST_FOREACH(stcb, &inp->sctp_asoc_list, sctp_tcblist) {
/* For each association */
SCTP_TCB_LOCK(stcb);
sctp_drain_mbufs(stcb);
SCTP_TCB_UNLOCK(stcb);
}
SCTP_INP_RUNLOCK(inp);
}
SCTP_INP_INFO_RUNLOCK();
#if defined(__FreeBSD__) && __FreeBSD_version >= 801000
CURVNET_RESTORE();
}
VNET_LIST_RUNLOCK_NOSLEEP();
#endif
}
/*
* start a new iterator
* iterates through all endpoints and associations based on the pcb_state
* flags and asoc_state. "af" (mandatory) is executed for all matching
* assocs and "ef" (optional) is executed when the iterator completes.
* "inpf" (optional) is executed for each new endpoint as it is being
* iterated through. inpe (optional) is called when the inp completes
* its way through all the stcbs.
*/
int
sctp_initiate_iterator(inp_func inpf,
asoc_func af,
inp_func inpe,
uint32_t pcb_state,
uint32_t pcb_features,
uint32_t asoc_state,
void *argp,
uint32_t argi,
end_func ef,
struct sctp_inpcb *s_inp,
uint8_t chunk_output_off)
{
struct sctp_iterator *it = NULL;
if (af == NULL) {
return (-1);
}
if (SCTP_BASE_VAR(sctp_pcb_initialized) == 0) {
SCTP_PRINTF("%s: abort on initialize being %d\n", __func__,
SCTP_BASE_VAR(sctp_pcb_initialized));
return (-1);
}
SCTP_MALLOC(it, struct sctp_iterator *, sizeof(struct sctp_iterator),
SCTP_M_ITER);
if (it == NULL) {
SCTP_LTRACE_ERR_RET(NULL, NULL, NULL, SCTP_FROM_SCTP_PCB, ENOMEM);
return (ENOMEM);
}
memset(it, 0, sizeof(*it));
it->function_assoc = af;
it->function_inp = inpf;
if (inpf)
it->done_current_ep = 0;
else
it->done_current_ep = 1;
it->function_atend = ef;
it->pointer = argp;
it->val = argi;
it->pcb_flags = pcb_state;
it->pcb_features = pcb_features;
it->asoc_state = asoc_state;
it->function_inp_end = inpe;
it->no_chunk_output = chunk_output_off;
#if defined(__FreeBSD__) && __FreeBSD_version >= 801000
it->vn = curvnet;
#endif
if (s_inp) {
/* Assume lock is held here */
it->inp = s_inp;
SCTP_INP_INCR_REF(it->inp);
it->iterator_flags = SCTP_ITERATOR_DO_SINGLE_INP;
} else {
SCTP_INP_INFO_RLOCK();
it->inp = LIST_FIRST(&SCTP_BASE_INFO(listhead));
if (it->inp) {
SCTP_INP_INCR_REF(it->inp);
}
SCTP_INP_INFO_RUNLOCK();
it->iterator_flags = SCTP_ITERATOR_DO_ALL_INP;
}
SCTP_IPI_ITERATOR_WQ_LOCK();
if (SCTP_BASE_VAR(sctp_pcb_initialized) == 0) {
SCTP_IPI_ITERATOR_WQ_UNLOCK();
SCTP_PRINTF("%s: rollback on initialize being %d it=%p\n", __func__,
SCTP_BASE_VAR(sctp_pcb_initialized), it);
SCTP_FREE(it, SCTP_M_ITER);
return (-1);
}
TAILQ_INSERT_TAIL(&sctp_it_ctl.iteratorhead, it, sctp_nxt_itr);
if (sctp_it_ctl.iterator_running == 0) {
sctp_wakeup_iterator();
}
SCTP_IPI_ITERATOR_WQ_UNLOCK();
/* sa_ignore MEMLEAK {memory is put on the tailq for the iterator} */
return (0);
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/good_1370_1 |
crossvul-cpp_data_good_2588_3 | /*
* midi.c -- Midi Wavetable Processing library
*
* Copyright (C) WildMIDI Developers 2001-2016
*
* This file is part of WildMIDI.
*
* WildMIDI is free software: you can redistribute and/or modify the player
* under the terms of the GNU General Public License and you can redistribute
* and/or modify the library under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation, either version 3 of
* the licenses, or(at your option) any later version.
*
* WildMIDI 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 and
* the GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU General Public License and the
* GNU Lesser General Public License along with WildMIDI. If not, see
* <http://www.gnu.org/licenses/>.
*/
#include "config.h"
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "common.h"
#include "wm_error.h"
#include "f_midi.h"
#include "wildmidi_lib.h"
#include "internal_midi.h"
#include "reverb.h"
#include "sample.h"
struct _mdi *
_WM_ParseNewMidi(uint8_t *midi_data, uint32_t midi_size) {
struct _mdi *mdi;
uint32_t tmp_val;
uint32_t midi_type;
uint8_t **tracks;
uint32_t *track_size;
uint32_t end_of_tracks = 0;
uint32_t no_tracks;
uint32_t i;
uint32_t divisions = 96;
uint32_t tempo = 500000;
float samples_per_delta_f = 0.0;
uint32_t sample_count = 0;
float sample_count_f = 0.0;
float sample_remainder = 0.0;
uint8_t *sysex_store = NULL;
uint32_t *track_delta;
uint8_t *track_end;
uint32_t smallest_delta = 0;
uint32_t subtract_delta = 0;
uint8_t *running_event;
uint32_t setup_ret = 0;
if (midi_size < 14) {
_WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_CORUPT, "(too short)", 0);
return (NULL);
}
if (!memcmp(midi_data, "RIFF", 4)) {
if (midi_size < 34) {
_WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_CORUPT, "(too short)", 0);
return (NULL);
}
midi_data += 20;
midi_size -= 20;
}
if (memcmp(midi_data, "MThd", 4)) {
_WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_NOT_MIDI, NULL, 0);
return (NULL);
}
midi_data += 4;
midi_size -= 4;
/*
* Get Midi Header Size - must always be 6
*/
tmp_val = *midi_data++ << 24;
tmp_val |= *midi_data++ << 16;
tmp_val |= *midi_data++ << 8;
tmp_val |= *midi_data++;
midi_size -= 4;
if (tmp_val != 6) {
_WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_CORUPT, NULL, 0);
return (NULL);
}
/*
* Get Midi Format - we only support 0, 1 & 2
*/
tmp_val = *midi_data++ << 8;
tmp_val |= *midi_data++;
midi_size -= 2;
if (tmp_val > 2) {
_WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_INVALID, NULL, 0);
return (NULL);
}
midi_type = tmp_val;
/*
* Get No. of Tracks
*/
tmp_val = *midi_data++ << 8;
tmp_val |= *midi_data++;
midi_size -= 2;
if (tmp_val < 1) {
_WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_CORUPT, "(no tracks)", 0);
return (NULL);
}
no_tracks = tmp_val;
/*
* Check that type 0 midi file has only 1 track
*/
if ((midi_type == 0) && (no_tracks > 1)) {
_WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_INVALID, "(expected 1 track for type 0 midi file, found more)", 0);
return (NULL);
}
/*
* Get Divisions
*/
divisions = *midi_data++ << 8;
divisions |= *midi_data++;
midi_size -= 2;
if (divisions & 0x00008000) {
_WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_INVALID, NULL, 0);
return (NULL);
}
samples_per_delta_f = _WM_GetSamplesPerTick(divisions, tempo);
mdi = _WM_initMDI();
_WM_midi_setup_divisions(mdi,divisions);
tracks = malloc(sizeof(uint8_t *) * no_tracks);
track_size = malloc(sizeof(uint32_t) * no_tracks);
track_delta = malloc(sizeof(uint32_t) * no_tracks);
track_end = malloc(sizeof(uint8_t) * no_tracks);
running_event = malloc(sizeof(uint8_t) * no_tracks);
smallest_delta = 0xffffffff;
for (i = 0; i < no_tracks; i++) {
if (midi_size < 8) {
_WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_CORUPT, "(too short)", 0);
goto _end;
}
if (memcmp(midi_data, "MTrk", 4) != 0) {
_WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_CORUPT, "(missing track header)", 0);
goto _end;
}
midi_data += 4;
midi_size -= 4;
/* track size */
tmp_val = *midi_data++ << 24;
tmp_val |= *midi_data++ << 16;
tmp_val |= *midi_data++ << 8;
tmp_val |= *midi_data++;
midi_size -= 4;
if (midi_size < tmp_val) {
_WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_CORUPT, "(too short)", 0);
goto _end;
}
if (tmp_val < 3) {
_WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_CORUPT, "(bad track size)", 0);
goto _end;
}
if ((midi_data[tmp_val - 3] != 0xFF)
|| (midi_data[tmp_val - 2] != 0x2F)
|| (midi_data[tmp_val - 1] != 0x00)) {
_WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_CORUPT, "(missing EOT)", 0);
goto _end;
}
tracks[i] = midi_data;
track_size[i] = tmp_val;
midi_data += tmp_val;
midi_size -= tmp_val;
track_end[i] = 0;
running_event[i] = 0;
track_delta[i] = 0;
while (*tracks[i] > 0x7F) {
track_delta[i] = (track_delta[i] << 7) + (*tracks[i] & 0x7F);
tracks[i]++;
track_size[i]--;
}
track_delta[i] = (track_delta[i] << 7) + (*tracks[i] & 0x7F);
tracks[i]++;
track_size[i]--;
if (midi_type == 1 ) {
if (track_delta[i] < smallest_delta) {
smallest_delta = track_delta[i];
}
} else {
/*
* Type 0 & 2 midi only needs delta from 1st track
* for initial sample calculations.
*/
if (i == 0) smallest_delta = track_delta[i];
}
}
subtract_delta = smallest_delta;
sample_count_f = (((float) smallest_delta * samples_per_delta_f) + sample_remainder);
sample_count = (uint32_t) sample_count_f;
sample_remainder = sample_count_f - (float) sample_count;
mdi->events[mdi->event_count - 1].samples_to_next += sample_count;
mdi->extra_info.approx_total_samples += sample_count;
/*
* Handle type 0 & 2 the same, but type 1 differently
*/
if (midi_type == 1) {
/* Type 1 */
while (end_of_tracks != no_tracks) {
smallest_delta = 0;
for (i = 0; i < no_tracks; i++) {
if (track_end[i])
continue;
if (track_delta[i]) {
track_delta[i] -= subtract_delta;
if (track_delta[i]) {
if ((!smallest_delta)
|| (smallest_delta > track_delta[i])) {
smallest_delta = track_delta[i];
}
continue;
}
}
do {
setup_ret = _WM_SetupMidiEvent(mdi, tracks[i], track_size[i], running_event[i]);
if (setup_ret == 0) {
goto _end;
}
if (tracks[i][0] > 0x7f) {
if (tracks[i][0] < 0xf0) {
/* Events 0x80 - 0xef set running event */
running_event[i] = tracks[i][0];
} else if ((tracks[i][0] == 0xf0) || (tracks[i][0] == 0xf7)) {
/* Sysex resets running event */
running_event[i] = 0;
} else if ((tracks[i][0] == 0xff) && (tracks[i][1] == 0x2f) && (tracks[i][2] == 0x00)) {
/* End of Track */
end_of_tracks++;
track_end[i] = 1;
tracks[i] += 3;
track_size[i] -= 3;
goto NEXT_TRACK;
} else if ((tracks[i][0] == 0xff) && (tracks[i][1] == 0x51) && (tracks[i][2] == 0x03)) {
/* Tempo */
tempo = (tracks[i][3] << 16) + (tracks[i][4] << 8)+ tracks[i][5];
if (!tempo)
tempo = 500000;
samples_per_delta_f = _WM_GetSamplesPerTick(divisions, tempo);
}
}
tracks[i] += setup_ret;
track_size[i] -= setup_ret;
if (*tracks[i] > 0x7f) {
do {
if (!track_size[i]) break;
track_delta[i] = (track_delta[i] << 7) + (*tracks[i] & 0x7F);
tracks[i]++;
track_size[i]--;
} while (*tracks[i] > 0x7f);
}
if (!track_size[i]) {
_WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_CORUPT, "(too short)", 0);
goto _end;
}
track_delta[i] = (track_delta[i] << 7) + (*tracks[i] & 0x7F);
tracks[i]++;
track_size[i]--;
} while (!track_delta[i]);
if ((!smallest_delta) || (smallest_delta > track_delta[i])) {
smallest_delta = track_delta[i];
}
NEXT_TRACK: continue;
}
subtract_delta = smallest_delta;
sample_count_f = (((float) smallest_delta * samples_per_delta_f)
+ sample_remainder);
sample_count = (uint32_t) sample_count_f;
sample_remainder = sample_count_f - (float) sample_count;
mdi->events[mdi->event_count - 1].samples_to_next += sample_count;
mdi->extra_info.approx_total_samples += sample_count;
}
} else {
/* Type 0 & 2 */
if (midi_type == 2) {
mdi->is_type2 = 1;
}
sample_remainder = 0.0;
for (i = 0; i < no_tracks; i++) {
running_event[i] = 0;
do {
setup_ret = _WM_SetupMidiEvent(mdi, tracks[i], track_size[i], running_event[i]);
if (setup_ret == 0) {
goto _end;
}
if (tracks[i][0] > 0x7f) {
if (tracks[i][0] < 0xf0) {
/* Events 0x80 - 0xef set running event */
running_event[i] = tracks[i][0];
} else if ((tracks[i][0] == 0xf0) || (tracks[i][0] == 0xf7)) {
/* Sysex resets running event */
running_event[i] = 0;
} else if ((tracks[i][0] == 0xff) && (tracks[i][1] == 0x2f) && (tracks[i][2] == 0x00)) {
/* End of Track */
track_end[i] = 1;
goto NEXT_TRACK2;
} else if ((tracks[i][0] == 0xff) && (tracks[i][1] == 0x51) && (tracks[i][2] == 0x03)) {
/* Tempo */
tempo = (tracks[i][3] << 16) + (tracks[i][4] << 8)+ tracks[i][5];
if (!tempo)
tempo = 500000;
samples_per_delta_f = _WM_GetSamplesPerTick(divisions, tempo);
}
}
tracks[i] += setup_ret;
track_size[i] -= setup_ret;
track_delta[i] = 0;
if (*tracks[i] > 0x7f) {
do {
if (!track_size[i]) break;
track_delta[i] = (track_delta[i] << 7) + (*tracks[i] & 0x7F);
tracks[i]++;
track_size[i]--;
} while (*tracks[i] > 0x7f);
}
if (!track_size[i]) {
_WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_CORUPT, "(too short)", 0);
goto _end;
}
track_delta[i] = (track_delta[i] << 7) + (*tracks[i] & 0x7F);
tracks[i]++;
track_size[i]--;
sample_count_f = (((float) track_delta[i] * samples_per_delta_f)
+ sample_remainder);
sample_count = (uint32_t) sample_count_f;
sample_remainder = sample_count_f - (float) sample_count;
mdi->events[mdi->event_count - 1].samples_to_next += sample_count;
mdi->extra_info.approx_total_samples += sample_count;
NEXT_TRACK2:
smallest_delta = track_delta[i]; /* Added just to keep Xcode happy */
UNUSED(smallest_delta); /* Added to just keep clang happy */
} while (track_end[i] == 0);
}
}
if ((mdi->reverb = _WM_init_reverb(_WM_SampleRate, _WM_reverb_room_width,
_WM_reverb_room_length, _WM_reverb_listen_posx, _WM_reverb_listen_posy))
== NULL) {
_WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_MEM, "to init reverb", 0);
goto _end;
}
mdi->extra_info.current_sample = 0;
mdi->current_event = &mdi->events[0];
mdi->samples_to_mix = 0;
mdi->note = NULL;
_WM_ResetToStart(mdi);
_end: free(sysex_store);
free(track_end);
free(track_delta);
free(running_event);
free(tracks);
free(track_size);
if (mdi->reverb) return (mdi);
_WM_freeMDI(mdi);
return (NULL);
}
/*
Convert WildMIDI's MDI events into a type 0 MIDI file.
returns
0 = successful
-1 = failed
**out points to place to store stuff
*outsize points to where to store byte counts
NOTE: This will only write out events that we do support.
*** CAUTION ***
This will output type 0 midi file reguardless of the original file type.
Type 2 midi files will have each original track play on the same track one
after the other in the type 0 file.
*/
int
_WM_Event2Midi(struct _mdi *mdi, uint8_t **out, uint32_t *outsize) {
uint32_t out_ofs = 0;
uint8_t running_event = 0;
uint32_t divisions = 96;
uint32_t tempo = 500000;
float samples_per_tick = 0.0;
uint32_t value = 0;
float value_f = 0.0;
struct _event *event = mdi->events;
uint32_t track_size = 0;
uint32_t track_start = 0;
uint32_t track_count = 0;
if (!mdi->event_count) {
_WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_CONVERT, "(No events to convert)", 0);
return -1;
}
samples_per_tick = _WM_GetSamplesPerTick(divisions, tempo);
/*
Note: This isn't accurate but will allow enough space for
events plus delta values.
*/
(*out) = malloc (sizeof(uint8_t) * (mdi->event_count * 12));
/* Midi Header */
(*out)[0] = 'M';
(*out)[1] = 'T';
(*out)[2] = 'h';
(*out)[3] = 'd';
(*out)[4] = 0x00;
(*out)[5] = 0x00;
(*out)[6] = 0x00;
(*out)[7] = 0x06;
if ((!(_WM_MixerOptions & WM_MO_SAVEASTYPE0)) && (mdi->is_type2)) {
/* Type 2 */
(*out)[8] = 0x00;
(*out)[9] = 0x02;
} else {
/* Type 0 */
(*out)[8] = 0x00;
(*out)[9] = 0x00;
}
/* No. of tracks stored in 10-11 *** See below */
/* Division stored in 12-13 *** See below */
/* Track Header */
(*out)[14] = 'M';
(*out)[15] = 'T';
(*out)[16] = 'r';
(*out)[17] = 'k';
/* Track size stored in 18-21 *** see below */
out_ofs = 22;
track_start = out_ofs;
track_count++;
do {
/* TODO Is there a better way? */
if (event->do_event == _WM_do_midi_divisions) {
// DEBUG
// fprintf(stderr,"Division: %u\r\n",event->event_data.data);
divisions = event->event_data.data.value;
(*out)[12] = (divisions >> 8) & 0xff;
(*out)[13] = divisions & 0xff;
samples_per_tick = _WM_GetSamplesPerTick(divisions, tempo);
} else if (event->do_event == _WM_do_note_off) {
// DEBUG
// fprintf(stderr,"Note Off: %u %.4x\r\n",event->event_data.channel, event->event_data.data);
if (running_event != (0x80 | event->event_data.channel)) {
(*out)[out_ofs++] = 0x80 | event->event_data.channel;
running_event = (*out)[out_ofs - 1];
}
(*out)[out_ofs++] = (event->event_data.data.value >> 8) & 0xff;
(*out)[out_ofs++] = event->event_data.data.value & 0xff;
} else if (event->do_event == _WM_do_note_on) {
// DEBUG
// fprintf(stderr,"Note On: %u %.4x\r\n",event->event_data.channel, event->event_data.data);
if (running_event != (0x90 | event->event_data.channel)) {
(*out)[out_ofs++] = 0x90 | event->event_data.channel;
running_event = (*out)[out_ofs - 1];
}
(*out)[out_ofs++] = (event->event_data.data.value >> 8) & 0xff;
(*out)[out_ofs++] = event->event_data.data.value & 0xff;
} else if (event->do_event == _WM_do_aftertouch) {
// DEBUG
// fprintf(stderr,"Aftertouch: %u %.4x\r\n",event->event_data.channel, event->event_data.data);
if (running_event != (0xa0 | event->event_data.channel)) {
(*out)[out_ofs++] = 0xa0 | event->event_data.channel;
running_event = (*out)[out_ofs - 1];
}
(*out)[out_ofs++] = (event->event_data.data.value >> 8) & 0xff;
(*out)[out_ofs++] = event->event_data.data.value & 0xff;
} else if (event->do_event == _WM_do_control_bank_select) {
// DEBUG
// fprintf(stderr,"Control Bank Select: %u %.4x\r\n",event->event_data.channel, event->event_data.data);
if (running_event != (0xb0 | event->event_data.channel)) {
(*out)[out_ofs++] = 0xb0 | event->event_data.channel;
running_event = (*out)[out_ofs - 1];
}
(*out)[out_ofs++] = 0;
(*out)[out_ofs++] = event->event_data.data.value & 0xff;
} else if (event->do_event == _WM_do_control_data_entry_course) {
// DEBUG
// fprintf(stderr,"Control Data Entry Course: %u %.4x\r\n",event->event_data.channel, event->event_data.data);
if (running_event != (0xb0 | event->event_data.channel)) {
(*out)[out_ofs++] = 0xb0 | event->event_data.channel;
running_event = (*out)[out_ofs - 1];
}
(*out)[out_ofs++] = 6;
(*out)[out_ofs++] = event->event_data.data.value & 0xff;
} else if (event->do_event == _WM_do_control_channel_volume) {
// DEBUG
// fprintf(stderr,"Control Channel Volume: %u %.4x\r\n",event->event_data.channel, event->event_data.data);
if (running_event != (0xb0 | event->event_data.channel)) {
(*out)[out_ofs++] = 0xb0 | event->event_data.channel;
running_event = (*out)[out_ofs - 1];
}
(*out)[out_ofs++] = 7;
(*out)[out_ofs++] = event->event_data.data.value & 0xff;
} else if (event->do_event == _WM_do_control_channel_balance) {
// DEBUG
// fprintf(stderr,"Control Channel Balance: %u %.4x\r\n",event->event_data.channel, event->event_data.data);
if (running_event != (0xb0 | event->event_data.channel)) {
(*out)[out_ofs++] = 0xb0 | event->event_data.channel;
running_event = (*out)[out_ofs - 1];
}
(*out)[out_ofs++] = 8;
(*out)[out_ofs++] = event->event_data.data.value & 0xff;
} else if (event->do_event == _WM_do_control_channel_pan) {
// DEBUG
// fprintf(stderr,"Control Channel Pan: %u %.4x\r\n",event->event_data.channel, event->event_data.data);
if (running_event != (0xb0 | event->event_data.channel)) {
(*out)[out_ofs++] = 0xb0 | event->event_data.channel;
running_event = (*out)[out_ofs - 1];
}
(*out)[out_ofs++] = 10;
(*out)[out_ofs++] = event->event_data.data.value & 0xff;
} else if (event->do_event == _WM_do_control_channel_expression) {
// DEBUG
// fprintf(stderr,"Control Channel Expression: %u %.4x\r\n",event->event_data.channel, event->event_data.data);
if (running_event != (0xb0 | event->event_data.channel)) {
(*out)[out_ofs++] = 0xb0 | event->event_data.channel;
running_event = (*out)[out_ofs - 1];
}
(*out)[out_ofs++] = 11;
(*out)[out_ofs++] = event->event_data.data.value & 0xff;
} else if (event->do_event == _WM_do_control_data_entry_fine) {
// DEBUG
// fprintf(stderr,"Control Data Entry Fine: %u %.4x\r\n",event->event_data.channel, event->event_data.data);
if (running_event != (0xb0 | event->event_data.channel)) {
(*out)[out_ofs++] = 0xb0 | event->event_data.channel;
running_event = (*out)[out_ofs - 1];
}
(*out)[out_ofs++] = 38;
(*out)[out_ofs++] = event->event_data.data.value & 0xff;
} else if (event->do_event == _WM_do_control_channel_hold) {
// DEBUG
// fprintf(stderr,"Control Channel Hold: %u %.4x\r\n",event->event_data.channel, event->event_data.data);
if (running_event != (0xb0 | event->event_data.channel)) {
(*out)[out_ofs++] = 0xb0 | event->event_data.channel;
running_event = (*out)[out_ofs - 1];
}
(*out)[out_ofs++] = 64;
(*out)[out_ofs++] = event->event_data.data.value & 0xff;
} else if (event->do_event == _WM_do_control_data_increment) {
// DEBUG
// fprintf(stderr,"Control Data Increment: %u %.4x\r\n",event->event_data.channel, event->event_data.data);
if (running_event != (0xb0 | event->event_data.channel)) {
(*out)[out_ofs++] = 0xb0 | event->event_data.channel;
running_event = (*out)[out_ofs - 1];
}
(*out)[out_ofs++] = 96;
(*out)[out_ofs++] = event->event_data.data.value & 0xff;
} else if (event->do_event == _WM_do_control_data_decrement) {
// DEBUG
//fprintf(stderr,"Control Data Decrement: %u %.4x\r\n",event->event_data.channel, event->event_data.data);
if (running_event != (0xb0 | event->event_data.channel)) {
(*out)[out_ofs++] = 0xb0 | event->event_data.channel;
running_event = (*out)[out_ofs - 1];
}
(*out)[out_ofs++] = 97;
(*out)[out_ofs++] = event->event_data.data.value & 0xff;
} else if (event->do_event == _WM_do_control_non_registered_param_fine) {
// DEBUG
// fprintf(stderr,"Control Non Registered Param: %u %.4x\r\n",event->event_data.channel, event->event_data.data);
if (running_event != (0xb0 | event->event_data.channel)) {
(*out)[out_ofs++] = 0xb0 | event->event_data.channel;
running_event = (*out)[out_ofs - 1];
}
(*out)[out_ofs++] = 98;
(*out)[out_ofs++] = event->event_data.data.value & 0x7f;
} else if (event->do_event == _WM_do_control_non_registered_param_course) {
// DEBUG
// fprintf(stderr,"Control Non Registered Param: %u %.4x\r\n",event->event_data.channel, event->event_data.data);
if (running_event != (0xb0 | event->event_data.channel)) {
(*out)[out_ofs++] = 0xb0 | event->event_data.channel;
running_event = (*out)[out_ofs - 1];
}
(*out)[out_ofs++] = 99;
(*out)[out_ofs++] = (event->event_data.data.value >> 7) & 0x7f;
} else if (event->do_event == _WM_do_control_registered_param_fine) {
// DEBUG
// fprintf(stderr,"Control Registered Param Fine: %u %.4x\r\n",event->event_data.channel, event->event_data.data);
if (running_event != (0xb0 | event->event_data.channel)) {
(*out)[out_ofs++] = 0xb0 | event->event_data.channel;
running_event = (*out)[out_ofs - 1];
}
(*out)[out_ofs++] = 100;
(*out)[out_ofs++] = event->event_data.data.value & 0x7f;
} else if (event->do_event == _WM_do_control_registered_param_course) {
// DEBUG
// fprintf(stderr,"Control Registered Param Course: %u %.4x\r\n",event->event_data.channel, event->event_data.data);
if (running_event != (0xb0 | event->event_data.channel)) {
(*out)[out_ofs++] = 0xb0 | event->event_data.channel;
running_event = (*out)[out_ofs - 1];
}
(*out)[out_ofs++] = 101;
(*out)[out_ofs++] = (event->event_data.data.value >> 7) & 0x7f;
} else if (event->do_event == _WM_do_control_channel_sound_off) {
// DEBUG
// fprintf(stderr,"Control Channel Sound Off: %u %.4x\r\n",event->event_data.channel, event->event_data.data);
if (running_event != (0xb0 | event->event_data.channel)) {
(*out)[out_ofs++] = 0xb0 | event->event_data.channel;
running_event = (*out)[out_ofs - 1];
}
(*out)[out_ofs++] = 120;
(*out)[out_ofs++] = event->event_data.data.value & 0xff;
} else if (event->do_event == _WM_do_control_channel_controllers_off) {
// DEBUG
// fprintf(stderr,"Control Channel Controllers Off: %u %.4x\r\n",event->event_data.channel, event->event_data.data);
if (running_event != (0xb0 | event->event_data.channel)) {
(*out)[out_ofs++] = 0xb0 | event->event_data.channel;
running_event = (*out)[out_ofs - 1];
}
(*out)[out_ofs++] = 121;
(*out)[out_ofs++] = event->event_data.data.value & 0xff;
} else if (event->do_event == _WM_do_control_channel_notes_off) {
// DEBUG
// fprintf(stderr,"Control Channel Notes Off: %u %.4x\r\n",event->event_data.channel, event->event_data.data);
if (running_event != (0xb0 | event->event_data.channel)) {
(*out)[out_ofs++] = 0xb0 | event->event_data.channel;
running_event = (*out)[out_ofs - 1];
}
(*out)[out_ofs++] = 123;
(*out)[out_ofs++] = event->event_data.data.value & 0xff;
} else if (event->do_event == _WM_do_control_dummy) {
// DEBUG
// fprintf(stderr,"Control Dummy Event: %u %.4x\r\n",event->event_data.channel, event->event_data.data);
if (running_event != (0xb0 | event->event_data.channel)) {
(*out)[out_ofs++] = 0xb0 | event->event_data.channel;
running_event = (*out)[out_ofs - 1];
}
(*out)[out_ofs++] = (event->event_data.data.value >> 8) & 0xff;
(*out)[out_ofs++] = event->event_data.data.value & 0xff;
} else if (event->do_event == _WM_do_patch) {
// DEBUG
// fprintf(stderr,"Patch: %u %.4x\r\n",event->event_data.channel, event->event_data.data);
if (running_event != (0xc0 | event->event_data.channel)) {
(*out)[out_ofs++] = 0xc0 | event->event_data.channel;
running_event = (*out)[out_ofs - 1];
}
(*out)[out_ofs++] = event->event_data.data.value & 0xff;
} else if (event->do_event == _WM_do_channel_pressure) {
// DEBUG
// fprintf(stderr,"Channel Pressure: %u %.4x\r\n",event->event_data.channel, event->event_data.data);
if (running_event != (0xd0 | event->event_data.channel)) {
(*out)[out_ofs++] = 0xd0 | event->event_data.channel;
running_event = (*out)[out_ofs - 1];
}
(*out)[out_ofs++] = event->event_data.data.value & 0xff;
} else if (event->do_event == _WM_do_pitch) {
// DEBUG
// fprintf(stderr,"Pitch: %u %.4x\r\n",event->event_data.channel, event->event_data.data);
if (running_event != (0xe0 | event->event_data.channel)) {
(*out)[out_ofs++] = 0xe0 | event->event_data.channel;
running_event = (*out)[out_ofs - 1];
}
(*out)[out_ofs++] = event->event_data.data.value & 0x7f;
(*out)[out_ofs++] = (event->event_data.data.value >> 7) & 0x7f;
} else if (event->do_event == _WM_do_sysex_roland_drum_track) {
// DEBUG
// fprintf(stderr,"Sysex Roland Drum Track: %u %.4x\r\n",event->event_data.channel, event->event_data.data);
uint8_t foo[] = {0xf0, 0x09, 0x41, 0x10, 0x42, 0x12, 0x40, 0x00, 0x15, 0x00, 0xf7};
uint8_t foo_ch = event->event_data.channel;
if (foo_ch == 9) {
foo_ch = 0;
} else if (foo_ch < 9) {
foo_ch++;
}
foo[7] = 0x10 | foo_ch;
foo[9] = event->event_data.data.value;
memcpy(&((*out)[out_ofs]),foo,11);
out_ofs += 11;
running_event = 0;
} else if (event->do_event == _WM_do_sysex_gm_reset) {
// DEBUG
// fprintf(stderr,"Sysex GM Reset\r\n");
uint8_t foo[] = {0xf0, 0x05, 0x7e, 0x7f, 0x09, 0x01, 0xf7};
memcpy(&((*out)[out_ofs]),foo,7);
out_ofs += 7;
running_event = 0;
} else if (event->do_event == _WM_do_sysex_roland_reset) {
// DEBUG
// fprintf(stderr,"Sysex Roland Reset\r\n");
uint8_t foo[] = {0xf0, 0x0a, 0x41, 0x10, 0x42, 0x12, 0x40, 0x00, 0x7f, 0x00, 0x41, 0xf7};
memcpy(&((*out)[out_ofs]),foo,12);
out_ofs += 12;
running_event = 0;
} else if (event->do_event == _WM_do_sysex_yamaha_reset) {
// DEBUG
// fprintf(stderr,"Sysex Yamaha Reset\r\n");
uint8_t foo[] = {0xf0, 0x08, 0x43, 0x10, 0x4c, 0x00, 0x00, 0x7e, 0x00, 0xf7};
memcpy(&((*out)[out_ofs]),foo,10);
out_ofs += 10;
running_event = 0;
} else if (event->do_event == _WM_do_meta_endoftrack) {
// DEBUG
// fprintf(stderr,"End Of Track\r\n");
if ((!(_WM_MixerOptions & WM_MO_SAVEASTYPE0)) && (mdi->is_type2)) {
/* Write end of track marker */
(*out)[out_ofs++] = 0xff;
(*out)[out_ofs++] = 0x2f;
(*out)[out_ofs++] = 0x00;
track_size = out_ofs - track_start;
(*out)[track_start - 4] = (track_size >> 24) & 0xff;
(*out)[track_start - 3] = (track_size >> 16) & 0xff;
(*out)[track_start - 2] = (track_size >> 8) & 0xff;
(*out)[track_start - 1] = track_size & 0xff;
if (event[1].do_event != NULL) {
(*out)[out_ofs++] = 'M';
(*out)[out_ofs++] = 'T';
(*out)[out_ofs++] = 'r';
(*out)[out_ofs++] = 'k';
track_count++;
out_ofs += 4;
track_start = out_ofs;
/* write out a 0 delta */
(*out)[out_ofs++] = 0;
running_event = 0;
}
}
goto NEXT_EVENT;
} else if (event->do_event == _WM_do_meta_tempo) {
// DEBUG
// fprintf(stderr,"Tempo: %u\r\n",event->event_data.data);
tempo = event->event_data.data.value & 0xffffff;
samples_per_tick = _WM_GetSamplesPerTick(divisions, tempo);
//DEBUG
//fprintf(stderr,"\rDEBUG: div %i, tempo %i, bpm %f, pps %f, spd %f\r\n", divisions, tempo, bpm_f, pulses_per_second_f, samples_per_delta_f);
(*out)[out_ofs++] = 0xff;
(*out)[out_ofs++] = 0x51;
(*out)[out_ofs++] = 0x03;
(*out)[out_ofs++] = (tempo & 0xff0000) >> 16;
(*out)[out_ofs++] = (tempo & 0xff00) >> 8;
(*out)[out_ofs++] = (tempo & 0xff);
} else if (event->do_event == _WM_do_meta_timesignature) {
// DEBUG
// fprintf(stderr,"Time Signature: %x\r\n",event->event_data.data);
(*out)[out_ofs++] = 0xff;
(*out)[out_ofs++] = 0x58;
(*out)[out_ofs++] = 0x04;
(*out)[out_ofs++] = (event->event_data.data.value & 0xff000000) >> 24;
(*out)[out_ofs++] = (event->event_data.data.value & 0xff0000) >> 16;
(*out)[out_ofs++] = (event->event_data.data.value & 0xff00) >> 8;
(*out)[out_ofs++] = (event->event_data.data.value & 0xff);
} else if (event->do_event == _WM_do_meta_keysignature) {
// DEBUG
// fprintf(stderr,"Key Signature: %x\r\n",event->event_data.data);
(*out)[out_ofs++] = 0xff;
(*out)[out_ofs++] = 0x59;
(*out)[out_ofs++] = 0x02;
(*out)[out_ofs++] = (event->event_data.data.value & 0xff00) >> 8;
(*out)[out_ofs++] = (event->event_data.data.value & 0xff);
} else if (event->do_event == _WM_do_meta_sequenceno) {
// DEBUG
// fprintf(stderr,"Sequence Number: %x\r\n",event->event_data.data);
(*out)[out_ofs++] = 0xff;
(*out)[out_ofs++] = 0x00;
(*out)[out_ofs++] = 0x02;
(*out)[out_ofs++] = (event->event_data.data.value & 0xff00) >> 8;
(*out)[out_ofs++] = (event->event_data.data.value & 0xff);
} else if (event->do_event == _WM_do_meta_channelprefix) {
// DEBUG
// fprintf(stderr,"Channel Prefix: %x\r\n",event->event_data.data);
(*out)[out_ofs++] = 0xff;
(*out)[out_ofs++] = 0x20;
(*out)[out_ofs++] = 0x01;
(*out)[out_ofs++] = (event->event_data.data.value & 0xff);
} else if (event->do_event == _WM_do_meta_portprefix) {
// DEBUG
// fprintf(stderr,"Port Prefix: %x\r\n",event->event_data.data);
(*out)[out_ofs++] = 0xff;
(*out)[out_ofs++] = 0x21;
(*out)[out_ofs++] = 0x01;
(*out)[out_ofs++] = (event->event_data.data.value & 0xff);
} else if (event->do_event == _WM_do_meta_smpteoffset) {
// DEBUG
// fprintf(stderr,"SMPTE Offset: %x\r\n",event->event_data.data);
(*out)[out_ofs++] = 0xff;
(*out)[out_ofs++] = 0x54;
(*out)[out_ofs++] = 0x05;
/*
Remember because of the 5 bytes we stored it a little hacky.
*/
(*out)[out_ofs++] = (event->event_data.channel & 0xff);
(*out)[out_ofs++] = (event->event_data.data.value & 0xff000000) >> 24;
(*out)[out_ofs++] = (event->event_data.data.value & 0xff0000) >> 16;
(*out)[out_ofs++] = (event->event_data.data.value & 0xff00) >> 8;
(*out)[out_ofs++] = (event->event_data.data.value & 0xff);
} else if (event->do_event == _WM_do_meta_text) {
(*out)[out_ofs++] = 0xff;
(*out)[out_ofs++] = 0x01;
goto _WRITE_TEXT;
} else if (event->do_event == _WM_do_meta_copyright) {
(*out)[out_ofs++] = 0xff;
(*out)[out_ofs++] = 0x02;
goto _WRITE_TEXT;
} else if (event->do_event == _WM_do_meta_trackname) {
(*out)[out_ofs++] = 0xff;
(*out)[out_ofs++] = 0x03;
goto _WRITE_TEXT;
} else if (event->do_event == _WM_do_meta_instrumentname) {
(*out)[out_ofs++] = 0xff;
(*out)[out_ofs++] = 0x04;
goto _WRITE_TEXT;
} else if (event->do_event == _WM_do_meta_lyric) {
(*out)[out_ofs++] = 0xff;
(*out)[out_ofs++] = 0x05;
goto _WRITE_TEXT;
} else if (event->do_event == _WM_do_meta_marker) {
(*out)[out_ofs++] = 0xff;
(*out)[out_ofs++] = 0x06;
goto _WRITE_TEXT;
} else if (event->do_event == _WM_do_meta_cuepoint) {
(*out)[out_ofs++] = 0xff;
(*out)[out_ofs++] = 0x07;
_WRITE_TEXT:
value = strlen(event->event_data.data.string);
if (value > 0x0fffffff)
(*out)[out_ofs++] = (((value >> 28) &0x7f) | 0x80);
if (value > 0x1fffff)
(*out)[out_ofs++] = (((value >> 21) &0x7f) | 0x80);
if (value > 0x3fff)
(*out)[out_ofs++] = (((value >> 14) & 0x7f) | 0x80);
if (value > 0x7f)
(*out)[out_ofs++] = (((value >> 7) & 0x7f) | 0x80);
(*out)[out_ofs++] = (value & 0x7f);
memcpy(&(*out)[out_ofs], event->event_data.data.string, value);
out_ofs += value;
} else {
// DEBUG
fprintf(stderr,"Unknown Event %.2x %.4x\n",event->event_data.channel, event->event_data.data.value);
event++;
continue;
}
value_f = (float)event->samples_to_next / samples_per_tick;
value = (uint32_t)(value_f + 0.5);
//DEBUG
//fprintf(stderr,"\rDEBUG: STN %i, SPD %f, Delta %i\r\n", event->samples_to_next, samples_per_delta_f, value);
if (value > 0x0fffffff)
(*out)[out_ofs++] = (((value >> 28) &0x7f) | 0x80);
if (value > 0x1fffff)
(*out)[out_ofs++] = (((value >> 21) &0x7f) | 0x80);
if (value > 0x3fff)
(*out)[out_ofs++] = (((value >> 14) & 0x7f) | 0x80);
if (value > 0x7f)
(*out)[out_ofs++] = (((value >> 7) & 0x7f) | 0x80);
(*out)[out_ofs++] = (value & 0x7f);
NEXT_EVENT:
event++;
} while (event->do_event != NULL);
if ((_WM_MixerOptions & WM_MO_SAVEASTYPE0) || (!mdi->is_type2)) {
/* Write end of track marker */
(*out)[out_ofs++] = 0xff;
(*out)[out_ofs++] = 0x2f;
(*out)[out_ofs++] = 0x00;
/* Write last track size */
track_size = out_ofs - track_start;
(*out)[track_start - 4] = (track_size >> 24) & 0xff;
(*out)[track_start - 3] = (track_size >> 16) & 0xff;
(*out)[track_start - 2] = (track_size >> 8) & 0xff;
(*out)[track_start - 1] = track_size & 0xff;
}
/* write track count */
(*out)[10] = (track_count >> 8) & 0xff;
(*out)[11] = track_count & 0xff;
(*out) = realloc((*out), out_ofs);
(*outsize) = out_ofs;
return 0;
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/good_2588_3 |
crossvul-cpp_data_good_504_0 | /* radare - LGPL - Copyright 2009-2018 - pancake, maijin */
#include "r_util.h"
#include "r_core.h"
#include "r_anal.h"
static const char *help_msg_a[] = {
"Usage:", "a", "[abdefFghoprxstc] [...]",
"aa", "[?]", "analyze all (fcns + bbs) (aa0 to avoid sub renaming)",
"a8", " [hexpairs]", "analyze bytes",
"ab", "[b] [addr]", "analyze block at given address",
"abb", " [len]", "analyze N basic blocks in [len] (section.size by default)",
"ac", " [cycles]", "analyze which op could be executed in [cycles]",
"ad", "[?]", "analyze data trampoline (wip)",
"ad", " [from] [to]", "analyze data pointers to (from-to)",
"ae", "[?] [expr]", "analyze opcode eval expression (see ao)",
"af", "[?]", "analyze Functions",
"aF", "", "same as above, but using anal.depth=1",
"ag", "[?] [options]", "draw graphs in various formats",
"ah", "[?]", "analysis hints (force opcode size, ...)",
"ai", " [addr]", "address information (show perms, stack, heap, ...)",
"aL", "", "list all asm/anal plugins (e asm.arch=?)",
"an"," [name] [@addr]","show/rename/create whatever flag/function is used at addr",
"ao", "[?] [len]", "analyze Opcodes (or emulate it)",
"aO", "[?] [len]", "Analyze N instructions in M bytes",
"ap", "", "find prelude for current offset",
"ar", "[?]", "like 'dr' but for the esil vm. (registers)",
"as", "[?] [num]", "analyze syscall using dbg.reg",
"av", "[?] [.]", "show vtables",
"ax", "[?]", "manage refs/xrefs (see also afx?)",
NULL
};
static const char *help_msg_aa[] = {
"Usage:", "aa[0*?]", " # see also 'af' and 'afna'",
"aa", " ", "alias for 'af@@ sym.*;af@entry0;afva'", //;.afna @@ fcn.*'",
"aa*", "", "analyze all flags starting with sym. (af @@ sym.*)",
"aaa", "[?]", "autoname functions after aa (see afna)",
"aab", "", "aab across bin.sections.rx",
"aac", " [len]", "analyze function calls (af @@ `pi len~call[1]`)",
"aac*", " [len]", "flag function calls without performing a complete analysis",
"aad", " [len]", "analyze data references to code",
"aae", " [len] ([addr])", "analyze references with ESIL (optionally to address)",
"aaE", "", "run aef on all functions (same as aef @@f)",
"aaf", " ", "analyze all functions (e anal.hasnext=1;afr @@c:isq)",
"aai", "[j]", "show info of all analysis parameters",
"aan", "", "autoname functions that either start with fcn.* or sym.func.*",
"aang", "", "find function and symbol names from golang binaries",
"aap", "", "find and analyze function preludes",
"aar", "[?] [len]", "analyze len bytes of instructions for references",
"aas", " [len]", "analyze symbols (af @@= `isq~[0]`)",
"aat", " [len]", "analyze all consecutive functions in section",
"aaT", " [len]", "analyze code after trap-sleds",
"aau", " [len]", "list mem areas (larger than len bytes) not covered by functions",
"aav", " [sat]", "find values referencing a specific section or map",
NULL
};
static const char *help_msg_aar[] = {
"Usage:", "aar", "[j*] [sz] # search and analyze xrefs",
"aar", " [sz]", "analyze xrefs in current section or sz bytes of code",
"aar*", " [sz]", "list found xrefs in radare commands format",
"aarj", " [sz]", "list found xrefs in JSON format",
NULL
};
static const char *help_msg_ab[] = {
"Usage:", "ab", "",
"ab", " [addr]", "show basic block information at given address",
"abb", " [length]", "analyze N bytes and extract basic blocks",
"abj", " [addr]", "display basic block information in JSON (alias to afbj)",
"abx", " [hexpair-bytes]", "analyze N bytes",
"abt[?]", " [addr] [num]", "find num paths from current offset to addr",
NULL
};
static const char *help_msg_abt[] = {
"Usage:", "abt", "[addr] [num] # find num paths from current offset to addr",
"abt", " [addr] [num]", "find num paths from current offset to addr",
"abtj", " [addr] [num]", "display paths in JSON",
NULL
};
static const char *help_msg_ad[] = {
"Usage:", "ad", "[kt] [...]",
"ad", " [N] [D]", "analyze N data words at D depth",
"ad4", " [N] [D]", "analyze N data words at D depth (asm.bits=32)",
"ad8", " [N] [D]", "analyze N data words at D depth (asm.bits=64)",
"adf", "", "analyze data in function (use like .adf @@=`afl~[0]`",
"adfg", "", "analyze data in function gaps",
"adt", "", "analyze data trampolines (wip)",
"adk", "", "analyze data kind (code, text, data, invalid, ...)",
NULL
};
static const char *help_msg_ae[] = {
"Usage:", "ae[idesr?] [arg]", "ESIL code emulation",
"ae", " [expr]", "evaluate ESIL expression",
"ae?", "", "show this help",
"ae??", "", "show ESIL help",
"ae[aA]", "[f] [count]", "analyse esil accesses (regs, mem..)",
"aec", "[?]", "continue until ^C",
"aecs", "", "continue until syscall",
"aecc", "", "continue until call",
"aecu", " [addr]", "continue until address",
"aecue", " [esil]", "continue until esil expression match",
"aef", " [addr]", "emulate function",
"aefa", " [addr]", "emulate function to find out args in given or current offset",
"aei", "", "initialize ESIL VM state (aei- to deinitialize)",
"aeim", " [addr] [size] [name]", "initialize ESIL VM stack (aeim- remove)",
"aeip", "", "initialize ESIL program counter to curseek",
"aek", " [query]", "perform sdb query on ESIL.info",
"aek-", "", "resets the ESIL.info sdb instance",
"aeli", "", "list loaded ESIL interrupts",
"aeli", " [file]", "load ESIL interrupts from shared object",
"aelir", " [interrupt number]", "remove ESIL interrupt and free it if needed",
"aep", "[?] [addr]", "manage esil pin hooks",
"aepc", " [addr]", "change esil PC to this address",
"aer", " [..]", "handle ESIL registers like 'ar' or 'dr' does",
"aets", "[?]", "ESIL Trace session",
"aes", "", "perform emulated debugger step",
"aesp", " [X] [N]", "evaluate N instr from offset X",
"aesb", "", "step back",
"aeso", " ", "step over",
"aesu", " [addr]", "step until given address",
"aesue", " [esil]", "step until esil expression match",
"aetr", "[esil]", "Convert an ESIL Expression to REIL",
"aex", " [hex]", "evaluate opcode expression",
NULL
};
static const char *help_detail_ae[] = {
"Examples:", "ESIL", " examples and documentation",
"+=", "", "A+=B => B,A,+=",
"+", "", "A=A+B => B,A,+,A,=",
"++", "", "increment, 2,A,++ == 3 (see rsi,--=[1], ... )",
"--", "", "decrement, 2,A,-- == 1",
"*=", "", "A*=B => B,A,*=",
"/=", "", "A/=B => B,A,/=",
"%=", "", "A%=B => B,A,%=",
"&=", "", "and ax, bx => bx,ax,&=",
"|", "", "or r0, r1, r2 => r2,r1,|,r0,=",
"!=", "", "negate all bits",
"^=", "", "xor ax, bx => bx,ax,^=",
"", "[]", "mov eax,[eax] => eax,[],eax,=",
"=", "[]", "mov [eax+3], 1 => 1,3,eax,+,=[]",
"=", "[1]", "mov byte[eax],1 => 1,eax,=[1]",
"=", "[8]", "mov [rax],1 => 1,rax,=[8]",
"[]", "", "peek from random position",
"[*]", "", "peek some from random position",
"=", "[*]", "poke some at random position",
"$", "", "int 0x80 => 0x80,$",
"$$", "", "simulate a hardware trap",
"==", "", "pops twice, compare and update esil flags",
"<", "", "compare for smaller",
"<=", "", "compare for smaller or equal",
">", "", "compare for bigger",
">=", "", "compare bigger for or equal",
">>=", "", "shr ax, bx => bx,ax,>>= # shift right",
"<<=", "", "shl ax, bx => bx,ax,<<= # shift left",
">>>=", "", "ror ax, bx => bx,ax,>>>= # rotate right",
"<<<=", "", "rol ax, bx => bx,ax,<<<= # rotate left",
"?{", "", "if popped value != 0 run the block until }",
"POP", "", "drops last element in the esil stack",
"DUP", "", "duplicate last value in stack",
"NUM", "", "evaluate last item in stack to number",
"PICK", "", "pick Nth element in stack",
"RPICK", "", "pick Nth element in reversed stack",
"SWAP", "", "swap last two values in stack",
"TRAP", "", "stop execution",
"BITS", "", "16,BITS # change bits, useful for arm/thumb",
"TODO", "", "the instruction is not yet esilized",
"STACK", "", "show contents of stack",
"CLEAR", "", "clears the esil stack",
"REPEAT", "", "repeat n times",
"BREAK", "", "terminates the string parsing",
"GOTO", "", "jump to the Nth word popped from the stack",
NULL
};
static const char *help_msg_aea[] = {
"Examples:", "aea", " show regs used in a range",
"aea", " [ops]", "Show regs used in N instructions (all,read,{no,}written,memreads,memwrites)",
"aea*", " [ops]", "Create mem.* flags for memory accesses",
"aeaf", "", "Show regs used in current function",
"aear", " [ops]", "Show regs read in N instructions",
"aeaw", " [ops]", "Show regs written in N instructions",
"aean", " [ops]", "Show regs not written in N instructions",
"aeaj", " [ops]", "Show aea output in JSON format",
"aeA", " [len]", "Show regs used in N bytes (subcommands are the same)",
NULL
};
static const char *help_msg_aec[] = {
"Examples:", "aec", " continue until ^c",
"aec", "", "Continue until exception",
"aecs", "", "Continue until syscall",
"aecc", "", "Continue until call",
"aecu", "[addr]", "Continue until address",
"aecue", "[addr]", "Continue until esil expression",
NULL
};
static const char *help_msg_aep[] = {
"Usage:", "aep[-c] ", " [...]",
"aepc", " [addr]", "change program counter for esil",
"aep", "-[addr]", "remove pin",
"aep", " [name] @ [addr]", "set pin",
"aep", "", "list pins",
NULL
};
static const char *help_msg_aets[] = {
"Usage:", "aets ", " [...]",
"aets", "", "List all ESIL trace sessions",
"aets+", "", "Add ESIL trace session",
NULL
};
static const char *help_msg_af[] = {
"Usage:", "af", "",
"af", " ([name]) ([addr])", "analyze functions (start at addr or $$)",
"afr", " ([name]) ([addr])", "analyze functions recursively",
"af+", " addr name [type] [diff]", "hand craft a function (requires afb+)",
"af-", " [addr]", "clean all function analysis data (or function at addr)",
"afb+", " fcnA bbA sz [j] [f] ([t]( [d]))", "add bb to function @ fcnaddr",
"afb", "[?] [addr]", "List basic blocks of given function",
"afB", " 16", "set current function as thumb (change asm.bits)",
"afC[lc]", " ([addr])@[addr]", "calculate the Cycles (afC) or Cyclomatic Complexity (afCc)",
"afc", "[?] type @[addr]", "set calling convention for function",
"afd", "[addr]","show function + delta for given offset",
"aff", "", "re-adjust function boundaries to fit",
"afF", "[1|0|]", "fold/unfold/toggle",
"afi", " [addr|fcn.name]", "show function(s) information (verbose afl)",
"afl", "[?] [ls*] [fcn name]", "list functions (addr, size, bbs, name) (see afll)",
"afm", " name", "merge two functions",
"afM", " name", "print functions map",
"afn", "[?] name [addr]", "rename name for function at address (change flag too)",
"afna", "", "suggest automatic name for current offset",
"afo", " [fcn.name]", "show address for the function named like this",
"afs", " [addr] [fcnsign]", "get/set function signature at current address",
"afS", "[stack_size]", "set stack frame size for function at current address",
"aft", "[?]", "type matching, type propagation",
"afu", " [addr]", "resize and analyze function from current address until addr",
"afv[bsra]", "?", "manipulate args, registers and variables in function",
"afx", "", "list function references",
NULL
};
static const char *help_msg_afb[] = {
"Usage:", "afb", " List basic blocks of given function",
".afbr-", "", "Set breakpoint on every return address of the function",
".afbr-*", "", "Remove breakpoint on every return address of the function",
"afb", " [addr]", "list basic blocks of function",
"afb.", " [addr]", "show info of current basic block",
"afb+", " fcn_at bbat bbsz [jump] [fail] ([type] ([diff]))", "add basic block by hand",
"afbr", "", "Show addresses of instructions which leave the function",
"afbi", "", "print current basic block information",
"afbj", " [addr]", "show basic blocks information in json",
"afbe", " bbfrom bbto", "add basic-block edge for switch-cases",
"afB", " [bits]", "define asm.bits for the given function",
"afbc", " [addr] [color(ut32)]", "set a color for the bb at a given address",
NULL
};
static const char *help_msg_afc[] = {
"Usage:", "afc[agl?]", "",
"afc", " convention", "Manually set calling convention for current function",
"afc", "", "Show Calling convention for the Current function",
"afcr", "[j]", "Show register usage for the current function",
"afca", "", "Analyse function for finding the current calling convention",
"afcf", " [name]", "Prints return type function(arg1, arg2...)",
"afcl", "", "List all available calling conventions",
"afco", " path", "Open Calling Convention sdb profile from given path",
NULL
};
static const char *help_msg_afC[] = {
"Usage:", "afC", " [addr]",
"afC", "", "function cycles cost",
"afCc", "", "cyclomatic complexity",
"afCl", "", "loop count (backward jumps)",
NULL
};
static const char *help_msg_afi[] = {
"Usage:", "afi[jlp*]", " <addr>",
"afi", "", "show information of the function",
"afi.", "", "show function name in current offset",
"afi*", "", "function, variables and arguments",
"afij", "", "function info in json format",
"afil", "", "verbose function info",
"afip", "", "show whether the function is pure or not",
NULL
};
static const char *help_msg_afl[] = {
"Usage:", "afl", " List all functions",
"afl", "", "list functions",
"afl+", "", "display sum all function sizes",
"aflc", "", "count of functions",
"aflj", "", "list functions in json",
"afll", "", "list functions in verbose mode",
"afllj", "", "list functions in verbose mode (alias to aflj)",
"aflq", "", "list functions in quiet mode",
"aflqj", "", "list functions in json quiet mode",
"afls", "", "sort function list by address",
NULL
};
static const char *help_msg_afll[] = {
"Usage:", "", " List functions in verbose mode",
"", "", "",
"Table fields:", "", "",
"", "", "",
"address", "", "start address",
"size", "", "function size (realsize)",
"nbbs", "", "number of basic blocks",
"edges", "", "number of edges between basic blocks",
"cc", "", "cyclomatic complexity ( cc = edges - blocks + 2 * exit_blocks)",
"cost", "", "cyclomatic cost",
"min bound", "", "minimal address",
"range", "", "function size",
"max bound", "", "maximal address",
"calls", "", "number of caller functions",
"locals", "", "number of local variables",
"args", "", "number of function arguments",
"xref", "", "number of cross references",
"frame", "", "function stack size",
"name", "", "function name",
NULL
};
static const char *help_msg_afn[] = {
"Usage:", "afn[sa]", " Analyze function names",
"afn", " [name]", "rename the function",
"afna", "", "construct a function name for the current offset",
"afns", "", "list all strings associated with the current function",
NULL
};
static const char *help_msg_aft[] = {
"Usage:", "aft[a|m]", "",
"afta", "", "setup memory and analyse do type matching analysis for all functions",
"aftm", "", "type matching analysis for current function",
NULL
};
static const char *help_msg_afv[] = {
"Usage:", "afv","[rbs]",
"afvr", "[?]", "manipulate register based arguments",
"afvb", "[?]", "manipulate bp based arguments/locals",
"afvs", "[?]", "manipulate sp based arguments/locals",
"afv*", "", "output r2 command to add args/locals to flagspace",
"afvR", " [varname]", "list addresses where vars are accessed (READ)",
"afvW", " [varname]", "list addresses where vars are accessed (WRITE)",
"afva", "", "analyze function arguments/locals",
"afvd", " name", "output r2 command for displaying the value of args/locals in the debugger",
"afvn", " [new_name] ([old_name])", "rename argument/local",
"afvt", " [name] [new_type]", "change type for given argument/local",
"afv-", "([name])", "remove all or given var",
NULL
};
static const char *help_msg_afvb[] = {
"Usage:", "afvb", " [idx] [name] ([type])",
"afvb", "", "list base pointer based arguments, locals",
"afvb*", "", "same as afvb but in r2 commands",
"afvb", " [idx] [name] ([type])", "define base pointer based arguments, locals",
"afvbj", "", "return list of base pointer based arguments, locals in JSON format",
"afvb-", " [name]", "delete argument/locals at the given name",
"afvbg", " [idx] [addr]", "define var get reference",
"afvbs", " [idx] [addr]", "define var set reference",
NULL
};
static const char *help_msg_afvr[] = {
"Usage:", "afvr", " [reg] [type] [name]",
"afvr", "", "list register based arguments",
"afvr*", "", "same as afvr but in r2 commands",
"afvr", " [reg] [name] ([type])", "define register arguments",
"afvrj", "", "return list of register arguments in JSON format",
"afvr-", " [name]", "delete register arguments at the given index",
"afvrg", " [reg] [addr]", "define argument get reference",
"afvrs", " [reg] [addr]", "define argument set reference",
NULL
};
static const char *help_msg_afvs[] = {
"Usage:", "afvs", " [idx] [type] [name]",
"afvs", "", "list stack based arguments and locals",
"afvs*", "", "same as afvs but in r2 commands",
"afvs", " [idx] [name] [type]", "define stack based arguments,locals",
"afvsj", "", "return list of stack based arguments and locals in JSON format",
"afvs-", " [name]", "delete stack based argument or locals with the given name",
"afvsg", " [idx] [addr]", "define var get reference",
"afvss", " [idx] [addr]", "define var set reference",
NULL
};
static const char *help_msg_ag[] = {
"Usage:", "ag<graphtype><format> [addr]", "",
"Graph commands:", "", "",
"aga", "[format]", "Data references graph",
"agA", "[format]", "Global data references graph",
"agc", "[format]", "Function callgraph",
"agC", "[format]", "Global callgraph",
"agd", "[format] [fcn addr]", "Diff graph",
"agf", "[format]", "Basic blocks function graph",
"agi", "[format]", "Imports graph",
"agr", "[format]", "References graph",
"agR", "[format]", "Global references graph",
"agx", "[format]", "Cross references graph",
"agg", "[format]", "Custom graph",
"ag-", "", "Clear the custom graph",
"agn", "[?] title body", "Add a node to the custom graph",
"age", "[?] title1 title2", "Add an edge to the custom graph",
"","","",
"Output formats:", "", "",
"<blank>", "", "Ascii art",
"*", "", "r2 commands",
"d", "", "Graphviz dot",
"g", "", "Graph Modelling Language (gml)",
"j", "", "json ('J' for formatted disassembly)",
"k", "", "SDB key-value",
"t", "", "Tiny ascii art",
"v", "", "Interactive ascii art",
"w", " [path]", "Write to path or display graph image (see graph.gv.format and graph.web)",
NULL
};
static const char *help_msg_age[] = {
"Usage:", "age [title1] [title2]", "",
"Examples:", "", "",
"age", " title1 title2", "Add an edge from the node with \"title1\" as title to the one with title \"title2\"",
"age", " \"title1 with spaces\" title2", "Add an edge from node \"title1 with spaces\" to node \"title2\"",
"age-", " title1 title2", "Remove an edge from the node with \"title1\" as title to the one with title \"title2\"",
"age?", "", "Show this help",
NULL
};
static const char *help_msg_agn[] = {
"Usage:", "agn [title] [body]", "",
"Examples:", "", "",
"agn", " title1 body1", "Add a node with title \"title1\" and body \"body1\"",
"agn", " \"title with space\" \"body with space\"", "Add a node with spaces in the title and in the body",
"agn", " title1 base64:Ym9keTE=", "Add a node with the body specified as base64",
"agn-", " title1", "Remove a node with title \"title1\"",
"agn?", "", "Show this help",
NULL
};
static const char *help_msg_ah[] = {
"Usage:", "ah[lba-]", "Analysis Hints",
"ah?", "", "show this help",
"ah?", " offset", "show hint of given offset",
"ah", "", "list hints in human-readable format",
"ah.", "", "list hints in human-readable format from current offset",
"ah-", "", "remove all hints",
"ah-", " offset [size]", "remove hints at given offset",
"ah*", " offset", "list hints in radare commands format",
"aha", " ppc 51", "set arch for a range of N bytes",
"ahb", " 16 @ $$", "force 16bit for current instruction",
"ahc", " 0x804804", "override call/jump address",
"ahe", " 3,eax,+=", "set vm analysis string",
"ahf", " 0x804840", "override fallback address for call",
"ahh", " 0x804840", "highlight this adrress offset in disasm",
"ahi", "[?] 10", "define numeric base for immediates (1, 8, 10, 16, s)",
"ahj", "", "list hints in JSON",
"aho", " foo a0,33", "replace opcode string",
"ahp", " addr", "set pointer hint",
"ahr", " val", "set hint for return value of a function",
"ahs", " 4", "set opcode size=4",
"ahS", " jz", "set asm.syntax=jz for this opcode",
NULL
};
static const char *help_msg_ahi[] = {
"Usage:", "ahi [sbodh] [@ offset]", " Define numeric base",
"ahi", " [base]", "set numeric base (1, 2, 8, 10, 16)",
"ahi", " b", "set base to binary (2)",
"ahi", " d", "set base to decimal (10)",
"ahi", " h", "set base to hexadecimal (16)",
"ahi", " o", "set base to octal (8)",
"ahi", " p", "set base to htons(port) (3)",
"ahi", " i", "set base to IP address (32)",
"ahi", " S", "set base to syscall (80)",
"ahi", " s", "set base to string (1)",
NULL
};
static const char *help_msg_ao[] = {
"Usage:", "ao[e?] [len]", "Analyze Opcodes",
"aoj", " N", "display opcode analysis information in JSON for N opcodes",
"aoe", " N", "display esil form for N opcodes",
"aor", " N", "display reil form for N opcodes",
"aos", " N", "display size of N opcodes",
"aom", " [id]", "list current or all mnemonics for current arch",
"aod", " [mnemonic]", "describe opcode for asm.arch",
"aoda", "", "show all mnemonic descriptions",
"ao", " 5", "display opcode analysis of 5 opcodes",
"ao*", "", "display opcode in r commands",
NULL
};
static const char *help_msg_ar[] = {
"Usage: ar", "", "# Analysis Registers",
"ar", "", "Show 'gpr' registers",
"ar0", "", "Reset register arenas to 0",
"ara", "[?]", "Manage register arenas",
"arA", "", "Show values of function argument calls (A0, A1, A2, ..)",
"ar", " 16", "Show 16 bit registers",
"ar", " 32", "Show 32 bit registers",
"ar", " all", "Show all bit registers",
"ar", " <type>", "Show all registers of given type",
"arC", "", "Display register profile comments",
"arr", "", "Show register references (telescoping)",
"arrj", "", "Show register references (telescoping) in JSON format",
"ar=", "([size])(:[regs])", "Show register values in columns",
"ar?", " <reg>", "Show register value",
"arb", " <type>", "Display hexdump of the given arena",
"arc", " <name>", "Conditional flag registers",
"ard", " <name>", "Show only different registers",
"arn", " <regalias>", "Get regname for pc,sp,bp,a0-3,zf,cf,of,sg",
"aro", "", "Show old (previous) register values",
"arp", "[?] <file>", "Load register profile from file",
"ars", "", "Stack register state",
"art", "", "List all register types",
"arw", " <hexnum>", "Set contents of the register arena",
".ar*", "", "Import register values as flags",
".ar-", "", "Unflag all registers",
NULL
};
static const char *help_msg_ara[] = {
"Usage:", "ara[+-s]", "Register Arena Push/Pop/Swap",
"ara", "", "show all register arenas allocated",
"ara", "+", "push a new register arena for each type",
"ara", "-", "pop last register arena",
"aras", "", "swap last two register arenas",
NULL
};
static const char *help_msg_arw[] = {
"Usage:", "arw ", "# Set contents of the register arena",
"arw", " <hexnum>", "Set contents of the register arena",
NULL
};
static const char *help_msg_as[] = {
"Usage: as[ljk?]", "", "syscall name <-> number utility",
"as", "", "show current syscall and arguments",
"as", " 4", "show syscall 4 based on asm.os and current regs/mem",
"asc[a]", " 4", "dump syscall info in .asm or .h",
"asf", " [k[=[v]]]", "list/set/unset pf function signatures (see fcnsign)",
"asj", "", "list of syscalls in JSON",
"asl", "", "list of syscalls by asm.os and asm.arch",
"asl", " close", "returns the syscall number for close",
"asl", " 4", "returns the name of the syscall number 4",
"ask", " [query]", "perform syscall/ queries",
NULL
};
static const char *help_msg_av[] = {
"Usage:", "av[?jr*]", " C++ vtables and RTTI",
"av", "", "search for vtables in data sections and show results",
"avj", "", "like av, but as json",
"av*", "", "like av, but as r2 commands",
"avr", "[j@addr]", "try to parse RTTI at vtable addr (see anal.cpp.abi)",
"avra", "[j]", "search for vtables and try to parse RTTI at each of them",
"avrD", " [classname]", "demangle a class name from RTTI",
NULL
};
static const char *help_msg_ax[] = {
"Usage:", "ax[?d-l*]", " # see also 'afx?'",
"ax", "", "list refs",
"ax*", "", "output radare commands",
"ax", " addr [at]", "add code ref pointing to addr (from curseek)",
"ax-", " [at]", "clean all refs/refs from addr",
"ax-*", "", "clean all refs/refs",
"axc", " addr [at]", "add generic code ref",
"axC", " addr [at]", "add code call ref",
"axg", " [addr]", "show xrefs graph to reach current function",
"axg*", " [addr]", "show xrefs graph to given address, use .axg*;aggv",
"axgj", " [addr]", "show xrefs graph to reach current function in json format",
"axd", " addr [at]", "add data ref",
"axq", "", "list refs in quiet/human-readable format",
"axj", "", "list refs in json format",
"axF", " [flg-glob]", "find data/code references of flags",
"axt", " [addr]", "find data/code references to this address",
"axf", " [addr]", "find data/code references from this address",
"axff", " [addr]", "find data/code references from this function",
"axs", " addr [at]", "add string ref",
NULL
};
static void cmd_anal_init(RCore *core) {
DEFINE_CMD_DESCRIPTOR (core, a);
DEFINE_CMD_DESCRIPTOR (core, aa);
DEFINE_CMD_DESCRIPTOR (core, aar);
DEFINE_CMD_DESCRIPTOR (core, ab);
DEFINE_CMD_DESCRIPTOR (core, ad);
DEFINE_CMD_DESCRIPTOR (core, ae);
DEFINE_CMD_DESCRIPTOR (core, aea);
DEFINE_CMD_DESCRIPTOR (core, aec);
DEFINE_CMD_DESCRIPTOR (core, aep);
DEFINE_CMD_DESCRIPTOR (core, af);
DEFINE_CMD_DESCRIPTOR (core, afb);
DEFINE_CMD_DESCRIPTOR (core, afc);
DEFINE_CMD_DESCRIPTOR (core, afC);
DEFINE_CMD_DESCRIPTOR (core, afi);
DEFINE_CMD_DESCRIPTOR (core, afl);
DEFINE_CMD_DESCRIPTOR (core, afll);
DEFINE_CMD_DESCRIPTOR (core, afn);
DEFINE_CMD_DESCRIPTOR (core, aft);
DEFINE_CMD_DESCRIPTOR (core, afv);
DEFINE_CMD_DESCRIPTOR (core, afvb);
DEFINE_CMD_DESCRIPTOR (core, afvr);
DEFINE_CMD_DESCRIPTOR (core, afvs);
DEFINE_CMD_DESCRIPTOR (core, ag);
DEFINE_CMD_DESCRIPTOR (core, age);
DEFINE_CMD_DESCRIPTOR (core, agn);
DEFINE_CMD_DESCRIPTOR (core, ah);
DEFINE_CMD_DESCRIPTOR (core, ahi);
DEFINE_CMD_DESCRIPTOR (core, ao);
DEFINE_CMD_DESCRIPTOR (core, ar);
DEFINE_CMD_DESCRIPTOR (core, ara);
DEFINE_CMD_DESCRIPTOR (core, arw);
DEFINE_CMD_DESCRIPTOR (core, as);
DEFINE_CMD_DESCRIPTOR (core, ax);
}
static int cmpaddr (const void *_a, const void *_b) {
const RAnalFunction *a = _a, *b = _b;
return a->addr - b->addr;
}
static int listOpDescriptions(void *_core, const char *k, const char *v) {
r_cons_printf ("%s=%s\n", k, v);
return 1;
}
/* better aac for windows-x86-32 */
#define JAYRO_03 0
#if JAYRO_03
static bool anal_is_bad_call(RCore *core, ut64 from, ut64 to, ut64 addr, ut8 *buf, int bufi) {
ut64 align = R_ABS (addr % PE_ALIGN);
ut32 call_bytes;
// XXX this is x86 specific
if (align == 0) {
call_bytes = (ut32)((ut8*)buf)[bufi + 3] << 24;
call_bytes |= (ut32)((ut8*)buf)[bufi + 2] << 16;
call_bytes |= (ut32)((ut8*)buf)[bufi + 1] << 8;
call_bytes |= (ut32)((ut8*)buf)[bufi];
} else {
call_bytes = (ut32)((ut8*)buf)[bufi - align + 3] << 24;
call_bytes |= (ut32)((ut8*)buf)[bufi - align + 2] << 16;
call_bytes |= (ut32)((ut8*)buf)[bufi - align + 1] << 8;
call_bytes |= (ut32)((ut8*)buf)[bufi - align];
}
if (call_bytes >= from && call_bytes <= to) {
return true;
}
call_bytes = (ut32)((ut8*)buf)[bufi + 4] << 24;
call_bytes |= (ut32)((ut8*)buf)[bufi + 3] << 16;
call_bytes |= (ut32)((ut8*)buf)[bufi + 2] << 8;
call_bytes |= (ut32)((ut8*)buf)[bufi + 1];
call_bytes += addr + 5;
if (call_bytes >= from && call_bytes <= to) {
return false;
}
return false;
}
#endif
static bool type_cmd_afta (RCore *core, RAnalFunction *fcn) {
RListIter *it;
ut64 seek;
const char *io_cache_key = "io.pcache.write";
bool io_cache = r_config_get_i (core->config, io_cache_key);
if (r_config_get_i (core->config, "cfg.debug")) {
eprintf ("TOFIX: afta can't run in debugger mode.\n");
return false;
}
if (!io_cache) {
// XXX. we shouldnt need this, but it breaks 'r2 -c aaa -w ls'
r_config_set_i (core->config, io_cache_key, true);
}
seek = core->offset;
r_core_cmd0 (core, "aei");
r_core_cmd0 (core, "aeim");
r_reg_arena_push (core->anal->reg);
// Iterating Reverse so that we get function in top-bottom call order
r_list_foreach_prev (core->anal->fcns, it, fcn) {
int ret = r_core_seek (core, fcn->addr, true);
if (!ret) {
continue;
}
r_anal_esil_set_pc (core->anal->esil, fcn->addr);
r_core_anal_type_match (core, fcn);
if (r_cons_is_breaked ()) {
break;
}
}
r_core_cmd0 (core, "aeim-");
r_core_cmd0 (core, "aei-");
r_core_seek (core, seek, true);
r_reg_arena_pop (core->anal->reg);
r_config_set_i (core->config, io_cache_key, io_cache);
return true;
}
static void type_cmd(RCore *core, const char *input) {
RAnalFunction *fcn = r_anal_get_fcn_in (core->anal, core->offset, -1);
if (!fcn && *input != '?' && *input != 'a') {
eprintf ("cant find function here\n");
return;
}
ut64 seek;
r_cons_break_push (NULL, NULL);
switch (*input) {
case 'a': // "afta"
type_cmd_afta (core, fcn);
break;
case 'm': // "aftm"
seek = core->offset;
r_anal_esil_set_pc (core->anal->esil, fcn? fcn->addr: core->offset);
r_core_anal_type_match (core, fcn);
r_core_seek (core, seek, true);
break;
case '?':
r_core_cmd_help (core, help_msg_aft);
break;
}
r_cons_break_pop ();
}
static int cc_print(void *p, const char *k, const char *v) {
if (!strcmp (v, "cc")) {
r_cons_println (k);
}
return 1;
}
static void find_refs(RCore *core, const char *glob) {
char cmd[128];
ut64 curseek = core->offset;
while (*glob == ' ') glob++;
if (!*glob) {
glob = "str.";
}
if (*glob == '?') {
eprintf ("Usage: axF [flag-str-filter]\n");
return;
}
eprintf ("Finding references of flags matching '%s'...\n", glob);
snprintf (cmd, sizeof (cmd) - 1, ".(findstref) @@= `f~%s[0]`", glob);
r_core_cmd0 (core, "(findstref,f here=$$,s entry0,/r here,f-here)");
r_core_cmd0 (core, cmd);
r_core_cmd0 (core, "(-findstref)");
r_core_seek (core, curseek, 1);
}
/* set flags for every function */
static void flag_every_function(RCore *core) {
RListIter *iter;
RAnalFunction *fcn;
r_flag_space_push (core->flags, "functions");
r_list_foreach (core->anal->fcns, iter, fcn) {
r_flag_set (core->flags, fcn->name,
fcn->addr, r_anal_fcn_size (fcn));
}
r_flag_space_pop (core->flags);
}
static void var_help(RCore *core, char ch) {
switch (ch) {
case 'b':
r_core_cmd_help (core, help_msg_afvb);
break;
case 's':
r_core_cmd_help (core, help_msg_afvs);
break;
case 'r':
r_core_cmd_help (core, help_msg_afvr);
break;
case '?':
r_core_cmd_help (core, help_msg_afv);
break;
default:
eprintf ("See afv?, afvb?, afvr? and afvs?\n");
}
}
static void var_accesses_list(RAnal *a, RAnalFunction *fcn, int delta, const char *typestr) {
const char *var_local = sdb_fmt ("var.0x%"PFMT64x".%d.%d.%s",
fcn->addr, 1, delta, typestr);
const char *xss = sdb_const_get (a->sdb_fcns, var_local, 0);
if (xss && *xss) {
r_cons_printf ("%s\n", xss);
} else {
r_cons_newline ();
}
}
static void list_vars(RCore *core, RAnalFunction *fcn, int type, const char *name) {
RAnalVar *var;
RListIter *iter;
RList *list = r_anal_var_all_list (core->anal, fcn);
if (type == '*') {
const char *bp = r_reg_get_name (core->anal->reg, R_REG_NAME_BP);
r_cons_printf ("f-fcnvar*\n");
r_list_foreach (list, iter, var) {
r_cons_printf ("f fcnvar.%s @ %s%s%d\n", var->name, bp,
var->delta>=0? "+":"", var->delta);
}
return;
}
if (type != 'W' && type != 'R') {
return;
}
const char *typestr = type == 'R'?"reads":"writes";
if (name && *name) {
var = r_anal_var_get_byname (core->anal, fcn->addr, name);
if (var) {
r_cons_printf ("%10s ", var->name);
var_accesses_list (core->anal, fcn, var->delta, typestr);
}
} else {
r_list_foreach (list, iter, var) {
r_cons_printf ("%10s ", var->name);
var_accesses_list (core->anal, fcn, var->delta, typestr);
}
}
}
static int cmd_an(RCore *core, bool use_json, const char *name)
{
ut64 off = core->offset;
RAnalOp op;
char *q = NULL;
ut64 tgt_addr = UT64_MAX;
if (use_json) {
r_cons_print ("[");
}
r_anal_op (core->anal, &op, off,
core->block + off - core->offset, 32, R_ANAL_OP_MASK_BASIC);
tgt_addr = op.jump != UT64_MAX ? op.jump : op.ptr;
if (op.var) {
RAnalFunction *fcn = r_anal_get_fcn_in (core->anal, off, 0);
if (fcn) {
RAnalVar *bar = r_anal_var_get_byname (core->anal, fcn->addr, op.var->name);
if (bar) {
if (name) {
r_anal_var_rename (core->anal, fcn->addr, bar->scope,
bar->kind, bar->name, name, true);
} else if (!use_json) {
r_cons_println (bar->name);
} else {
r_cons_printf ("{\"type\":\"var\",\"name\":\"%s\"}",
bar->name);
}
} else {
eprintf ("Cannot find variable\n");
}
} else {
eprintf ("Cannot find function\n");
}
} else if (tgt_addr != UT64_MAX) {
RAnalFunction *fcn = r_anal_get_fcn_at (core->anal, tgt_addr, R_ANAL_FCN_TYPE_NULL);
RFlagItem *f = r_flag_get_i (core->flags, tgt_addr);
if (fcn) {
if (name) {
q = r_str_newf ("afn %s 0x%"PFMT64x, name, tgt_addr);
} else if (!use_json) {
r_cons_println (fcn->name);
} else {
r_cons_printf ("{\"type\":\"function\",\"name\":\"%s\"}",
fcn->name);
}
} else if (f) {
if (name) {
q = r_str_newf ("fr %s %s", f->name, name);
} else if (!use_json) {
r_cons_println (f->name);
} else {
r_cons_printf ("{\"type\":\"flag\",\"name\":\"%s\"}",
f->name);
}
} else {
if (name) {
q = r_str_newf ("f %s @ 0x%"PFMT64x, name, tgt_addr);
} else if (!use_json) {
r_cons_printf ("0x%" PFMT64x "\n", tgt_addr);
} else {
r_cons_printf ("{\"type\":\"address\",\"offset\":"
"%" PFMT64u "}", tgt_addr);
}
}
}
if (use_json) {
r_cons_print ("]\n");
}
if (q) {
r_core_cmd0 (core, q);
free (q);
}
r_anal_op_fini (&op);
return 0;
}
static int var_cmd(RCore *core, const char *str) {
char *p, *ostr;
int delta, type = *str, res = true;
RAnalVar *v1;
RAnalFunction *fcn = r_anal_get_fcn_in (core->anal, core->offset, -1);
ostr = p = NULL;
if (!str[0]) {
// "afv"
if (fcn) {
r_core_cmd0 (core, "afvs");
r_core_cmd0 (core, "afvb");
r_core_cmd0 (core, "afvr");
return true;
}
eprintf ("Cannot find function\n");
return false;
}
if (str[0] == 'j') {
// "afvj"
if (fcn) {
r_cons_printf ("{\"sp\":");
r_core_cmd0 (core, "afvsj");
r_cons_printf (",\"bp\":");
r_core_cmd0 (core, "afvbj");
r_cons_printf (",\"reg\":");
r_core_cmd0 (core, "afvrj");
r_cons_printf ("}\n");
return true;
}
eprintf ("Cannot find function\n");
return false;
}
if (!str[0] || str[1] == '?'|| str[0] == '?') {
var_help (core, *str);
return res;
}
if (!fcn) {
eprintf ("Cannot find function in 0x%08"PFMT64x"\n", core->offset);
return false;
}
ostr = p = strdup (str);
/* Variable access CFvs = set fun var */
switch (str[0]) {
case '-':
// "afv"
if (fcn) {
r_core_cmdf (core, "afvs-%s", str + 1);
r_core_cmdf (core, "afvb-%s", str + 1);
r_core_cmdf (core, "afvr-%s", str + 1);
return true;
}
eprintf ("Cannot find function\n");
return false;
case 'R': // "afvR"
case 'W': // "afvW"
case '*': // "afv*"
{
char *name = r_str_trim_head (strchr (ostr, ' '));
list_vars (core, fcn, str[0], name);
return true;
}
case 'a': // "afva"
r_anal_var_delete_all (core->anal, fcn->addr, R_ANAL_VAR_KIND_REG);
r_anal_var_delete_all (core->anal, fcn->addr, R_ANAL_VAR_KIND_BPV);
r_anal_var_delete_all (core->anal, fcn->addr, R_ANAL_VAR_KIND_SPV);
r_core_recover_vars (core, fcn, false);
free (p);
return true;
case 'n':
if (str[1]) { // "afvn"
RAnalOp *op = r_core_anal_op (core, core->offset, R_ANAL_OP_MASK_BASIC);
char *new_name = r_str_trim_head (strchr (ostr, ' '));
if (!new_name) {
r_anal_op_free (op);
free (ostr);
return false;
}
char *old_name = strchr (new_name, ' ');
if (!old_name) {
if (op && op->var) {
old_name = op->var->name;
} else {
eprintf ("Cannot find var @ 0x%08"PFMT64x"\n", core->offset);
r_anal_op_free (op);
free (ostr);
return false;
}
} else {
*old_name++ = 0;
r_str_trim (old_name);
}
v1 = r_anal_var_get_byname (core->anal, fcn->addr, old_name);
if (v1) {
r_anal_var_rename (core->anal, fcn->addr, R_ANAL_VAR_SCOPE_LOCAL,
v1->kind, old_name, new_name, true);
r_anal_var_free (v1);
} else {
eprintf ("Cant find var by name\n");
}
r_anal_op_free (op);
free (ostr);
} else {
RListIter *iter;
RAnalVar *v;
RList *list = r_anal_var_all_list (core->anal, fcn);
r_list_foreach (list, iter, v) {
r_cons_printf ("%s\n", v->name);
}
}
return true;
case 'd': // "afvd"
if (str[1]) {
p = r_str_trim (strchr (ostr, ' '));
if (!p) {
free (ostr);
return false;
}
v1 = r_anal_var_get_byname (core->anal, fcn->addr, p);
if (!v1) {
free (ostr);
return false;
}
r_anal_var_display (core->anal, v1->delta, v1->kind, v1->type);
r_anal_var_free (v1);
free (ostr);
} else {
RListIter *iter;
RAnalVar *p;
RList *list = r_anal_var_all_list (core->anal, fcn);
r_list_foreach (list, iter, p) {
char *a = r_core_cmd_strf (core, ".afvd %s", p->name);
if ((a && !*a) || !a) {
free (a);
a = strdup ("\n");
}
r_cons_printf ("%s %s = %s", p->isarg ? "arg": "var", p->name, a);
free (a);
}
r_list_free (list);
}
return true;
case 't':{ // "afvt"
p = strchr (ostr, ' ');
if (!p++) {
free (ostr);
return false;
}
char *type = strchr (p, ' ');
if (!type) {
free (ostr);
return false;
}
*type++ = 0;
v1 = r_anal_var_get_byname (core->anal, fcn->addr, p);
if (!v1) {
eprintf ("Cant find get by name %s\n", p);
free (ostr);
return false;
}
r_anal_var_retype (core->anal, fcn->addr,
R_ANAL_VAR_SCOPE_LOCAL, -1, v1->kind, type, -1, v1->isarg, p);
r_anal_var_free (v1);
free (ostr);
return true;
}
}
switch (str[1]) { // afv[bsr]
case '\0':
case '*':
case 'j':
r_anal_var_list_show (core->anal, fcn, type, str[1]);
if (str[1] == 'j') {
r_cons_print ("\n");
}
break;
case '.':
r_anal_var_list_show (core->anal, fcn, core->offset, 0);
break;
case '-': // "afv[bsr]-"
if (str[2] == '*') {
r_anal_var_delete_all (core->anal, fcn->addr, type);
} else {
if (IS_DIGIT (str[2])) {
r_anal_var_delete (core->anal, fcn->addr,
type, 1, (int)r_num_math (core->num, str + 1));
} else {
char *name = r_str_trim ( strdup (str + 2));
r_anal_var_delete_byname (core->anal, fcn, type, name);
free (name);
}
}
break;
case 'd':
eprintf ("This command is deprecated, use afvd instead\n");
break;
case 't':
eprintf ("This command is deprecated use afvt instead\n");
break;
case 's':
case 'g':
if (str[2] != '\0') {
int rw = 0; // 0 = read, 1 = write
int idx = r_num_math (core->num, str + 2);
char *vaddr;
char *p = r_str_trim (strchr (ostr, ' '));
if (!p) {
var_help (core, type);
break;
}
ut64 addr = core->offset;
if ((vaddr = strchr (p , ' '))) {
addr = r_num_math (core->num, vaddr);
}
RAnalVar *var = r_anal_var_get (core->anal, fcn->addr,
str[0], R_ANAL_VAR_SCOPE_LOCAL, idx);
if (!var) {
eprintf ("Cannot find variable with delta %d\n", idx);
res = false;
break;
}
rw = (str[1] == 'g')? 0: 1;
r_anal_var_access (core->anal, fcn->addr, str[0],
R_ANAL_VAR_SCOPE_LOCAL, idx, rw, addr);
r_anal_var_free (var);
} else {
eprintf ("Missing argument\n");
}
break;
case ' ': {
const char *name;
char *vartype;
bool isarg = false;
int size = 4;
int scope = 1;
for (str++; *str == ' ';) str++;
p = strchr (str, ' ');
if (!p) {
var_help (core, type);
break;
}
*p++ = 0;
if (type == 'r') { //registers
RRegItem *i = r_reg_get (core->anal->reg, str, -1);
if (!i) {
eprintf ("Register not found");
break;
}
delta = i->index;
isarg = true;
} else {
delta = r_num_math (core->num, str);
}
name = p;
if (!name) {
eprintf ("Missing name\n");
break;
}
vartype = strchr (name, ' ');
if (!vartype) {
vartype = "int";
} else {
*vartype++ = 0;
}
if ((type == 'b') && delta > 0) {
isarg = true;
} else if ((type == 's') && delta > fcn->maxstack) {
isarg = true;
}
r_anal_var_add (core->anal, fcn->addr,scope,
delta, type, vartype,
size, isarg, name);
}
break;
};
free (ostr);
return res;
}
static void print_trampolines(RCore *core, ut64 a, ut64 b, size_t element_size) {
int i;
for (i = 0; i < core->blocksize; i += element_size) {
ut32 n;
memcpy (&n, core->block + i, sizeof (ut32));
if (n >= a && n <= b) {
if (element_size == 4) {
r_cons_printf ("f trampoline.%x @ 0x%" PFMT64x "\n", n, core->offset + i);
} else {
r_cons_printf ("f trampoline.%" PFMT64x " @ 0x%" PFMT64x "\n", n, core->offset + i);
}
r_cons_printf ("Cd %u @ 0x%" PFMT64x ":%u\n", element_size, core->offset + i, element_size);
// TODO: add data xrefs
}
}
}
static void cmd_anal_trampoline(RCore *core, const char *input) {
int bits = r_config_get_i (core->config, "asm.bits");
char *p, *inp = strdup (input);
p = strchr (inp, ' ');
if (p) {
*p = 0;
}
ut64 a = r_num_math (core->num, inp);
ut64 b = p? r_num_math (core->num, p + 1): 0;
free (inp);
switch (bits) {
case 32:
print_trampolines (core, a, b, 4);
break;
case 64:
print_trampolines (core, a, b, 8);
break;
}
}
static const char *syscallNumber(int n) {
return sdb_fmt (n > 1000 ? "0x%x" : "%d", n);
}
R_API char *cmd_syscall_dostr(RCore *core, int n, ut64 addr) {
char *res = NULL;
int i;
char str[64];
int defVector = r_syscall_get_swi (core->anal->syscall);
if (defVector > 0) {
n = -1;
}
if (n == -1) {
n = (int)r_debug_reg_get (core->dbg, "oeax");
if (!n || n == -1) {
const char *a0 = r_reg_get_name (core->anal->reg, R_REG_NAME_SN);
n = (a0 == NULL)? -1: (int)r_debug_reg_get (core->dbg, a0);
}
}
RSyscallItem *item = (defVector > 0)
? r_syscall_get (core->anal->syscall, n, -1)
: r_syscall_get (core->anal->syscall, 0, n);
if (!item) {
res = r_str_appendf (res, "%s = unknown ()", syscallNumber (n));
return res;
}
res = r_str_appendf (res, "%s = %s (", syscallNumber (item->num), item->name);
// TODO: move this to r_syscall
//TODO replace the hardcoded CC with the sdb ones
for (i = 0; i < item->args; i++) {
// XXX this is a hack to make syscall args work on x86-32 and x86-64
// we need to shift sn first.. which is bad, but needs to be redesigned
int regidx = i;
if (core->assembler->bits == 32) {
regidx++;
}
ut64 arg = r_debug_arg_get (core->dbg, R_ANAL_CC_TYPE_FASTCALL, regidx);
//r_cons_printf ("(%d:0x%"PFMT64x")\n", i, arg);
if (item->sargs) {
switch (item->sargs[i]) {
case 'p': // pointer
res = r_str_appendf (res, "0x%08" PFMT64x "", arg);
break;
case 'i':
res = r_str_appendf (res, "%" PFMT64u "", arg);
break;
case 'z':
memset (str, 0, sizeof (str));
r_io_read_at (core->io, arg, (ut8 *)str, sizeof (str) - 1);
r_str_filter (str, strlen (str));
res = r_str_appendf (res, "\"%s\"", str);
break;
case 'Z': {
//TODO replace the hardcoded CC with the sdb ones
ut64 len = r_debug_arg_get (core->dbg, R_ANAL_CC_TYPE_FASTCALL, i + 2);
len = R_MIN (len + 1, sizeof (str) - 1);
if (len == 0) {
len = 16; // override default
}
(void)r_io_read_at (core->io, arg, (ut8 *)str, len);
str[len] = 0;
r_str_filter (str, -1);
res = r_str_appendf (res, "\"%s\"", str);
} break;
default:
res = r_str_appendf (res, "0x%08" PFMT64x "", arg);
break;
}
} else {
res = r_str_appendf (res, "0x%08" PFMT64x "", arg);
}
if (i + 1 < item->args) {
res = r_str_appendf (res, ", ");
}
}
r_syscall_item_free (item);
res = r_str_appendf (res, ")");
return res;
}
static void cmd_syscall_do(RCore *core, int n, ut64 addr) {
char *msg = cmd_syscall_dostr (core, n, addr);
if (msg) {
r_cons_println (msg);
free (msg);
}
}
static void core_anal_bytes(RCore *core, const ut8 *buf, int len, int nops, int fmt) {
int stacksize = r_config_get_i (core->config, "esil.stack.depth");
bool iotrap = r_config_get_i (core->config, "esil.iotrap");
bool romem = r_config_get_i (core->config, "esil.romem");
bool stats = r_config_get_i (core->config, "esil.stats");
bool be = core->print->big_endian;
bool use_color = core->print->flags & R_PRINT_FLAGS_COLOR;
core->parser->relsub = r_config_get_i (core->config, "asm.relsub");
int ret, i, j, idx, size;
const char *color = "";
const char *esilstr;
const char *opexstr;
RAnalHint *hint;
RAnalEsil *esil = NULL;
RAsmOp asmop;
RAnalOp op = {0};
ut64 addr;
bool isFirst = true;
unsigned int addrsize = r_config_get_i (core->config, "esil.addr.size");
int totalsize = 0;
// Variables required for setting up ESIL to REIL conversion
if (use_color) {
color = core->cons->pal.label;
}
switch (fmt) {
case 'j':
r_cons_printf ("[");
break;
case 'r':
// Setup for ESIL to REIL conversion
esil = r_anal_esil_new (stacksize, iotrap, addrsize);
if (!esil) {
return;
}
r_anal_esil_to_reil_setup (esil, core->anal, romem, stats);
r_anal_esil_set_pc (esil, core->offset);
break;
}
for (i = idx = ret = 0; idx < len && (!nops || (nops && i < nops)); i++, idx += ret) {
addr = core->offset + idx;
// TODO: use more anal hints
hint = r_anal_hint_get (core->anal, addr);
r_asm_set_pc (core->assembler, addr);
(void)r_asm_disassemble (core->assembler, &asmop, buf + idx, len - idx);
ret = r_anal_op (core->anal, &op, core->offset + idx, buf + idx, len - idx, R_ANAL_OP_MASK_ESIL);
esilstr = R_STRBUF_SAFEGET (&op.esil);
opexstr = R_STRBUF_SAFEGET (&op.opex);
char *mnem = strdup (r_asm_op_get_asm (&asmop));
char *sp = strchr (mnem, ' ');
if (sp) {
*sp = 0;
if (op.prefix) {
char *arg = strdup (sp + 1);
char *sp = strchr (arg, ' ');
if (sp) {
*sp = 0;
}
free (mnem);
mnem = arg;
}
}
if (ret < 1 && fmt != 'd') {
eprintf ("Oops at 0x%08" PFMT64x " (", core->offset + idx);
for (i = idx, j = 0; i < core->blocksize && j < 3; ++i, ++j) {
eprintf ("%02x ", buf[i]);
}
eprintf ("...)\n");
free (mnem);
break;
}
size = (hint && hint->size)? hint->size: op.size;
if (fmt == 'd') {
char *opname = strdup (r_asm_op_get_asm (&asmop));
if (opname) {
r_str_split (opname, ' ');
char *d = r_asm_describe (core->assembler, opname);
if (d && *d) {
r_cons_printf ("%s: %s\n", opname, d);
free (d);
} else {
eprintf ("Unknown opcode\n");
}
free (opname);
}
} else if (fmt == 'e') {
if (*esilstr) {
if (use_color) {
r_cons_printf ("%s0x%" PFMT64x Color_RESET " %s\n", color, core->offset + idx, esilstr);
} else {
r_cons_printf ("0x%" PFMT64x " %s\n", core->offset + idx, esilstr);
}
}
} else if (fmt == 's') {
totalsize += op.size;
} else if (fmt == 'r') {
if (*esilstr) {
if (use_color) {
r_cons_printf ("%s0x%" PFMT64x Color_RESET "\n", color, core->offset + idx);
} else {
r_cons_printf ("0x%" PFMT64x "\n", core->offset + idx);
}
r_anal_esil_parse (esil, esilstr);
r_anal_esil_dumpstack (esil);
r_anal_esil_stack_free (esil);
}
} else if (fmt == 'j') {
if (isFirst) {
isFirst = false;
} else {
r_cons_print (",");
}
r_cons_printf ("{\"opcode\":\"%s\",", r_asm_op_get_asm (&asmop));
{
char strsub[128] = { 0 };
// pc+33
r_parse_varsub (core->parser, NULL,
core->offset + idx,
asmop.size, r_asm_op_get_asm (&asmop),
strsub, sizeof (strsub));
{
ut64 killme = UT64_MAX;
if (r_io_read_i (core->io, op.ptr, &killme, op.refptr, be)) {
core->parser->relsub_addr = killme;
}
}
// 0x33->sym.xx
char *p = strdup (strsub);
if (p) {
r_parse_filter (core->parser, addr, core->flags, p,
strsub, sizeof (strsub), be);
free (p);
}
r_cons_printf ("\"disasm\":\"%s\",", strsub);
}
r_cons_printf ("\"mnemonic\":\"%s\",", mnem);
if (hint && hint->opcode) {
r_cons_printf ("\"ophint\":\"%s\",", hint->opcode);
}
r_cons_printf ("\"sign\":%s,", r_str_bool (op.sign));
r_cons_printf ("\"prefix\":%" PFMT64u ",", op.prefix);
r_cons_printf ("\"id\":%d,", op.id);
if (opexstr && *opexstr) {
r_cons_printf ("\"opex\":%s,", opexstr);
}
r_cons_printf ("\"addr\":%" PFMT64u ",", core->offset + idx);
r_cons_printf ("\"bytes\":\"");
for (j = 0; j < size; j++) {
r_cons_printf ("%02x", buf[j + idx]);
}
r_cons_printf ("\",");
if (op.val != UT64_MAX) {
r_cons_printf ("\"val\": %" PFMT64u ",", op.val);
}
if (op.ptr != UT64_MAX) {
r_cons_printf ("\"ptr\": %" PFMT64u ",", op.ptr);
}
r_cons_printf ("\"size\": %d,", size);
r_cons_printf ("\"type\": \"%s\",",
r_anal_optype_to_string (op.type));
if (op.reg) {
r_cons_printf ("\"reg\": \"%s\",", op.reg);
}
if (op.ireg) {
r_cons_printf ("\"ireg\": \"%s\",", op.ireg);
}
if (op.scale) {
r_cons_printf ("\"scale\":%d,", op.scale);
}
if (hint && hint->esil) {
r_cons_printf ("\"esil\": \"%s\",", hint->esil);
} else if (*esilstr) {
r_cons_printf ("\"esil\": \"%s\",", esilstr);
}
if (hint && hint->jump != UT64_MAX) {
op.jump = hint->jump;
}
if (op.jump != UT64_MAX) {
r_cons_printf ("\"jump\":%" PFMT64u ",", op.jump);
}
if (hint && hint->fail != UT64_MAX) {
op.fail = hint->fail;
}
if (op.refptr != -1) {
r_cons_printf ("\"refptr\":%d,", op.refptr);
}
if (op.fail != UT64_MAX) {
r_cons_printf ("\"fail\":%" PFMT64u ",", op.fail);
}
r_cons_printf ("\"cycles\":%d,", op.cycles);
if (op.failcycles) {
r_cons_printf ("\"failcycles\":%d,", op.failcycles);
}
r_cons_printf ("\"delay\":%d,", op.delay);
{
const char *p = r_anal_stackop_tostring (op.stackop);
if (p && *p && strcmp (p, "null"))
r_cons_printf ("\"stack\":\"%s\",", p);
}
if (op.stackptr) {
r_cons_printf ("\"stackptr\":%d,", op.stackptr);
}
{
const char *arg = (op.type & R_ANAL_OP_TYPE_COND)
? r_anal_cond_tostring (op.cond): NULL;
if (arg) {
r_cons_printf ("\"cond\":\"%s\",", arg);
}
}
r_cons_printf ("\"family\":\"%s\"}", r_anal_op_family_to_string (op.family));
} else {
#define printline(k, fmt, arg)\
{ \
if (use_color)\
r_cons_printf ("%s%s: " Color_RESET, color, k);\
else\
r_cons_printf ("%s: ", k);\
if (fmt) r_cons_printf (fmt, arg);\
}
printline ("address", "0x%" PFMT64x "\n", core->offset + idx);
printline ("opcode", "%s\n", r_asm_op_get_asm (&asmop));
printline ("mnemonic", "%s\n", mnem);
if (hint) {
if (hint->opcode) {
printline ("ophint", "%s\n", hint->opcode);
}
#if 0
// addr should not override core->offset + idx.. its silly
if (hint->addr != UT64_MAX) {
printline ("addr", "0x%08" PFMT64x "\n", (hint->addr + idx));
}
#endif
}
printline ("prefix", "%" PFMT64u "\n", op.prefix);
printline ("id", "%d\n", op.id);
#if 0
// no opex here to avoid lot of tests broken..and having json in here is not much useful imho
if (opexstr && *opexstr) {
printline ("opex", "%s\n", opexstr);
}
#endif
printline ("bytes", NULL, 0);
int minsz = R_MIN (len, size);
minsz = R_MAX (minsz, 0);
for (j = 0; j < minsz; j++) {
ut8 ch = ((j + idx - 1) > minsz)? 0xff: buf[j + idx];
r_cons_printf ("%02x", ch);
}
r_cons_newline ();
if (op.val != UT64_MAX) {
printline ("val", "0x%08" PFMT64x "\n", op.val);
}
if (op.ptr != UT64_MAX) {
printline ("ptr", "0x%08" PFMT64x "\n", op.ptr);
}
if (op.refptr != -1) {
printline ("refptr", "%d\n", op.refptr);
}
printline ("size", "%d\n", size);
printline ("sign", "%s\n", r_str_bool (op.sign));
printline ("type", "%s\n", r_anal_optype_to_string (op.type));
printline ("cycles", "%d\n", op.cycles);
if (op.failcycles) {
printline ("failcycles", "%d\n", op.failcycles);
}
{
const char *t2 = r_anal_optype_to_string (op.type2);
if (t2 && strcmp (t2, "null")) {
printline ("type2", "%s\n", t2);
}
}
if (op.reg) {
printline ("reg", "%s\n", op.reg);
}
if (op.ireg) {
printline ("ireg", "%s\n", op.ireg);
}
if (op.scale) {
printline ("scale", "%d\n", op.scale);
}
if (hint && hint->esil) {
printline ("esil", "%s\n", hint->esil);
} else if (*esilstr) {
printline ("esil", "%s\n", esilstr);
}
if (hint && hint->jump != UT64_MAX) {
op.jump = hint->jump;
}
if (op.jump != UT64_MAX) {
printline ("jump", "0x%08" PFMT64x "\n", op.jump);
}
if (op.direction != 0) {
const char * dir = op.direction == 1 ? "read"
: op.direction == 2 ? "write"
: op.direction == 4 ? "exec"
: op.direction == 8 ? "ref": "none";
printline ("direction", "%s\n", dir);
}
if (hint && hint->fail != UT64_MAX) {
op.fail = hint->fail;
}
if (op.fail != UT64_MAX) {
printline ("fail", "0x%08" PFMT64x "\n", op.fail);
}
if (op.delay) {
printline ("delay", "%d\n", op.delay);
}
printline ("stack", "%s\n", r_anal_stackop_tostring (op.stackop));
{
const char *arg = (op.type & R_ANAL_OP_TYPE_COND)? r_anal_cond_tostring (op.cond): NULL;
if (arg) {
printline ("cond", "%s\n", arg);
}
}
printline ("family", "%s\n", r_anal_op_family_to_string (op.family));
printline ("stackop", "%s\n", r_anal_stackop_tostring (op.stackop));
if (op.stackptr) {
printline ("stackptr", "%"PFMT64u"\n", op.stackptr);
}
}
//r_cons_printf ("false: 0x%08"PFMT64x"\n", core->offset+idx);
//free (hint);
free (mnem);
r_anal_hint_free (hint);
r_anal_op_fini (&op);
}
r_anal_op_fini (&op);
if (fmt == 'j') {
r_cons_printf ("]");
r_cons_newline ();
} else if (fmt == 's') {
r_cons_printf ("%d\n", totalsize);
}
r_anal_esil_free (esil);
}
static int bb_cmp(const void *a, const void *b) {
const RAnalBlock *ba = a;
const RAnalBlock *bb = b;
return ba->addr - bb->addr;
}
static int anal_fcn_list_bb(RCore *core, const char *input, bool one) {
RDebugTracepoint *tp = NULL;
RListIter *iter;
RAnalBlock *b;
int mode = 0;
ut64 addr, bbaddr = UT64_MAX;
bool firstItem = true;
if (*input == '.') {
one = true;
input++;
}
if (*input) {
mode = *input;
input++;
}
if (*input == '.') {
one = true;
input++;
}
if (input && *input) {
addr = bbaddr = r_num_math (core->num, input);
} else {
addr = core->offset;
}
if (one) {
bbaddr = addr;
}
RAnalFunction *fcn = r_anal_get_fcn_in (core->anal, addr, 0);
if (!fcn) {
return false;
}
switch (mode) {
case 'j':
r_cons_printf ("[");
break;
case '*':
r_cons_printf ("fs blocks\n");
break;
}
r_list_sort (fcn->bbs, bb_cmp);
r_list_foreach (fcn->bbs, iter, b) {
if (one) {
if (bbaddr != UT64_MAX && (bbaddr < b->addr || bbaddr >= (b->addr + b->size))) {
continue;
}
}
switch (mode) {
case 'r':
if (b->jump == UT64_MAX) {
ut64 retaddr = b->addr;
if (b->op_pos) {
retaddr += b->op_pos[b->ninstr - 2];
}
if (!strcmp (input, "*")) {
r_cons_printf ("db 0x%08"PFMT64x"\n", retaddr);
} else if (!strcmp (input, "-*")) {
r_cons_printf ("db-0x%08"PFMT64x"\n", retaddr);
} else {
r_cons_printf ("0x%08"PFMT64x"\n", retaddr);
}
}
break;
case '*':
r_cons_printf ("f bb.%05" PFMT64x " = 0x%08" PFMT64x "\n",
b->addr & 0xFFFFF, b->addr);
break;
case 'q':
r_cons_printf ("0x%08" PFMT64x "\n", b->addr);
break;
case 'j':
//r_cons_printf ("%" PFMT64u "%s", b->addr, iter->n? ",": "");
{
RListIter *iter2;
RAnalBlock *b2;
int inputs = 0;
int outputs = 0;
r_list_foreach (fcn->bbs, iter2, b2) {
if (b2->jump == b->addr) {
inputs++;
}
if (b2->fail == b->addr) {
inputs++;
}
}
if (b->jump != UT64_MAX) {
outputs ++;
}
if (b->fail != UT64_MAX) {
outputs ++;
}
r_cons_printf ("%s{", firstItem? "": ",");
firstItem = false;
if (b->jump != UT64_MAX) {
r_cons_printf ("\"jump\":%"PFMT64u",", b->jump);
}
if (b->fail != UT64_MAX) {
r_cons_printf ("\"fail\":%"PFMT64u",", b->fail);
}
if (b->switch_op) {
r_cons_print ("\"switch_op\":{");
r_cons_printf ("\"addr\":%"PFMT64u",", b->switch_op->addr);
r_cons_printf ("\"min_val\":%"PFMT64u",", b->switch_op->min_val);
r_cons_printf ("\"def_val\":%"PFMT64u",", b->switch_op->def_val);
r_cons_printf ("\"max_val\":%"PFMT64u",", b->switch_op->max_val);
r_cons_print ("\"cases\":[");
{
RListIter *case_op_iter;
RAnalCaseOp *case_op;
r_list_foreach (b->switch_op->cases, case_op_iter, case_op) {
r_cons_printf ("%s{", case_op_iter->p ? "," : "");
r_cons_printf ("\"addr\":%"PFMT64u",", case_op->addr);
r_cons_printf ("\"jump\":%"PFMT64u",", case_op->jump);
r_cons_printf ("\"value\":%"PFMT64u",", case_op->value);
r_cons_printf ("\"cond\":%"PFMT32u",", case_op->cond);
r_cons_printf ("\"bb_ref_to\":%"PFMT64u",", case_op->bb_ref_to);
r_cons_printf ("\"bb_ref_from\":%"PFMT64u"", case_op->bb_ref_from);
r_cons_print ("}");
}
}
r_cons_print ("]},");
}
r_cons_printf ("\"addr\":%" PFMT64u ",\"size\":%d,\"inputs\":%d,\"outputs\":%d,\"ninstr\":%d,\"traced\":%s}",
b->addr, b->size, inputs, outputs, b->ninstr, r_str_bool (b->traced));
}
break;
case 'i':
{
RListIter *iter2;
RAnalBlock *b2;
int inputs = 0;
int outputs = 0;
r_list_foreach (fcn->bbs, iter2, b2) {
if (b2->jump == b->addr) {
inputs++;
}
if (b2->fail == b->addr) {
inputs++;
}
}
if (b->jump != UT64_MAX) {
outputs ++;
}
if (b->fail != UT64_MAX) {
outputs ++;
}
firstItem = false;
if (b->jump != UT64_MAX) {
r_cons_printf ("jump: 0x%08"PFMT64x"\n", b->jump);
}
if (b->fail != UT64_MAX) {
r_cons_printf ("fail: 0x%08"PFMT64x"\n", b->fail);
}
r_cons_printf ("addr: 0x%08"PFMT64x"\nsize: %d\ninputs: %d\noutputs: %d\nninstr: %d\ntraced: %s\n",
b->addr, b->size, inputs, outputs, b->ninstr, r_str_bool (b->traced));
}
break;
default:
tp = r_debug_trace_get (core->dbg, b->addr);
r_cons_printf ("0x%08" PFMT64x " 0x%08" PFMT64x " %02X:%04X %d",
b->addr, b->addr + b->size,
tp? tp->times: 0, tp? tp->count: 0,
b->size);
if (b->jump != UT64_MAX) {
r_cons_printf (" j 0x%08" PFMT64x, b->jump);
}
if (b->fail != UT64_MAX) {
r_cons_printf (" f 0x%08" PFMT64x, b->fail);
}
r_cons_newline ();
break;
}
}
if (mode == 'j') {
r_cons_printf ("]\n");
}
return true;
}
static bool anal_bb_edge (RCore *core, const char *input) {
// "afbe" switch-bb-addr case-bb-addr
char *arg = strdup (r_str_trim_ro(input));
char *sp = strchr (arg, ' ');
if (sp) {
*sp++ = 0;
ut64 sw_at = r_num_math (core->num, arg);
ut64 cs_at = r_num_math (core->num, sp);
RAnalFunction *fcn = r_anal_get_fcn_in (core->anal, sw_at, 0);
if (fcn) {
RAnalBlock *bb;
RListIter *iter;
r_list_foreach (fcn->bbs, iter, bb) {
if (sw_at >= bb->addr && sw_at < (bb->addr + bb->size)) {
if (!bb->switch_op) {
bb->switch_op = r_anal_switch_op_new (
sw_at, 0, 0);
}
r_anal_switch_op_add_case (bb->switch_op, cs_at, 0, cs_at);
}
}
free (arg);
return true;
}
}
free (arg);
return false;
}
static bool anal_fcn_del_bb(RCore *core, const char *input) {
ut64 addr = r_num_math (core->num, input);
if (!addr) {
addr = core->offset;
}
RAnalFunction *fcn = r_anal_get_fcn_in (core->anal, addr, -1);
if (fcn) {
if (!strcmp (input, "*")) {
r_list_free (fcn->bbs);
fcn->bbs = NULL;
} else {
RAnalBlock *b;
RListIter *iter;
r_list_foreach (fcn->bbs, iter, b) {
if (b->addr == addr) {
r_list_delete (fcn->bbs, iter);
return true;
}
}
eprintf ("Cannot find basic block\n");
}
} else {
eprintf ("Cannot find function\n");
}
return false;
}
static int anal_fcn_add_bb(RCore *core, const char *input) {
// fcn_addr bb_addr bb_size [jump] [fail]
char *ptr;
const char *ptr2 = NULL;
ut64 fcnaddr = -1LL, addr = -1LL;
ut64 size = 0LL;
ut64 jump = UT64_MAX;
ut64 fail = UT64_MAX;
int type = R_ANAL_BB_TYPE_NULL;
RAnalFunction *fcn = NULL;
RAnalDiff *diff = NULL;
while (*input == ' ') input++;
ptr = strdup (input);
switch (r_str_word_set0 (ptr)) {
case 7:
ptr2 = r_str_word_get0 (ptr, 6);
if (!(diff = r_anal_diff_new ())) {
eprintf ("error: Cannot init RAnalDiff\n");
free (ptr);
return false;
}
if (ptr2[0] == 'm') {
diff->type = R_ANAL_DIFF_TYPE_MATCH;
} else if (ptr2[0] == 'u') {
diff->type = R_ANAL_DIFF_TYPE_UNMATCH;
}
case 6:
ptr2 = r_str_word_get0 (ptr, 5);
if (strchr (ptr2, 'h')) {
type |= R_ANAL_BB_TYPE_HEAD;
}
if (strchr (ptr2, 'b')) {
type |= R_ANAL_BB_TYPE_BODY;
}
if (strchr (ptr2, 'l')) {
type |= R_ANAL_BB_TYPE_LAST;
}
if (strchr (ptr2, 'f')) {
type |= R_ANAL_BB_TYPE_FOOT;
}
case 5: // get fail
fail = r_num_math (core->num, r_str_word_get0 (ptr, 4));
case 4: // get jump
jump = r_num_math (core->num, r_str_word_get0 (ptr, 3));
case 3: // get size
size = r_num_math (core->num, r_str_word_get0 (ptr, 2));
case 2: // get addr
addr = r_num_math (core->num, r_str_word_get0 (ptr, 1));
case 1: // get fcnaddr
fcnaddr = r_num_math (core->num, r_str_word_get0 (ptr, 0));
}
fcn = r_anal_get_fcn_in (core->anal, fcnaddr, 0);
if (fcn) {
int ret = r_anal_fcn_add_bb (core->anal, fcn, addr, size, jump, fail, type, diff);
if (!ret) {
eprintf ("Cannot add basic block\n");
}
} else {
eprintf ("Cannot find function at 0x%" PFMT64x "\n", fcnaddr);
}
r_anal_diff_free (diff);
free (ptr);
return true;
}
static void r_core_anal_nofunclist (RCore *core, const char *input) {
int minlen = (int)(input[0]==' ') ? r_num_math (core->num, input + 1): 16;
ut64 code_size = r_num_get (core->num, "$SS");
ut64 base_addr = r_num_get (core->num, "$S");
ut64 chunk_size, chunk_offset, i;
RListIter *iter, *iter2;
RAnalFunction *fcn;
RAnalBlock *b;
char* bitmap;
int counter;
if (minlen < 1) {
minlen = 1;
}
if (code_size < 1) {
return;
}
bitmap = calloc (1, code_size+64);
if (!bitmap) {
return;
}
// for each function
r_list_foreach (core->anal->fcns, iter, fcn) {
// for each basic block in the function
r_list_foreach (fcn->bbs, iter2, b) {
// if it is not withing range, continue
if ((fcn->addr < base_addr) || (fcn->addr >= base_addr+code_size))
continue;
// otherwise mark each byte in the BB in the bitmap
for (counter = 0; counter < b->size; counter++) {
bitmap[b->addr+counter-base_addr] = '=';
}
// finally, add a special marker to show the beginning of a
// function
bitmap[fcn->addr-base_addr] = 'F';
}
}
// Now we print the list of memory regions that are not assigned to a function
chunk_size = 0;
chunk_offset = 0;
for (i = 0; i < code_size; i++) {
if (bitmap[i]){
// We only print a region is its size is bigger than 15 bytes
if (chunk_size >= minlen){
fcn = r_anal_get_fcn_in (core->anal, base_addr+chunk_offset, R_ANAL_FCN_TYPE_FCN | R_ANAL_FCN_TYPE_SYM);
if (fcn) {
r_cons_printf ("0x%08"PFMT64x" %6d %s\n", base_addr+chunk_offset, chunk_size, fcn->name);
} else {
r_cons_printf ("0x%08"PFMT64x" %6d\n", base_addr+chunk_offset, chunk_size);
}
}
chunk_size = 0;
chunk_offset = i+1;
continue;
}
chunk_size+=1;
}
if (chunk_size >= 16) {
fcn = r_anal_get_fcn_in (core->anal, base_addr+chunk_offset, R_ANAL_FCN_TYPE_FCN | R_ANAL_FCN_TYPE_SYM);
if (fcn) {
r_cons_printf ("0x%08"PFMT64x" %6d %s\n", base_addr+chunk_offset, chunk_size, fcn->name);
} else {
r_cons_printf ("0x%08"PFMT64x" %6d\n", base_addr+chunk_offset, chunk_size);
}
}
free(bitmap);
}
static void r_core_anal_fmap (RCore *core, const char *input) {
int show_color = r_config_get_i (core->config, "scr.color");
int cols = r_config_get_i (core->config, "hex.cols") * 4;
ut64 code_size = r_num_get (core->num, "$SS");
ut64 base_addr = r_num_get (core->num, "$S");
RListIter *iter, *iter2;
RAnalFunction *fcn;
RAnalBlock *b;
char* bitmap;
int assigned;
ut64 i;
if (code_size < 1) {
return;
}
bitmap = calloc (1, code_size+64);
if (!bitmap) {
return;
}
// for each function
r_list_foreach (core->anal->fcns, iter, fcn) {
// for each basic block in the function
r_list_foreach (fcn->bbs, iter2, b) {
// if it is not within range, continue
if ((fcn->addr < base_addr) || (fcn->addr >= base_addr+code_size))
continue;
// otherwise mark each byte in the BB in the bitmap
int counter = 1;
for (counter = 0; counter < b->size; counter++) {
bitmap[b->addr+counter-base_addr] = '=';
}
bitmap[fcn->addr-base_addr] = 'F';
}
}
// print the bitmap
assigned = 0;
if (cols < 1) {
cols = 1;
}
for (i = 0; i < code_size; i += 1) {
if (!(i % cols)) {
r_cons_printf ("\n0x%08"PFMT64x" ", base_addr+i);
}
if (bitmap[i]) {
assigned++;
}
if (show_color) {
if (bitmap[i]) {
r_cons_printf ("%s%c\x1b[0m", Color_GREEN, bitmap[i]);
} else {
r_cons_printf (".");
}
} else {
r_cons_printf ("%c", bitmap[i] ? bitmap[i] : '.' );
}
}
r_cons_printf ("\n%d / %d (%.2lf%%) bytes assigned to a function\n", assigned, code_size, 100.0*( (float) assigned) / code_size);
free(bitmap);
}
static bool fcnNeedsPrefix(const char *name) {
if (!strncmp (name, "entry", 5)) {
return false;
}
if (!strncmp (name, "main", 4)) {
return false;
}
return (!strchr (name, '.'));
}
/* TODO: move into r_anal_fcn_rename(); */
static bool setFunctionName(RCore *core, ut64 off, const char *_name, bool prefix) {
char *name, *nname = NULL;
RAnalFunction *fcn;
if (!core || !_name) {
return false;
}
const char *fcnpfx = r_config_get (core->config, "anal.fcnprefix");
if (!fcnpfx) {
fcnpfx = "fcn";
}
if (r_reg_get (core->anal->reg, _name, -1)) {
name = r_str_newf ("%s.%s", fcnpfx, _name);
} else {
name = strdup (_name);
}
fcn = r_anal_get_fcn_in (core->anal, off,
R_ANAL_FCN_TYPE_FCN | R_ANAL_FCN_TYPE_SYM | R_ANAL_FCN_TYPE_LOC);
if (!fcn) {
free (name);
return false;
}
if (prefix && fcnNeedsPrefix (name)) {
nname = r_str_newf ("%s.%s", fcnpfx, name);
} else {
nname = strdup (name);
}
char *oname = fcn->name;
r_flag_rename (core->flags, r_flag_get (core->flags, fcn->name), nname);
fcn->name = strdup (nname);
if (core->anal->cb.on_fcn_rename) {
core->anal->cb.on_fcn_rename (core->anal,
core->anal->user, fcn, nname);
}
free (oname);
free (nname);
free (name);
return true;
}
static void afCc(RCore *core, const char *input) {
ut64 addr;
RAnalFunction *fcn;
if (*input == ' ') {
addr = r_num_math (core->num, input);
} else {
addr = core->offset;
}
if (addr == 0LL) {
fcn = r_anal_fcn_find_name (core->anal, input + 3);
} else {
fcn = r_anal_get_fcn_in (core->anal, addr, R_ANAL_FCN_TYPE_NULL);
}
if (fcn) {
ut32 totalCycles = r_anal_fcn_cost (core->anal, fcn);
// FIXME: This defeats the purpose of the function, but afC is used in project files.
// cf. canal.c
r_cons_printf ("%d\n", totalCycles);
} else {
eprintf ("Cannot find function\n");
}
}
static int cmd_anal_fcn(RCore *core, const char *input) {
char i;
r_cons_break_timeout (r_config_get_i (core->config, "anal.timeout"));
switch (input[1]) {
case 'f': // "aff"
r_anal_fcn_fit_overlaps (core->anal, NULL);
break;
case 'a':
if (input[2] == 'l') { // afal : list function call arguments
int show_args = r_config_get_i (core->config, "dbg.funcarg");
if (show_args) {
r_core_print_func_args (core);
}
break;
}
case 'd': // "afd"
{
ut64 addr = 0;
if (input[2] == '?') {
eprintf ("afd [offset]\n");
} else if (input[2] == ' ') {
addr = r_num_math (core->num, input + 2);
} else {
addr = core->offset;
}
RAnalFunction *fcn = r_anal_get_fcn_in (core->anal, addr, 0);
if (fcn) {
if (fcn->addr != addr) {
r_cons_printf ("%s + %d\n", fcn->name,
(int)(addr - fcn->addr));
} else {
r_cons_println (fcn->name);
}
} else {
eprintf ("Cannot find function\n");
}
}
break;
case '-': // "af-"
if (!input[2] || !strcmp (input + 2, "*")) {
RAnalFunction *f;
RListIter *iter;
r_list_foreach (core->anal->fcns, iter, f) {
r_anal_del_jmprefs (core->anal, f);
}
r_list_purge (core->anal->fcns);
core->anal->fcn_tree = NULL;
} else {
ut64 addr = input[2]
? r_num_math (core->num, input + 2)
: core->offset;
r_anal_fcn_del_locs (core->anal, addr);
r_anal_fcn_del (core->anal, addr);
}
break;
case 'u': // "afu"
{
ut64 addr = core->offset;
ut64 addr_end = r_num_math (core->num, input + 2);
if (addr_end < addr) {
eprintf ("Invalid address ranges\n");
} else {
int depth = 1;
ut64 a, b;
const char *c;
a = r_config_get_i (core->config, "anal.from");
b = r_config_get_i (core->config, "anal.to");
c = r_config_get (core->config, "anal.limits");
r_config_set_i (core->config, "anal.from", addr);
r_config_set_i (core->config, "anal.to", addr_end);
r_config_set (core->config, "anal.limits", "true");
RAnalFunction *fcn = r_anal_get_fcn_in (core->anal, addr, 0);
if (fcn) {
r_anal_fcn_resize (core->anal, fcn, addr_end - addr);
}
r_core_anal_fcn (core, addr, UT64_MAX,
R_ANAL_REF_TYPE_NULL, depth);
fcn = r_anal_get_fcn_in (core->anal, addr, 0);
if (fcn) {
r_anal_fcn_resize (core->anal, fcn, addr_end - addr);
}
r_config_set_i (core->config, "anal.from", a);
r_config_set_i (core->config, "anal.to", b);
r_config_set (core->config, "anal.limits", c? c: "");
}
}
break;
case '+': { // "af+"
if (input[2] != ' ') {
eprintf ("Missing arguments\n");
return false;
}
char *ptr = strdup (input + 3);
const char *ptr2;
int n = r_str_word_set0 (ptr);
const char *name = NULL;
ut64 addr = UT64_MAX;
ut64 size = 0LL;
RAnalDiff *diff = NULL;
int type = R_ANAL_FCN_TYPE_FCN;
if (n > 1) {
switch (n) {
case 5:
size = r_num_math (core->num, r_str_word_get0 (ptr, 4));
case 4:
ptr2 = r_str_word_get0 (ptr, 3);
if (!(diff = r_anal_diff_new ())) {
eprintf ("error: Cannot init RAnalDiff\n");
free (ptr);
return false;
}
if (ptr2[0] == 'm') {
diff->type = R_ANAL_DIFF_TYPE_MATCH;
} else if (ptr2[0] == 'u') {
diff->type = R_ANAL_DIFF_TYPE_UNMATCH;
}
case 3:
ptr2 = r_str_word_get0 (ptr, 2);
if (strchr (ptr2, 'l')) {
type = R_ANAL_FCN_TYPE_LOC;
} else if (strchr (ptr2, 'i')) {
type = R_ANAL_FCN_TYPE_IMP;
} else if (strchr (ptr2, 's')) {
type = R_ANAL_FCN_TYPE_SYM;
} else {
type = R_ANAL_FCN_TYPE_FCN;
}
case 2:
name = r_str_word_get0 (ptr, 1);
case 1:
addr = r_num_math (core->num, r_str_word_get0 (ptr, 0));
}
if (!r_anal_fcn_add (core->anal, addr, size, name, type, diff)) {
eprintf ("Cannot add function (duplicated)\n");
}
}
r_anal_diff_free (diff);
free (ptr);
}
break;
case 'o': // "afo"
{
RAnalFunction *fcn;
ut64 addr = core->offset;
if (input[2] == ' ')
addr = r_num_math (core->num, input + 3);
if (addr == 0LL) {
fcn = r_anal_fcn_find_name (core->anal, input + 3);
} else {
fcn = r_anal_get_fcn_in (core->anal, addr, R_ANAL_FCN_TYPE_NULL);
}
if (fcn) {
r_cons_printf ("0x%08" PFMT64x "\n", fcn->addr);
}
}
break;
case 'i': // "afi"
switch (input[2]) {
case '?':
r_core_cmd_help (core, help_msg_afi);
break;
case '.': // "afi."
{
ut64 addr = core->offset;
if (input[3] == ' ') {
addr = r_num_math (core->num, input + 3);
}
RAnalFunction *fcn = r_anal_get_fcn_in (core->anal, addr, R_ANAL_FCN_TYPE_NULL);
if (fcn) {
r_cons_printf ("%s\n", fcn->name);
}
}
break;
case 'l': // "afil"
if (input[3] == '?') {
// TODO #7967 help refactor
help_msg_afll[1] = "afil";
r_core_cmd_help (core, help_msg_afll);
break;
}
/* fallthrough */
case 'j': // "afij"
case '*': // "afi*"
r_core_anal_fcn_list (core, input + 3, input + 2);
break;
case 'p': // "afip"
{
RAnalFunction *fcn = r_anal_get_fcn_in (core->anal, core->offset, R_ANAL_FCN_TYPE_NULL);
if (fcn) {
r_cons_printf ("is-pure: %s\n", r_anal_fcn_get_purity (core->anal, fcn) ? "true" : "false");
}
}
break;
default:
i = 1;
r_core_anal_fcn_list (core, input + 2, &i);
break;
}
break;
case 'l': // "afl"
switch (input[2]) {
case '?':
r_core_cmd_help (core, help_msg_afl);
break;
case 's': // "afls"
r_list_sort (core->anal->fcns, cmpaddr);
break;
case 'l': // "afll"
if (input[3] == '?') {
// TODO #7967 help refactor
help_msg_afll[1] = "afll";
r_core_cmd_help (core, help_msg_afll);
break;
}
/* fallthrough */
case 'j': // "aflj"
case 'q': // "aflq"
case '+': // "afl+"
case '*': // "afl*"
r_core_anal_fcn_list (core, NULL, input + 2);
break;
case 'c': // "aflc"
r_cons_printf ("%d\n", r_list_length (core->anal->fcns));
break;
default: // "afl "
r_core_anal_fcn_list (core, NULL, "o");
break;
}
break;
case 's': // "afs"
{
ut64 addr;
RAnalFunction *f;
const char *arg = input + 2;
if (input[2] && (addr = r_num_math (core->num, arg))) {
arg = strchr (arg, ' ');
if (arg) {
arg++;
}
} else {
addr = core->offset;
}
if ((f = r_anal_get_fcn_in (core->anal, addr, R_ANAL_FCN_TYPE_NULL))) {
if (arg && *arg) {
r_anal_str_to_fcn (core->anal, f, arg);
} else {
char *str = r_anal_fcn_to_string (core->anal, f);
r_cons_println (str);
free (str);
}
} else {
eprintf ("No function defined at 0x%08" PFMT64x "\n", addr);
}
}
break;
case 'm': // "afm" - merge two functions
r_core_anal_fcn_merge (core, core->offset, r_num_math (core->num, input + 2));
break;
case 'M': // "afM" - print functions map
r_core_anal_fmap (core, input + 1);
break;
case 'v': // "afv"
var_cmd (core, input + 2);
break;
case 't': // "aft"
type_cmd (core, input + 2);
break;
case 'C': // "afC"
if (input[2] == 'c') {
RAnalFunction *fcn;
if ((fcn = r_anal_get_fcn_in (core->anal, core->offset, 0)) != NULL) {
r_cons_printf ("%i\n", r_anal_fcn_cc (fcn));
} else {
eprintf ("Error: Cannot find function at 0x08%" PFMT64x "\n", core->offset);
}
} else if (input[2] == 'l') {
RAnalFunction *fcn;
if ((fcn = r_anal_get_fcn_in (core->anal, core->offset, 0)) != NULL) {
r_cons_printf ("%d\n", r_anal_fcn_loops (fcn));
} else {
eprintf ("Error: Cannot find function at 0x08%" PFMT64x "\n", core->offset);
}
} else if (input[2] == '?') {
r_core_cmd_help (core, help_msg_afC);
} else {
afCc (core, input + 3);
}
break;
case 'c':{ // "afc"
RAnalFunction *fcn = r_anal_get_fcn_in (core->anal, core->offset, 0);
if (!fcn && !(input[2] == '?'|| input[2] == 'l' || input[2] == 'o' || input[2] == 'f')) {
eprintf ("Cannot find function here\n");
break;
}
switch (input[2]) {
case '\0': // "afc"
r_cons_println (fcn->cc);
break;
case ' ': { // "afc "
char *cc = r_str_trim (strdup (input + 3));
if (!r_anal_cc_exist (core->anal, cc)) {
eprintf ("Unknown calling convention '%s'\n"
"See afcl for available types\n", cc);
} else {
fcn->cc = r_str_const (r_anal_cc_to_constant (core->anal, cc));
}
break;
}
case 'a': // "afca"
eprintf ("Todo\n");
break;
case 'f': { // "afcf"
bool json = false;
if (input[3] == 'j') {
json = true;
r_cons_printf ("[");
}
char *p = strchr (input, ' ');
const char *fcn_name = p? r_str_trim (strdup (p)): NULL;
char *key = NULL;
RListIter *iter;
RAnalFuncArg *arg;
if (fcn && !fcn_name) {
fcn_name = fcn->name;
}
if (fcn_name) {
key = resolve_fcn_name (core->anal, fcn_name);
}
if (key) {
const char *fcn_type = r_type_func_ret (core->anal->sdb_types, key);
int nargs = r_type_func_args_count (core->anal->sdb_types, key);
if (fcn_type) {
char *sp = " ";
if (*fcn_type && (fcn_type[strlen (fcn_type) - 1] == '*')) {
sp = "";
}
if (json) {
r_cons_printf ("{\"name\": \"%s\"",r_str_get (key));
r_cons_printf (",\"return\": \"%s\"",r_str_get (fcn_type));
r_cons_printf (",\"count\": %d", nargs);
if (nargs) {
r_cons_printf (",\"args\":[", nargs);
}
} else {
r_cons_printf ("%s%s%s(", r_str_get (fcn_type), sp, r_str_get (key));
if (!nargs) {
r_cons_println ("void)");
break;
}
}
bool first = true;
RList *list = r_core_get_func_args (core, fcn_name);
r_list_foreach (list, iter, arg) {
RListIter *nextele = r_list_iter_get_next (iter);
char *type = arg->orig_c_type;
char *sp1 = " ";
if (*type && (type[strlen (type) - 1] == '*')) {
sp1 = "";
}
if (json) {
r_cons_printf ("%s{\"name\": \"%s\",\"type\":\"%s\"}",
first? "": ",", arg->name, type);
first = false;
} else {
r_cons_printf ("%s%s%s%s", type, sp1, arg->name, nextele?", ":")");
}
}
if (json) {
if (nargs) {
r_cons_printf ("]");
}
r_cons_printf ("}");
} else {
r_cons_println ("");
}
}
}
if (json) {
r_cons_printf ("]\n");
}
break;
}
case 'l': // "afcl" list all function Calling conventions.
sdb_foreach (core->anal->sdb_cc, cc_print, NULL);
break;
case 'o': { // "afco"
char *dbpath = r_str_trim (strdup (input + 3));
if (r_file_exists (dbpath)) {
Sdb *db = sdb_new (0, dbpath, 0);
sdb_merge (core->anal->sdb_cc, db);
sdb_close (db);
sdb_free (db);
}
free (dbpath);
break;
}
case 'r': { // "afcr"
int i;
char *out, *cmd, *regname, *tmp;
char *subvec_str = r_str_new ("");
char *json_str = r_str_new ("");
// if json_str initialize to NULL, it's possible for afcrj to output a (NULL)
// subvec_str and json_str should be valid until exiting this code block
bool json = input[3] == 'j'? true: false;
for (i = 0; i <= 11; i++) {
if (i == 0) {
cmd = r_str_newf ("cc.%s.ret", fcn->cc);
} else {
cmd = r_str_newf ("cc.%s.arg%d", fcn->cc, i);
}
if (i < 7) {
regname = r_str_new (cmd);
} else {
regname = r_str_newf ("cc.%s.float_arg%d", fcn->cc, i - 6);
}
out = sdb_querys (core->anal->sdb_cc, NULL, 0, cmd);
free (cmd);
if (out) {
out[strlen (out) - 1] = 0;
if (json) {
tmp = subvec_str;
subvec_str = r_str_newf ("%s,\"%s\"", subvec_str, out);
free (tmp);
} else {
r_cons_printf ("%s: %s\n", regname, out);
}
free (out);
}
free (regname);
if (!subvec_str[0]) {
continue;
}
switch (i) {
case 0: {
tmp = json_str;
json_str = r_str_newf ("%s,\"ret\":%s", json_str, subvec_str + 1);
free (tmp);
} break;
case 6: {
tmp = json_str;
json_str = r_str_newf ("%s,\"args\":[%s]", json_str, subvec_str + 1);
free (tmp);
} break;
case 11: {
tmp = json_str;
json_str = r_str_newf ("%s,\"float_args\":[%s]", json_str, subvec_str + 1);
free (tmp);
} break;
default:
continue;
}
free (subvec_str);
subvec_str = r_str_new ("");
}
if (json && json_str[0]) {
r_cons_printf ("{%s}\n", json_str + 1);
}
free (subvec_str);
free (json_str);
} break;
case '?': // "afc?"
default:
r_core_cmd_help (core, help_msg_afc);
}
}break;
case 'B': // "afB" // set function bits
if (input[2] == ' ') {
RAnalFunction *fcn = r_anal_get_fcn_in (core->anal, core->offset,
R_ANAL_FCN_TYPE_FCN | R_ANAL_FCN_TYPE_SYM);
if (fcn) {
int bits = atoi (input + 3);
r_anal_hint_set_bits (core->anal, fcn->addr, bits);
r_anal_hint_set_bits (core->anal,
fcn->addr + r_anal_fcn_size (fcn),
core->anal->bits);
fcn->bits = bits;
} else {
eprintf ("Cannot find function to set bits\n");
}
} else {
eprintf ("Usage: afB [bits]\n");
}
break;
case 'b': // "afb"
switch (input[2]) {
case '-': // "afb-"
anal_fcn_del_bb (core, input + 3);
break;
case 'e': // "afbe"
anal_bb_edge (core, input + 3);
break;
case 0:
case ' ': // "afb "
case 'q': // "afbq"
case 'r': // "afbr"
case '*': // "afb*"
case 'j': // "afbj"
anal_fcn_list_bb (core, input + 2, false);
break;
case 'i': // "afbi"
anal_fcn_list_bb (core, input + 2, true);
break;
case '.': // "afb."
anal_fcn_list_bb (core, input[2]? " $$": input + 2, true);
break;
case '+': // "afb+"
anal_fcn_add_bb (core, input + 3);
break;
case 'c': // "afbc"
{
const char *ptr = input + 3;
ut64 addr = r_num_math (core->num, ptr);
ut32 color;
ptr = strchr (ptr, ' ');
if (ptr) {
ptr = strchr (ptr + 1, ' ');
if (ptr) {
color = r_num_math (core->num, ptr + 1);
RAnalOp *op = r_core_op_anal (core, addr);
if (op) {
r_anal_colorize_bb (core->anal, addr, color);
r_anal_op_free (op);
} else {
eprintf ("Cannot analyze opcode at 0x%08" PFMT64x "\n", addr);
}
}
}
}
break;
default:
case '?':
r_core_cmd_help (core, help_msg_afb);
break;
}
break;
case 'n': // "afn"
switch (input[2]) {
case 's': // "afns"
free (r_core_anal_fcn_autoname (core, core->offset, 1));
break;
case 'a': // "afna"
{
char *name = r_core_anal_fcn_autoname (core, core->offset, 0);
if (name) {
r_cons_printf ("afn %s 0x%08" PFMT64x "\n", name, core->offset);
free (name);
}
}
break;
case 0: // "afn"
{
RAnalFunction *fcn = r_anal_get_fcn_in (core->anal, core->offset, -1);
if (fcn) {
r_cons_printf ("%s\n", fcn->name);
}
}
break;
case ' ': // "afn "
{
ut64 off = core->offset;
char *p, *name = strdup (input + 3);
if ((p = strchr (name, ' '))) {
*p++ = 0;
off = r_num_math (core->num, p);
}
if (*name == '?') {
eprintf ("Usage: afn newname [off] # set new name to given function\n");
} else {
if (!*name || !setFunctionName (core, off, name, false)) {
eprintf ("Cannot find function '%s' at 0x%08" PFMT64x "\n", name, off);
}
}
free (name);
}
break;
default:
r_core_cmd_help (core, help_msg_afn);
break;
}
break;
case 'S': // afS"
{
RAnalFunction *fcn = r_anal_get_fcn_in (core->anal, core->offset, -1);
if (fcn) {
fcn->maxstack = r_num_math (core->num, input + 3);
//fcn->stack = fcn->maxstack;
}
}
break;
#if 0
/* this is undocumented and probably have no uses. plz discuss */
case 'e': // "afe"
{
RAnalFunction *fcn;
ut64 off = core->offset;
char *p, *name = strdup ((input[2]&&input[3])? input + 3: "");
if ((p = strchr (name, ' '))) {
*p = 0;
off = r_num_math (core->num, p + 1);
}
fcn = r_anal_get_fcn_in (core->anal, off, R_ANAL_FCN_TYPE_FCN | R_ANAL_FCN_TYPE_SYM);
if (fcn) {
RAnalBlock *b;
RListIter *iter;
RAnalRef *r;
r_list_foreach (fcn->refs, iter, r) {
r_cons_printf ("0x%08" PFMT64x " -%c 0x%08" PFMT64x "\n", r->at, r->type, r->addr);
}
r_list_foreach (fcn->bbs, iter, b) {
int ok = 0;
if (b->type == R_ANAL_BB_TYPE_LAST) ok = 1;
if (b->type == R_ANAL_BB_TYPE_FOOT) ok = 1;
if (b->jump == UT64_MAX && b->fail == UT64_MAX) ok = 1;
if (ok) {
r_cons_printf ("0x%08" PFMT64x " -r\n", b->addr);
// TODO: check if destination is outside the function boundaries
}
}
} else eprintf ("Cannot find function at 0x%08" PFMT64x "\n", core->offset);
free (name);
}
break;
#endif
case 'x': // "afx"
switch (input[2]) {
case '\0': // "afx"
case 'j': // "afxj"
case ' ': // "afx "
if (input[2] == 'j') {
r_cons_printf ("[");
}
// list xrefs from current address
{
ut64 addr = input[2]==' '? r_num_math (core->num, input + 2): core->offset;
RAnalFunction *fcn = r_anal_get_fcn_in (core->anal, addr, R_ANAL_FCN_TYPE_NULL);
if (fcn) {
RAnalRef *ref;
RListIter *iter;
RList *refs = r_anal_fcn_get_refs (core->anal, fcn);
r_list_foreach (refs, iter, ref) {
if (input[2] == 'j') {
r_cons_printf ("{\"type\":\"%c\",\"from\":%"PFMT64u",\"to\":%"PFMT64u"}%s",
ref->type, ref->at, ref->addr, iter->n? ",": "");
} else {
r_cons_printf ("%c 0x%08" PFMT64x " -> 0x%08" PFMT64x "\n",
ref->type, ref->at, ref->addr);
}
}
r_list_free (refs);
} else {
eprintf ("Cannot find function at 0x%08"PFMT64x"\n", addr);
}
}
if (input[2] == 'j') {
r_cons_printf ("]\n");
}
break;
default:
eprintf ("Wrong command. Look at af?\n");
break;
}
break;
case 'F': // "afF"
{
int val = input[2] && r_num_math (core->num, input + 2);
RAnalFunction *fcn = r_anal_get_fcn_in (core->anal, core->offset, R_ANAL_FCN_TYPE_NULL);
if (fcn) {
fcn->folded = input[2]? val: !fcn->folded;
}
}
break;
case '?': // "af?"
r_core_cmd_help (core, help_msg_af);
break;
case 'r': // "afr" // analyze function recursively
case ' ': // "af "
case '\0': // "af"
{
char *uaddr = NULL, *name = NULL;
int depth = r_config_get_i (core->config, "anal.depth");
bool analyze_recursively = r_config_get_i (core->config, "anal.calls");
RAnalFunction *fcn;
RAnalFunction *fcni;
RListIter *iter;
ut64 addr = core->offset;
if (input[1] == 'r') {
input++;
analyze_recursively = true;
}
// first undefine
if (input[0] && input[1] == ' ') {
name = strdup (input + 2);
uaddr = strchr (name, ' ');
if (uaddr) {
*uaddr++ = 0;
addr = r_num_math (core->num, uaddr);
}
// depth = 1; // or 1?
// disable hasnext
}
//r_core_anal_undefine (core, core->offset);
r_core_anal_fcn (core, addr, UT64_MAX, R_ANAL_REF_TYPE_NULL, depth);
fcn = r_anal_get_fcn_in (core->anal, addr, 0);
if (fcn) {
/* ensure we use a proper name */
setFunctionName (core, addr, fcn->name, false);
}
if (analyze_recursively) {
fcn = r_anal_get_fcn_in (core->anal, addr, 0); /// XXX wrong in case of nopskip
if (fcn) {
RAnalRef *ref;
RListIter *iter;
RList *refs = r_anal_fcn_get_refs (core->anal, fcn);
r_list_foreach (refs, iter, ref) {
if (ref->addr == UT64_MAX) {
//eprintf ("Warning: ignore 0x%08"PFMT64x" call 0x%08"PFMT64x"\n", ref->at, ref->addr);
continue;
}
if (ref->type != R_ANAL_REF_TYPE_CODE && ref->type != R_ANAL_REF_TYPE_CALL) {
/* only follow code/call references */
continue;
}
if (!r_io_is_valid_offset (core->io, ref->addr, !core->anal->opt.noncode)) {
continue;
}
r_core_anal_fcn (core, ref->addr, fcn->addr, R_ANAL_REF_TYPE_CALL, depth);
/* use recursivity here */
#if 1
RAnalFunction *f = r_anal_get_fcn_at (core->anal, ref->addr, 0);
if (f) {
RListIter *iter;
RAnalRef *ref;
RList *refs1 = r_anal_fcn_get_refs (core->anal, f);
r_list_foreach (refs1, iter, ref) {
if (!r_io_is_valid_offset (core->io, ref->addr, !core->anal->opt.noncode)) {
continue;
}
if (ref->type != 'c' && ref->type != 'C') {
continue;
}
r_core_anal_fcn (core, ref->addr, f->addr, R_ANAL_REF_TYPE_CALL, depth);
// recursively follow fcn->refs again and again
}
r_list_free (refs1);
} else {
f = r_anal_get_fcn_in (core->anal, fcn->addr, 0);
if (f) {
/* cut function */
r_anal_fcn_resize (core->anal, f, addr - fcn->addr);
r_core_anal_fcn (core, ref->addr, fcn->addr,
R_ANAL_REF_TYPE_CALL, depth);
f = r_anal_get_fcn_at (core->anal, fcn->addr, 0);
}
if (!f) {
eprintf ("Cannot find function at 0x%08" PFMT64x "\n", fcn->addr);
}
}
#endif
}
r_list_free (refs);
}
}
if (name) {
if (*name && !setFunctionName (core, addr, name, true)) {
eprintf ("Cannot find function '%s' at 0x%08" PFMT64x "\n", name, (ut64)addr);
}
free (name);
}
if (core->anal->opt.vars) {
r_list_foreach (core->anal->fcns, iter, fcni) {
if (r_cons_is_breaked ()) {
break;
}
r_core_recover_vars (core, fcni, true);
}
}
flag_every_function (core);
}
default:
return false;
break;
}
return true;
}
// size: 0: bits; -1: any; >0: exact size
static void __anal_reg_list(RCore *core, int type, int bits, char mode) {
RReg *hack = core->dbg->reg;
const char *use_color;
int use_colors = r_config_get_i (core->config, "scr.color");
if (use_colors) {
#undef ConsP
#define ConsP(x) (core->cons && core->cons->pal.x)? core->cons->pal.x
use_color = ConsP (creg) : Color_BWHITE;
} else {
use_color = NULL;
}
if (bits < 0) {
// TODO Change the `size` argument of r_debug_reg_list to use -1 for any and 0 for anal->bits
bits = 0;
} else if (!bits) {
bits = core->anal->bits;
}
int mode2 = mode;
if (core->anal) {
core->dbg->reg = core->anal->reg;
if (core->anal->cur && core->anal->cur->arch) {
/* workaround for thumb */
if (!strcmp (core->anal->cur->arch, "arm") && bits == 16) {
bits = 32;
}
/* workaround for 6502 */
if (!strcmp (core->anal->cur->arch, "6502") && bits == 8) {
mode2 = mode == 'j' ? 'J' : mode;
if (mode == 'j') {
r_cons_printf ("{");
}
r_debug_reg_list (core->dbg, R_REG_TYPE_GPR, 16, mode2, use_color); // XXX detect which one is current usage
if (mode == 'j') {
r_cons_printf (",");
}
}
if (!strcmp (core->anal->cur->arch, "avr") && bits == 8) {
mode2 = mode == 'j' ? 'J' : mode;
if (mode == 'j') {
r_cons_printf ("{");
}
r_debug_reg_list (core->dbg, R_REG_TYPE_GPR, 16, mode2, use_color); // XXX detect which one is current usage
if (mode == 'j') {
r_cons_printf (",");
}
}
}
}
if (mode == '=') {
int pcbits = 0;
const char *pcname = r_reg_get_name (core->anal->reg, R_REG_NAME_PC);
RRegItem *reg = r_reg_get (core->anal->reg, pcname, 0);
if (bits != reg->size) {
pcbits = reg->size;
}
if (pcbits) {
r_debug_reg_list (core->dbg, R_REG_TYPE_GPR, pcbits, 2, use_color); // XXX detect which one is current usage
}
}
r_debug_reg_list (core->dbg, type, bits, mode2, use_color);
if (mode2 == 'J') {
r_cons_print ("}\n");
}
core->dbg->reg = hack;
}
// XXX dup from drp :OOO
void cmd_anal_reg(RCore *core, const char *str) {
int size = 0, i, type = R_REG_TYPE_GPR;
int bits = (core->anal->bits & R_SYS_BITS_64)? 64: 32;
int use_colors = r_config_get_i (core->config, "scr.color");
struct r_reg_item_t *r;
const char *use_color;
const char *name;
char *arg;
if (use_colors) {
#define ConsP(x) (core->cons && core->cons->pal.x)? core->cons->pal.x
use_color = ConsP (creg)
: Color_BWHITE;
} else {
use_color = NULL;
}
switch (str[0]) {
case 'l': // "arl"
{
RRegSet *rs = r_reg_regset_get (core->anal->reg, R_REG_TYPE_GPR);
if (rs) {
RRegItem *r;
RListIter *iter;
r_list_foreach (rs->regs, iter, r) {
r_cons_println (r->name);
}
}
} break;
case '0': // "ar0"
r_reg_arena_zero (core->anal->reg);
break;
case 'A': // "arA"
{
int nargs = 4;
RReg *reg = core->anal->reg;
for (i = 0; i < nargs; i++) {
const char *name = r_reg_get_name (reg, r_reg_get_name_idx (sdb_fmt ("A%d", i)));
ut64 off = r_reg_getv (core->anal->reg, name);
r_cons_printf ("0x%08"PFMT64x" ", off);
// XXX very ugly hack
char *s = r_core_cmd_strf (core, "pxr 32 @ 0x%08"PFMT64x, off);
if (s) {
char *nl = strchr (s, '\n');
if (nl) {
*nl = 0;
r_cons_printf ("%s\n", s);
}
free (s);
}
// r_core_cmd0 (core, "ar A0,A1,A2,A3");
}
}
break;
case 'C': // "arC"
if (core->anal->reg->reg_profile_cmt) {
r_cons_println (core->anal->reg->reg_profile_cmt);
}
break;
case 'w': // "arw"
switch (str[1]) {
case '?': {
r_core_cmd_help (core, help_msg_arw);
break;
}
case ' ':
r_reg_arena_set_bytes (core->anal->reg, str + 1);
break;
default:
r_core_cmd_help (core, help_msg_arw);
break;
}
break;
case 'a': // "ara"
switch (str[1]) {
case '?': // "ara?"
r_core_cmd_help (core, help_msg_ara);
break;
case 's': // "aras"
r_reg_arena_swap (core->anal->reg, false);
break;
case '+': // "ara+"
r_reg_arena_push (core->anal->reg);
break;
case '-': // "ara-"
r_reg_arena_pop (core->anal->reg);
break;
default: {
int i, j;
RRegArena *a;
RListIter *iter;
for (i = 0; i < R_REG_TYPE_LAST; i++) {
RRegSet *rs = &core->anal->reg->regset[i];
j = 0;
r_list_foreach (rs->pool, iter, a) {
r_cons_printf ("%s %p %d %d %s %d\n",
(a == rs->arena)? "*": ".", a,
i, j, r_reg_get_type (i), a->size);
j++;
}
}
} break;
}
break;
case '?': // "ar?"
if (str[1]) {
ut64 off = r_reg_getv (core->anal->reg, str + 1);
r_cons_printf ("0x%08" PFMT64x "\n", off);
} else {
r_core_cmd_help (core, help_msg_ar);
}
break;
case 'r': // "arr"
switch (str[1]) {
case 'j': // "arrj"
r_core_debug_rr (core, core->dbg->reg, 'j');
break;
default:
r_core_debug_rr (core, core->dbg->reg, 0);
break;
}
break;
case 'S': { // "arS"
int sz;
ut8 *buf = r_reg_get_bytes (core->anal->reg, R_REG_TYPE_GPR, &sz);
r_cons_printf ("%d\n", sz);
free (buf);
} break;
case 'b': { // "arb" WORK IN PROGRESS // DEBUG COMMAND
int len, type = R_REG_TYPE_GPR;
arg = strchr (str, ' ');
if (arg) {
char *string = r_str_trim (strdup (arg + 1));
if (string) {
type = r_reg_type_by_name (string);
if (type == -1 && string[0] != 'a') {
type = R_REG_TYPE_GPR;
}
free (string);
}
}
ut8 *buf = r_reg_get_bytes (core->dbg->reg, type, &len);
if (buf) {
r_print_hexdump (core->print, 0LL, buf, len, 32, 4, 1);
free (buf);
}
} break;
case 'c': // "arc"
// TODO: set flag values with drc zf=1
{
RRegItem *r;
const char *name = r_str_trim_ro (str + 1);
if (*name && name[1]) {
r = r_reg_cond_get (core->dbg->reg, name);
if (r) {
r_cons_println (r->name);
} else {
int id = r_reg_cond_from_string (name);
RRegFlags *rf = r_reg_cond_retrieve (core->dbg->reg, NULL);
if (rf) {
int o = r_reg_cond_bits (core->dbg->reg, id, rf);
core->num->value = o;
// ORLY?
r_cons_printf ("%d\n", o);
free (rf);
} else {
eprintf ("unknown conditional or flag register\n");
}
}
} else {
RRegFlags *rf = r_reg_cond_retrieve (core->dbg->reg, NULL);
if (rf) {
r_cons_printf ("| s:%d z:%d c:%d o:%d p:%d\n",
rf->s, rf->z, rf->c, rf->o, rf->p);
if (*name == '=') {
for (i = 0; i < R_REG_COND_LAST; i++) {
r_cons_printf ("%s:%d ",
r_reg_cond_to_string (i),
r_reg_cond_bits (core->dbg->reg, i, rf));
}
r_cons_newline ();
} else {
for (i = 0; i < R_REG_COND_LAST; i++) {
r_cons_printf ("%d %s\n",
r_reg_cond_bits (core->dbg->reg, i, rf),
r_reg_cond_to_string (i));
}
}
free (rf);
}
}
}
break;
case 's': // "ars"
switch (str[1]) {
case '-': // "ars-"
r_reg_arena_pop (core->dbg->reg);
// restore debug registers if in debugger mode
r_debug_reg_sync (core->dbg, R_REG_TYPE_GPR, true);
break;
case '+': // "ars+"
r_reg_arena_push (core->dbg->reg);
break;
case '?': { // "ars?"
// TODO #7967 help refactor: dup from drp
const char *help_msg[] = {
"Usage:", "drs", " # Register states commands",
"drs", "", "List register stack",
"drs+", "", "Push register state",
"drs-", "", "Pop register state",
NULL };
r_core_cmd_help (core, help_msg);
} break;
default:
r_cons_printf ("%d\n", r_list_length (
core->dbg->reg->regset[0].pool));
break;
}
break;
case 'p': // "arp"
// XXX we have to break out .h for these cmd_xxx files.
cmd_reg_profile (core, 'a', str);
break;
case 't': // "art"
for (i = 0; (name = r_reg_get_type (i)); i++)
r_cons_println (name);
break;
case 'n': // "arn"
if (*(str + 1) == '\0') {
eprintf ("Oops. try arn [PC|SP|BP|A0|A1|A2|A3|A4|R0|R1|ZF|SF|NF|OF]\n");
break;
}
name = r_reg_get_name (core->dbg->reg, r_reg_get_name_idx (str + 2));
if (name && *name) {
r_cons_println (name);
} else {
eprintf ("Oops. try arn [PC|SP|BP|A0|A1|A2|A3|A4|R0|R1|ZF|SF|NF|OF]\n");
}
break;
case 'd': // "ard"
r_debug_reg_list (core->dbg, R_REG_TYPE_GPR, bits, 3, use_color); // XXX detect which one is current usage
break;
case 'o': // "aro"
r_reg_arena_swap (core->dbg->reg, false);
r_debug_reg_list (core->dbg, R_REG_TYPE_GPR, bits, 0, use_color); // XXX detect which one is current usage
r_reg_arena_swap (core->dbg->reg, false);
break;
case '=': // "ar="
{
char *p = NULL;
char *bits = NULL;
if (str[1]) {
p = strdup (str + 1);
if (str[1] != ':') {
// Bits were specified
bits = strtok (p, ":");
if (r_str_isnumber (bits)) {
st64 sz = r_num_math (core->num, bits);
if (sz > 0) {
size = sz;
}
} else {
r_core_cmd_help (core, help_msg_ar);
break;
}
}
int len = bits ? strlen (bits) : 0;
if (str[len + 1] == ':') {
// We have some regs
char *regs = bits ? strtok (NULL, ":") : strtok ((char *)str + 1, ":");
char *reg = strtok (regs, " ");
RList *q_regs = r_list_new ();
if (q_regs) {
while (reg) {
r_list_append (q_regs, reg);
reg = strtok (NULL, " ");
}
core->dbg->q_regs = q_regs;
}
}
}
__anal_reg_list (core, type, size, 2);
if (!r_list_empty (core->dbg->q_regs)) {
r_list_free (core->dbg->q_regs);
}
core->dbg->q_regs = NULL;
free (p);
}
break;
case '-': // "ar-"
case '*': // "ar*"
case 'R': // "arR"
case 'j': // "arj"
case '\0': // "ar"
__anal_reg_list (core, type, size, str[0]);
break;
case ' ': { // "ar "
arg = strchr (str + 1, '=');
if (arg) {
char *ostr, *regname;
*arg = 0;
ostr = r_str_trim (strdup (str + 1));
regname = r_str_trim_nc (ostr);
r = r_reg_get (core->dbg->reg, regname, -1);
if (!r) {
int role = r_reg_get_name_idx (regname);
if (role != -1) {
const char *alias = r_reg_get_name (core->dbg->reg, role);
r = r_reg_get (core->dbg->reg, alias, -1);
}
}
if (r) {
//eprintf ("%s 0x%08"PFMT64x" -> ", str,
// r_reg_get_value (core->dbg->reg, r));
r_reg_set_value (core->dbg->reg, r,
r_num_math (core->num, arg + 1));
r_debug_reg_sync (core->dbg, R_REG_TYPE_ALL, true);
//eprintf ("0x%08"PFMT64x"\n",
// r_reg_get_value (core->dbg->reg, r));
r_core_cmdf (core, ".dr*%d", bits);
} else {
eprintf ("ar: Unknown register '%s'\n", regname);
}
free (ostr);
return;
}
char name[32];
int i = 1, j;
while (str[i]) {
if (str[i] == ',') {
i++;
} else {
for (j = i; str[++j] && str[j] != ','; );
if (j - i + 1 <= sizeof name) {
r_str_ncpy (name, str + i, j - i + 1);
if (IS_DIGIT (name[0])) { // e.g. ar 32
__anal_reg_list (core, R_REG_TYPE_GPR, atoi (name), '\0');
} else if (showreg (core, name) > 0) { // e.g. ar rax
} else { // e.g. ar gpr ; ar all
type = r_reg_type_by_name (name);
// TODO differentiate ALL and illegal register types and print error message for the latter
__anal_reg_list (core, type, -1, '\0');
}
}
i = j;
}
}
}
}
}
static ut64 initializeEsil(RCore *core) {
const char *name = r_reg_get_name (core->anal->reg, R_REG_NAME_PC);
int romem = r_config_get_i (core->config, "esil.romem");
int stats = r_config_get_i (core->config, "esil.stats");
int iotrap = r_config_get_i (core->config, "esil.iotrap");
int exectrap = r_config_get_i (core->config, "esil.exectrap");
int stacksize = r_config_get_i (core->config, "esil.stack.depth");
int noNULL = r_config_get_i (core->config, "esil.noNULL");
unsigned int addrsize = r_config_get_i (core->config, "esil.addr.size");
if (!(core->anal->esil = r_anal_esil_new (stacksize, iotrap, addrsize))) {
return UT64_MAX;
}
ut64 addr;
RAnalEsil *esil = core->anal->esil;
r_anal_esil_setup (esil, core->anal, romem, stats, noNULL); // setup io
esil->exectrap = exectrap;
RList *entries = r_bin_get_entries (core->bin);
RBinAddr *entry = NULL;
RBinInfo *info = NULL;
if (entries && !r_list_empty (entries)) {
entry = (RBinAddr *)r_list_pop (entries);
info = r_bin_get_info (core->bin);
addr = info->has_va? entry->vaddr: entry->paddr;
r_list_push (entries, entry);
} else {
addr = core->offset;
}
r_reg_setv (core->anal->reg, name, addr);
// set memory read only
return addr;
}
R_API int r_core_esil_step(RCore *core, ut64 until_addr, const char *until_expr, ut64 *prev_addr) {
#define return_tail(x) { tail_return_value = x; goto tail_return; }
int tail_return_value = 0;
int ret;
ut8 code[32];
RAnalOp op = {0};
RAnalEsil *esil = core->anal->esil;
const char *name = r_reg_get_name (core->anal->reg, R_REG_NAME_PC);
bool breakoninvalid = r_config_get_i (core->config, "esil.breakoninvalid");
if (!esil) {
// TODO inititalizeEsil (core);
int stacksize = r_config_get_i (core->config, "esil.stack.depth");
int iotrap = r_config_get_i (core->config, "esil.iotrap");
int romem = r_config_get_i (core->config, "esil.romem");
int stats = r_config_get_i (core->config, "esil.stats");
int noNULL = r_config_get_i (core->config, "esil.noNULL");
int verbose = r_config_get_i (core->config, "esil.verbose");
unsigned int addrsize = r_config_get_i (core->config, "esil.addr.size");
if (!(esil = r_anal_esil_new (stacksize, iotrap, addrsize))) {
return 0;
}
r_anal_esil_setup (esil, core->anal, romem, stats, noNULL); // setup io
core->anal->esil = esil;
esil->verbose = verbose;
{
const char *s = r_config_get (core->config, "cmd.esil.intr");
if (s) {
char *my = strdup (s);
if (my) {
r_config_set (core->config, "cmd.esil.intr", my);
free (my);
}
}
}
}
esil->cmd = r_core_esil_cmd;
ut64 addr = r_reg_getv (core->anal->reg, name);
r_cons_break_push (NULL, NULL);
repeat:
if (r_cons_is_breaked ()) {
eprintf ("[+] ESIL emulation interrupted at 0x%08" PFMT64x "\n", addr);
return_tail (0);
}
if (!esil) {
addr = initializeEsil (core);
esil = core->anal->esil;
if (!esil) {
return_tail (0);
}
} else {
esil->trap = 0;
addr = r_reg_getv (core->anal->reg, name);
//eprintf ("PC=0x%"PFMT64x"\n", (ut64)addr);
}
if (prev_addr) {
*prev_addr = addr;
}
if (esil->exectrap) {
if (!r_io_is_valid_offset (core->io, addr, R_PERM_X)) {
esil->trap = R_ANAL_TRAP_EXEC_ERR;
esil->trap_code = addr;
eprintf ("[ESIL] Trap, trying to execute on non-executable memory\n");
return_tail (1);
}
}
r_asm_set_pc (core->assembler, addr);
// run esil pin command here
const char *pincmd = r_anal_pin_call (core->anal, addr);
if (pincmd) {
r_core_cmd0 (core, pincmd);
ut64 pc = r_debug_reg_get (core->dbg, "PC");
if (addr != pc) {
return_tail (1);
}
}
int dataAlign = r_anal_archinfo (esil->anal, R_ANAL_ARCHINFO_DATA_ALIGN);
if (dataAlign > 1) {
if (addr % dataAlign) {
if (esil->cmd && esil->cmd_trap) {
esil->cmd (esil, esil->cmd_trap, addr, R_ANAL_TRAP_UNALIGNED);
}
if (breakoninvalid) {
r_cons_printf ("[ESIL] Stopped execution in an unaligned instruction (see e??esil.breakoninvalid)\n");
return_tail (0);
}
}
}
(void)r_io_read_at (core->io, addr, code, sizeof (code));
// TODO: sometimes this is dupe
ret = r_anal_op (core->anal, &op, addr, code, sizeof (code), R_ANAL_OP_MASK_ESIL);
// if type is JMP then we execute the next N instructions
// update the esil pointer because RAnal.op() can change it
esil = core->anal->esil;
if (op.size < 1 || ret < 0) {
if (esil->cmd && esil->cmd_trap) {
esil->cmd (esil, esil->cmd_trap, addr, R_ANAL_TRAP_INVALID);
}
if (breakoninvalid) {
r_cons_printf ("[ESIL] Stopped execution in an invalid instruction (see e??esil.breakoninvalid)\n");
return_tail (0);
}
op.size = 1; // avoid inverted stepping
}
{
/* apply hint */
RAnalHint *hint = r_anal_hint_get (core->anal, addr);
r_anal_op_hint (&op, hint);
r_anal_hint_free (hint);
}
if (r_config_get_i (core->config, "cfg.r2wars")) {
// this is x86 and r2wars specific, shouldnt hurt outside x86
ut64 vECX = r_reg_getv (core->anal->reg, "ecx");
if (op.prefix & R_ANAL_OP_PREFIX_REP && vECX > 1) {
char *tmp = strstr (op.esil.ptr, ",ecx,?{,5,GOTO,}");
if (tmp) {
tmp[0] = 0;
}
op.esil.len -= 16;
} else {
r_reg_setv (core->anal->reg, name, addr + op.size);
}
} else {
r_reg_setv (core->anal->reg, name, addr + op.size);
}
if (ret) {
r_anal_esil_set_pc (esil, addr);
if (core->dbg->trace->enabled) {
RReg *reg = core->dbg->reg;
core->dbg->reg = core->anal->reg;
r_debug_trace_pc (core->dbg, addr);
core->dbg->reg = reg;
} else {
r_anal_esil_parse (esil, R_STRBUF_SAFEGET (&op.esil));
if (core->anal->cur && core->anal->cur->esil_post_loop) {
core->anal->cur->esil_post_loop (esil, &op);
}
r_anal_esil_stack_free (esil);
}
// only support 1 slot for now
if (op.delay) {
ut8 code2[32];
ut64 naddr = addr + op.size;
RAnalOp op2 = {0};
// emulate only 1 instruction
r_anal_esil_set_pc (esil, naddr);
(void)r_io_read_at (core->io, naddr, code2, sizeof (code2));
// TODO: sometimes this is dupe
ret = r_anal_op (core->anal, &op2, naddr, code2, sizeof (code2), R_ANAL_OP_MASK_ESIL);
switch (op2.type) {
case R_ANAL_OP_TYPE_CJMP:
case R_ANAL_OP_TYPE_JMP:
case R_ANAL_OP_TYPE_CRET:
case R_ANAL_OP_TYPE_RET:
// branches are illegal in a delay slot
esil->trap = R_ANAL_TRAP_EXEC_ERR;
esil->trap_code = addr;
eprintf ("[ESIL] Trap, trying to execute a branch in a delay slot\n");
return_tail (1);
break;
}
r_anal_esil_parse (esil, R_STRBUF_SAFEGET (&op2.esil));
r_anal_op_fini (&op2);
}
tail_return_value = 1;
}
st64 follow = (st64)r_config_get_i (core->config, "dbg.follow");
if (follow > 0) {
ut64 pc = r_debug_reg_get (core->dbg, "PC");
if ((pc < core->offset) || (pc > (core->offset + follow))) {
r_core_cmd0 (core, "sr PC");
}
}
// check breakpoints
ut64 pc = r_reg_getv (core->anal->reg, name);
if (r_bp_get_at (core->dbg->bp, pc)) {
r_cons_printf ("[ESIL] hit breakpoint at 0x%"PFMT64x "\n", pc);
return_tail (0);
}
// check addr
if (until_addr != UT64_MAX) {
if (pc == until_addr) {
return_tail (0);
}
goto repeat;
}
// check esil
if (esil && esil->trap) {
if (core->anal->esil->verbose) {
eprintf ("TRAP\n");
}
return_tail (0);
}
if (until_expr) {
if (r_anal_esil_condition (core->anal->esil, until_expr)) {
if (core->anal->esil->verbose) {
eprintf ("ESIL BREAK!\n");
}
return_tail (0);
}
goto repeat;
}
tail_return:
r_anal_op_fini (&op);
r_cons_break_pop ();
return tail_return_value;
}
R_API int r_core_esil_step_back(RCore *core) {
RAnalEsil *esil = core->anal->esil;
RListIter *tail;
const char *name = r_reg_get_name (core->anal->reg, R_REG_NAME_PC);
ut64 prev = 0;
ut64 end = r_reg_getv (core->anal->reg, name);
if (!esil || !(tail = r_list_tail (esil->sessions))) {
return 0;
}
RAnalEsilSession *before = (RAnalEsilSession *) tail->data;
if (!before) {
eprintf ("Cannot find any previous state here\n");
return 0;
}
eprintf ("NOTE: step back in esil is setting an initial state and stepping into pc is the same.\n");
eprintf ("NOTE: this is extremely wrong and poorly efficient. so don't use this feature unless\n");
eprintf ("NOTE: you are going to fix it by making it consistent with dts, which is also broken as hell\n");
eprintf ("Execute until 0x%08"PFMT64x"\n", end);
r_anal_esil_session_set (esil, before);
r_core_esil_step (core, end, NULL, &prev);
eprintf ("Before 0x%08"PFMT64x"\n", prev);
r_anal_esil_session_set (esil, before);
r_core_esil_step (core, prev, NULL, NULL);
return 1;
}
static void cmd_address_info(RCore *core, const char *addrstr, int fmt) {
ut64 addr, type;
if (!addrstr || !*addrstr) {
addr = core->offset;
} else {
addr = r_num_math (core->num, addrstr);
}
type = r_core_anal_address (core, addr);
int isp = 0;
switch (fmt) {
case 'j':
#define COMMA isp++? ",": ""
r_cons_printf ("{");
if (type & R_ANAL_ADDR_TYPE_PROGRAM)
r_cons_printf ("%s\"program\":true", COMMA);
if (type & R_ANAL_ADDR_TYPE_LIBRARY)
r_cons_printf ("%s\"library\":true", COMMA);
if (type & R_ANAL_ADDR_TYPE_EXEC)
r_cons_printf ("%s\"exec\":true", COMMA);
if (type & R_ANAL_ADDR_TYPE_READ)
r_cons_printf ("%s\"read\":true", COMMA);
if (type & R_ANAL_ADDR_TYPE_WRITE)
r_cons_printf ("%s\"write\":true", COMMA);
if (type & R_ANAL_ADDR_TYPE_FLAG)
r_cons_printf ("%s\"flag\":true", COMMA);
if (type & R_ANAL_ADDR_TYPE_FUNC)
r_cons_printf ("%s\"func\":true", COMMA);
if (type & R_ANAL_ADDR_TYPE_STACK)
r_cons_printf ("%s\"stack\":true", COMMA);
if (type & R_ANAL_ADDR_TYPE_HEAP)
r_cons_printf ("%s\"heap\":true", COMMA);
if (type & R_ANAL_ADDR_TYPE_REG)
r_cons_printf ("%s\"reg\":true", COMMA);
if (type & R_ANAL_ADDR_TYPE_ASCII)
r_cons_printf ("%s\"ascii\":true", COMMA);
if (type & R_ANAL_ADDR_TYPE_SEQUENCE)
r_cons_printf ("%s\"sequence\":true", COMMA);
r_cons_print ("}");
break;
default:
if (type & R_ANAL_ADDR_TYPE_PROGRAM)
r_cons_printf ("program\n");
if (type & R_ANAL_ADDR_TYPE_LIBRARY)
r_cons_printf ("library\n");
if (type & R_ANAL_ADDR_TYPE_EXEC)
r_cons_printf ("exec\n");
if (type & R_ANAL_ADDR_TYPE_READ)
r_cons_printf ("read\n");
if (type & R_ANAL_ADDR_TYPE_WRITE)
r_cons_printf ("write\n");
if (type & R_ANAL_ADDR_TYPE_FLAG)
r_cons_printf ("flag\n");
if (type & R_ANAL_ADDR_TYPE_FUNC)
r_cons_printf ("func\n");
if (type & R_ANAL_ADDR_TYPE_STACK)
r_cons_printf ("stack\n");
if (type & R_ANAL_ADDR_TYPE_HEAP)
r_cons_printf ("heap\n");
if (type & R_ANAL_ADDR_TYPE_REG)
r_cons_printf ("reg\n");
if (type & R_ANAL_ADDR_TYPE_ASCII)
r_cons_printf ("ascii\n");
if (type & R_ANAL_ADDR_TYPE_SEQUENCE)
r_cons_printf ("sequence\n");
}
}
static void cmd_anal_info(RCore *core, const char *input) {
switch (input[0]) {
case '?':
eprintf ("Usage: ai @ rsp\n");
break;
case ' ':
cmd_address_info (core, input, 0);
break;
case 'j': // "aij"
cmd_address_info (core, input + 1, 'j');
break;
default:
cmd_address_info (core, NULL, 0);
break;
}
}
static void initialize_stack (RCore *core, ut64 addr, ut64 size) {
const char *mode = r_config_get (core->config, "esil.fillstack");
if (mode && *mode && *mode != '0') {
const ut64 bs = 4096 * 32;
ut64 i;
for (i = 0; i < size; i += bs) {
ut64 left = R_MIN (bs, size - i);
// r_core_cmdf (core, "wx 10203040 @ 0x%llx", addr);
switch (*mode) {
case 'd': // "debrujn"
r_core_cmdf (core, "wopD %"PFMT64u" @ 0x%"PFMT64x, left, addr + i);
break;
case 's': // "seq"
r_core_cmdf (core, "woe 1 0xff 1 4 @ 0x%"PFMT64x"!0x%"PFMT64x, addr + i, left);
break;
case 'r': // "random"
r_core_cmdf (core, "woR %"PFMT64u" @ 0x%"PFMT64x"!0x%"PFMT64x, left, addr + i, left);
break;
case 'z': // "zero"
case '0':
r_core_cmdf (core, "wow 00 @ 0x%"PFMT64x"!0x%"PFMT64x, addr + i, left);
break;
}
}
// eprintf ("[*] Initializing ESIL stack with pattern\n");
// r_core_cmdf (core, "woe 0 10 4 @ 0x%"PFMT64x, size, addr);
}
}
static void cmd_esil_mem(RCore *core, const char *input) {
RAnalEsil *esil = core->anal->esil;
RIOMap *stack_map;
ut64 curoff = core->offset;
const char *patt = "";
ut64 addr = 0x100000;
ut32 size = 0xf0000;
char name[128];
RFlagItem *fi;
const char *sp, *pc;
char uri[32];
char nomalloc[256];
char *p;
if (!esil) {
int stacksize = r_config_get_i (core->config, "esil.stack.depth");
int iotrap = r_config_get_i (core->config, "esil.iotrap");
int romem = r_config_get_i (core->config, "esil.romem");
int stats = r_config_get_i (core->config, "esil.stats");
int noNULL = r_config_get_i (core->config, "esil.noNULL");
int verbose = r_config_get_i (core->config, "esil.verbose");
unsigned int addrsize = r_config_get_i (core->config, "esil.addr.size");
if (!(esil = r_anal_esil_new (stacksize, iotrap, addrsize))) {
return;
}
r_anal_esil_setup (esil, core->anal, romem, stats, noNULL); // setup io
core->anal->esil = esil;
esil->verbose = verbose;
{
const char *s = r_config_get (core->config, "cmd.esil.intr");
if (s) {
char *my = strdup (s);
if (my) {
r_config_set (core->config, "cmd.esil.intr", my);
free (my);
}
}
}
}
if (*input == '?') {
eprintf ("Usage: aeim [addr] [size] [name] - initialize ESIL VM stack\n");
eprintf ("Default: 0x100000 0xf0000\n");
eprintf ("See ae? for more help\n");
return;
}
if (input[0] == 'p') {
fi = r_flag_get (core->flags, "aeim.stack");
if (fi) {
addr = fi->offset;
size = fi->size;
} else {
cmd_esil_mem (core, "");
}
if (esil) {
esil->stack_addr = addr;
esil->stack_size = size;
}
initialize_stack (core, addr, size);
return;
}
if (!*input) {
char *fi = sdb_get(core->sdb, "aeim.fd", 0);
if (fi) {
// Close the fd associated with the aeim stack
ut64 fd = sdb_atoi (fi);
(void)r_io_fd_close (core->io, fd);
}
}
addr = r_config_get_i (core->config, "esil.stack.addr");
size = r_config_get_i (core->config, "esil.stack.size");
patt = r_config_get (core->config, "esil.stack.pattern");
p = strncpy (nomalloc, input, 255);
if ((p = strchr (p, ' '))) {
while (*p == ' ') p++;
addr = r_num_math (core->num, p);
if ((p = strchr (p, ' '))) {
while (*p == ' ') p++;
size = (ut32)r_num_math (core->num, p);
if (size < 1) {
size = 0xf0000;
}
if ((p = strchr (p, ' '))) {
while (*p == ' ') p++;
snprintf (name, sizeof (name), "mem.%s", p);
} else {
snprintf (name, sizeof (name), "mem.0x%" PFMT64x "_0x%x", addr, size);
}
} else {
snprintf (name, sizeof (name), "mem.0x%" PFMT64x "_0x%x", addr, size);
}
} else {
snprintf (name, sizeof (name), "mem.0x%" PFMT64x "_0x%x", addr, size);
}
if (*input == '-') {
if (esil->stack_fd > 2) { //0, 1, 2 are reserved for stdio/stderr
r_io_fd_close (core->io, esil->stack_fd);
// no need to kill the maps, r_io_map_cleanup does that for us in the close
esil->stack_fd = 0;
} else {
eprintf ("Cannot deinitialize %s\n", name);
}
r_flag_unset_name (core->flags, name);
r_flag_unset_name (core->flags, "aeim.stack");
sdb_unset(core->sdb, "aeim.fd", 0);
// eprintf ("Deinitialized %s\n", name);
return;
}
snprintf (uri, sizeof (uri), "malloc://%d", (int)size);
esil->stack_fd = r_io_fd_open (core->io, uri, R_PERM_RW, 0);
if (!(stack_map = r_io_map_add (core->io, esil->stack_fd, R_PERM_RW, 0LL, addr, size))) {
r_io_fd_close (core->io, esil->stack_fd);
eprintf ("Cannot create map for tha stack, fd %d got closed again\n", esil->stack_fd);
esil->stack_fd = 0;
return;
}
r_io_map_set_name (stack_map, name);
// r_flag_set (core->flags, name, addr, size); //why is this here?
char val[128], *v;
v = sdb_itoa (esil->stack_fd, val, 10);
sdb_set(core->sdb, "aeim.fd", v, 0);
r_config_set_i (core->config, "io.va", true);
if (patt && *patt) {
switch (*patt) {
case '0':
// do nothing
break;
case 'd':
r_core_cmdf (core, "wopD %d @ 0x%"PFMT64x, size, addr);
break;
case 'i':
r_core_cmdf (core, "woe 0 255 1 @ 0x%"PFMT64x"!%d",addr, size);
break;
case 'w':
r_core_cmdf (core, "woe 0 0xffff 1 4 @ 0x%"PFMT64x"!%d",addr, size);
break;
}
}
// SP
sp = r_reg_get_name (core->dbg->reg, R_REG_NAME_SP);
r_debug_reg_set (core->dbg, sp, addr + (size / 2));
// BP
sp = r_reg_get_name (core->dbg->reg, R_REG_NAME_BP);
r_debug_reg_set (core->dbg, sp, addr + (size / 2));
// PC
pc = r_reg_get_name (core->dbg->reg, R_REG_NAME_PC);
r_debug_reg_set (core->dbg, pc, curoff);
r_core_cmd0 (core, ".ar*");
if (esil) {
esil->stack_addr = addr;
esil->stack_size = size;
}
initialize_stack (core, addr, size);
r_core_seek (core, curoff, 0);
}
#if 0
static ut64 opc = UT64_MAX;
static ut8 *regstate = NULL;
static void esil_init (RCore *core) {
const char *pc = r_reg_get_name (core->anal->reg, R_REG_NAME_PC);
int noNULL = r_config_get_i (core->config, "esil.noNULL");
opc = r_reg_getv (core->anal->reg, pc);
if (!opc || opc==UT64_MAX) {
opc = core->offset;
}
if (!core->anal->esil) {
int iotrap = r_config_get_i (core->config, "esil.iotrap");
ut64 stackSize = r_config_get_i (core->config, "esil.stack.size");
unsigned int addrsize = r_config_get_i (core->config, "esil.addr.size");
if (!(core->anal->esil = r_anal_esil_new (stackSize, iotrap, addrsize))) {
R_FREE (regstate);
return;
}
r_anal_esil_setup (core->anal->esil, core->anal, 0, 0, noNULL);
}
free (regstate);
regstate = r_reg_arena_peek (core->anal->reg);
}
static void esil_fini(RCore *core) {
const char *pc = r_reg_get_name (core->anal->reg, R_REG_NAME_PC);
r_reg_arena_poke (core->anal->reg, regstate);
r_reg_setv (core->anal->reg, pc, opc);
R_FREE (regstate);
}
#endif
typedef struct {
RList *regs;
RList *regread;
RList *regwrite;
RList *inputregs;
} AeaStats;
static void aea_stats_init (AeaStats *stats) {
stats->regs = r_list_newf (free);
stats->regread = r_list_newf (free);
stats->regwrite = r_list_newf (free);
stats->inputregs = r_list_newf (free);
}
static void aea_stats_fini (AeaStats *stats) {
R_FREE (stats->regs);
R_FREE (stats->regread);
R_FREE (stats->regwrite);
R_FREE (stats->inputregs);
}
static bool contains(RList *list, const char *name) {
RListIter *iter;
const char *n;
r_list_foreach (list, iter, n) {
if (!strcmp (name, n))
return true;
}
return false;
}
static char *oldregread = NULL;
static RList *mymemxsr = NULL;
static RList *mymemxsw = NULL;
#define R_NEW_DUP(x) memcpy((void*)malloc(sizeof(x)), &(x), sizeof(x))
typedef struct {
ut64 addr;
int size;
} AeaMemItem;
static int mymemwrite(RAnalEsil *esil, ut64 addr, const ut8 *buf, int len) {
RListIter *iter;
AeaMemItem *n;
r_list_foreach (mymemxsw, iter, n) {
if (addr == n->addr) {
return len;
}
}
if (!r_io_is_valid_offset (esil->anal->iob.io, addr, 0)) {
return false;
}
n = R_NEW (AeaMemItem);
if (n) {
n->addr = addr;
n->size = len;
r_list_push (mymemxsw, n);
}
return len;
}
static int mymemread(RAnalEsil *esil, ut64 addr, ut8 *buf, int len) {
RListIter *iter;
AeaMemItem *n;
r_list_foreach (mymemxsr, iter, n) {
if (addr == n->addr) {
return len;
}
}
if (!r_io_is_valid_offset (esil->anal->iob.io, addr, 0)) {
return false;
}
n = R_NEW (AeaMemItem);
if (n) {
n->addr = addr;
n->size = len;
r_list_push (mymemxsr, n);
}
return len;
}
static int myregwrite(RAnalEsil *esil, const char *name, ut64 *val) {
AeaStats *stats = esil->user;
if (oldregread && !strcmp (name, oldregread)) {
r_list_pop (stats->regread);
R_FREE (oldregread)
}
if (!IS_DIGIT (*name)) {
if (!contains (stats->regs, name)) {
r_list_push (stats->regs, strdup (name));
}
if (!contains (stats->regwrite, name)) {
r_list_push (stats->regwrite, strdup (name));
}
}
return 0;
}
static int myregread(RAnalEsil *esil, const char *name, ut64 *val, int *len) {
AeaStats *stats = esil->user;
if (!IS_DIGIT (*name)) {
if (!contains (stats->inputregs, name)) {
if (!contains (stats->regwrite, name)) {
r_list_push (stats->inputregs, strdup (name));
}
}
if (!contains (stats->regs, name)) {
r_list_push (stats->regs, strdup (name));
}
if (!contains (stats->regread, name)) {
r_list_push (stats->regread, strdup (name));
}
}
return 0;
}
static void showregs (RList *list) {
if (!r_list_empty (list)) {
char *reg;
RListIter *iter;
r_list_foreach (list, iter, reg) {
r_cons_print (reg);
if (iter->n) {
r_cons_printf (" ");
}
}
}
r_cons_newline();
}
static void showregs_json (RList *list) {
r_cons_printf ("[");
if (!r_list_empty (list)) {
char *reg;
RListIter *iter;
r_list_foreach (list, iter, reg) {
r_cons_printf ("\"%s\"", reg);
if (iter->n) {
r_cons_printf (",");
}
}
}
r_cons_printf ("]");
}
static bool cmd_aea(RCore* core, int mode, ut64 addr, int length) {
RAnalEsil *esil;
int ptr, ops, ops_end = 0, len, buf_sz, maxopsize;
ut64 addr_end;
AeaStats stats;
const char *esilstr;
RAnalOp aop = R_EMPTY;
ut8 *buf;
RList* regnow;
if (!core) {
return false;
}
maxopsize = r_anal_archinfo (core->anal, R_ANAL_ARCHINFO_MAX_OP_SIZE);
if (maxopsize < 1) {
maxopsize = 16;
}
if (mode & 1) {
// number of bytes / length
buf_sz = length;
} else {
// number of instructions / opcodes
ops_end = length;
if (ops_end < 1) {
ops_end = 1;
}
buf_sz = ops_end * maxopsize;
}
if (buf_sz < 1) {
buf_sz = maxopsize;
}
addr_end = addr + buf_sz;
buf = malloc (buf_sz);
if (!buf) {
return false;
}
(void)r_io_read_at (core->io, addr, (ut8 *)buf, buf_sz);
aea_stats_init (&stats);
//esil_init (core);
//esil = core->anal->esil;
r_reg_arena_push (core->anal->reg);
int stacksize = r_config_get_i (core->config, "esil.stack.depth");
bool iotrap = r_config_get_i (core->config, "esil.iotrap");
int romem = r_config_get_i (core->config, "esil.romem");
int stats1 = r_config_get_i (core->config, "esil.stats");
int noNULL = r_config_get_i (core->config, "esil.noNULL");
unsigned int addrsize = r_config_get_i (core->config, "esil.addr.size");
esil = r_anal_esil_new (stacksize, iotrap, addrsize);
r_anal_esil_setup (esil, core->anal, romem, stats1, noNULL); // setup io
# define hasNext(x) (x&1) ? (addr<addr_end) : (ops<ops_end)
mymemxsr = r_list_new ();
mymemxsw = r_list_new ();
esil->user = &stats;
esil->cb.hook_reg_write = myregwrite;
esil->cb.hook_reg_read = myregread;
esil->cb.hook_mem_write = mymemwrite;
esil->cb.hook_mem_read = mymemread;
esil->nowrite = true;
for (ops = ptr = 0; ptr < buf_sz && hasNext (mode); ops++, ptr += len) {
len = r_anal_op (core->anal, &aop, addr + ptr, buf + ptr, buf_sz - ptr, R_ANAL_OP_MASK_ESIL);
esilstr = R_STRBUF_SAFEGET (&aop.esil);
if (len < 1) {
eprintf ("Invalid 0x%08"PFMT64x" instruction %02x %02x\n",
addr + ptr, buf[ptr], buf[ptr + 1]);
break;
}
if (r_config_get_i (core->config, "cfg.r2wars")) {
if (aop.prefix & R_ANAL_OP_PREFIX_REP) {
char * tmp = strstr (esilstr, ",ecx,?{,5,GOTO,}");
if (tmp) {
tmp[0] = 0;
}
}
}
r_anal_esil_parse (esil, esilstr);
r_anal_esil_stack_free (esil);
r_anal_op_fini (&aop);
}
esil->nowrite = false;
esil->cb.hook_reg_write = NULL;
esil->cb.hook_reg_read = NULL;
//esil_fini (core);
r_anal_esil_free (esil);
r_reg_arena_pop (core->anal->reg);
regnow = r_list_newf (free);
{
RListIter *iter;
char *reg;
r_list_foreach (stats.regs, iter, reg) {
if (!contains (stats.regwrite, reg)) {
r_list_push (regnow, strdup (reg));
}
}
}
if ((mode >> 5) & 1) {
RListIter *iter;
AeaMemItem *n;
int c = 0;
r_cons_printf ("f-mem.*\n");
r_list_foreach (mymemxsr, iter, n) {
r_cons_printf ("f mem.read.%d 0x%08x @ 0x%08"PFMT64x"\n", c++, n->size, n->addr);
}
c = 0;
r_list_foreach (mymemxsw, iter, n) {
r_cons_printf ("f mem.write.%d 0x%08x @ 0x%08"PFMT64x"\n", c++, n->size, n->addr);
}
}
/* show registers used */
if ((mode >> 1) & 1) {
showregs (stats.regread);
} else if ((mode >> 2) & 1) {
showregs (stats.regwrite);
} else if ((mode >> 3) & 1) {
showregs (regnow);
} else if ((mode >> 4) & 1) {
r_cons_printf ("{\"A\":");
showregs_json (stats.regs);
r_cons_printf (",\"I\":");
showregs_json (stats.inputregs);
r_cons_printf (",\"R\":");
showregs_json (stats.regread);
r_cons_printf (",\"W\":");
showregs_json (stats.regwrite);
r_cons_printf (",\"N\":");
showregs_json (regnow);
r_cons_printf ("}");
r_cons_newline();
} else if ((mode >> 5) & 1) {
// nothing
} else {
r_cons_printf (" I: ");
showregs (stats.inputregs);
r_cons_printf (" A: ");
showregs (stats.regs);
r_cons_printf (" R: ");
showregs (stats.regread);
r_cons_printf (" W: ");
showregs (stats.regwrite);
r_cons_printf ("NW: ");
if (r_list_length (regnow)) {
showregs (regnow);
} else {
r_cons_newline();
}
RListIter *iter;
ut64 *n;
if (!r_list_empty (mymemxsr)) {
r_cons_printf ("@R:");
r_list_foreach (mymemxsr, iter, n) {
r_cons_printf (" 0x%08"PFMT64x, *n);
}
r_cons_newline ();
}
if (!r_list_empty (mymemxsw)) {
r_cons_printf ("@W:");
r_list_foreach (mymemxsw, iter, n) {
r_cons_printf (" 0x%08"PFMT64x, *n);
}
r_cons_newline ();
}
}
r_list_free (mymemxsr);
r_list_free (mymemxsw);
mymemxsr = NULL;
mymemxsw = NULL;
aea_stats_fini (&stats);
free (buf);
R_FREE (regnow);
return true;
}
static void cmd_aespc(RCore *core, ut64 addr, int off) {
RAnalEsil *esil = core->anal->esil;
int i, j = 0;
int instr_size = 0;
ut8 *buf;
RAnalOp aop = {0};
int ret , bsize = R_MAX (64, core->blocksize);
const int mininstrsz = r_anal_archinfo (core->anal, R_ANAL_ARCHINFO_MIN_OP_SIZE);
const int minopcode = R_MAX (1, mininstrsz);
const char *pc = r_reg_get_name (core->dbg->reg, R_REG_NAME_PC);
RRegItem *r = r_reg_get (core->dbg->reg, pc, -1);
int stacksize = r_config_get_i (core->config, "esil.stack.depth");
int iotrap = r_config_get_i (core->config, "esil.iotrap");
unsigned int addrsize = r_config_get_i (core->config, "esil.addr.size");
if (!esil) {
if (!(esil = r_anal_esil_new (stacksize, iotrap, addrsize))) {
return;
}
}
buf = malloc (bsize);
if (!buf) {
eprintf ("Cannot allocate %d byte(s)\n", bsize);
free (buf);
return;
}
if (addr == -1) {
addr = r_debug_reg_get (core->dbg, pc);
}
ut64 curpc = addr;
ut64 oldoff = core->offset;
for (i = 0, j = 0; j < off ; i++, j++) {
if (r_cons_is_breaked ()) {
break;
}
if (i >= (bsize - 32)) {
i = 0;
}
if (!i) {
r_io_read_at (core->io, addr, buf, bsize);
}
ret = r_anal_op (core->anal, &aop, addr, buf + i, bsize - i, R_ANAL_OP_MASK_BASIC);
instr_size += ret;
int inc = (core->search->align > 0)? core->search->align - 1: ret - 1;
if (inc < 0) {
inc = minopcode;
}
i += inc;
addr += inc;
r_anal_op_fini (&aop);
}
r_reg_set_value (core->dbg->reg, r, curpc);
r_core_esil_step (core, curpc + instr_size, NULL, NULL);
r_core_seek (core, oldoff, 1);
}
static const char _handler_no_name[] = "<no name>";
static int _aeli_iter(dictkv* kv, void* ud) {
RAnalEsilInterrupt* interrupt = kv->u;
r_cons_printf ("%3x: %s\n", kv->k, interrupt->handler->name ? interrupt->handler->name : _handler_no_name);
return 0;
}
static void r_anal_aefa (RCore *core, const char *arg) {
ut64 to = r_num_math (core->num, arg);
ut64 at, from = core->offset;
RAnalFunction *fcn = r_anal_get_fcn_in (core->anal, to, -1);
if (!from || from == UT64_MAX) {
if (fcn) {
from = fcn->addr;
} else {
eprintf ("Usage: aefa [from] # if no from address is given, uses fcn.addr\n");
return;
}
}
eprintf ("Emulate from 0x%08"PFMT64x" to 0x%08"PFMT64x"\n", from, to);
eprintf ("Resolve call args for 0x%08"PFMT64x"\n", to);
// emulate
// XXX do not use commands, here, just use the api
r_core_cmd0 (core, "aeim"); // XXX
ut64 off = core->offset;
for (at = from; at < to ; at++) {
r_core_cmdf (core, "aepc 0x%08"PFMT64x, at);
r_core_cmd0 (core, "aeso");
r_core_seek (core, at, 1);
int delta = r_num_get (core->num, "$l");
if (delta < 1) {
break;
}
at += delta - 1;
}
r_core_seek (core, off, 1);
// the logic of identifying args by function types and
// show json format and arg name goes into arA
r_core_cmd0 (core, "arA");
#if 0
// get results
const char *fcn_type = r_type_func_ret (core->anal->sdb_types, fcn->name);
const char *key = resolve_fcn_name (core->anal, fcn->name);
RList *list = r_core_get_func_args (core, key);
if (!r_list_empty (list)) {
eprintf ("HAS signature\n");
}
int i, nargs = 3; // r_type_func_args_count (core->anal->sdb_types, fcn->name);
if (nargs > 0) {
int i;
eprintf ("NARGS %d (%s)\n", nargs, key);
for (i = 0; i < nargs; i++) {
ut64 v = r_debug_arg_get (core->dbg, R_ANAL_CC_TYPE_STDCALL, i);
eprintf ("arg: 0x%08"PFMT64x"\n", v);
}
}
#endif
}
static void cmd_anal_esil(RCore *core, const char *input) {
RAnalEsil *esil = core->anal->esil;
ut64 addr = core->offset;
ut64 adr ;
char *n, *n1;
int off;
int stacksize = r_config_get_i (core->config, "esil.stack.depth");
int iotrap = r_config_get_i (core->config, "esil.iotrap");
int romem = r_config_get_i (core->config, "esil.romem");
int stats = r_config_get_i (core->config, "esil.stats");
int noNULL = r_config_get_i (core->config, "esil.noNULL");
ut64 until_addr = UT64_MAX;
unsigned int addrsize = r_config_get_i (core->config, "esil.addr.size");
const char *until_expr = NULL;
RAnalOp *op = NULL;
switch (input[0]) {
case 'p': // "aep"
switch (input[1]) {
case 'c':
if (input[2] == ' ') {
// seek to this address
r_core_cmdf (core, "ar PC=%s", input + 3);
r_core_cmd0 (core, ".ar*");
} else {
eprintf ("Missing argument\n");
}
break;
case 0:
r_anal_pin_list (core->anal);
break;
case '-':
if (input[2])
addr = r_num_math (core->num, input + 2);
r_anal_pin_unset (core->anal, addr);
break;
case ' ':
r_anal_pin (core->anal, addr, input + 2);
break;
default:
r_core_cmd_help (core, help_msg_aep);
break;
}
break;
case 'r': // "aer"
// 'aer' is an alias for 'ar'
cmd_anal_reg (core, input + 1);
break;
case '*':
// XXX: this is wip, not working atm
if (core->anal->esil) {
r_cons_printf ("trap: %d\n", core->anal->esil->trap);
r_cons_printf ("trap-code: %d\n", core->anal->esil->trap_code);
} else {
eprintf ("esil vm not initialized. run `aei`\n");
}
break;
case ' ':
//r_anal_esil_eval (core->anal, input+1);
if (!esil) {
if (!(core->anal->esil = esil = r_anal_esil_new (stacksize, iotrap, addrsize)))
return;
}
r_anal_esil_setup (esil, core->anal, romem, stats, noNULL); // setup io
r_anal_esil_set_pc (esil, core->offset);
r_anal_esil_parse (esil, input + 1);
r_anal_esil_dumpstack (esil);
r_anal_esil_stack_free (esil);
break;
case 's': // "aes"
// "aes" "aeso" "aesu" "aesue"
// aes -> single step
// aesb -> single step back
// aeso -> single step over
// aesu -> until address
// aesue -> until esil expression
switch (input[1]) {
case '?':
eprintf ("See: ae?~aes\n");
break;
case 'l': // "aesl"
{
ut64 pc = r_debug_reg_get (core->dbg, "PC");
RAnalOp *op = r_core_anal_op (core, pc, R_ANAL_OP_MASK_BASIC);
// TODO: honor hint
if (!op) {
break;
}
r_core_esil_step (core, UT64_MAX, NULL, NULL);
r_debug_reg_set (core->dbg, "PC", pc + op->size);
r_anal_esil_set_pc (esil, pc + op->size);
r_core_cmd0 (core, ".ar*");
r_anal_op_free (op);
} break;
case 'b': // "aesb"
if (!r_core_esil_step_back (core)) {
eprintf ("cannnot step back\n");
}
r_core_cmd0 (core, ".ar*");
break;
case 'u': // "aesu"
if (input[2] == 'e') {
until_expr = input + 3;
} else {
until_addr = r_num_math (core->num, input + 2);
}
r_core_esil_step (core, until_addr, until_expr, NULL);
r_core_cmd0 (core, ".ar*");
break;
case 'o': // "aeso"
// step over
op = r_core_anal_op (core, r_reg_getv (core->anal->reg,
r_reg_get_name (core->anal->reg, R_REG_NAME_PC)), R_ANAL_OP_MASK_BASIC);
if (op && op->type == R_ANAL_OP_TYPE_CALL) {
until_addr = op->addr + op->size;
}
r_core_esil_step (core, until_addr, until_expr, NULL);
r_anal_op_free (op);
r_core_cmd0 (core, ".ar*");
break;
case 'p': //"aesp"
n = strchr (input, ' ');
n1 = n ? strchr (n + 1, ' ') : NULL;
if ((!n || !n1) || (!(n + 1) || !(n1 + 1))) {
eprintf ("aesp [offset] [num]\n");
break;
}
adr = r_num_math (core->num, n + 1);
off = r_num_math (core->num, n1 + 1);
cmd_aespc (core, adr, off);
break;
case ' ':
n = strchr (input, ' ');
if (!(n + 1)) {
r_core_esil_step (core, until_addr, until_expr, NULL);
break;
}
off = r_num_math (core->num, n + 1);
cmd_aespc (core, -1, off);
break;
default:
r_core_esil_step (core, until_addr, until_expr, NULL);
r_core_cmd0 (core, ".ar*");
break;
}
break;
case 'c': // "aec"
if (input[1] == '?') { // "aec?"
r_core_cmd_help (core, help_msg_aec);
} else if (input[1] == 's') { // "aecs"
const char *pc = r_reg_get_name (core->anal->reg, R_REG_NAME_PC);
for (;;) {
if (!r_core_esil_step (core, UT64_MAX, NULL, NULL)) {
break;
}
r_core_cmd0 (core, ".ar*");
addr = r_num_get (core->num, pc);
op = r_core_anal_op (core, addr, R_ANAL_OP_MASK_BASIC);
if (!op) {
break;
}
if (op->type == R_ANAL_OP_TYPE_SWI) {
eprintf ("syscall at 0x%08" PFMT64x "\n", addr);
break;
} else if (op->type == R_ANAL_OP_TYPE_TRAP) {
eprintf ("trap at 0x%08" PFMT64x "\n", addr);
break;
}
r_anal_op_free (op);
op = NULL;
if (core->anal->esil->trap || core->anal->esil->trap_code) {
break;
}
}
if (op) {
r_anal_op_free (op);
op = NULL;
}
} else if (input[1] == 'c') { // "aecc"
const char *pc = r_reg_get_name (core->anal->reg, R_REG_NAME_PC);
for (;;) {
if (!r_core_esil_step (core, UT64_MAX, NULL, NULL)) {
break;
}
r_core_cmd0 (core, ".ar*");
addr = r_num_get (core->num, pc);
op = r_core_anal_op (core, addr, R_ANAL_OP_MASK_BASIC);
if (!op) {
break;
}
if (op->type == R_ANAL_OP_TYPE_CALL || op->type == R_ANAL_OP_TYPE_UCALL) {
eprintf ("call at 0x%08" PFMT64x "\n", addr);
break;
}
r_anal_op_free (op);
op = NULL;
if (core->anal->esil->trap || core->anal->esil->trap_code) {
break;
}
}
if (op) {
r_anal_op_free (op);
}
} else {
// "aec" -> continue until ^C
// "aecu" -> until address
// "aecue" -> until esil expression
if (input[1] == 'u' && input[2] == 'e')
until_expr = input + 3;
else if (input[1] == 'u')
until_addr = r_num_math (core->num, input + 2);
else until_expr = "0";
r_core_esil_step (core, until_addr, until_expr, NULL);
r_core_cmd0 (core, ".ar*");
}
break;
case 'i': // "aei"
switch (input[1]) {
case 's': // "aeis"
case 'm': // "aeim"
cmd_esil_mem (core, input + 2);
break;
case 'p': // "aeip" // initialize pc = $$
r_core_cmd0 (core, "ar PC=$$");
break;
case '?':
cmd_esil_mem (core, "?");
break;
case '-':
if (esil) {
sdb_reset (esil->stats);
}
r_anal_esil_free (esil);
core->anal->esil = NULL;
break;
case 0: //lolololol
r_anal_esil_free (esil);
// reinitialize
{
const char *pc = r_reg_get_name (core->anal->reg, R_REG_NAME_PC);
if (r_reg_getv (core->anal->reg, pc) == 0LL) {
r_core_cmd0 (core, "ar PC=$$");
}
}
if (!(esil = core->anal->esil = r_anal_esil_new (stacksize, iotrap, addrsize))) {
return;
}
r_anal_esil_setup (esil, core->anal, romem, stats, noNULL); // setup io
esil->verbose = (int)r_config_get_i (core->config, "esil.verbose");
/* restore user settings for interrupt handling */
{
const char *s = r_config_get (core->config, "cmd.esil.intr");
if (s) {
char *my = strdup (s);
if (my) {
r_config_set (core->config, "cmd.esil.intr", my);
free (my);
}
}
}
break;
}
break;
case 'k': // "aek"
switch (input[1]) {
case '\0':
input = "123*";
/* fall through */
case ' ':
if (esil && esil->stats) {
char *out = sdb_querys (esil->stats, NULL, 0, input + 2);
if (out) {
r_cons_println (out);
free (out);
}
} else {
eprintf ("esil.stats is empty. Run 'aei'\n");
}
break;
case '-':
if (esil) {
sdb_reset (esil->stats);
}
break;
}
break;
case 'l': // ael commands
switch (input[1]) {
case 'i': // aeli interrupts
switch (input[2]) {
case ' ': // "aeli" with arguments
if (!r_anal_esil_load_interrupts_from_lib (esil, input + 3)) {
eprintf ("Failed to load interrupts from '%s'.", input + 3);
}
break;
case 0: // "aeli" with no args
if (esil && esil->interrupts) {
dict_foreach (esil->interrupts, _aeli_iter, NULL);
}
break;
case 'r': // "aelir"
if (esil && esil->interrupts) {
RAnalEsilInterrupt* interrupt = dict_getu (esil->interrupts, r_num_math (core->num, input + 3));
r_anal_esil_interrupt_free (esil, interrupt);
}
break;
// TODO: display help?
}
}
break;
case 'f': // "aef"
if (input[1] == 'a') { // "aefa"
r_anal_aefa (core, r_str_trim_ro (input + 2));
} else {
RListIter *iter;
RAnalBlock *bb;
RAnalFunction *fcn = r_anal_get_fcn_in (core->anal,
core->offset, R_ANAL_FCN_TYPE_FCN | R_ANAL_FCN_TYPE_SYM);
if (fcn) {
// emulate every instruction in the function recursively across all the basic blocks
r_list_foreach (fcn->bbs, iter, bb) {
ut64 pc = bb->addr;
ut64 end = bb->addr + bb->size;
RAnalOp op;
ut8 *buf;
int ret, bbs = end - pc;
if (bbs < 1 || bbs > 0xfffff) {
eprintf ("Invalid block size\n");
}
// eprintf ("[*] Emulating 0x%08"PFMT64x" basic block 0x%08" PFMT64x " - 0x%08" PFMT64x "\r[", fcn->addr, pc, end);
buf = calloc (1, bbs + 1);
r_io_read_at (core->io, pc, buf, bbs);
int left;
while (pc < end) {
left = R_MIN (end - pc, 32);
r_asm_set_pc (core->assembler, pc);
ret = r_anal_op (core->anal, &op, addr, buf, left, R_ANAL_OP_MASK_ESIL); // read overflow
if (ret) {
r_reg_set_value_by_role (core->anal->reg, R_REG_NAME_PC, pc);
r_anal_esil_parse (esil, R_STRBUF_SAFEGET (&op.esil));
r_anal_esil_dumpstack (esil);
r_anal_esil_stack_free (esil);
pc += op.size;
} else {
pc += 4; // XXX
}
}
}
} else {
eprintf ("Cannot find function at 0x%08" PFMT64x "\n", core->offset);
}
} break;
case 't': // "aet"
switch (input[1]) {
case 'r': // "aetr"
{
// anal ESIL to REIL.
RAnalEsil *esil = r_anal_esil_new (stacksize, iotrap, addrsize);
if (!esil) {
return;
}
r_anal_esil_to_reil_setup (esil, core->anal, romem, stats);
r_anal_esil_set_pc (esil, core->offset);
r_anal_esil_parse (esil, input + 2);
r_anal_esil_dumpstack (esil);
r_anal_esil_free (esil);
break;
}
case 's': // "aets"
switch (input[2]) {
case 0:
r_anal_esil_session_list (esil);
break;
case '+':
r_anal_esil_session_add (esil);
break;
default:
r_core_cmd_help (core, help_msg_aets);
break;
}
break;
default:
eprintf ("Unknown command. Use `aetr`.\n");
break;
}
break;
case 'A': // "aeA"
if (input[1] == '?') {
r_core_cmd_help (core, help_msg_aea);
} else if (input[1] == 'r') {
cmd_aea (core, 1 + (1<<1), core->offset, r_num_math (core->num, input+2));
} else if (input[1] == 'w') {
cmd_aea (core, 1 + (1<<2), core->offset, r_num_math (core->num, input+2));
} else if (input[1] == 'n') {
cmd_aea (core, 1 + (1<<3), core->offset, r_num_math (core->num, input+2));
} else if (input[1] == 'j') {
cmd_aea (core, 1 + (1<<4), core->offset, r_num_math (core->num, input+2));
} else if (input[1] == '*') {
cmd_aea (core, 1 + (1<<5), core->offset, r_num_math (core->num, input+2));
} else if (input[1] == 'f') {
RAnalFunction *fcn = r_anal_get_fcn_in (core->anal, core->offset, -1);
if (fcn) {
cmd_aea (core, 1, fcn->addr, r_anal_fcn_size (fcn));
}
} else {
cmd_aea (core, 1, core->offset, (int)r_num_math (core->num, input+2));
}
break;
case 'a': // "aea"
if (input[1] == '?') {
r_core_cmd_help (core, help_msg_aea);
} else if (input[1] == 'r') {
cmd_aea (core, 1<<1, core->offset, r_num_math (core->num, input+2));
} else if (input[1] == 'w') {
cmd_aea (core, 1<<2, core->offset, r_num_math (core->num, input+2));
} else if (input[1] == 'n') {
cmd_aea (core, 1<<3, core->offset, r_num_math (core->num, input+2));
} else if (input[1] == 'j') {
cmd_aea (core, 1<<4, core->offset, r_num_math (core->num, input+2));
} else if (input[1] == '*') {
cmd_aea (core, 1<<5, core->offset, r_num_math (core->num, input+2));
} else if (input[1] == 'f') {
RAnalFunction *fcn = r_anal_get_fcn_in (core->anal, core->offset, -1);
// "aeafj"
if (fcn) {
switch (input[2]) {
case 'j': // "aeafj"
cmd_aea (core, 1<<4, fcn->addr, r_anal_fcn_size (fcn));
break;
default:
cmd_aea (core, 1, fcn->addr, r_anal_fcn_size (fcn));
break;
}
break;
}
} else if (input[1] == 'b') { // "aeab"
RAnalBlock *bb = r_anal_bb_from_offset (core->anal, core->offset);
if (bb) {
switch (input[2]) {
case 'j': // "aeabj"
cmd_aea (core, 1<<4, bb->addr, bb->size);
break;
default:
cmd_aea (core, 1, bb->addr, bb->size);
break;
}
}
} else {
const char *arg = input[1]? input + 2: "";
ut64 len = r_num_math (core->num, arg);
cmd_aea (core, 0, core->offset, len);
}
break;
case 'x': { // "aex"
char *hex;
int ret, bufsz;
input = r_str_trim_ro (input + 1);
hex = strdup (input);
if (!hex) {
break;
}
RAnalOp aop = R_EMPTY;
bufsz = r_hex_str2bin (hex, (ut8*)hex);
ret = r_anal_op (core->anal, &aop, core->offset,
(const ut8*)hex, bufsz, R_ANAL_OP_MASK_ESIL);
if (ret>0) {
const char *str = R_STRBUF_SAFEGET (&aop.esil);
char *str2 = r_str_newf (" %s", str);
cmd_anal_esil (core, str2);
free (str2);
}
r_anal_op_fini (&aop);
break;
}
case '?': // "ae?"
if (input[1] == '?') {
r_core_cmd_help (core, help_detail_ae);
break;
}
/* fallthrough */
default:
r_core_cmd_help (core, help_msg_ae);
break;
}
}
static void cmd_anal_bytes(RCore *core, const char *input) {
int len = core->blocksize;
int tbs = len;
if (input[0]) {
len = (int)r_num_get (core->num, input + 1);
if (len > tbs) {
r_core_block_size (core, len);
}
}
core_anal_bytes (core, core->block, len, 0, input[0]);
if (tbs != core->blocksize) {
r_core_block_size (core, tbs);
}
}
static void cmd_anal_opcode(RCore *core, const char *input) {
int l, len = core->blocksize;
ut32 tbs = core->blocksize;
switch (input[0]) {
case 's': // "aos"
case 'j': // "aoj"
case 'e': // "aoe"
case 'r': {
int count = 1;
int obs = core->blocksize;
if (input[1] && input[2]) {
l = (int)r_num_get (core->num, input + 1);
if (l > 0) {
count = l;
}
l *= 8;
if (l > obs) {
r_core_block_size (core, l);
}
} else {
count = 1;
}
core_anal_bytes (core, core->block, core->blocksize, count, input[0]);
if (obs != core->blocksize) {
r_core_block_size (core, obs);
}
}
break;
case 'm': // "aom"
if (input[1] == '?') {
r_cons_printf ("Usage: aom[ljd] [arg] .. list mnemonics for asm.arch\n");
r_cons_printf (". = current, l = list, d = describe, j=json)\n");
} else if (input[1] == 'd') {
const int id = (input[2]==' ')
?(int)r_num_math (core->num, input + 2): -1;
char *ops = r_asm_mnemonics (core->assembler, id, false);
if (ops) {
char *ptr = ops;
char *nl = strchr (ptr, '\n');
while (nl) {
*nl = 0;
char *desc = r_asm_describe (core->assembler, ptr);
if (desc) {
const char *pad = r_str_pad (' ', 16 - strlen (ptr));
r_cons_printf ("%s%s%s\n", ptr, pad, desc);
free (desc);
} else {
r_cons_printf ("%s\n", ptr);
}
ptr = nl + 1;
nl = strchr (ptr, '\n');
}
free (ops);
}
} else if (input[1] == 'l' || input[1] == '=' || input[1] == ' ' || input[1] == 'j') {
if (input[1] == ' ' && !IS_DIGIT (input[2])) {
r_cons_printf ("%d\n", r_asm_mnemonics_byname (core->assembler, input + 2));
} else {
const int id = (input[1] == ' ')
?(int)r_num_math (core->num, input + 2): -1;
char *ops = r_asm_mnemonics (core->assembler, id, input[1] == 'j');
if (ops) {
r_cons_println (ops);
free (ops);
}
}
} else {
r_core_cmd0 (core, "ao~mnemonic[1]");
}
break;
case 'd': // "aod"
if (input[1] == 'a') { // "aoda"
// list sdb database
sdb_foreach (core->assembler->pair, listOpDescriptions, core);
} else if (input[1] == 0) {
int cur = R_MAX (core->print->cur, 0);
// XXX: we need cmd_xxx.h (cmd_anal.h)
core_anal_bytes (core, core->block + cur, core->blocksize, 1, 'd');
} else if (input[1] == ' ') {
char *d = r_asm_describe (core->assembler, input + 2);
if (d && *d) {
r_cons_println (d);
free (d);
} else {
eprintf ("Unknown mnemonic\n");
}
} else {
eprintf ("Use: aod[?a] ([opcode]) describe current, [given] or all mnemonics\n");
}
break;
case '*':
r_core_anal_hint_list (core->anal, input[0]);
break;
case 0:
case ' ': {
int count = 0;
if (input[0]) {
l = (int)r_num_get (core->num, input + 1);
if (l > 0) {
count = l;
}
if (l > tbs) {
r_core_block_size (core, l * 4);
//len = l;
}
} else {
len = l = core->blocksize;
count = 1;
}
core_anal_bytes (core, core->block, len, count, 0);
}
break;
default:
case '?':
r_core_cmd_help (core, help_msg_ao);
break;
}
}
static void cmd_anal_jumps(RCore *core, const char *input) {
r_core_cmdf (core, "af @@= `ax~ref.code.jmp[1]`");
}
// TODO: cleanup to reuse code
static void cmd_anal_aftertraps(RCore *core, const char *input) {
int bufi, minop = 1; // 4
ut8 *buf;
RBinFile *binfile;
RAnalOp op = {0};
ut64 addr, addr_end;
ut64 len = r_num_math (core->num, input);
if (len > 0xffffff) {
eprintf ("Too big\n");
return;
}
binfile = r_core_bin_cur (core);
if (!binfile) {
eprintf ("cur binfile NULL\n");
return;
}
addr = core->offset;
if (!len) {
// ignore search.in to avoid problems. analysis != search
RIOSection *sec = r_io_section_vget (core->io, addr);
if (sec && (sec->perm & R_PERM_X)) {
// search in current section
if (sec->size > binfile->size) {
addr = sec->vaddr;
if (binfile->size > sec->paddr) {
len = binfile->size - sec->paddr;
} else {
eprintf ("Opps something went wrong aac\n");
return;
}
} else {
addr = sec->vaddr;
len = sec->size;
}
} else {
if (sec && sec->vaddr != sec->paddr && binfile->size > (core->offset - sec->vaddr + sec->paddr)) {
len = binfile->size - (core->offset - sec->vaddr + sec->paddr);
} else {
if (binfile->size > core->offset) {
len = binfile->size - core->offset;
} else {
eprintf ("Oops invalid range\n");
len = 0;
}
}
}
}
addr_end = addr + len;
if (!(buf = malloc (4096))) {
return;
}
bufi = 0;
int trapcount = 0;
int nopcount = 0;
r_cons_break_push (NULL, NULL);
while (addr < addr_end) {
if (r_cons_is_breaked ()) {
break;
}
// TODO: too many ioreads here
if (bufi > 4000) {
bufi = 0;
}
if (!bufi) {
r_io_read_at (core->io, addr, buf, 4096);
}
if (r_anal_op (core->anal, &op, addr, buf + bufi, 4096 - bufi, R_ANAL_OP_MASK_BASIC)) {
if (op.size < 1) {
// XXX must be +4 on arm/mips/.. like we do in disasm.c
op.size = minop;
}
if (op.type == R_ANAL_OP_TYPE_TRAP) {
trapcount ++;
} else if (op.type == R_ANAL_OP_TYPE_NOP) {
nopcount ++;
} else {
if (nopcount > 1) {
r_cons_printf ("af @ 0x%08"PFMT64x"\n", addr);
nopcount = 0;
}
if (trapcount > 0) {
r_cons_printf ("af @ 0x%08"PFMT64x"\n", addr);
trapcount = 0;
}
}
} else {
op.size = minop;
}
addr += (op.size > 0)? op.size : 1;
bufi += (op.size > 0)? op.size : 1;
r_anal_op_fini (&op);
}
r_cons_break_pop ();
free (buf);
}
static void cmd_anal_blocks(RCore *core, const char *input) {
ut64 from , to;
char *arg = strchr (input, ' ');
r_cons_break_push (NULL, NULL);
if (!arg) {
RList *list = r_core_get_boundaries_prot (core, R_PERM_X, NULL, "anal");
RListIter *iter;
RIOMap* map;
if (!list) {
goto ctrl_c;
}
r_list_foreach (list, iter, map) {
from = map->itv.addr;
to = r_itv_end (map->itv);
if (r_cons_is_breaked ()) {
goto ctrl_c;
}
if (!from && !to) {
eprintf ("Cannot determine search boundaries\n");
} else if (to - from > UT32_MAX) {
eprintf ("Skipping huge range\n");
} else {
r_core_cmdf (core, "abb 0x%08"PFMT64x" @ 0x%08"PFMT64x, (to - from), from);
}
}
} else {
ut64 sz = r_num_math (core->num, arg + 1);
r_core_cmdf (core, "abb 0x%08"PFMT64x" @ 0x%08"PFMT64x, sz, core->offset);
}
ctrl_c:
r_cons_break_pop ();
}
static void _anal_calls(RCore *core, ut64 addr, ut64 addr_end, bool printCommands, bool importsOnly) {
RAnalOp op;
int depth = r_config_get_i (core->config, "anal.depth");
const int addrbytes = core->io->addrbytes;
const int bsz = 4096;
int bufi = 0;
int bufi_max = bsz - 16;
if (addr_end - addr > UT32_MAX) {
return;
}
ut8 *buf = malloc (bsz);
ut8 *block0 = calloc (1, bsz);
ut8 *block1 = malloc (bsz);
if (!buf || !block0 || !block1) {
eprintf ("Error: cannot allocate buf or block\n");
free (buf);
free (block0);
free (block1);
return;
}
memset (block1, -1, bsz);
int minop = r_anal_archinfo (core->anal, R_ANAL_ARCHINFO_MIN_OP_SIZE);
if (minop < 1) {
minop = 1;
}
int setBits = r_config_get_i (core->config, "asm.bits");
r_cons_break_push (NULL, NULL);
while (addr < addr_end && !r_cons_is_breaked ()) {
// TODO: too many ioreads here
if (bufi > bufi_max) {
bufi = 0;
}
if (!bufi) {
(void)r_io_read_at (core->io, addr, buf, bsz);
}
if (!memcmp (buf, block0, bsz) || !memcmp (buf, block1, bsz)) {
//eprintf ("Error: skipping uninitialized block \n");
addr += bsz;
continue;
}
RAnalHint *hint = r_anal_hint_get (core->anal, addr);
if (hint && hint->bits) {
setBits = hint->bits;
}
if (setBits != core->assembler->bits) {
r_config_set_i (core->config, "asm.bits", setBits);
}
if (r_anal_op (core->anal, &op, addr, buf + bufi, bsz - bufi, 0) > 0) {
if (op.size < 1) {
op.size = minop;
}
if (op.type == R_ANAL_OP_TYPE_CALL) {
bool isValidCall = true;
if (importsOnly) {
RFlagItem *f = r_flag_get_i (core->flags, op.jump);
if (!f || !strstr (f->name, "imp.")) {
isValidCall = false;
}
}
if (isValidCall) {
#if JAYRO_03
if (!anal_is_bad_call (core, from, to, addr, buf, bufi)) {
fcn = r_anal_get_fcn_in (core->anal, op.jump, R_ANAL_FCN_TYPE_ROOT);
if (!fcn) {
r_core_anal_fcn (core, op.jump, addr, R_ANAL_REF_TYPE_CALL, depth);
}
}
#else
if (printCommands) {
r_cons_printf ("ax 0x%08" PFMT64x " 0x%08" PFMT64x "\n", op.jump, addr);
} else {
// add xref here
r_anal_xrefs_set (core->anal, addr, op.jump, R_ANAL_REF_TYPE_CALL);
if (r_io_is_valid_offset (core->io, op.jump, 1)) {
r_core_anal_fcn (core, op.jump, addr, R_ANAL_REF_TYPE_CALL, depth);
}
}
#endif
}
}
} else {
op.size = minop;
}
if ((int)op.size < 1) {
op.size = minop;
}
addr += op.size;
bufi += addrbytes * op.size;
r_anal_op_fini (&op);
}
r_cons_break_pop ();
free (buf);
free (block0);
free (block1);
}
static void cmd_anal_calls(RCore *core, const char *input, bool printCommands, bool importsOnly) {
RList *ranges = NULL;
RIOMap *r;
RBinFile *binfile;
ut64 addr;
ut64 len = r_num_math (core->num, input);
if (len > 0xffffff) {
eprintf ("Too big\n");
return;
}
binfile = r_core_bin_cur (core);
addr = core->offset;
if (binfile) {
if (len) {
RIOMap *m = R_NEW0 (RIOMap);
m->itv.addr = addr;
m->itv.size = len;
ranges = r_list_newf ((RListFree)free);
r_list_append (ranges, m);
} else {
ranges = r_core_get_boundaries_prot (core, R_PERM_X, NULL, "anal");
}
}
r_cons_break_push (NULL, NULL);
if (!binfile || (ranges && !r_list_length (ranges))) {
RListIter *iter;
RIOMap *map;
r_list_free (ranges);
ranges = r_core_get_boundaries_prot (core, 0, NULL, "anal");
if (ranges) {
r_list_foreach (ranges, iter, map) {
ut64 addr = map->itv.addr;
_anal_calls (core, addr, r_itv_end (map->itv), printCommands, importsOnly);
}
}
} else {
RListIter *iter;
if (binfile) {
r_list_foreach (ranges, iter, r) {
addr = r->itv.addr;
//this normally will happen on fuzzed binaries, dunno if with huge
//binaries as well
if (r_cons_is_breaked ()) {
break;
}
_anal_calls (core, addr, r_itv_end (r->itv), printCommands, importsOnly);
}
}
}
r_cons_break_pop ();
r_list_free (ranges);
}
static void cmd_asf(RCore *core, const char *input) {
char *ret;
if (input[0] == ' ') {
ret = sdb_querys (core->anal->sdb_fcnsign, NULL, 0, input + 1);
} else {
ret = sdb_querys (core->anal->sdb_fcnsign, NULL, 0, "*");
}
if (ret && *ret) {
r_cons_println (ret);
}
free (ret);
}
static void cmd_anal_syscall(RCore *core, const char *input) {
RSyscallItem *si;
RListIter *iter;
RList *list;
RNum *num = NULL;
char *out;
int n;
switch (input[0]) {
case 'c': // "asc"
if (input[1] == 'a') {
if (input[2] == ' ') {
if (!isalpha ((ut8)input[3]) && (n = r_num_math (num, input + 3)) >= 0 ) {
si = r_syscall_get (core->anal->syscall, n, -1);
if (si) {
r_cons_printf (".equ SYS_%s %s\n", si->name, syscallNumber (n));
}
else eprintf ("Unknown syscall number\n");
} else {
n = r_syscall_get_num (core->anal->syscall, input + 3);
if (n != -1) {
r_cons_printf (".equ SYS_%s %s\n", input + 3, syscallNumber (n));
} else {
eprintf ("Unknown syscall name\n");
}
}
} else {
list = r_syscall_list (core->anal->syscall);
r_list_foreach (list, iter, si) {
r_cons_printf (".equ SYS_%s %s\n",
si->name, syscallNumber (si->num));
}
r_list_free (list);
}
} else {
if (input[1] == ' ') {
if (!isalpha ((ut8)input[2]) && (n = r_num_math (num, input + 2)) >= 0 ) {
si = r_syscall_get (core->anal->syscall, n, -1);
if (si) {
r_cons_printf ("#define SYS_%s %s\n", si->name, syscallNumber (n));
}
else eprintf ("Unknown syscall number\n");
} else {
n = r_syscall_get_num (core->anal->syscall, input + 2);
if (n != -1) {
r_cons_printf ("#define SYS_%s %s\n", input + 2, syscallNumber (n));
} else {
eprintf ("Unknown syscall name\n");
}
}
} else {
list = r_syscall_list (core->anal->syscall);
r_list_foreach (list, iter, si) {
r_cons_printf ("#define SYS_%s %d\n",
si->name, syscallNumber (si->num));
}
r_list_free (list);
}
}
break;
case 'f': // "asf"
cmd_asf (core, input + 1);
break;
case 'l': // "asl"
if (input[1] == ' ') {
if (!isalpha ((ut8)input[2]) && (n = r_num_math (num, input + 2)) >= 0 ) {
si = r_syscall_get (core->anal->syscall, n, -1);
if (si)
r_cons_println (si->name);
else eprintf ("Unknown syscall number\n");
} else {
n = r_syscall_get_num (core->anal->syscall, input + 2);
if (n != -1) {
r_cons_printf ("%s\n", syscallNumber (n));
} else {
eprintf ("Unknown syscall name\n");
}
}
} else {
list = r_syscall_list (core->anal->syscall);
r_list_foreach (list, iter, si) {
r_cons_printf ("%s = 0x%02x.%s\n",
si->name, si->swi, syscallNumber (si->num));
}
r_list_free (list);
}
break;
case 'j': // "asj"
list = r_syscall_list (core->anal->syscall);
r_cons_printf ("[");
r_list_foreach (list, iter, si) {
r_cons_printf ("{\"name\":\"%s\","
"\"swi\":\"%d\",\"num\":\"%d\"}",
si->name, si->swi, si->num);
if (iter->n) {
r_cons_printf (",");
}
}
r_cons_printf ("]\n");
r_list_free (list);
// JSON support
break;
case '\0':
cmd_syscall_do (core, -1, core->offset);
break;
case ' ':
cmd_syscall_do (core, (int)r_num_get (core->num, input + 1), -1);
break;
case 'k': // "ask"
if (input[1] == ' ') {
out = sdb_querys (core->anal->syscall->db, NULL, 0, input + 2);
if (out) {
r_cons_println (out);
free (out);
}
} else eprintf ("|ERROR| Usage: ask [query]\n");
break;
default:
case '?':
r_core_cmd_help (core, help_msg_as);
break;
}
}
static void anal_axg (RCore *core, const char *input, int level, Sdb *db, int opts) {
char arg[32], pre[128];
RListIter *iter;
RAnalRef *ref;
ut64 addr = core->offset;
bool is_json = opts & R_CORE_ANAL_JSON;
bool is_r2 = opts & R_CORE_ANAL_GRAPHBODY;
if (input && *input) {
addr = r_num_math (core->num, input);
}
// eprintf ("Path between 0x%08"PFMT64x" .. 0x%08"PFMT64x"\n", core->offset, addr);
int spaces = (level + 1) * 2;
if (spaces > sizeof (pre) - 4) {
spaces = sizeof (pre) - 4;
}
memset (pre, ' ', sizeof (pre));
strcpy (pre + spaces, "- ");
RList *xrefs = r_anal_xrefs_get (core->anal, addr);
if (!r_list_empty (xrefs)) {
RAnalFunction *fcn = r_anal_get_fcn_in (core->anal, addr, -1);
if (fcn) {
if (is_r2) {
r_cons_printf ("agn 0x%08"PFMT64x" %s\n", fcn->addr, fcn->name);
} else if (is_json) {
r_cons_printf ("{\"%"PFMT64u"\":{\"type\":\"fcn\","
"\"fcn_addr\":%"PFMT64u",\"name\":\"%s\",\"refs\":[",
addr, fcn->addr, fcn->name);
} else {
//if (sdb_add (db, fcn->name, "1", 0)) {
r_cons_printf ("%s0x%08"PFMT64x" fcn 0x%08"PFMT64x" %s\n",
pre + 2, addr, fcn->addr, fcn->name);
//}
}
} else {
if (is_r2) {
r_cons_printf ("age 0x%08"PFMT64x"\n", fcn->addr);
} else if (is_json) {
r_cons_printf ("{\"%"PFMT64u"\":{\"refs\":[", addr);
} else {
//snprintf (arg, sizeof (arg), "0x%08"PFMT64x, addr);
//if (sdb_add (db, arg, "1", 0)) {
r_cons_printf ("%s0x%08"PFMT64x"\n", pre+2, addr);
//}
}
}
}
r_list_foreach (xrefs, iter, ref) {
RAnalFunction *fcn = r_anal_get_fcn_in (core->anal, ref->addr, -1);
if (fcn) {
if (is_r2) {
r_cons_printf ("agn 0x%08"PFMT64x" %s\n", fcn->addr, fcn->name);
r_cons_printf ("age 0x%08"PFMT64x" 0x%08"PFMT64x"\n", fcn->addr, addr);
} else if (is_json) {
if (level == 0) {
r_cons_printf ("{\"%"PFMT64u"\":{\"type\":\"fcn\",\"fcn_addr\": %"PFMT64u",\"name\":\"%s\",\"refs\":[", ref->addr, fcn->addr, fcn->name);
} else {
r_cons_printf ("]}},{\"%"PFMT64u"\":{\"type\":\"fcn\",\"fcn_addr\": %"PFMT64u",\"name\":\"%s\",\"refs\":[", ref->addr, fcn->addr, fcn->name);
}
} else {
r_cons_printf ("%s0x%08"PFMT64x" fcn 0x%08"PFMT64x" %s\n", pre, ref->addr, fcn->addr, fcn->name);
}
if (sdb_add (db, fcn->name, "1", 0)) {
snprintf (arg, sizeof (arg), "0x%08"PFMT64x, fcn->addr);
anal_axg (core, arg, level + 1, db, opts);
} else {
if (is_json) {
r_cons_printf ("]}}");
}
}
if (is_json) {
if (iter->n) {
r_cons_printf (",");
}
}
} else {
if (is_r2) {
r_cons_printf ("agn 0x%08"PFMT64x" ???\n", ref->addr);
r_cons_printf ("age 0x%08"PFMT64x" 0x%08"PFMT64x"\n", ref->addr, addr);
} else if (is_json) {
r_cons_printf ("{\"%"PFMT64u"\":{\"type\":\"???\",\"refs\":[", ref->addr);
} else {
r_cons_printf ("%s0x%08"PFMT64x" ???\n", pre, ref->addr);
}
snprintf (arg, sizeof (arg), "0x%08"PFMT64x, ref->addr);
if (sdb_add (db, arg, "1", 0)) {
anal_axg (core, arg, level + 1, db, opts);
} else {
if (is_json) {
r_cons_printf ("]}}");
}
}
if (is_json) {
if (iter->n) {
r_cons_printf (",");
}
}
}
}
if (is_json) {
r_cons_printf ("]}}");
if (level == 0) {
r_cons_printf ("\n");
}
}
r_list_free (xrefs);
}
static void cmd_anal_ucall_ref (RCore *core, ut64 addr) {
RAnalFunction * fcn = r_anal_get_fcn_at (core->anal, addr, R_ANAL_FCN_TYPE_NULL);
if (fcn) {
r_cons_printf (" ; %s", fcn->name);
} else {
r_cons_printf (" ; 0x%" PFMT64x, addr);
}
}
static char *get_buf_asm(RCore *core, ut64 from, ut64 addr, RAnalFunction *fcn, bool color) {
int has_color = core->print->flags & R_PRINT_FLAGS_COLOR;
char str[512];
const int size = 12;
ut8 buf[12];
RAsmOp asmop = {0};
char *buf_asm = NULL;
bool asm_varsub = r_config_get_i (core->config, "asm.var.sub");
core->parser->pseudo = r_config_get_i (core->config, "asm.pseudo");
core->parser->relsub = r_config_get_i (core->config, "asm.relsub");
core->parser->localvar_only = r_config_get_i (core->config, "asm.var.subonly");
if (core->parser->relsub) {
core->parser->relsub_addr = from;
}
r_io_read_at (core->io, addr, buf, size);
r_asm_set_pc (core->assembler, addr);
r_asm_disassemble (core->assembler, &asmop, buf, size);
int ba_len = r_strbuf_length (&asmop.buf_asm) + 128;
char *ba = malloc (ba_len);
strcpy (ba, r_strbuf_get (&asmop.buf_asm));
if (asm_varsub) {
r_parse_varsub (core->parser, fcn, addr, asmop.size,
ba, ba, sizeof (asmop.buf_asm));
}
r_parse_filter (core->parser, addr, core->flags,
ba, str, sizeof (str), core->print->big_endian);
r_asm_op_set_asm (&asmop, ba);
free (ba);
if (color && has_color) {
buf_asm = r_print_colorize_opcode (core->print, str,
core->cons->pal.reg, core->cons->pal.num, false, fcn ? fcn->addr : 0);
} else {
buf_asm = r_str_new (str);
}
return buf_asm;
}
#define var_ref_list(a,d,t) sdb_fmt ("var.0x%"PFMT64x".%d.%d.%s",\
a, 1, d, (t == 'R')?"reads":"writes");
static bool cmd_anal_refs(RCore *core, const char *input) {
ut64 addr = core->offset;
switch (input[0]) {
case '-': { // "ax-"
RList *list;
RListIter *iter;
RAnalRef *ref;
char *cp_inp = strdup (input + 1);
char *ptr = r_str_trim_head (cp_inp);
if (!strcmp (ptr, "*")) { // "ax-*"
r_anal_xrefs_init (core->anal);
} else {
int n = r_str_word_set0 (ptr);
ut64 from = UT64_MAX, to = UT64_MAX;
switch (n) {
case 2:
from = r_num_math (core->num, r_str_word_get0 (ptr, 1));
//fall through
case 1: // get addr
to = r_num_math (core->num, r_str_word_get0 (ptr, 0));
break;
default:
to = core->offset;
break;
}
list = r_anal_xrefs_get (core->anal, to);
if (list) {
r_list_foreach (list, iter, ref) {
if (from != UT64_MAX && from == ref->addr) {
r_anal_xref_del (core->anal, ref->addr, ref->at);
}
if (from == UT64_MAX) {
r_anal_xref_del (core->anal, ref->addr, ref->at);
}
}
}
r_list_free (list);
}
free (cp_inp);
} break;
case 'g': // "axg"
{
Sdb *db = sdb_new0 ();
if (input[1] == '*') {
anal_axg (core, input + 2, 0, db, R_CORE_ANAL_GRAPHBODY); // r2 commands
} else if (input[1] == 'j') {
anal_axg (core, input + 2, 0, db, R_CORE_ANAL_JSON);
} else {
anal_axg (core, input[1] ? input + 2 : NULL, 0, db, 0);
}
sdb_free (db);
}
break;
case '\0': // "ax"
case 'j': // "axj"
case 'q': // "axq"
case '*': // "ax*"
r_anal_xrefs_list (core->anal, input[0]);
break;
case 't': { // "axt"
RList *list = NULL;
RAnalFunction *fcn;
RAnalRef *ref;
RListIter *iter;
char *space = strchr (input, ' ');
char *tmp = NULL;
char *name = space ? strdup (space + 1): NULL;
if (name && (tmp = strchr (name, ' '))) {
char *varname = tmp + 1;
*tmp = '\0';
RAnalFunction *fcn = r_anal_fcn_find_name (core->anal, name);
if (fcn) {
RAnalVar *var = r_anal_var_get_byname (core->anal, fcn->addr, varname);
if (var) {
const char *rvar = var_ref_list (fcn->addr, var->delta, 'R');
const char *wvar = var_ref_list (fcn->addr, var->delta, 'W');
char *res = sdb_get (core->anal->sdb_fcns, rvar, 0);
char *res1 = sdb_get (core->anal->sdb_fcns, wvar, 0);
const char *ref;
RListIter *iter;
RList *list = (res && *res)? r_str_split_list (res, ","): NULL;
RList *list1 = (res1 && *res1)? r_str_split_list (res1, ","): NULL;
r_list_join (list , list1);
r_list_foreach (list, iter, ref) {
ut64 addr = r_num_math (NULL, ref);
char *op = get_buf_asm (core, core->offset, addr, fcn, true);
r_cons_printf ("%s 0x%"PFMT64x" [DATA] %s\n", fcn? fcn->name : "(nofunc)", addr, op);
free (op);
}
free (res);
free (res1);
free (name);
r_anal_var_free (var);
r_list_free (list);
r_list_free (list1);
break;
}
}
}
if (space) {
addr = r_num_math (core->num, space + 1);
} else {
addr = core->offset;
}
list = r_anal_xrefs_get (core->anal, addr);
if (list) {
if (input[1] == 'q') { // "axtq"
r_list_foreach (list, iter, ref) {
r_cons_printf ("0x%" PFMT64x "\n", ref->addr);
}
} else if (input[1] == 'j') { // "axtj"
r_cons_printf ("[");
r_list_foreach (list, iter, ref) {
fcn = r_anal_get_fcn_in (core->anal, ref->addr, 0);
char *str = get_buf_asm (core, addr, ref->addr, fcn, false);
r_cons_printf ("{\"from\":%" PFMT64u ",\"type\":\"%s\",\"opcode\":\"%s\"",
ref->addr, r_anal_xrefs_type_tostring (ref->type), str);
if (fcn) {
r_cons_printf (",\"fcn_addr\":%"PFMT64u",\"fcn_name\":\"%s\"", fcn->addr, fcn->name);
}
RFlagItem *fi = r_flag_get_at (core->flags, fcn? fcn->addr: ref->addr, true);
if (fi) {
if (fcn && strcmp (fcn->name, fi->name)) {
r_cons_printf (",\"flag\":\"%s\"", fi->name);
}
if (fi->realname && strcmp (fi->name, fi->realname)) {
char *escaped = r_str_escape (fi->realname);
if (escaped) {
r_cons_printf (",\"realname\":\"%s\"", escaped);
free (escaped);
}
}
}
r_cons_printf ("}%s", iter->n? ",": "");
free (str);
}
r_cons_printf ("]");
r_cons_newline ();
} else if (input[1] == 'g') { // axtg
r_list_foreach (list, iter, ref) {
char *str = r_core_cmd_strf (core, "fd 0x%"PFMT64x, ref->addr);
if (!str) {
str = strdup ("?\n");
}
r_str_trim_tail (str);
r_cons_printf ("agn 0x%" PFMT64x " \"%s\"\n", ref->addr, str);
free (str);
}
if (input[2] != '*') {
RAnalFunction *fcn = r_anal_get_fcn_in (core->anal, addr, 0);
r_cons_printf ("agn 0x%" PFMT64x " \"%s\"\n", addr, fcn?fcn->name: "$$");
}
r_list_foreach (list, iter, ref) {
r_cons_printf ("age 0x%" PFMT64x " 0x%"PFMT64x"\n", ref->addr, addr);
}
} else if (input[1] == '*') { // axt*
// TODO: implement multi-line comments
r_list_foreach (list, iter, ref)
r_cons_printf ("CCa 0x%" PFMT64x " \"XREF type %d at 0x%" PFMT64x"%s\n",
ref->addr, ref->type, addr, iter->n? ",": "");
} else { // axt
RAnalFunction *fcn;
char *comment;
r_list_foreach (list, iter, ref) {
fcn = r_anal_get_fcn_in (core->anal, ref->addr, 0);
char *buf_asm = get_buf_asm (core, addr, ref->addr, fcn, true);
comment = r_meta_get_string (core->anal, R_META_TYPE_COMMENT, ref->addr);
char *buf_fcn = comment
? r_str_newf ("%s; %s", fcn ? fcn->name : "(nofunc)", strtok (comment, "\n"))
: r_str_newf ("%s", fcn ? fcn->name : "(nofunc)");
r_cons_printf ("%s 0x%" PFMT64x " [%s] %s\n",
buf_fcn, ref->addr, r_anal_xrefs_type_tostring (ref->type), buf_asm);
free (buf_asm);
free (buf_fcn);
}
}
} else {
if (input[1] == 'j') { // "axtj"
r_cons_print ("[]\n");
}
}
r_list_free (list);
} break;
case 'f':
if (input[1] == 'f') {
RAnalFunction * fcn = r_anal_get_fcn_in (core->anal, addr, 0);
RListIter *iter;
RAnalRef *refi;
RList *refs = r_anal_fcn_get_refs (core->anal, fcn);
r_list_foreach (refs, iter, refi) {
RFlagItem *f = r_flag_get_at (core->flags, refi->addr, true);
const char *name = f ? f->name: "";
r_cons_printf ("%c 0x%08"PFMT64x" 0x%08"PFMT64x" %s\n",
refi->type == R_ANAL_REF_TYPE_CALL?'C':'J',
refi->at, refi->addr, name);
}
} else { // "axf"
ut8 buf[12];
RAsmOp asmop;
char *buf_asm = NULL;
RList *list, *list_ = NULL;
RAnalRef *ref;
RListIter *iter;
char *space = strchr (input, ' ');
RAnalFunction * fcn = r_anal_get_fcn_in (core->anal, addr, 0);
if (space) {
addr = r_num_math (core->num, space + 1);
} else {
addr = core->offset;
}
if (input[1] == '.') { // "axf."
list = list_ = r_anal_xrefs_get_from (core->anal, addr);
if (!list) {
list = r_anal_fcn_get_refs (core->anal, fcn);
}
} else {
list = r_anal_refs_get (core->anal, addr);
}
if (list) {
if (input[1] == 'q') { // "axfq"
r_list_foreach (list, iter, ref) {
r_cons_printf ("0x%" PFMT64x "\n", ref->at);
}
} else if (input[1] == 'j') { // "axfj"
r_cons_print ("[");
r_list_foreach (list, iter, ref) {
r_io_read_at (core->io, ref->at, buf, 12);
r_asm_set_pc (core->assembler, ref->at);
r_asm_disassemble (core->assembler, &asmop, buf, 12);
r_cons_printf ("{\"from\":%" PFMT64u ",\"to\":%" PFMT64u ",\"type\":\"%s\",\"opcode\":\"%s\"}%s",
ref->at, ref->addr, r_anal_xrefs_type_tostring (ref->type), r_asm_op_get_asm (&asmop), iter->n? ",": "");
}
r_cons_print ("]\n");
} else if (input[1] == '*') { // "axf*"
// TODO: implement multi-line comments
r_list_foreach (list, iter, ref) {
r_cons_printf ("CCa 0x%" PFMT64x " \"XREF from 0x%" PFMT64x "\n",
ref->at, ref->type, r_asm_op_get_asm (&asmop), iter->n? ",": "");
}
} else { // "axf"
char str[512];
int has_color = core->print->flags & R_PRINT_FLAGS_COLOR;
r_list_foreach (list, iter, ref) {
r_io_read_at (core->io, ref->at, buf, 12);
r_asm_set_pc (core->assembler, ref->at);
r_asm_disassemble (core->assembler, &asmop, buf, 12);
r_parse_filter (core->parser, ref->at, core->flags, r_asm_op_get_asm (&asmop),
str, sizeof (str), core->print->big_endian);
if (has_color) {
buf_asm = r_print_colorize_opcode (core->print, str,
core->cons->pal.reg, core->cons->pal.num, false, fcn ? fcn->addr : 0);
} else {
buf_asm = r_str_new (str);
}
r_cons_printf ("%c 0x%" PFMT64x " %s",
ref->type, ref->at, buf_asm);
if (ref->type == R_ANAL_REF_TYPE_CALL) {
RAnalOp aop;
r_anal_op (core->anal, &aop, ref->at, buf, 12, R_ANAL_OP_MASK_BASIC);
if (aop.type == R_ANAL_OP_TYPE_UCALL) {
cmd_anal_ucall_ref (core, ref->addr);
}
}
r_cons_newline ();
free (buf_asm);
}
}
} else {
if (input[1] == 'j') { // "axfj"
r_cons_print ("[]\n");
}
}
r_list_free (list);
}
break;
case 'F': // "axF"
find_refs (core, input + 1);
break;
case 'C': // "axC"
case 'c': // "axc"
case 'd': // "axd"
case 's': // "axs"
case ' ': // "ax "
{
char *ptr = strdup (r_str_trim_head ((char *)input + 1));
int n = r_str_word_set0 (ptr);
ut64 at = core->offset;
ut64 addr = UT64_MAX;
RAnalRefType reftype = r_anal_xrefs_type (input[0]);
switch (n) {
case 2: // get at
at = r_num_math (core->num, r_str_word_get0 (ptr, 1));
/* fall through */
case 1: // get addr
addr = r_num_math (core->num, r_str_word_get0 (ptr, 0));
break;
default:
free (ptr);
return false;
}
r_anal_xrefs_set (core->anal, at, addr, reftype);
free (ptr);
}
break;
default:
case '?':
r_core_cmd_help (core, help_msg_ax);
break;
}
return true;
}
static void cmd_anal_hint(RCore *core, const char *input) {
switch (input[0]) {
case '?':
if (input[1]) {
ut64 addr = r_num_math (core->num, input + 1);
r_core_anal_hint_print (core->anal, addr, 0);
} else {
r_core_cmd_help (core, help_msg_ah);
}
break;
case '.': // "ah."
r_core_anal_hint_print (core->anal, core->offset, 0);
break;
case 'a': // "aha" set arch
if (input[1]) {
int i;
char *ptr = strdup (input + 2);
i = r_str_word_set0 (ptr);
if (i == 2) {
r_num_math (core->num, r_str_word_get0 (ptr, 1));
}
r_anal_hint_set_arch (core->anal, core->offset, r_str_word_get0 (ptr, 0));
free (ptr);
} else if (input[1] == '-') {
r_anal_hint_unset_arch (core->anal, core->offset);
} else {
eprintf ("Missing argument\n");
}
break;
case 'b': // "ahb" set bits
if (input[1]) {
char *ptr = strdup (input + 2);
int bits;
int i = r_str_word_set0 (ptr);
if (i == 2) {
r_num_math (core->num, r_str_word_get0 (ptr, 1));
}
bits = r_num_math (core->num, r_str_word_get0 (ptr, 0));
r_anal_hint_set_bits (core->anal, core->offset, bits);
free (ptr);
} else if (input[1] == '-') {
r_anal_hint_unset_bits (core->anal, core->offset);
} else {
eprintf ("Missing argument\n");
}
break;
case 'i': // "ahi"
if (input[1] == '?') {
r_core_cmd_help (core, help_msg_ahi);
} else if (input[1] == ' ') {
// You can either specify immbase with letters, or numbers
const int base =
(input[2] == 's') ? 1 :
(input[2] == 'b') ? 2 :
(input[2] == 'p') ? 3 :
(input[2] == 'o') ? 8 :
(input[2] == 'd') ? 10 :
(input[2] == 'h') ? 16 :
(input[2] == 'i') ? 32 : // ip address
(input[2] == 'S') ? 80 : // syscall
(int) r_num_math (core->num, input + 1);
r_anal_hint_set_immbase (core->anal, core->offset, base);
} else if (input[1] == '-') { // "ahi-"
r_anal_hint_set_immbase (core->anal, core->offset, 0);
} else {
eprintf ("|ERROR| Usage: ahi [base]\n");
}
break;
case 'h': // "ahh"
if (input[1] == '-') {
r_anal_hint_unset_high (core->anal, core->offset);
} else if (input[1] == ' ') {
r_anal_hint_set_high (core->anal, r_num_math (core->num, input + 1));
} else {
r_anal_hint_set_high (core->anal, core->offset);
}
break;
case 'c': // "ahc"
if (input[1] == ' ') {
r_anal_hint_set_jump (
core->anal, core->offset,
r_num_math (core->num, input + 1));
} else if (input[1] == '-') {
r_anal_hint_unset_jump (core->anal, core->offset);
}
break;
case 'f': // "ahf"
if (input[1] == ' ') {
r_anal_hint_set_fail (
core->anal, core->offset,
r_num_math (core->num, input + 1));
} else if (input[1] == '-') {
r_anal_hint_unset_fail (core->anal, core->offset);
}
break;
case 's': // "ahs" set size (opcode length)
if (input[1] == ' ') {
r_anal_hint_set_size (core->anal, core->offset, atoi (input + 1));
} else if (input[1] == '-') {
r_anal_hint_unset_size (core->anal, core->offset);
} else {
eprintf ("Usage: ahs 16\n");
}
break;
case 'S': // "ahS" set size (opcode length)
if (input[1] == ' ') {
r_anal_hint_set_syntax (core->anal, core->offset, input + 2);
} else if (input[1] == '-') {
r_anal_hint_unset_syntax (core->anal, core->offset);
} else {
eprintf ("Usage: ahS att\n");
}
break;
case 'o': // "aho" set opcode string
if (input[1] == ' ') {
r_anal_hint_set_opcode (core->anal, core->offset, input + 2);
} else if (input[1] == '-') {
r_anal_hint_unset_opcode (core->anal, core->offset);
} else {
eprintf ("Usage: aho popall\n");
}
break;
case 'e': // "ahe" set ESIL string
if (input[1] == ' ') {
r_anal_hint_set_esil (core->anal, core->offset, input + 2);
} else if (input[1] == '-') {
r_anal_hint_unset_esil (core->anal, core->offset);
} else {
eprintf ("Usage: ahe r0,pc,=\n");
}
break;
#if 0
case 'e': // set endian
if (input[1] == ' ') {
r_anal_hint_set_opcode (core->anal, core->offset, atoi (input + 1));
} else if (input[1] == '-') {
r_anal_hint_unset_opcode (core->anal, core->offset);
}
break;
#endif
case 'p': // "ahp"
if (input[1] == ' ') {
r_anal_hint_set_pointer (core->anal, core->offset, r_num_math (core->num, input + 1));
} else if (input[1] == '-') { // "ahp-"
r_anal_hint_unset_pointer (core->anal, core->offset);
}
break;
case 'r': // "ahr"
if (input[1] == ' ') {
r_anal_hint_set_ret (core->anal, core->offset, r_num_math (core->num, input + 1));
} else if (input[1] == '-') { // "ahr-"
r_anal_hint_unset_ret (core->anal, core->offset);
}
case '*': // "ah*"
if (input[1] == ' ') {
char *ptr = strdup (r_str_trim_ro (input + 2));
r_str_word_set0 (ptr);
ut64 addr = r_num_math (core->num, r_str_word_get0 (ptr, 0));
r_core_anal_hint_print (core->anal, addr, '*');
} else {
r_core_anal_hint_list (core->anal, input[0]);
}
break;
case 'j': // "ahj"
case '\0': // "ah"
r_core_anal_hint_list (core->anal, input[0]);
break;
case '-': // "ah-"
if (input[1]) {
if (input[1] == '*') {
r_anal_hint_clear (core->anal);
} else {
char *ptr = strdup (r_str_trim_ro (input + 1));
ut64 addr;
int size = 1;
int i = r_str_word_set0 (ptr);
if (i == 2) {
size = r_num_math (core->num, r_str_word_get0 (ptr, 1));
}
const char *a0 = r_str_word_get0 (ptr, 0);
if (a0 && *a0) {
addr = r_num_math (core->num, a0);
} else {
addr = core->offset;
}
r_anal_hint_del (core->anal, addr, size);
free (ptr);
}
} else {
r_anal_hint_clear (core->anal);
}
break;
}
}
static void agraph_print_node_gml(RANode *n, void *user) {
r_cons_printf (" node [\n"
" id %d\n"
" label \"%s\"\n"
" ]\n", n->gnode->idx, n->title);
}
static void agraph_print_edge_gml(RANode *from, RANode *to, void *user) {
r_cons_printf (" edge [\n"
" source %d\n"
" target %d\n"
" ]\n", from->gnode->idx, to->gnode->idx
);
}
static void agraph_print_node_dot(RANode *n, void *user) {
char *label = strdup (n->body);
//label = r_str_replace (label, "\n", "\\l", 1);
if (!label || !*label) {
r_cons_printf ("\"%s\" [URL=\"%s\", color=\"lightgray\", label=\"%s\"]\n",
n->title, n->title, n->title);
} else {
r_cons_printf ("\"%s\" [URL=\"%s\", color=\"lightgray\", label=\"%s\\n%s\"]\n",
n->title, n->title, n->title, label);
}
free (label);
}
static void agraph_print_node(RANode *n, void *user) {
char *encbody, *cmd;
int len = strlen (n->body);
if (len > 0 && n->body[len - 1] == '\n') {
len--;
}
encbody = r_base64_encode_dyn (n->body, len);
cmd = r_str_newf ("agn \"%s\" base64:%s\n", n->title, encbody);
r_cons_printf (cmd);
free (cmd);
free (encbody);
}
static char *getViewerPath() {
int i;
const char *viewers[] = {
#if __WINDOWS__
"explorer",
#else
"open",
"geeqie",
"gqview",
"eog",
"xdg-open",
#endif
NULL
};
for (i = 0; viewers[i]; i++) {
char *viewerPath = r_file_path (viewers[i]);
if (viewerPath && strcmp (viewerPath, viewers[i])) {
return viewerPath;
}
free (viewerPath);
}
return NULL;
}
static char* graph_cmd(RCore *core, char *r2_cmd, const char *save_path) {
const char *dot = "dot";
char *cmd = NULL;
const char *ext = r_config_get (core->config, "graph.gv.format");
char *dotPath = r_file_path (dot);
if (!strcmp (dotPath, dot)) {
free (dotPath);
dot = "xdot";
dotPath = r_file_path (dot);
if (!strcmp (dotPath, dot)) {
free (dotPath);
return r_str_new ("agf");
}
}
if (save_path && *save_path) {
cmd = r_str_newf ("%s > a.dot;!%s -T%s -o%s a.dot;",
r2_cmd, dot, ext, save_path);
} else {
char *viewer = getViewerPath();
if (viewer) {
cmd = r_str_newf ("%s > a.dot;!%s -T%s -oa.%s a.dot;!%s a.%s",
r2_cmd, dot, ext, ext, viewer, ext);
free (viewer);
} else {
eprintf ("Cannot find a valid picture viewer\n");
}
}
free (dotPath);
return cmd;
}
static void agraph_print_edge_dot(RANode *from, RANode *to, void *user) {
r_cons_printf ("\"%s\" -> \"%s\"\n", from->title, to->title);
}
static void agraph_print_edge(RANode *from, RANode *to, void *user) {
r_cons_printf ("age \"%s\" \"%s\"\n", from->title, to->title);
}
static void cmd_agraph_node(RCore *core, const char *input) {
switch (*input) {
case ' ': { // "agn"
char *newbody = NULL;
char **args, *body;
int n_args, B_LEN = strlen ("base64:");
input++;
args = r_str_argv (input, &n_args);
if (n_args < 1 || n_args > 2) {
r_cons_printf ("Wrong arguments\n");
r_str_argv_free (args);
break;
}
// strdup cause there is double free in r_str_argv_free due to a realloc call
if (n_args > 1) {
body = strdup (args[1]);
if (strncmp (body, "base64:", B_LEN) == 0) {
body = r_str_replace (body, "\\n", "", true);
newbody = (char *)r_base64_decode_dyn (body + B_LEN, -1);
free (body);
if (!newbody) {
eprintf ("Cannot allocate buffer\n");
r_str_argv_free (args);
break;
}
body = newbody;
}
body = r_str_append (body, "\n");
} else {
body = strdup ("");
}
r_agraph_add_node (core->graph, args[0], body);
r_str_argv_free (args);
free (body);
//free newbody it's not necessary since r_str_append reallocate the space
break;
}
case '-': { // "agn-"
char **args;
int n_args;
input++;
args = r_str_argv (input, &n_args);
if (n_args != 1) {
r_cons_printf ("Wrong arguments\n");
r_str_argv_free (args);
break;
}
r_agraph_del_node (core->graph, args[0]);
r_str_argv_free (args);
break;
}
case '?':
default:
r_core_cmd_help (core, help_msg_agn);
break;
}
}
static void cmd_agraph_edge(RCore *core, const char *input) {
switch (*input) {
case ' ': // "age"
case '-': { // "age-"
RANode *u, *v;
char **args;
int n_args;
args = r_str_argv (input + 1, &n_args);
if (n_args != 2) {
r_cons_printf ("Wrong arguments\n");
r_str_argv_free (args);
break;
}
u = r_agraph_get_node (core->graph, args[0]);
v = r_agraph_get_node (core->graph, args[1]);
if (!u || !v) {
if (!u) {
r_cons_printf ("Node %s not found!\n", args[0]);
} else {
r_cons_printf ("Node %s not found!\n", args[1]);
}
r_str_argv_free (args);
break;
}
if (*input == ' ') {
r_agraph_add_edge (core->graph, u, v);
} else {
r_agraph_del_edge (core->graph, u, v);
}
r_str_argv_free (args);
break;
}
case '?':
default:
r_core_cmd_help (core, help_msg_age);
break;
}
}
static void cmd_agraph_print(RCore *core, const char *input) {
switch (*input) {
case 0:
core->graph->can->linemode = r_config_get_i (core->config, "graph.linemode");
core->graph->can->color = r_config_get_i (core->config, "scr.color");
r_agraph_set_title (core->graph,
r_config_get (core->config, "graph.title"));
r_agraph_print (core->graph);
break;
case 't':{ // "aggt" - tiny graph
core->graph->is_tiny = true;
int e = r_config_get_i (core->config, "graph.edges");
r_config_set_i (core->config, "graph.edges", 0);
r_core_visual_graph (core, core->graph, NULL, false);
r_config_set_i (core->config, "graph.edges", e);
core->graph->is_tiny = false;
break;
}
case 'k': // "aggk"
{
Sdb *db = r_agraph_get_sdb (core->graph);
char *o = sdb_querys (db, "null", 0, "*");
r_cons_print (o);
free (o);
break;
}
case 'v': // "aggv"
case 'i': // "aggi" - open current core->graph in interactive mode
{
RANode *ran = r_agraph_get_first_node (core->graph);
if (ran) {
r_agraph_set_title (core->graph, r_config_get (core->config, "graph.title"));
r_agraph_set_curnode (core->graph, ran);
core->graph->force_update_seek = true;
core->graph->need_set_layout = true;
core->graph->layout = r_config_get_i (core->config, "graph.layout");
int ov = r_config_get_i (core->config, "scr.interactive");
core->graph->need_update_dim = true;
r_core_visual_graph (core, core->graph, NULL, true);
r_config_set_i (core->config, "scr.interactive", ov);
r_cons_show_cursor (true);
r_cons_enable_mouse (false);
} else {
eprintf ("This graph contains no nodes\n");
}
break;
}
case 'd': { // "aggd" - dot format
const char *font = r_config_get (core->config, "graph.font");
r_cons_printf ("digraph code {\ngraph [bgcolor=white];\n"
"node [color=lightgray, style=filled shape=box "
"fontname=\"%s\" fontsize=\"8\"];\n", font);
r_agraph_foreach (core->graph, agraph_print_node_dot, NULL);
r_agraph_foreach_edge (core->graph, agraph_print_edge_dot, NULL);
r_cons_printf ("}\n");
break;
}
case '*': // "agg*" -
r_agraph_foreach (core->graph, agraph_print_node, NULL);
r_agraph_foreach_edge (core->graph, agraph_print_edge, NULL);
break;
case 'J':
case 'j':
r_cons_printf ("{\"nodes\":[");
r_agraph_print_json (core->graph);
r_cons_printf ("]}\n");
break;
case 'g':
r_cons_printf ("graph\n[\n" "hierarchic 1\n" "label \"\"\n" "directed 1\n");
r_agraph_foreach (core->graph, agraph_print_node_gml, NULL);
r_agraph_foreach_edge (core->graph, agraph_print_edge_gml, NULL);
r_cons_print ("]\n");
break;
case 'w':{ // "aggw"
if (r_config_get_i (core->config, "graph.web")) {
r_core_cmd0 (core, "=H /graph/");
} else {
char *cmd = graph_cmd (core, "aggd", input + 1);
if (cmd && *cmd) {
if (input[1]) {
r_cons_printf ("Saving to file %s ...\n", input + 1);
r_cons_flush ();
}
r_core_cmd0 (core, cmd);
}
free (cmd);
}
break;
}
default:
eprintf ("Usage: see ag?\n");
}
}
static void cmd_anal_graph(RCore *core, const char *input) {
// Honor asm.graph=false in json as well
RConfigHold *hc = r_config_hold_new (core->config);
r_config_save_num (hc, "asm.offset", NULL);
const bool o_graph_offset = r_config_get_i (core->config, "graph.offset");
switch (input[0]) {
case 'f': // "agf"
switch (input[1]) {
case 0: // "agf"
r_core_visual_graph (core, NULL, NULL, false);
break;
case ' ':{ // "agf "
RAnalFunction *fcn = r_anal_get_fcn_in (core->anal, core->offset, 0);
r_core_visual_graph (core, NULL, fcn, false);
break;
}
case 'v': // "agfv"
eprintf ("\rRendering graph...");
RAnalFunction *fcn = r_anal_get_fcn_in (core->anal, core->offset, 0);
if (fcn) {
r_core_visual_graph (core, NULL, fcn, 1);
}
r_cons_enable_mouse (false);
r_cons_show_cursor (true);
break;
case 't': { // "agft" - tiny graph
int e = r_config_get_i (core->config, "graph.edges");
r_config_set_i (core->config, "graph.edges", 0);
RAnalFunction *fcn = r_anal_get_fcn_in (core->anal, core->offset, 0);
r_core_visual_graph (core, NULL, fcn, 2);
r_config_set_i (core->config, "graph.edges", e);
break;
}
case 'd': // "agfd"
if (input[2] == 'm') {
r_core_anal_graph (core, r_num_math (core->num, input + 3),
R_CORE_ANAL_GRAPHLINES);
} else {
r_core_anal_graph (core, r_num_math (core->num, input + 2),
R_CORE_ANAL_GRAPHBODY);
}
break;
case 'j': // "agfj"
r_core_anal_graph (core, r_num_math (core->num, input + 2), R_CORE_ANAL_JSON);
break;
case 'J': // "agfJ"
r_config_set_i (core->config, "asm.offset", o_graph_offset);
r_core_anal_graph (core, r_num_math (core->num, input + 2),
R_CORE_ANAL_JSON | R_CORE_ANAL_JSON_FORMAT_DISASM);
r_config_restore (hc);
r_config_hold_free (hc);
break;
case 'g':{ // "agfg"
RAnalFunction *fcn = r_anal_get_fcn_in (core->anal, core->offset, 0);
r_core_print_bb_gml (core, fcn);
break;
}
case 'k':{ // "agfk"
r_core_cmdf (core, "ag-; .agf* @ %"PFMT64u"; aggk", core->offset);
break;
}
case '*':{// "agf*"
RAnalFunction *fcn = r_anal_get_fcn_in (core->anal, core->offset, 0);
r_core_print_bb_custom (core, fcn);
break;
}
case 'w':// "agfw"
if (r_config_get_i (core->config, "graph.web")) {
r_core_cmd0 (core, "=H /graph/");
} else {
char *cmdargs = r_str_newf ("agfd @ 0x%"PFMT64x, core->offset);
char *cmd = graph_cmd (core, cmdargs, input + 2);
if (cmd && *cmd) {
if (*(input + 2)) {
r_cons_printf ("Saving to file %s ...\n", input + 2);
r_cons_flush ();
}
r_core_cmd0 (core, cmd);
}
free (cmd);
free (cmdargs);
}
break;
default:
eprintf ("Usage: see ag?\n");
break;
}
break;
case '-': // "ag-"
r_agraph_reset (core->graph);
break;
case 'n': // "agn"
cmd_agraph_node (core, input + 1);
break;
case 'e': // "age"
cmd_agraph_edge (core, input + 1);
break;
case 'g': // "agg"
cmd_agraph_print (core, input + 1);
break;
case 's': // "ags"
r_core_anal_graph (core, r_num_math (core->num, input + 1), 0);
break;
case 'C': // "agC"
switch (input[1]) {
case 'v':
case 't':
case 'k':
case 'w':
case ' ':
case 0: {
core->graph->is_callgraph = true;
r_core_cmdf (core, "ag-; .agC*; agg%s;", input + 1);
core->graph->is_callgraph = false;
break;
}
case 'J':
case 'j':
r_core_anal_callgraph (core, UT64_MAX, R_GRAPH_FORMAT_JSON);
break;
case 'g':
r_core_anal_callgraph (core, UT64_MAX, R_GRAPH_FORMAT_GML);
break;
case 'd':
r_core_anal_callgraph (core, UT64_MAX, R_GRAPH_FORMAT_DOT);
break;
case '*':
r_core_anal_callgraph (core, UT64_MAX, R_GRAPH_FORMAT_CMD);
break;
default:
eprintf ("Usage: see ag?\n");
break;
}
break;
case 'r': // "agr" references graph
switch (input[1]) {
case 'v':
case 't':
case 'd':
case 'J':
case 'j':
case 'g':
case 'k':
case 'w':
case ' ': {
core->graph->is_callgraph = true;
r_core_cmdf (core, "ag-; .agr* @ %"PFMT64u"; agg%s;", core->offset, input + 1);
core->graph->is_callgraph = false;
break;
}
case '*': {
r_core_anal_coderefs (core, core->offset);
}
break;
case 0:
r_core_cmd0 (core, "ag-; .agr* $$; agg;");
break;
default:
eprintf ("Usage: see ag?\n");
break;
}
break;
case 'R': // "agR" global refs
switch (input[1]) {
case 'v':
case 't':
case 'd':
case 'J':
case 'j':
case 'g':
case 'k':
case 'w':
case ' ':
case 0: {
core->graph->is_callgraph = true;
r_core_cmdf (core, "ag-; .agR*; agg%s;", input + 1);
core->graph->is_callgraph = false;
break;
}
case '*': {
ut64 from = r_config_get_i (core->config, "graph.from");
ut64 to = r_config_get_i (core->config, "graph.to");
RListIter *it;
RAnalFunction *fcn;
r_list_foreach (core->anal->fcns, it, fcn) {
if ((from == UT64_MAX && to == UT64_MAX) || R_BETWEEN (from, fcn->addr, to)) {
r_core_anal_coderefs (core, fcn->addr);
}
}
break;
}
default:
eprintf ("Usage: see ag?\n");
break;
}
break;
case 'x': // "agx" cross refs
switch (input[1]) {
case 'v':
case 't':
case 'd':
case 'J':
case 'j':
case 'g':
case 'k':
case 'w':
case ' ': {
r_core_cmdf (core, "ag-; .agx* @ %"PFMT64u"; agg%s;", core->offset, input + 1);
break;
}
case '*': {
r_core_anal_codexrefs (core, core->offset);
}
break;
case 0:
r_core_cmd0 (core, "ag-; .agx* $$; agg;");
break;
default:
eprintf ("Usage: see ag?\n");
break;
}
break;
case 'i': // "agi" import graph
switch (input[1]) {
case 'v':
case 't':
case 'd':
case 'J':
case 'j':
case 'g':
case 'k':
case 'w':
case ' ':
case 0:
r_core_cmdf (core, "ag-; .agi*; agg%s;", input + 1);
break;
case '*':
r_core_anal_importxrefs (core);
break;
default:
eprintf ("Usage: see ag?\n");
break;
}
break;
case 'c': // "agc"
switch (input[1]) {
case 'v':
case 't':
case 'k':
case 'w':
case ' ': {
core->graph->is_callgraph = true;
r_core_cmdf (core, "ag-; .agc* @ %"PFMT64u"; agg%s;", core->offset, input + 1);
core->graph->is_callgraph = false;
break;
}
case 0:
core->graph->is_callgraph = true;
r_core_cmd0 (core, "ag-; .agc* $$; agg;");
core->graph->is_callgraph = false;
break;
case 'g': {
r_core_anal_callgraph (core, core->offset, R_GRAPH_FORMAT_GMLFCN);
break;
}
case 'd': {
r_core_anal_callgraph (core, core->offset, R_GRAPH_FORMAT_DOT);
break;
}
case 'J':
case 'j': {
r_core_anal_callgraph (core, core->offset, R_GRAPH_FORMAT_JSON);
break;
}
case '*': {
r_core_anal_callgraph (core, core->offset, R_GRAPH_FORMAT_CMD);
break;
}
default:
eprintf ("Usage: see ag?\n");
break;
}
break;
case 'j': // "agj" alias for agfj
r_core_cmdf (core, "agfj%s", input + 1);
break;
case 'J': // "agJ" alias for agfJ
r_core_cmdf (core, "agfJ%s", input + 1);
break;
case 'k': // "agk" alias for agfk
r_core_cmdf (core, "agfk%s", input + 1);
break;
case 'l': // "agl"
r_core_anal_graph (core, r_num_math (core->num, input + 1), R_CORE_ANAL_GRAPHLINES);
break;
case 'a': // "aga"
switch (input[1]) {
case 'v':
case 't':
case 'k':
case 'w':
case 'g':
case 'j':
case 'J':
case 'd':
case ' ': {
r_core_cmdf (core, "ag-; .aga* @ %"PFMT64u"; agg%s;", core->offset, input + 1);
break;
}
case 0:
r_core_cmd0 (core, "ag-; .aga* $$; agg;");
break;
case '*': {
r_core_anal_datarefs (core, core->offset);
break;
}
default:
eprintf ("Usage: see ag?\n");
break;
}
break;
case 'A': // "agA" global data refs
switch (input[1]) {
case 'v':
case 't':
case 'd':
case 'J':
case 'j':
case 'g':
case 'k':
case 'w':
case ' ':
case 0: {
r_core_cmdf (core, "ag-; .agA*; agg%c;", input[1]);
break;
}
case '*': {
ut64 from = r_config_get_i (core->config, "graph.from");
ut64 to = r_config_get_i (core->config, "graph.to");
RListIter *it;
RAnalFunction *fcn;
r_list_foreach (core->anal->fcns, it, fcn) {
if ((from == UT64_MAX && to == UT64_MAX) || R_BETWEEN (from, fcn->addr, to)) {
r_core_anal_datarefs (core, fcn->addr);
}
}
break;
}
default:
eprintf ("Usage: see ag?\n");
break;
}
break;
case 'd': // "agd"
switch (input[1]) {
case 'v':
case 't':
case 'j':
case 'J':
case 'g':
case 'k':
case '*':
case ' ':
case 0:
eprintf ("Currently the only supported formats for the diff graph are 'agdd' and 'agdw'\n");
break;
case 'd': {
ut64 addr = input[2]? r_num_math (core->num, input + 2): core->offset;
r_core_gdiff_fcn (core, addr, core->offset);
r_core_anal_graph (core, addr, R_CORE_ANAL_GRAPHBODY | R_CORE_ANAL_GRAPHDIFF);
break;
}
case 'w': {
char *cmdargs = r_str_newf ("agdd 0x%"PFMT64x, core->offset);
char *cmd = graph_cmd (core, cmdargs, input + 2);
if (cmd && *cmd) {
r_core_cmd0 (core, cmd);
}
free (cmd);
free (cmdargs);
break;
}
}
break;
case 'v': // "agv" alias for "agfv"
r_core_cmdf (core, "agfv%s", input + 1);
break;
case 'w':// "agw"
if (r_config_get_i (core->config, "graph.web")) {
r_core_cmd0 (core, "=H /graph/");
} else {
char *cmdargs = r_str_newf ("agfd @ 0x%"PFMT64x, core->offset);
char *cmd = graph_cmd (core, cmdargs, input + 1);
if (cmd && *cmd) {
if (input[1]) {
r_cons_printf ("Saving to file %s ...\n", input + 1);
r_cons_flush ();
}
r_core_cmd0 (core, cmd);
}
free (cmd);
free (cmdargs);
}
break;
default:
r_core_cmd_help (core, help_msg_ag);
break;
}
}
R_API int r_core_anal_refs(RCore *core, const char *input) {
int cfg_debug = r_config_get_i (core->config, "cfg.debug");
ut64 from, to;
char *ptr;
int rad, n;
if (*input == '?') {
r_core_cmd_help (core, help_msg_aar);
return 0;
}
if (*input == 'j' || *input == '*') {
rad = *input;
input++;
} else {
rad = 0;
}
from = to = 0;
ptr = r_str_trim_head (strdup (input));
n = r_str_word_set0 (ptr);
if (!n) {
// get boundaries of current memory map, section or io map
if (cfg_debug) {
RDebugMap *map = r_debug_map_get (core->dbg, core->offset);
if (map) {
from = map->addr;
to = map->addr_end;
}
} else {
RList *list = r_core_get_boundaries_prot (core, R_PERM_X, NULL, "anal");
RListIter *iter;
RIOMap* map;
if (!list) {
return 0;
}
r_list_foreach (list, iter, map) {
from = map->itv.addr;
to = r_itv_end (map->itv);
if (r_cons_is_breaked ()) {
break;
}
if (!from && !to) {
eprintf ("Cannot determine xref search boundaries\n");
} else if (to - from > UT32_MAX) {
eprintf ("Skipping huge range\n");
} else {
r_core_anal_search_xrefs (core, from, to, rad);
}
}
free (ptr);
r_list_free (list);
return 1;
}
} else if (n == 1) {
from = core->offset;
to = core->offset + r_num_math (core->num, r_str_word_get0 (ptr, 0));
} else {
eprintf ("Invalid number of arguments\n");
}
free (ptr);
if (from == UT64_MAX && to == UT64_MAX) {
return false;
}
if (!from && !to) {
return false;
}
if (to - from > r_io_size (core->io)) {
return false;
}
return r_core_anal_search_xrefs (core, from, to, rad);
}
static const char *oldstr = NULL;
static int compute_coverage(RCore *core) {
RListIter *iter;
SdbListIter *iter2;
RAnalFunction *fcn;
RIOSection *sec;
int cov = 0;
r_list_foreach (core->anal->fcns, iter, fcn) {
ls_foreach (core->io->sections, iter2, sec) {
if (sec->perm & R_PERM_X) {
ut64 section_end = sec->vaddr + sec->vsize;
ut64 s = r_anal_fcn_realsize (fcn);
if (fcn->addr >= sec->vaddr && (fcn->addr + s) < section_end) {
cov += s;
}
}
}
}
return cov;
}
static int compute_code (RCore* core) {
int code = 0;
SdbListIter *iter;
RIOSection *sec;
ls_foreach (core->io->sections, iter, sec) {
if (sec->perm & R_PERM_X) {
code += sec->vsize;
}
}
return code;
}
static int compute_calls(RCore *core) {
RListIter *iter;
RAnalFunction *fcn;
RList *xrefs;
int cov = 0;
r_list_foreach (core->anal->fcns, iter, fcn) {
xrefs = r_anal_fcn_get_xrefs (core->anal, fcn);
if (xrefs) {
cov += r_list_length (xrefs);
xrefs = NULL;
}
r_list_free (xrefs);
}
return cov;
}
static void r_core_anal_info (RCore *core, const char *input) {
int fcns = r_list_length (core->anal->fcns);
int strs = r_flag_count (core->flags, "str.*");
int syms = r_flag_count (core->flags, "sym.*");
int imps = r_flag_count (core->flags, "sym.imp.*");
int code = compute_code (core);
int covr = compute_coverage (core);
int call = compute_calls (core);
int xrfs = r_anal_xrefs_count (core->anal);
int cvpc = (code > 0)? (covr * 100 / code): 0;
if (*input == 'j') {
r_cons_printf ("{\"fcns\":%d", fcns);
r_cons_printf (",\"xrefs\":%d", xrfs);
r_cons_printf (",\"calls\":%d", call);
r_cons_printf (",\"strings\":%d", strs);
r_cons_printf (",\"symbols\":%d", syms);
r_cons_printf (",\"imports\":%d", imps);
r_cons_printf (",\"covrage\":%d", covr);
r_cons_printf (",\"codesz\":%d", code);
r_cons_printf (",\"percent\":%d}\n", cvpc);
} else {
r_cons_printf ("fcns %d\n", fcns);
r_cons_printf ("xrefs %d\n", xrfs);
r_cons_printf ("calls %d\n", call);
r_cons_printf ("strings %d\n", strs);
r_cons_printf ("symbols %d\n", syms);
r_cons_printf ("imports %d\n", imps);
r_cons_printf ("covrage %d\n", covr);
r_cons_printf ("codesz %d\n", code);
r_cons_printf ("percent %d%%\n", cvpc);
}
}
static void cmd_anal_aad(RCore *core, const char *input) {
RListIter *iter;
RAnalRef *ref;
RList *list = r_list_newf (NULL);
r_anal_xrefs_from (core->anal, list, "xref", R_ANAL_REF_TYPE_DATA, UT64_MAX);
r_list_foreach (list, iter, ref) {
if (r_io_is_valid_offset (core->io, ref->addr, false)) {
r_core_anal_fcn (core, ref->at, ref->addr, R_ANAL_REF_TYPE_NULL, 1);
}
}
r_list_free (list);
}
static bool archIsArmOrThumb(RCore *core) {
RAsm *as = core ? core->assembler : NULL;
if (as && as->cur && as->cur->arch) {
if (r_str_startswith (as->cur->arch, "mips")) {
return true;
}
if (r_str_startswith (as->cur->arch, "arm")) {
if (as->bits < 64) {
return true;
}
}
}
return false;
}
bool archIsMips (RCore *core) {
return strstr (core->assembler->cur->name, "mips");
}
void _CbInRangeAav(RCore *core, ut64 from, ut64 to, int vsize, bool asterisk, int count) {
bool isarm = archIsArmOrThumb (core);
if (isarm) {
if (to & 1) {
// .dword 0x000080b9 in reality is 0x000080b8
to--;
r_anal_hint_set_bits (core->anal, to, 16);
// can we assume is gonna be always a function?
} else {
r_core_seek_archbits (core, from);
ut64 bits = r_config_get_i (core->config, "asm.bits");
r_anal_hint_set_bits (core->anal, from, bits);
}
} else {
bool ismips = archIsMips (core);
if (ismips) {
if (from % 4 || to % 4) {
eprintf ("False positive\n");
return;
}
}
}
if (asterisk) {
r_cons_printf ("ax 0x%"PFMT64x " 0x%"PFMT64x "\n", to, from);
r_cons_printf ("Cd %d @ 0x%"PFMT64x "\n", vsize, from);
r_cons_printf ("f+ aav.0x%08"PFMT64x "= 0x%08"PFMT64x, to, to);
} else {
#if 1
r_anal_xrefs_set (core->anal, from, to, R_ANAL_REF_TYPE_NULL);
r_meta_add (core->anal, 'd', from, from + vsize, NULL);
if (!r_flag_get_at (core->flags, to, false)) {
char *name = r_str_newf ("aav.0x%08"PFMT64x, to);
r_flag_set (core->flags, name, to, vsize);
free (name);
}
#else
r_core_cmdf (core, "ax 0x%"PFMT64x " 0x%"PFMT64x, to, from);
r_core_cmdf (core, "Cd %d @ 0x%"PFMT64x, vsize, from);
r_core_cmdf (core, "f+ aav.0x%08"PFMT64x "= 0x%08"PFMT64x, to, to);
#endif
}
}
static void cmd_anal_aav(RCore *core, const char *input) {
#define seti(x,y) r_config_set_i(core->config, x, y);
#define geti(x) r_config_get_i(core->config, x);
ut64 o_align = geti ("search.align");
bool asterisk = strchr (input, '*');;
bool is_debug = r_config_get_i (core->config, "cfg.debug");
// pre
int archAlign = r_anal_archinfo (core->anal, R_ANAL_ARCHINFO_ALIGN);
seti ("search.align", archAlign);
int vsize = 4; // 32bit dword
if (core->assembler->bits == 64) {
vsize = 8;
}
// body
oldstr = r_print_rowlog (core->print, "Analyze value pointers (aav)");
r_print_rowlog_done (core->print, oldstr);
r_cons_break_push (NULL, NULL);
if (is_debug) {
RList *list = r_core_get_boundaries_prot (core, 0, "dbg.map", "anal");
RListIter *iter;
RIOMap *map;
if (!list) {
goto beach;
}
r_list_foreach (list, iter, map) {
if (r_cons_is_breaked ()) {
break;
}
oldstr = r_print_rowlog (core->print, sdb_fmt ("from 0x%"PFMT64x" to 0x%"PFMT64x" (aav)", map->itv.addr, r_itv_end (map->itv)));
r_print_rowlog_done (core->print, oldstr);
(void)r_core_search_value_in_range (core, map->itv,
map->itv.addr, r_itv_end (map->itv), vsize, asterisk, _CbInRangeAav);
}
r_list_free (list);
} else {
RList *list = r_core_get_boundaries_prot (core, 0, NULL, "anal");
if (!list) {
goto beach;
}
RListIter *iter, *iter2;
RIOMap *map, *map2;
ut64 from = UT64_MAX;
ut64 to = UT64_MAX;
// find values pointing to non-executable regions
r_list_foreach (list, iter2, map2) {
if (r_cons_is_breaked ()) {
break;
}
//TODO: Reduce multiple hits for same addr
from = r_itv_begin (map2->itv);
to = r_itv_end (map2->itv);
oldstr = r_print_rowlog (core->print, sdb_fmt ("Value from 0x%08"PFMT64x " to 0x%08" PFMT64x " (aav)", from, to));
r_print_rowlog_done (core->print, oldstr);
r_list_foreach (list, iter, map) {
ut64 begin = map->itv.addr;
ut64 end = r_itv_end (map->itv);
if (r_cons_is_breaked ()) {
break;
}
if (end - begin > UT32_MAX) {
oldstr = r_print_rowlog (core->print, "Skipping huge range");
r_print_rowlog_done (core->print, oldstr);
continue;
}
oldstr = r_print_rowlog (core->print, sdb_fmt ("0x%08"PFMT64x"-0x%08"PFMT64x" in 0x%"PFMT64x"-0x%"PFMT64x" (aav)", from, to, begin, end));
r_print_rowlog_done (core->print, oldstr);
(void)r_core_search_value_in_range (core, map->itv, from, to, vsize, asterisk, _CbInRangeAav);
}
}
r_list_free (list);
}
beach:
r_cons_break_pop ();
// end
seti ("search.align", o_align);
}
static void cmd_anal_abt(RCore *core, const char *input) {
bool json = false;
switch (*input) {
case '?': r_core_cmd_help (core, help_msg_abt); break;
case 'j':
json = true;
input++;
case ' ': {
ut64 addr;
char *p;
int n = 1;
p = strchr (input + 1, ' ');
if (p) {
*p = '\0';
n = *(++p)? r_num_math (core->num, p): 1;
}
addr = r_num_math (core->num, input + 1);
RList *paths = r_core_anal_graph_to (core, addr, n);
if (paths) {
RAnalBlock *bb;
RList *path;
RListIter *pathi;
RListIter *bbi;
bool first_path = true, first_bb = true;
if (json) {
r_cons_printf ("[");
}
r_list_foreach (paths, pathi, path) {
if (json) {
if (!first_path) {
r_cons_printf (", ");
}
}
r_cons_printf ("[");
r_list_foreach (path, bbi, bb) {
if (json && !first_bb) {
r_cons_printf (", ");
}
r_cons_printf ("0x%08" PFMT64x, bb->addr);
if (!json) {
r_cons_printf ("\n");
}
first_bb = false;
}
r_cons_printf ("%s", json? "]": "\n");
first_bb = true;
first_path = false;
r_list_purge (path);
free (path);
}
if (json) {
r_cons_printf ("]\n");
}
r_list_purge (paths);
free (paths);
}
}
case '\0':
break;
}
}
static int cmd_anal_all(RCore *core, const char *input) {
switch (*input) {
case '?':
r_core_cmd_help (core, help_msg_aa);
break;
case 'b': // "aab"
cmd_anal_blocks (core, input + 1);
break;
case 'f': // "aaf"
{
const int analHasnext = r_config_get_i (core->config, "anal.hasnext");
r_config_set_i (core->config, "anal.hasnext", true);
r_core_cmd0 (core, "afr@@c:isq");
r_config_set_i (core->config, "anal.hasnext", analHasnext);
break;
}
case 'c': // "aac"
switch (input[1]) {
case '*': // "aac*"
cmd_anal_calls (core, input + 1, true, false);
break;
case 'i': // "aaci"
cmd_anal_calls (core, input + 1, input[2] == '*', true);
break;
case '?': // "aac?"
eprintf ("Usage: aac, aac* or aaci (imports xrefs only)\n");
break;
default: // "aac"
cmd_anal_calls (core, input + 1, false, false);
break;
}
case 'j': // "aaj"
cmd_anal_jumps (core, input + 1);
break;
case '*': // "aa*"
r_core_cmd0 (core, "af @@ sym.*");
r_core_cmd0 (core, "af @@ entry*");
break;
case 'd': // "aad"
cmd_anal_aad (core, input);
break;
case 'v': // "aav"
cmd_anal_aav (core, input);
break;
case 'u': // "aau" - print areas not covered by functions
r_core_anal_nofunclist (core, input + 1);
break;
case 'i': // "aai"
r_core_anal_info (core, input + 1);
break;
case 's': // "aas"
r_core_cmd0 (core, "af @@= `isq~[0]`");
r_core_cmd0 (core, "af @@ entry*");
break;
case 'n': // "aan"
switch (input[1]) {
case 'g': // "aang"
r_core_anal_autoname_all_golang_fcns (core);
break;
default: // "aan"
r_core_anal_autoname_all_fcns (core);
}
break;
case 'p': // "aap"
if (*input == '?') {
// TODO: accept parameters for ranges
eprintf ("Usage: /aap ; find in memory for function preludes");
} else {
r_core_search_preludes (core);
}
break;
case '\0': // "aa"
case 'a':
if (input[0] && (input[1] == '?' || (input[1] && input[2] == '?'))) {
r_cons_println ("Usage: See aa? for more help");
} else {
char *dh_orig = NULL;
if (!strncmp (input, "aaaaa", 5)) {
eprintf ("An r2 developer is coming to your place to manually analyze this program. Please wait for it\n");
if (r_config_get_i (core->config, "scr.interactive")) {
r_cons_any_key (NULL);
}
goto jacuzzi;
}
ut64 curseek = core->offset;
oldstr = r_print_rowlog (core->print, "Analyze all flags starting with sym. and entry0 (aa)");
r_cons_break_push (NULL, NULL);
r_cons_break_timeout (r_config_get_i (core->config, "anal.timeout"));
r_core_anal_all (core);
r_print_rowlog_done (core->print, oldstr);
// Run pending analysis immediately after analysis
// Usefull when running commands with ";" or via r2 -c,-i
run_pending_anal (core);
dh_orig = core->dbg->h
? strdup (core->dbg->h->name)
: strdup ("esil");
if (core->io && core->io->desc && core->io->desc->plugin && !core->io->desc->plugin->isdbg) {
//use dh_origin if we are debugging
R_FREE (dh_orig);
}
if (r_cons_is_breaked ()) {
goto jacuzzi;
}
r_cons_clear_line (1);
if (*input == 'a') { // "aaa"
if (r_str_startswith (r_config_get (core->config, "bin.lang"), "go")) {
oldstr = r_print_rowlog (core->print, "Find function and symbol names from golang binaries (aang)");
r_print_rowlog_done (core->print, oldstr);
r_core_anal_autoname_all_golang_fcns (core);
oldstr = r_print_rowlog (core->print, "Analyze all flags starting with sym.go. (aF @@ sym.go.*)");
r_core_cmd0 (core, "aF @@ sym.go.*");
r_print_rowlog_done (core->print, oldstr);
}
if (dh_orig && strcmp (dh_orig, "esil")) {
r_core_cmd0 (core, "dL esil");
}
int c = r_config_get_i (core->config, "anal.calls");
if (!r_str_startswith (r_config_get (core->config, "asm.arch"), "x86")) {
r_core_cmd0 (core, "aav");
bool ioCache = r_config_get_i (core->config, "io.pcache");
r_config_set_i (core->config, "io.pcache", 1);
oldstr = r_print_rowlog (core->print, "Emulate code to find computed references (aae)");
r_core_cmd0 (core, "aae $SS @ $S");
r_print_rowlog_done (core->print, oldstr);
if (!ioCache) {
r_core_cmd0 (core, "wc-*");
}
r_config_set_i (core->config, "io.pcache", ioCache);
if (r_cons_is_breaked ()) {
goto jacuzzi;
}
}
r_config_set_i (core->config, "anal.calls", 1);
r_core_cmd0 (core, "s $S");
if (r_cons_is_breaked ()) {
goto jacuzzi;
}
oldstr = r_print_rowlog (core->print, "Analyze function calls (aac)");
(void)cmd_anal_calls (core, "", false, false); // "aac"
r_core_seek (core, curseek, 1);
// oldstr = r_print_rowlog (core->print, "Analyze data refs as code (LEA)");
// (void) cmd_anal_aad (core, NULL); // "aad"
r_print_rowlog_done (core->print, oldstr);
if (r_cons_is_breaked ()) {
goto jacuzzi;
}
oldstr = r_print_rowlog (core->print, "Analyze len bytes of instructions for references (aar)");
(void)r_core_anal_refs (core, ""); // "aar"
r_print_rowlog_done (core->print, oldstr);
if (r_cons_is_breaked ()) {
goto jacuzzi;
}
run_pending_anal (core);
r_config_set_i (core->config, "anal.calls", c);
if (r_cons_is_breaked ()) {
goto jacuzzi;
}
if (r_config_get_i (core->config, "anal.autoname")) {
oldstr = r_print_rowlog (core->print, "Constructing a function name for fcn.* and sym.func.* functions (aan)");
r_core_anal_autoname_all_fcns (core);
r_print_rowlog_done (core->print, oldstr);
}
if (core->anal->opt.vars) {
RAnalFunction *fcni;
RListIter *iter;
r_list_foreach (core->anal->fcns, iter, fcni) {
if (r_cons_is_breaked ()) {
break;
}
RList *list = r_anal_var_list (core->anal, fcni, 'r');
if (!r_list_empty (list)) {
r_list_free (list);
continue;
}
//extract only reg based var here
r_core_recover_vars (core, fcni, true);
r_list_free (list);
}
}
if (!sdb_isempty (core->anal->sdb_zigns)) {
oldstr = r_print_rowlog (core->print, "Check for zignature from zigns folder (z/)");
r_core_cmd0 (core, "z/");
r_print_rowlog_done (core->print, oldstr);
}
if (input[1] == 'a') { // "aaaa"
oldstr = r_print_rowlog (core->print, "Enable constraint types analysis for variables");
r_config_set (core->config, "anal.types.constraint", "true");
r_print_rowlog_done (core->print, oldstr);
} else {
oldstr = r_print_rowlog (core->print, "Type matching analysis for all functions (afta)");
r_core_cmd0 (core, "afta");
r_print_rowlog_done (core->print, oldstr);
oldstr = r_print_rowlog (core->print, "Use -AA or aaaa to perform additional experimental analysis.");
r_print_rowlog_done (core->print, oldstr);
}
r_core_cmd0 (core, "s-");
if (dh_orig) {
r_core_cmdf (core, "dL %s;dpa", dh_orig);
}
}
r_core_seek (core, curseek, 1);
jacuzzi:
flag_every_function (core);
r_cons_break_pop ();
R_FREE (dh_orig);
}
break;
case 't': { // "aat"
ut64 cur = core->offset;
bool hasnext = r_config_get_i (core->config, "anal.hasnext");
RListIter *iter;
RIOMap *map;
RList *list = r_core_get_boundaries_prot (core, R_PERM_X, NULL, "anal");
if (!list) {
break;
}
r_list_foreach (list, iter, map) {
r_core_seek (core, map->itv.addr, 1);
r_config_set_i (core->config, "anal.hasnext", 1);
r_core_cmd0 (core, "afr");
r_config_set_i (core->config, "anal.hasnext", hasnext);
}
r_list_free (list);
r_core_seek (core, cur, 1);
break;
}
case 'T': // "aaT"
cmd_anal_aftertraps (core, input + 1);
break;
case 'E': // "aaE"
r_core_cmd0 (core, "aef @@f");
break;
case 'e': // "aae"
if (input[1]) {
const char *len = (char *)input + 1;
char *addr = strchr (input + 2, ' ');
if (addr) {
*addr++ = 0;
}
r_core_anal_esil (core, len, addr);
} else {
ut64 at = core->offset;
RIOMap *map;
RListIter *iter;
RList *list = r_core_get_boundaries_prot (core, -1, NULL, "anal");
if (!list) {
break;
}
r_list_foreach (list, iter, map) {
r_core_seek (core, map->itv.addr, 1);
r_core_anal_esil (core, "$SS", NULL);
}
r_list_free (list);
r_core_seek (core, at, 1);
}
break;
case 'r':
(void)r_core_anal_refs (core, input + 1);
break;
default:
r_core_cmd_help (core, help_msg_aa);
break;
}
return true;
}
static bool anal_fcn_data (RCore *core, const char *input) {
RAnalFunction *fcn = r_anal_get_fcn_in (core->anal, core->offset, -1);
ut32 fcn_size = r_anal_fcn_size (fcn);
if (fcn) {
int i;
bool gap = false;
ut64 gap_addr = UT64_MAX;
char *bitmap = calloc (1, fcn_size);
if (bitmap) {
RAnalBlock *b;
RListIter *iter;
r_list_foreach (fcn->bbs, iter, b) {
int f = b->addr - fcn->addr;
int t = R_MIN (f + b->size, fcn_size);
if (f >= 0) {
while (f < t) {
bitmap[f++] = 1;
}
}
}
}
for (i = 0; i < fcn_size; i++) {
ut64 here = fcn->addr + i;
if (bitmap && bitmap[i]) {
if (gap) {
r_cons_printf ("Cd %d @ 0x%08"PFMT64x"\n", here - gap_addr, gap_addr);
gap = false;
}
gap_addr = UT64_MAX;
} else {
if (!gap) {
gap = true;
gap_addr = here;
}
}
}
if (gap) {
r_cons_printf ("Cd %d @ 0x%08"PFMT64x"\n", fcn->addr + fcn_size - gap_addr, gap_addr);
gap = false;
}
free (bitmap);
return true;
}
return false;
}
static bool anal_fcn_data_gaps (RCore *core, const char *input) {
ut64 end = UT64_MAX;
RAnalFunction *fcn;
RListIter *iter;
int i, wordsize = (core->assembler->bits == 64)? 8: 4;
r_list_sort (core->anal->fcns, cmpaddr);
r_list_foreach (core->anal->fcns, iter, fcn) {
if (end != UT64_MAX) {
int range = fcn->addr - end;
if (range > 0) {
for (i = 0; i + wordsize < range; i+= wordsize) {
r_cons_printf ("Cd %d @ 0x%08"PFMT64x"\n", wordsize, end + i);
}
r_cons_printf ("Cd %d @ 0x%08"PFMT64x"\n", range - i, end + i);
//r_cons_printf ("Cd %d @ 0x%08"PFMT64x"\n", range, end);
}
}
end = fcn->addr + r_anal_fcn_size (fcn);
}
return true;
}
static void cmd_anal_rtti(RCore *core, const char *input) {
switch (input[0]) {
case '\0': // "avr"
case 'j': // "avrj"
r_anal_rtti_print_at_vtable (core->anal, core->offset, input[0]);
break;
case 'a': // "avra"
r_anal_rtti_print_all (core->anal, input[1]);
break;
case 'D': { // "avrD"
char *dup = strdup (input + 1);
if (!dup) {
break;
}
char *name = r_str_trim (dup);
char *demangled = r_anal_rtti_demangle_class_name (core->anal, dup);
free (name);
if (demangled) {
r_cons_println (demangled);
free (demangled);
}
break;
}
default :
r_core_cmd_help (core, help_msg_av);
break;
}
}
static void cmd_anal_virtual_functions(RCore *core, const char* input) {
switch (input[0]) {
case '\0': // "av"
case '*': // "av*"
case 'j': // "avj"
r_anal_list_vtables (core->anal, input[0]);
break;
case 'r': // "avr"
cmd_anal_rtti (core, input + 1);
break;
default :
r_core_cmd_help (core, help_msg_av);
break;
}
}
static int cmd_anal(void *data, const char *input) {
const char *r;
RCore *core = (RCore *)data;
ut32 tbs = core->blocksize;
switch (input[0]) {
case 'p': // "ap"
{
const ut8 *prelude = (const ut8*)"\xe9\x2d"; //:fffff000";
const int prelude_sz = 2;
const int bufsz = 4096;
ut8 *buf = calloc (1, bufsz);
ut64 off = core->offset;
if (input[1] == ' ') {
off = r_num_math (core->num, input+1);
r_io_read_at (core->io, off - bufsz + prelude_sz, buf, bufsz);
} else {
r_io_read_at (core->io, off - bufsz + prelude_sz, buf, bufsz);
}
//const char *prelude = "\x2d\xe9\xf0\x47"; //:fffff000";
r_mem_reverse (buf, bufsz);
//r_print_hexdump (NULL, off, buf, bufsz, 16, -16);
const ut8 *pos = r_mem_mem (buf, bufsz, prelude, prelude_sz);
if (pos) {
int delta = (size_t)(pos - buf);
eprintf ("POS = %d\n", delta);
eprintf ("HIT = 0x%"PFMT64x"\n", off - delta);
r_cons_printf ("0x%08"PFMT64x"\n", off - delta);
} else {
eprintf ("Cannot find prelude\n");
}
free (buf);
}
break;
case '8':
{
ut8 *buf = malloc (strlen (input) + 1);
if (buf) {
int len = r_hex_str2bin (input + 1, buf);
if (len > 0) {
core_anal_bytes (core, buf, len, 0, input[1]);
}
free (buf);
}
}
break;
case 'b':
if (input[1] == 'b') { // "abb"
core_anal_bbs (core, input + 2);
} else if (input[1] == 'r') { // "abr"
core_anal_bbs_range (core, input + 2);
} else if (input[1] == 't') {
cmd_anal_abt (core, input+2);
} else if (input[1] == 'j') { // "abj"
anal_fcn_list_bb (core, input + 1, false);
} else if (input[1] == ' ' || !input[1]) {
// find block
ut64 addr = core->offset;
if (input[1]) {
addr = r_num_math (core->num, input + 1);
}
r_core_cmdf (core, "afbi @ 0x%"PFMT64x, addr);
} else {
r_core_cmd_help (core, help_msg_ab);
}
break;
case 'L': return r_core_cmd0 (core, "e asm.arch=??"); break;
case 'i': cmd_anal_info (core, input + 1); break; // "ai"
case 'r': cmd_anal_reg (core, input + 1); break; // "ar"
case 'e': cmd_anal_esil (core, input + 1); break; // "ae"
case 'o': cmd_anal_opcode (core, input + 1); break; // "ao"
case 'O': cmd_anal_bytes (core, input + 1); break; // "aO"
case 'F': // "aF"
r_core_anal_fcn (core, core->offset, UT64_MAX, R_ANAL_REF_TYPE_NULL, 1);
break;
case 'f': // "af"
{
int res = cmd_anal_fcn (core, input);
run_pending_anal (core);
if (!res) {
return false;
}
}
break;
case 'n': // 'an'
{
const char *name = NULL;
bool use_json = false;
if (input[1] == 'j') {
use_json = true;
input++;
}
if (input[1] == ' ') {
name = input + 1;
while (name[0] == ' ') {
name++;
}
char *end = strchr (name, ' ');
if (end) {
*end = '\0';
}
if (*name == '\0') {
name = NULL;
}
}
cmd_an (core, use_json, name);
}
break;
case 'g': // "ag"
cmd_anal_graph (core, input + 1);
break;
case 's': // "as"
cmd_anal_syscall (core, input + 1);
break;
case 'v': // "av"
cmd_anal_virtual_functions (core, input + 1);
break;
case 'x': // "ax"
if (!cmd_anal_refs (core, input + 1)) {
return false;
}
break;
case 'a': // "aa"
if (!cmd_anal_all (core, input + 1)) {
return false;
}
break;
case 'c': // "ac"
{
RList *hooks;
RListIter *iter;
RAnalCycleHook *hook;
char *instr_tmp = NULL;
int ccl = input[1]? r_num_math (core->num, &input[2]): 0; //get cycles to look for
int cr = r_config_get_i (core->config, "asm.cmt.right");
int fun = r_config_get_i (core->config, "asm.functions");
int li = r_config_get_i (core->config, "asm.lines");
int xr = r_config_get_i (core->config, "asm.xrefs");
r_config_set_i (core->config, "asm.cmt.right", true);
r_config_set_i (core->config, "asm.functions", false);
r_config_set_i (core->config, "asm.lines", false);
r_config_set_i (core->config, "asm.xrefs", false);
hooks = r_core_anal_cycles (core, ccl); //analyse
r_cons_clear_line (1);
r_list_foreach (hooks, iter, hook) {
instr_tmp = r_core_disassemble_instr (core, hook->addr, 1);
r_cons_printf ("After %4i cycles:\t%s", (ccl - hook->cycles), instr_tmp);
r_cons_flush ();
free (instr_tmp);
}
r_list_free (hooks);
r_config_set_i (core->config, "asm.cmt.right", cr); //reset settings
r_config_set_i (core->config, "asm.functions", fun);
r_config_set_i (core->config, "asm.lines", li);
r_config_set_i (core->config, "asm.xrefs", xr);
}
break;
case 'd': // "ad"
switch (input[1]) {
case 'f': // "adf"
if (input[2] == 'g') {
anal_fcn_data_gaps (core, input + 1);
} else {
anal_fcn_data (core, input + 1);
}
break;
case 't': // "adt"
cmd_anal_trampoline (core, input + 2);
break;
case ' ': { // "ad"
const int default_depth = 1;
const char *p;
int a, b;
a = r_num_math (core->num, input + 2);
p = strchr (input + 2, ' ');
b = p? r_num_math (core->num, p + 1): default_depth;
if (a < 1) {
a = 1;
}
if (b < 1) {
b = 1;
}
r_core_anal_data (core, core->offset, a, b, 0);
} break;
case 'k': // "adk"
r = r_anal_data_kind (core->anal,
core->offset, core->block, core->blocksize);
r_cons_println (r);
break;
case '\0': // "ad"
r_core_anal_data (core, core->offset, 2 + (core->blocksize / 4), 1, 0);
break;
case '4': // "ad4"
r_core_anal_data (core, core->offset, 2 + (core->blocksize / 4), 1, 4);
break;
case '8': // "ad8"
r_core_anal_data (core, core->offset, 2 + (core->blocksize / 4), 1, 8);
break;
default:
r_core_cmd_help (core, help_msg_ad);
break;
}
break;
case 'h': // "ah"
cmd_anal_hint (core, input + 1);
break;
case '!': // "a!"
if (core->anal && core->anal->cur && core->anal->cur->cmd_ext) {
return core->anal->cur->cmd_ext (core->anal, input + 1);
} else {
r_cons_printf ("No plugins for this analysis plugin\n");
}
break;
default:
r_core_cmd_help (core, help_msg_a);
#if 0
r_cons_printf ("Examples:\n"
" f ts @ `S*~text:0[3]`; f t @ section..text\n"
" f ds @ `S*~data:0[3]`; f d @ section..data\n"
" .ad t t+ts @ d:ds\n",
NULL);
#endif
break;
}
if (tbs != core->blocksize) {
r_core_block_size (core, tbs);
}
if (r_cons_is_breaked ()) {
r_cons_clear_line (1);
}
return 0;
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/good_504_0 |
crossvul-cpp_data_bad_2644_1 | /*
* Copyright (c) 1994, 1995, 1996, 1997
* The Regents of the University of California. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that: (1) source code distributions
* retain the above copyright notice and this paragraph in its entirety, (2)
* distributions including binary code include the above copyright notice and
* this paragraph in its entirety in the documentation or other materials
* provided with the distribution, and (3) all advertising materials mentioning
* features or use of this software display the following acknowledgement:
* ``This product includes software developed by the University of California,
* Lawrence Berkeley Laboratory and its contributors.'' Neither the name of
* the University nor the names of its contributors may be used to endorse
* or promote products derived from this software without specific prior
* written permission.
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
/* \summary: Asynchronous Transfer Mode (ATM) printer */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <netdissect-stdinc.h>
#include "netdissect.h"
#include "extract.h"
#include "addrtoname.h"
#include "atm.h"
#include "llc.h"
/* start of the original atmuni31.h */
/*
* Copyright (c) 1997 Yen Yen Lim and North Dakota State University
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by Yen Yen Lim and
North Dakota State University
* 4. 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.
*/
/* Based on UNI3.1 standard by ATM Forum */
/* ATM traffic types based on VPI=0 and (the following VCI */
#define VCI_PPC 0x05 /* Point-to-point signal msg */
#define VCI_BCC 0x02 /* Broadcast signal msg */
#define VCI_OAMF4SC 0x03 /* Segment OAM F4 flow cell */
#define VCI_OAMF4EC 0x04 /* End-to-end OAM F4 flow cell */
#define VCI_METAC 0x01 /* Meta signal msg */
#define VCI_ILMIC 0x10 /* ILMI msg */
/* Q.2931 signalling messages */
#define CALL_PROCEED 0x02 /* call proceeding */
#define CONNECT 0x07 /* connect */
#define CONNECT_ACK 0x0f /* connect_ack */
#define SETUP 0x05 /* setup */
#define RELEASE 0x4d /* release */
#define RELEASE_DONE 0x5a /* release_done */
#define RESTART 0x46 /* restart */
#define RESTART_ACK 0x4e /* restart ack */
#define STATUS 0x7d /* status */
#define STATUS_ENQ 0x75 /* status ack */
#define ADD_PARTY 0x80 /* add party */
#define ADD_PARTY_ACK 0x81 /* add party ack */
#define ADD_PARTY_REJ 0x82 /* add party rej */
#define DROP_PARTY 0x83 /* drop party */
#define DROP_PARTY_ACK 0x84 /* drop party ack */
/* Information Element Parameters in the signalling messages */
#define CAUSE 0x08 /* cause */
#define ENDPT_REF 0x54 /* endpoint reference */
#define AAL_PARA 0x58 /* ATM adaptation layer parameters */
#define TRAFF_DESCRIP 0x59 /* atm traffic descriptors */
#define CONNECT_ID 0x5a /* connection identifier */
#define QOS_PARA 0x5c /* quality of service parameters */
#define B_HIGHER 0x5d /* broadband higher layer information */
#define B_BEARER 0x5e /* broadband bearer capability */
#define B_LOWER 0x5f /* broadband lower information */
#define CALLING_PARTY 0x6c /* calling party number */
#define CALLED_PARTY 0x70 /* called party nmber */
#define Q2931 0x09
/* Q.2931 signalling general messages format */
#define PROTO_POS 0 /* offset of protocol discriminator */
#define CALL_REF_POS 2 /* offset of call reference value */
#define MSG_TYPE_POS 5 /* offset of message type */
#define MSG_LEN_POS 7 /* offset of mesage length */
#define IE_BEGIN_POS 9 /* offset of first information element */
/* format of signalling messages */
#define TYPE_POS 0
#define LEN_POS 2
#define FIELD_BEGIN_POS 4
/* end of the original atmuni31.h */
static const char tstr[] = "[|atm]";
#define OAM_CRC10_MASK 0x3ff
#define OAM_PAYLOAD_LEN 48
#define OAM_FUNCTION_SPECIFIC_LEN 45 /* this excludes crc10 and cell-type/function-type */
#define OAM_CELLTYPE_FUNCTYPE_LEN 1
static const struct tok oam_f_values[] = {
{ VCI_OAMF4SC, "OAM F4 (segment)" },
{ VCI_OAMF4EC, "OAM F4 (end)" },
{ 0, NULL }
};
static const struct tok atm_pty_values[] = {
{ 0x0, "user data, uncongested, SDU 0" },
{ 0x1, "user data, uncongested, SDU 1" },
{ 0x2, "user data, congested, SDU 0" },
{ 0x3, "user data, congested, SDU 1" },
{ 0x4, "VCC OAM F5 flow segment" },
{ 0x5, "VCC OAM F5 flow end-to-end" },
{ 0x6, "Traffic Control and resource Mgmt" },
{ 0, NULL }
};
#define OAM_CELLTYPE_FM 0x1
#define OAM_CELLTYPE_PM 0x2
#define OAM_CELLTYPE_AD 0x8
#define OAM_CELLTYPE_SM 0xf
static const struct tok oam_celltype_values[] = {
{ OAM_CELLTYPE_FM, "Fault Management" },
{ OAM_CELLTYPE_PM, "Performance Management" },
{ OAM_CELLTYPE_AD, "activate/deactivate" },
{ OAM_CELLTYPE_SM, "System Management" },
{ 0, NULL }
};
#define OAM_FM_FUNCTYPE_AIS 0x0
#define OAM_FM_FUNCTYPE_RDI 0x1
#define OAM_FM_FUNCTYPE_CONTCHECK 0x4
#define OAM_FM_FUNCTYPE_LOOPBACK 0x8
static const struct tok oam_fm_functype_values[] = {
{ OAM_FM_FUNCTYPE_AIS, "AIS" },
{ OAM_FM_FUNCTYPE_RDI, "RDI" },
{ OAM_FM_FUNCTYPE_CONTCHECK, "Continuity Check" },
{ OAM_FM_FUNCTYPE_LOOPBACK, "Loopback" },
{ 0, NULL }
};
static const struct tok oam_pm_functype_values[] = {
{ 0x0, "Forward Monitoring" },
{ 0x1, "Backward Reporting" },
{ 0x2, "Monitoring and Reporting" },
{ 0, NULL }
};
static const struct tok oam_ad_functype_values[] = {
{ 0x0, "Performance Monitoring" },
{ 0x1, "Continuity Check" },
{ 0, NULL }
};
#define OAM_FM_LOOPBACK_INDICATOR_MASK 0x1
static const struct tok oam_fm_loopback_indicator_values[] = {
{ 0x0, "Reply" },
{ 0x1, "Request" },
{ 0, NULL }
};
static const struct tok *oam_functype_values[16] = {
NULL,
oam_fm_functype_values, /* 1 */
oam_pm_functype_values, /* 2 */
NULL,
NULL,
NULL,
NULL,
NULL,
oam_ad_functype_values, /* 8 */
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL
};
/*
* Print an RFC 1483 LLC-encapsulated ATM frame.
*/
static u_int
atm_llc_print(netdissect_options *ndo,
const u_char *p, int length, int caplen)
{
int llc_hdrlen;
llc_hdrlen = llc_print(ndo, p, length, caplen, NULL, NULL);
if (llc_hdrlen < 0) {
/* packet not known, print raw packet */
if (!ndo->ndo_suppress_default_print)
ND_DEFAULTPRINT(p, caplen);
llc_hdrlen = -llc_hdrlen;
}
return (llc_hdrlen);
}
/*
* Given a SAP value, generate the LLC header value for a UI packet
* with that SAP as the source and destination SAP.
*/
#define LLC_UI_HDR(sap) ((sap)<<16 | (sap<<8) | 0x03)
/*
* This is the top level routine of the printer. 'p' points
* to the LLC/SNAP header of the packet, 'h->ts' is the timestamp,
* 'h->len' is the length of the packet off the wire, and 'h->caplen'
* is the number of bytes actually captured.
*/
u_int
atm_if_print(netdissect_options *ndo,
const struct pcap_pkthdr *h, const u_char *p)
{
u_int caplen = h->caplen;
u_int length = h->len;
uint32_t llchdr;
u_int hdrlen = 0;
if (caplen < 1 || length < 1) {
ND_PRINT((ndo, "%s", tstr));
return (caplen);
}
/* Cisco Style NLPID ? */
if (*p == LLC_UI) {
if (ndo->ndo_eflag)
ND_PRINT((ndo, "CNLPID "));
isoclns_print(ndo, p + 1, length - 1, caplen - 1);
return hdrlen;
}
/*
* Must have at least a DSAP, an SSAP, and the first byte of the
* control field.
*/
if (caplen < 3 || length < 3) {
ND_PRINT((ndo, "%s", tstr));
return (caplen);
}
/*
* Extract the presumed LLC header into a variable, for quick
* testing.
* Then check for a header that's neither a header for a SNAP
* packet nor an RFC 2684 routed NLPID-formatted PDU nor
* an 802.2-but-no-SNAP IP packet.
*/
llchdr = EXTRACT_24BITS(p);
if (llchdr != LLC_UI_HDR(LLCSAP_SNAP) &&
llchdr != LLC_UI_HDR(LLCSAP_ISONS) &&
llchdr != LLC_UI_HDR(LLCSAP_IP)) {
/*
* XXX - assume 802.6 MAC header from Fore driver.
*
* Unfortunately, the above list doesn't check for
* all known SAPs, doesn't check for headers where
* the source and destination SAP aren't the same,
* and doesn't check for non-UI frames. It also
* runs the risk of an 802.6 MAC header that happens
* to begin with one of those values being
* incorrectly treated as an 802.2 header.
*
* So is that Fore driver still around? And, if so,
* is it still putting 802.6 MAC headers on ATM
* packets? If so, could it be changed to use a
* new DLT_IEEE802_6 value if we added it?
*/
if (caplen < 20 || length < 20) {
ND_PRINT((ndo, "%s", tstr));
return (caplen);
}
if (ndo->ndo_eflag)
ND_PRINT((ndo, "%08x%08x %08x%08x ",
EXTRACT_32BITS(p),
EXTRACT_32BITS(p+4),
EXTRACT_32BITS(p+8),
EXTRACT_32BITS(p+12)));
p += 20;
length -= 20;
caplen -= 20;
hdrlen += 20;
}
hdrlen += atm_llc_print(ndo, p, length, caplen);
return (hdrlen);
}
/*
* ATM signalling.
*/
static const struct tok msgtype2str[] = {
{ CALL_PROCEED, "Call_proceeding" },
{ CONNECT, "Connect" },
{ CONNECT_ACK, "Connect_ack" },
{ SETUP, "Setup" },
{ RELEASE, "Release" },
{ RELEASE_DONE, "Release_complete" },
{ RESTART, "Restart" },
{ RESTART_ACK, "Restart_ack" },
{ STATUS, "Status" },
{ STATUS_ENQ, "Status_enquiry" },
{ ADD_PARTY, "Add_party" },
{ ADD_PARTY_ACK, "Add_party_ack" },
{ ADD_PARTY_REJ, "Add_party_reject" },
{ DROP_PARTY, "Drop_party" },
{ DROP_PARTY_ACK, "Drop_party_ack" },
{ 0, NULL }
};
static void
sig_print(netdissect_options *ndo,
const u_char *p)
{
uint32_t call_ref;
ND_TCHECK(p[PROTO_POS]);
if (p[PROTO_POS] == Q2931) {
/*
* protocol:Q.2931 for User to Network Interface
* (UNI 3.1) signalling
*/
ND_PRINT((ndo, "Q.2931"));
ND_TCHECK(p[MSG_TYPE_POS]);
ND_PRINT((ndo, ":%s ",
tok2str(msgtype2str, "msgtype#%d", p[MSG_TYPE_POS])));
/*
* The call reference comes before the message type,
* so if we know we have the message type, which we
* do from the caplen test above, we also know we have
* the call reference.
*/
call_ref = EXTRACT_24BITS(&p[CALL_REF_POS]);
ND_PRINT((ndo, "CALL_REF:0x%06x", call_ref));
} else {
/* SSCOP with some unknown protocol atop it */
ND_PRINT((ndo, "SSCOP, proto %d ", p[PROTO_POS]));
}
return;
trunc:
ND_PRINT((ndo, " %s", tstr));
}
/*
* Print an ATM PDU (such as an AAL5 PDU).
*/
void
atm_print(netdissect_options *ndo,
u_int vpi, u_int vci, u_int traftype, const u_char *p, u_int length,
u_int caplen)
{
if (ndo->ndo_eflag)
ND_PRINT((ndo, "VPI:%u VCI:%u ", vpi, vci));
if (vpi == 0) {
switch (vci) {
case VCI_PPC:
sig_print(ndo, p);
return;
case VCI_BCC:
ND_PRINT((ndo, "broadcast sig: "));
return;
case VCI_OAMF4SC: /* fall through */
case VCI_OAMF4EC:
oam_print(ndo, p, length, ATM_OAM_HEC);
return;
case VCI_METAC:
ND_PRINT((ndo, "meta: "));
return;
case VCI_ILMIC:
ND_PRINT((ndo, "ilmi: "));
snmp_print(ndo, p, length);
return;
}
}
switch (traftype) {
case ATM_LLC:
default:
/*
* Assumes traffic is LLC if unknown.
*/
atm_llc_print(ndo, p, length, caplen);
break;
case ATM_LANE:
lane_print(ndo, p, length, caplen);
break;
}
}
struct oam_fm_loopback_t {
uint8_t loopback_indicator;
uint8_t correlation_tag[4];
uint8_t loopback_id[12];
uint8_t source_id[12];
uint8_t unused[16];
};
struct oam_fm_ais_rdi_t {
uint8_t failure_type;
uint8_t failure_location[16];
uint8_t unused[28];
};
void
oam_print (netdissect_options *ndo,
const u_char *p, u_int length, u_int hec)
{
uint32_t cell_header;
uint16_t vpi, vci, cksum, cksum_shouldbe, idx;
uint8_t cell_type, func_type, payload, clp;
union {
const struct oam_fm_loopback_t *oam_fm_loopback;
const struct oam_fm_ais_rdi_t *oam_fm_ais_rdi;
} oam_ptr;
ND_TCHECK(*(p+ATM_HDR_LEN_NOHEC+hec));
cell_header = EXTRACT_32BITS(p+hec);
cell_type = ((*(p+ATM_HDR_LEN_NOHEC+hec))>>4) & 0x0f;
func_type = (*(p+ATM_HDR_LEN_NOHEC+hec)) & 0x0f;
vpi = (cell_header>>20)&0xff;
vci = (cell_header>>4)&0xffff;
payload = (cell_header>>1)&0x7;
clp = cell_header&0x1;
ND_PRINT((ndo, "%s, vpi %u, vci %u, payload [ %s ], clp %u, length %u",
tok2str(oam_f_values, "OAM F5", vci),
vpi, vci,
tok2str(atm_pty_values, "Unknown", payload),
clp, length));
if (!ndo->ndo_vflag) {
return;
}
ND_PRINT((ndo, "\n\tcell-type %s (%u)",
tok2str(oam_celltype_values, "unknown", cell_type),
cell_type));
if (oam_functype_values[cell_type] == NULL)
ND_PRINT((ndo, ", func-type unknown (%u)", func_type));
else
ND_PRINT((ndo, ", func-type %s (%u)",
tok2str(oam_functype_values[cell_type],"none",func_type),
func_type));
p += ATM_HDR_LEN_NOHEC + hec;
switch (cell_type << 4 | func_type) {
case (OAM_CELLTYPE_FM << 4 | OAM_FM_FUNCTYPE_LOOPBACK):
oam_ptr.oam_fm_loopback = (const struct oam_fm_loopback_t *)(p + OAM_CELLTYPE_FUNCTYPE_LEN);
ND_TCHECK(*oam_ptr.oam_fm_loopback);
ND_PRINT((ndo, "\n\tLoopback-Indicator %s, Correlation-Tag 0x%08x",
tok2str(oam_fm_loopback_indicator_values,
"Unknown",
oam_ptr.oam_fm_loopback->loopback_indicator & OAM_FM_LOOPBACK_INDICATOR_MASK),
EXTRACT_32BITS(&oam_ptr.oam_fm_loopback->correlation_tag)));
ND_PRINT((ndo, "\n\tLocation-ID "));
for (idx = 0; idx < sizeof(oam_ptr.oam_fm_loopback->loopback_id); idx++) {
if (idx % 2) {
ND_PRINT((ndo, "%04x ", EXTRACT_16BITS(&oam_ptr.oam_fm_loopback->loopback_id[idx])));
}
}
ND_PRINT((ndo, "\n\tSource-ID "));
for (idx = 0; idx < sizeof(oam_ptr.oam_fm_loopback->source_id); idx++) {
if (idx % 2) {
ND_PRINT((ndo, "%04x ", EXTRACT_16BITS(&oam_ptr.oam_fm_loopback->source_id[idx])));
}
}
break;
case (OAM_CELLTYPE_FM << 4 | OAM_FM_FUNCTYPE_AIS):
case (OAM_CELLTYPE_FM << 4 | OAM_FM_FUNCTYPE_RDI):
oam_ptr.oam_fm_ais_rdi = (const struct oam_fm_ais_rdi_t *)(p + OAM_CELLTYPE_FUNCTYPE_LEN);
ND_TCHECK(*oam_ptr.oam_fm_ais_rdi);
ND_PRINT((ndo, "\n\tFailure-type 0x%02x", oam_ptr.oam_fm_ais_rdi->failure_type));
ND_PRINT((ndo, "\n\tLocation-ID "));
for (idx = 0; idx < sizeof(oam_ptr.oam_fm_ais_rdi->failure_location); idx++) {
if (idx % 2) {
ND_PRINT((ndo, "%04x ", EXTRACT_16BITS(&oam_ptr.oam_fm_ais_rdi->failure_location[idx])));
}
}
break;
case (OAM_CELLTYPE_FM << 4 | OAM_FM_FUNCTYPE_CONTCHECK):
/* FIXME */
break;
default:
break;
}
/* crc10 checksum verification */
ND_TCHECK2(*(p + OAM_CELLTYPE_FUNCTYPE_LEN + OAM_FUNCTION_SPECIFIC_LEN), 2);
cksum = EXTRACT_16BITS(p + OAM_CELLTYPE_FUNCTYPE_LEN + OAM_FUNCTION_SPECIFIC_LEN)
& OAM_CRC10_MASK;
cksum_shouldbe = verify_crc10_cksum(0, p, OAM_PAYLOAD_LEN);
ND_PRINT((ndo, "\n\tcksum 0x%03x (%scorrect)",
cksum,
cksum_shouldbe == 0 ? "" : "in"));
return;
trunc:
ND_PRINT((ndo, "[|oam]"));
return;
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_2644_1 |
crossvul-cpp_data_good_2722_0 | /*
* Copyright (C) 1999 WIDE Project.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the project nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* Extensively modified by Hannes Gredler (hannes@gredler.at) for more
* complete BGP support.
*/
/* \summary: Border Gateway Protocol (BGP) printer */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <netdissect-stdinc.h>
#include <stdio.h>
#include <string.h>
#include "netdissect.h"
#include "addrtoname.h"
#include "extract.h"
#include "af.h"
#include "l2vpn.h"
struct bgp {
uint8_t bgp_marker[16];
uint16_t bgp_len;
uint8_t bgp_type;
};
#define BGP_SIZE 19 /* unaligned */
#define BGP_OPEN 1
#define BGP_UPDATE 2
#define BGP_NOTIFICATION 3
#define BGP_KEEPALIVE 4
#define BGP_ROUTE_REFRESH 5
static const struct tok bgp_msg_values[] = {
{ BGP_OPEN, "Open"},
{ BGP_UPDATE, "Update"},
{ BGP_NOTIFICATION, "Notification"},
{ BGP_KEEPALIVE, "Keepalive"},
{ BGP_ROUTE_REFRESH, "Route Refresh"},
{ 0, NULL}
};
struct bgp_open {
uint8_t bgpo_marker[16];
uint16_t bgpo_len;
uint8_t bgpo_type;
uint8_t bgpo_version;
uint16_t bgpo_myas;
uint16_t bgpo_holdtime;
uint32_t bgpo_id;
uint8_t bgpo_optlen;
/* options should follow */
};
#define BGP_OPEN_SIZE 29 /* unaligned */
struct bgp_opt {
uint8_t bgpopt_type;
uint8_t bgpopt_len;
/* variable length */
};
#define BGP_OPT_SIZE 2 /* some compilers may pad to 4 bytes */
#define BGP_CAP_HEADER_SIZE 2 /* some compilers may pad to 4 bytes */
struct bgp_notification {
uint8_t bgpn_marker[16];
uint16_t bgpn_len;
uint8_t bgpn_type;
uint8_t bgpn_major;
uint8_t bgpn_minor;
};
#define BGP_NOTIFICATION_SIZE 21 /* unaligned */
struct bgp_route_refresh {
uint8_t bgp_marker[16];
uint16_t len;
uint8_t type;
uint8_t afi[2]; /* the compiler messes this structure up */
uint8_t res; /* when doing misaligned sequences of int8 and int16 */
uint8_t safi; /* afi should be int16 - so we have to access it using */
}; /* EXTRACT_16BITS(&bgp_route_refresh->afi) (sigh) */
#define BGP_ROUTE_REFRESH_SIZE 23
#define bgp_attr_lenlen(flags, p) \
(((flags) & 0x10) ? 2 : 1)
#define bgp_attr_len(flags, p) \
(((flags) & 0x10) ? EXTRACT_16BITS(p) : *(p))
#define BGPTYPE_ORIGIN 1
#define BGPTYPE_AS_PATH 2
#define BGPTYPE_NEXT_HOP 3
#define BGPTYPE_MULTI_EXIT_DISC 4
#define BGPTYPE_LOCAL_PREF 5
#define BGPTYPE_ATOMIC_AGGREGATE 6
#define BGPTYPE_AGGREGATOR 7
#define BGPTYPE_COMMUNITIES 8 /* RFC1997 */
#define BGPTYPE_ORIGINATOR_ID 9 /* RFC4456 */
#define BGPTYPE_CLUSTER_LIST 10 /* RFC4456 */
#define BGPTYPE_DPA 11 /* deprecated, draft-ietf-idr-bgp-dpa */
#define BGPTYPE_ADVERTISERS 12 /* deprecated RFC1863 */
#define BGPTYPE_RCID_PATH 13 /* deprecated RFC1863 */
#define BGPTYPE_MP_REACH_NLRI 14 /* RFC4760 */
#define BGPTYPE_MP_UNREACH_NLRI 15 /* RFC4760 */
#define BGPTYPE_EXTD_COMMUNITIES 16 /* RFC4360 */
#define BGPTYPE_AS4_PATH 17 /* RFC6793 */
#define BGPTYPE_AGGREGATOR4 18 /* RFC6793 */
#define BGPTYPE_PMSI_TUNNEL 22 /* RFC6514 */
#define BGPTYPE_TUNNEL_ENCAP 23 /* RFC5512 */
#define BGPTYPE_TRAFFIC_ENG 24 /* RFC5543 */
#define BGPTYPE_IPV6_EXTD_COMMUNITIES 25 /* RFC5701 */
#define BGPTYPE_AIGP 26 /* RFC7311 */
#define BGPTYPE_PE_DISTINGUISHER_LABEL 27 /* RFC6514 */
#define BGPTYPE_ENTROPY_LABEL 28 /* RFC6790 */
#define BGPTYPE_LARGE_COMMUNITY 32 /* draft-ietf-idr-large-community-05 */
#define BGPTYPE_ATTR_SET 128 /* RFC6368 */
#define BGP_MP_NLRI_MINSIZE 3 /* End of RIB Marker detection */
static const struct tok bgp_attr_values[] = {
{ BGPTYPE_ORIGIN, "Origin"},
{ BGPTYPE_AS_PATH, "AS Path"},
{ BGPTYPE_AS4_PATH, "AS4 Path"},
{ BGPTYPE_NEXT_HOP, "Next Hop"},
{ BGPTYPE_MULTI_EXIT_DISC, "Multi Exit Discriminator"},
{ BGPTYPE_LOCAL_PREF, "Local Preference"},
{ BGPTYPE_ATOMIC_AGGREGATE, "Atomic Aggregate"},
{ BGPTYPE_AGGREGATOR, "Aggregator"},
{ BGPTYPE_AGGREGATOR4, "Aggregator4"},
{ BGPTYPE_COMMUNITIES, "Community"},
{ BGPTYPE_ORIGINATOR_ID, "Originator ID"},
{ BGPTYPE_CLUSTER_LIST, "Cluster List"},
{ BGPTYPE_DPA, "DPA"},
{ BGPTYPE_ADVERTISERS, "Advertisers"},
{ BGPTYPE_RCID_PATH, "RCID Path / Cluster ID"},
{ BGPTYPE_MP_REACH_NLRI, "Multi-Protocol Reach NLRI"},
{ BGPTYPE_MP_UNREACH_NLRI, "Multi-Protocol Unreach NLRI"},
{ BGPTYPE_EXTD_COMMUNITIES, "Extended Community"},
{ BGPTYPE_PMSI_TUNNEL, "PMSI Tunnel"},
{ BGPTYPE_TUNNEL_ENCAP, "Tunnel Encapsulation"},
{ BGPTYPE_TRAFFIC_ENG, "Traffic Engineering"},
{ BGPTYPE_IPV6_EXTD_COMMUNITIES, "IPv6 Extended Community"},
{ BGPTYPE_AIGP, "Accumulated IGP Metric"},
{ BGPTYPE_PE_DISTINGUISHER_LABEL, "PE Distinguisher Label"},
{ BGPTYPE_ENTROPY_LABEL, "Entropy Label"},
{ BGPTYPE_LARGE_COMMUNITY, "Large Community"},
{ BGPTYPE_ATTR_SET, "Attribute Set"},
{ 255, "Reserved for development"},
{ 0, NULL}
};
#define BGP_AS_SET 1
#define BGP_AS_SEQUENCE 2
#define BGP_CONFED_AS_SEQUENCE 3 /* draft-ietf-idr-rfc3065bis-01 */
#define BGP_CONFED_AS_SET 4 /* draft-ietf-idr-rfc3065bis-01 */
#define BGP_AS_SEG_TYPE_MIN BGP_AS_SET
#define BGP_AS_SEG_TYPE_MAX BGP_CONFED_AS_SET
static const struct tok bgp_as_path_segment_open_values[] = {
{ BGP_AS_SEQUENCE, ""},
{ BGP_AS_SET, "{ "},
{ BGP_CONFED_AS_SEQUENCE, "( "},
{ BGP_CONFED_AS_SET, "({ "},
{ 0, NULL}
};
static const struct tok bgp_as_path_segment_close_values[] = {
{ BGP_AS_SEQUENCE, ""},
{ BGP_AS_SET, "}"},
{ BGP_CONFED_AS_SEQUENCE, ")"},
{ BGP_CONFED_AS_SET, "})"},
{ 0, NULL}
};
#define BGP_OPT_AUTH 1
#define BGP_OPT_CAP 2
static const struct tok bgp_opt_values[] = {
{ BGP_OPT_AUTH, "Authentication Information"},
{ BGP_OPT_CAP, "Capabilities Advertisement"},
{ 0, NULL}
};
#define BGP_CAPCODE_MP 1 /* RFC2858 */
#define BGP_CAPCODE_RR 2 /* RFC2918 */
#define BGP_CAPCODE_ORF 3 /* RFC5291 */
#define BGP_CAPCODE_MR 4 /* RFC3107 */
#define BGP_CAPCODE_EXT_NH 5 /* RFC5549 */
#define BGP_CAPCODE_RESTART 64 /* RFC4724 */
#define BGP_CAPCODE_AS_NEW 65 /* RFC6793 */
#define BGP_CAPCODE_DYN_CAP 67 /* draft-ietf-idr-dynamic-cap */
#define BGP_CAPCODE_MULTISESS 68 /* draft-ietf-idr-bgp-multisession */
#define BGP_CAPCODE_ADD_PATH 69 /* RFC7911 */
#define BGP_CAPCODE_ENH_RR 70 /* draft-keyur-bgp-enhanced-route-refresh */
#define BGP_CAPCODE_RR_CISCO 128
static const struct tok bgp_capcode_values[] = {
{ BGP_CAPCODE_MP, "Multiprotocol Extensions"},
{ BGP_CAPCODE_RR, "Route Refresh"},
{ BGP_CAPCODE_ORF, "Cooperative Route Filtering"},
{ BGP_CAPCODE_MR, "Multiple Routes to a Destination"},
{ BGP_CAPCODE_EXT_NH, "Extended Next Hop Encoding"},
{ BGP_CAPCODE_RESTART, "Graceful Restart"},
{ BGP_CAPCODE_AS_NEW, "32-Bit AS Number"},
{ BGP_CAPCODE_DYN_CAP, "Dynamic Capability"},
{ BGP_CAPCODE_MULTISESS, "Multisession BGP"},
{ BGP_CAPCODE_ADD_PATH, "Multiple Paths"},
{ BGP_CAPCODE_ENH_RR, "Enhanced Route Refresh"},
{ BGP_CAPCODE_RR_CISCO, "Route Refresh (Cisco)"},
{ 0, NULL}
};
#define BGP_NOTIFY_MAJOR_MSG 1
#define BGP_NOTIFY_MAJOR_OPEN 2
#define BGP_NOTIFY_MAJOR_UPDATE 3
#define BGP_NOTIFY_MAJOR_HOLDTIME 4
#define BGP_NOTIFY_MAJOR_FSM 5
#define BGP_NOTIFY_MAJOR_CEASE 6
#define BGP_NOTIFY_MAJOR_CAP 7
static const struct tok bgp_notify_major_values[] = {
{ BGP_NOTIFY_MAJOR_MSG, "Message Header Error"},
{ BGP_NOTIFY_MAJOR_OPEN, "OPEN Message Error"},
{ BGP_NOTIFY_MAJOR_UPDATE, "UPDATE Message Error"},
{ BGP_NOTIFY_MAJOR_HOLDTIME,"Hold Timer Expired"},
{ BGP_NOTIFY_MAJOR_FSM, "Finite State Machine Error"},
{ BGP_NOTIFY_MAJOR_CEASE, "Cease"},
{ BGP_NOTIFY_MAJOR_CAP, "Capability Message Error"},
{ 0, NULL}
};
/* draft-ietf-idr-cease-subcode-02 */
#define BGP_NOTIFY_MINOR_CEASE_MAXPRFX 1
/* draft-ietf-idr-shutdown-07 */
#define BGP_NOTIFY_MINOR_CEASE_SHUT 2
#define BGP_NOTIFY_MINOR_CEASE_RESET 4
#define BGP_NOTIFY_MINOR_CEASE_ADMIN_SHUTDOWN_LEN 128
static const struct tok bgp_notify_minor_cease_values[] = {
{ BGP_NOTIFY_MINOR_CEASE_MAXPRFX, "Maximum Number of Prefixes Reached"},
{ BGP_NOTIFY_MINOR_CEASE_SHUT, "Administrative Shutdown"},
{ 3, "Peer Unconfigured"},
{ BGP_NOTIFY_MINOR_CEASE_RESET, "Administrative Reset"},
{ 5, "Connection Rejected"},
{ 6, "Other Configuration Change"},
{ 7, "Connection Collision Resolution"},
{ 0, NULL}
};
static const struct tok bgp_notify_minor_msg_values[] = {
{ 1, "Connection Not Synchronized"},
{ 2, "Bad Message Length"},
{ 3, "Bad Message Type"},
{ 0, NULL}
};
static const struct tok bgp_notify_minor_open_values[] = {
{ 1, "Unsupported Version Number"},
{ 2, "Bad Peer AS"},
{ 3, "Bad BGP Identifier"},
{ 4, "Unsupported Optional Parameter"},
{ 5, "Authentication Failure"},
{ 6, "Unacceptable Hold Time"},
{ 7, "Capability Message Error"},
{ 0, NULL}
};
static const struct tok bgp_notify_minor_update_values[] = {
{ 1, "Malformed Attribute List"},
{ 2, "Unrecognized Well-known Attribute"},
{ 3, "Missing Well-known Attribute"},
{ 4, "Attribute Flags Error"},
{ 5, "Attribute Length Error"},
{ 6, "Invalid ORIGIN Attribute"},
{ 7, "AS Routing Loop"},
{ 8, "Invalid NEXT_HOP Attribute"},
{ 9, "Optional Attribute Error"},
{ 10, "Invalid Network Field"},
{ 11, "Malformed AS_PATH"},
{ 0, NULL}
};
static const struct tok bgp_notify_minor_fsm_values[] = {
{ 0, "Unspecified Error"},
{ 1, "In OpenSent State"},
{ 2, "In OpenConfirm State"},
{ 3, "In Established State"},
{ 0, NULL }
};
static const struct tok bgp_notify_minor_cap_values[] = {
{ 1, "Invalid Action Value" },
{ 2, "Invalid Capability Length" },
{ 3, "Malformed Capability Value" },
{ 4, "Unsupported Capability Code" },
{ 0, NULL }
};
static const struct tok bgp_origin_values[] = {
{ 0, "IGP"},
{ 1, "EGP"},
{ 2, "Incomplete"},
{ 0, NULL}
};
#define BGP_PMSI_TUNNEL_RSVP_P2MP 1
#define BGP_PMSI_TUNNEL_LDP_P2MP 2
#define BGP_PMSI_TUNNEL_PIM_SSM 3
#define BGP_PMSI_TUNNEL_PIM_SM 4
#define BGP_PMSI_TUNNEL_PIM_BIDIR 5
#define BGP_PMSI_TUNNEL_INGRESS 6
#define BGP_PMSI_TUNNEL_LDP_MP2MP 7
static const struct tok bgp_pmsi_tunnel_values[] = {
{ BGP_PMSI_TUNNEL_RSVP_P2MP, "RSVP-TE P2MP LSP"},
{ BGP_PMSI_TUNNEL_LDP_P2MP, "LDP P2MP LSP"},
{ BGP_PMSI_TUNNEL_PIM_SSM, "PIM-SSM Tree"},
{ BGP_PMSI_TUNNEL_PIM_SM, "PIM-SM Tree"},
{ BGP_PMSI_TUNNEL_PIM_BIDIR, "PIM-Bidir Tree"},
{ BGP_PMSI_TUNNEL_INGRESS, "Ingress Replication"},
{ BGP_PMSI_TUNNEL_LDP_MP2MP, "LDP MP2MP LSP"},
{ 0, NULL}
};
static const struct tok bgp_pmsi_flag_values[] = {
{ 0x01, "Leaf Information required"},
{ 0, NULL}
};
#define BGP_AIGP_TLV 1
static const struct tok bgp_aigp_values[] = {
{ BGP_AIGP_TLV, "AIGP"},
{ 0, NULL}
};
/* Subsequent address family identifier, RFC2283 section 7 */
#define SAFNUM_RES 0
#define SAFNUM_UNICAST 1
#define SAFNUM_MULTICAST 2
#define SAFNUM_UNIMULTICAST 3 /* deprecated now */
/* labeled BGP RFC3107 */
#define SAFNUM_LABUNICAST 4
/* RFC6514 */
#define SAFNUM_MULTICAST_VPN 5
/* draft-nalawade-kapoor-tunnel-safi */
#define SAFNUM_TUNNEL 64
/* RFC4761 */
#define SAFNUM_VPLS 65
/* RFC6037 */
#define SAFNUM_MDT 66
/* RFC4364 */
#define SAFNUM_VPNUNICAST 128
/* RFC6513 */
#define SAFNUM_VPNMULTICAST 129
#define SAFNUM_VPNUNIMULTICAST 130 /* deprecated now */
/* RFC4684 */
#define SAFNUM_RT_ROUTING_INFO 132
#define BGP_VPN_RD_LEN 8
static const struct tok bgp_safi_values[] = {
{ SAFNUM_RES, "Reserved"},
{ SAFNUM_UNICAST, "Unicast"},
{ SAFNUM_MULTICAST, "Multicast"},
{ SAFNUM_UNIMULTICAST, "Unicast+Multicast"},
{ SAFNUM_LABUNICAST, "labeled Unicast"},
{ SAFNUM_TUNNEL, "Tunnel"},
{ SAFNUM_VPLS, "VPLS"},
{ SAFNUM_MDT, "MDT"},
{ SAFNUM_VPNUNICAST, "labeled VPN Unicast"},
{ SAFNUM_VPNMULTICAST, "labeled VPN Multicast"},
{ SAFNUM_VPNUNIMULTICAST, "labeled VPN Unicast+Multicast"},
{ SAFNUM_RT_ROUTING_INFO, "Route Target Routing Information"},
{ SAFNUM_MULTICAST_VPN, "Multicast VPN"},
{ 0, NULL }
};
/* well-known community */
#define BGP_COMMUNITY_NO_EXPORT 0xffffff01
#define BGP_COMMUNITY_NO_ADVERT 0xffffff02
#define BGP_COMMUNITY_NO_EXPORT_SUBCONFED 0xffffff03
/* Extended community type - draft-ietf-idr-bgp-ext-communities-05 */
#define BGP_EXT_COM_RT_0 0x0002 /* Route Target,Format AS(2bytes):AN(4bytes) */
#define BGP_EXT_COM_RT_1 0x0102 /* Route Target,Format IP address:AN(2bytes) */
#define BGP_EXT_COM_RT_2 0x0202 /* Route Target,Format AN(4bytes):local(2bytes) */
#define BGP_EXT_COM_RO_0 0x0003 /* Route Origin,Format AS(2bytes):AN(4bytes) */
#define BGP_EXT_COM_RO_1 0x0103 /* Route Origin,Format IP address:AN(2bytes) */
#define BGP_EXT_COM_RO_2 0x0203 /* Route Origin,Format AN(4bytes):local(2bytes) */
#define BGP_EXT_COM_LINKBAND 0x4004 /* Link Bandwidth,Format AS(2B):Bandwidth(4B) */
/* rfc2547 bgp-mpls-vpns */
#define BGP_EXT_COM_VPN_ORIGIN 0x0005 /* OSPF Domain ID / VPN of Origin - draft-rosen-vpns-ospf-bgp-mpls */
#define BGP_EXT_COM_VPN_ORIGIN2 0x0105 /* duplicate - keep for backwards compatability */
#define BGP_EXT_COM_VPN_ORIGIN3 0x0205 /* duplicate - keep for backwards compatability */
#define BGP_EXT_COM_VPN_ORIGIN4 0x8005 /* duplicate - keep for backwards compatability */
#define BGP_EXT_COM_OSPF_RTYPE 0x0306 /* OSPF Route Type,Format Area(4B):RouteType(1B):Options(1B) */
#define BGP_EXT_COM_OSPF_RTYPE2 0x8000 /* duplicate - keep for backwards compatability */
#define BGP_EXT_COM_OSPF_RID 0x0107 /* OSPF Router ID,Format RouterID(4B):Unused(2B) */
#define BGP_EXT_COM_OSPF_RID2 0x8001 /* duplicate - keep for backwards compatability */
#define BGP_EXT_COM_L2INFO 0x800a /* draft-kompella-ppvpn-l2vpn */
#define BGP_EXT_COM_SOURCE_AS 0x0009 /* RFC-ietf-l3vpn-2547bis-mcast-bgp-08.txt */
#define BGP_EXT_COM_VRF_RT_IMP 0x010b /* RFC-ietf-l3vpn-2547bis-mcast-bgp-08.txt */
#define BGP_EXT_COM_L2VPN_RT_0 0x000a /* L2VPN Identifier,Format AS(2bytes):AN(4bytes) */
#define BGP_EXT_COM_L2VPN_RT_1 0xF10a /* L2VPN Identifier,Format IP address:AN(2bytes) */
/* http://www.cisco.com/en/US/tech/tk436/tk428/technologies_tech_note09186a00801eb09a.shtml */
#define BGP_EXT_COM_EIGRP_GEN 0x8800
#define BGP_EXT_COM_EIGRP_METRIC_AS_DELAY 0x8801
#define BGP_EXT_COM_EIGRP_METRIC_REL_NH_BW 0x8802
#define BGP_EXT_COM_EIGRP_METRIC_LOAD_MTU 0x8803
#define BGP_EXT_COM_EIGRP_EXT_REMAS_REMID 0x8804
#define BGP_EXT_COM_EIGRP_EXT_REMPROTO_REMMETRIC 0x8805
static const struct tok bgp_extd_comm_flag_values[] = {
{ 0x8000, "vendor-specific"},
{ 0x4000, "non-transitive"},
{ 0, NULL},
};
static const struct tok bgp_extd_comm_subtype_values[] = {
{ BGP_EXT_COM_RT_0, "target"},
{ BGP_EXT_COM_RT_1, "target"},
{ BGP_EXT_COM_RT_2, "target"},
{ BGP_EXT_COM_RO_0, "origin"},
{ BGP_EXT_COM_RO_1, "origin"},
{ BGP_EXT_COM_RO_2, "origin"},
{ BGP_EXT_COM_LINKBAND, "link-BW"},
{ BGP_EXT_COM_VPN_ORIGIN, "ospf-domain"},
{ BGP_EXT_COM_VPN_ORIGIN2, "ospf-domain"},
{ BGP_EXT_COM_VPN_ORIGIN3, "ospf-domain"},
{ BGP_EXT_COM_VPN_ORIGIN4, "ospf-domain"},
{ BGP_EXT_COM_OSPF_RTYPE, "ospf-route-type"},
{ BGP_EXT_COM_OSPF_RTYPE2, "ospf-route-type"},
{ BGP_EXT_COM_OSPF_RID, "ospf-router-id"},
{ BGP_EXT_COM_OSPF_RID2, "ospf-router-id"},
{ BGP_EXT_COM_L2INFO, "layer2-info"},
{ BGP_EXT_COM_EIGRP_GEN , "eigrp-general-route (flag, tag)" },
{ BGP_EXT_COM_EIGRP_METRIC_AS_DELAY , "eigrp-route-metric (AS, delay)" },
{ BGP_EXT_COM_EIGRP_METRIC_REL_NH_BW , "eigrp-route-metric (reliability, nexthop, bandwidth)" },
{ BGP_EXT_COM_EIGRP_METRIC_LOAD_MTU , "eigrp-route-metric (load, MTU)" },
{ BGP_EXT_COM_EIGRP_EXT_REMAS_REMID , "eigrp-external-route (remote-AS, remote-ID)" },
{ BGP_EXT_COM_EIGRP_EXT_REMPROTO_REMMETRIC , "eigrp-external-route (remote-proto, remote-metric)" },
{ BGP_EXT_COM_SOURCE_AS, "source-AS" },
{ BGP_EXT_COM_VRF_RT_IMP, "vrf-route-import"},
{ BGP_EXT_COM_L2VPN_RT_0, "l2vpn-id"},
{ BGP_EXT_COM_L2VPN_RT_1, "l2vpn-id"},
{ 0, NULL},
};
/* OSPF codes for BGP_EXT_COM_OSPF_RTYPE draft-rosen-vpns-ospf-bgp-mpls */
#define BGP_OSPF_RTYPE_RTR 1 /* OSPF Router LSA */
#define BGP_OSPF_RTYPE_NET 2 /* OSPF Network LSA */
#define BGP_OSPF_RTYPE_SUM 3 /* OSPF Summary LSA */
#define BGP_OSPF_RTYPE_EXT 5 /* OSPF External LSA, note that ASBR doesn't apply to MPLS-VPN */
#define BGP_OSPF_RTYPE_NSSA 7 /* OSPF NSSA External*/
#define BGP_OSPF_RTYPE_SHAM 129 /* OSPF-MPLS-VPN Sham link */
#define BGP_OSPF_RTYPE_METRIC_TYPE 0x1 /* LSB of RTYPE Options Field */
static const struct tok bgp_extd_comm_ospf_rtype_values[] = {
{ BGP_OSPF_RTYPE_RTR, "Router" },
{ BGP_OSPF_RTYPE_NET, "Network" },
{ BGP_OSPF_RTYPE_SUM, "Summary" },
{ BGP_OSPF_RTYPE_EXT, "External" },
{ BGP_OSPF_RTYPE_NSSA,"NSSA External" },
{ BGP_OSPF_RTYPE_SHAM,"MPLS-VPN Sham" },
{ 0, NULL },
};
/* ADD-PATH Send/Receive field values */
static const struct tok bgp_add_path_recvsend[] = {
{ 1, "Receive" },
{ 2, "Send" },
{ 3, "Both" },
{ 0, NULL },
};
static char astostr[20];
/*
* as_printf
*
* Convert an AS number into a string and return string pointer.
*
* Depending on bflag is set or not, AS number is converted into ASDOT notation
* or plain number notation.
*
*/
static char *
as_printf(netdissect_options *ndo,
char *str, int size, u_int asnum)
{
if (!ndo->ndo_bflag || asnum <= 0xFFFF) {
snprintf(str, size, "%u", asnum);
} else {
snprintf(str, size, "%u.%u", asnum >> 16, asnum & 0xFFFF);
}
return str;
}
#define ITEMCHECK(minlen) if (itemlen < minlen) goto badtlv;
int
decode_prefix4(netdissect_options *ndo,
const u_char *pptr, u_int itemlen, char *buf, u_int buflen)
{
struct in_addr addr;
u_int plen, plenbytes;
ND_TCHECK(pptr[0]);
ITEMCHECK(1);
plen = pptr[0];
if (32 < plen)
return -1;
itemlen -= 1;
memset(&addr, 0, sizeof(addr));
plenbytes = (plen + 7) / 8;
ND_TCHECK2(pptr[1], plenbytes);
ITEMCHECK(plenbytes);
memcpy(&addr, &pptr[1], plenbytes);
if (plen % 8) {
((u_char *)&addr)[plenbytes - 1] &=
((0xff00 >> (plen % 8)) & 0xff);
}
snprintf(buf, buflen, "%s/%d", ipaddr_string(ndo, &addr), plen);
return 1 + plenbytes;
trunc:
return -2;
badtlv:
return -3;
}
static int
decode_labeled_prefix4(netdissect_options *ndo,
const u_char *pptr, u_int itemlen, char *buf, u_int buflen)
{
struct in_addr addr;
u_int plen, plenbytes;
/* prefix length and label = 4 bytes */
ND_TCHECK2(pptr[0], 4);
ITEMCHECK(4);
plen = pptr[0]; /* get prefix length */
/* this is one of the weirdnesses of rfc3107
the label length (actually the label + COS bits)
is added to the prefix length;
we also do only read out just one label -
there is no real application for advertisement of
stacked labels in a single BGP message
*/
if (24 > plen)
return -1;
plen-=24; /* adjust prefixlen - labellength */
if (32 < plen)
return -1;
itemlen -= 4;
memset(&addr, 0, sizeof(addr));
plenbytes = (plen + 7) / 8;
ND_TCHECK2(pptr[4], plenbytes);
ITEMCHECK(plenbytes);
memcpy(&addr, &pptr[4], plenbytes);
if (plen % 8) {
((u_char *)&addr)[plenbytes - 1] &=
((0xff00 >> (plen % 8)) & 0xff);
}
/* the label may get offsetted by 4 bits so lets shift it right */
snprintf(buf, buflen, "%s/%d, label:%u %s",
ipaddr_string(ndo, &addr),
plen,
EXTRACT_24BITS(pptr+1)>>4,
((pptr[3]&1)==0) ? "(BOGUS: Bottom of Stack NOT set!)" : "(bottom)" );
return 4 + plenbytes;
trunc:
return -2;
badtlv:
return -3;
}
/*
* bgp_vpn_ip_print
*
* print an ipv4 or ipv6 address into a buffer dependend on address length.
*/
static char *
bgp_vpn_ip_print(netdissect_options *ndo,
const u_char *pptr, u_int addr_length)
{
/* worst case string is s fully formatted v6 address */
static char addr[sizeof("1234:5678:89ab:cdef:1234:5678:89ab:cdef")];
char *pos = addr;
switch(addr_length) {
case (sizeof(struct in_addr) << 3): /* 32 */
ND_TCHECK2(pptr[0], sizeof(struct in_addr));
snprintf(pos, sizeof(addr), "%s", ipaddr_string(ndo, pptr));
break;
case (sizeof(struct in6_addr) << 3): /* 128 */
ND_TCHECK2(pptr[0], sizeof(struct in6_addr));
snprintf(pos, sizeof(addr), "%s", ip6addr_string(ndo, pptr));
break;
default:
snprintf(pos, sizeof(addr), "bogus address length %u", addr_length);
break;
}
pos += strlen(pos);
trunc:
*(pos) = '\0';
return (addr);
}
/*
* bgp_vpn_sg_print
*
* print an multicast s,g entry into a buffer.
* the s,g entry is encoded like this.
*
* +-----------------------------------+
* | Multicast Source Length (1 octet) |
* +-----------------------------------+
* | Multicast Source (Variable) |
* +-----------------------------------+
* | Multicast Group Length (1 octet) |
* +-----------------------------------+
* | Multicast Group (Variable) |
* +-----------------------------------+
*
* return the number of bytes read from the wire.
*/
static int
bgp_vpn_sg_print(netdissect_options *ndo,
const u_char *pptr, char *buf, u_int buflen)
{
uint8_t addr_length;
u_int total_length, offset;
total_length = 0;
/* Source address length, encoded in bits */
ND_TCHECK2(pptr[0], 1);
addr_length = *pptr++;
/* Source address */
ND_TCHECK2(pptr[0], (addr_length >> 3));
total_length += (addr_length >> 3) + 1;
offset = strlen(buf);
if (addr_length) {
snprintf(buf + offset, buflen - offset, ", Source %s",
bgp_vpn_ip_print(ndo, pptr, addr_length));
pptr += (addr_length >> 3);
}
/* Group address length, encoded in bits */
ND_TCHECK2(pptr[0], 1);
addr_length = *pptr++;
/* Group address */
ND_TCHECK2(pptr[0], (addr_length >> 3));
total_length += (addr_length >> 3) + 1;
offset = strlen(buf);
if (addr_length) {
snprintf(buf + offset, buflen - offset, ", Group %s",
bgp_vpn_ip_print(ndo, pptr, addr_length));
pptr += (addr_length >> 3);
}
trunc:
return (total_length);
}
/* RDs and RTs share the same semantics
* we use bgp_vpn_rd_print for
* printing route targets inside a NLRI */
char *
bgp_vpn_rd_print(netdissect_options *ndo,
const u_char *pptr)
{
/* allocate space for the largest possible string */
static char rd[sizeof("xxxxxxxxxx:xxxxx (xxx.xxx.xxx.xxx:xxxxx)")];
char *pos = rd;
/* ok lets load the RD format */
switch (EXTRACT_16BITS(pptr)) {
/* 2-byte-AS:number fmt*/
case 0:
snprintf(pos, sizeof(rd) - (pos - rd), "%u:%u (= %u.%u.%u.%u)",
EXTRACT_16BITS(pptr+2),
EXTRACT_32BITS(pptr+4),
*(pptr+4), *(pptr+5), *(pptr+6), *(pptr+7));
break;
/* IP-address:AS fmt*/
case 1:
snprintf(pos, sizeof(rd) - (pos - rd), "%u.%u.%u.%u:%u",
*(pptr+2), *(pptr+3), *(pptr+4), *(pptr+5), EXTRACT_16BITS(pptr+6));
break;
/* 4-byte-AS:number fmt*/
case 2:
snprintf(pos, sizeof(rd) - (pos - rd), "%s:%u (%u.%u.%u.%u:%u)",
as_printf(ndo, astostr, sizeof(astostr), EXTRACT_32BITS(pptr+2)),
EXTRACT_16BITS(pptr+6), *(pptr+2), *(pptr+3), *(pptr+4),
*(pptr+5), EXTRACT_16BITS(pptr+6));
break;
default:
snprintf(pos, sizeof(rd) - (pos - rd), "unknown RD format");
break;
}
pos += strlen(pos);
*(pos) = '\0';
return (rd);
}
static int
decode_rt_routing_info(netdissect_options *ndo,
const u_char *pptr, char *buf, u_int buflen)
{
uint8_t route_target[8];
u_int plen;
ND_TCHECK(pptr[0]);
plen = pptr[0]; /* get prefix length */
if (0 == plen) {
snprintf(buf, buflen, "default route target");
return 1;
}
if (32 > plen)
return -1;
plen-=32; /* adjust prefix length */
if (64 < plen)
return -1;
memset(&route_target, 0, sizeof(route_target));
ND_TCHECK2(pptr[1], (plen + 7) / 8);
memcpy(&route_target, &pptr[1], (plen + 7) / 8);
if (plen % 8) {
((u_char *)&route_target)[(plen + 7) / 8 - 1] &=
((0xff00 >> (plen % 8)) & 0xff);
}
snprintf(buf, buflen, "origin AS: %s, route target %s",
as_printf(ndo, astostr, sizeof(astostr), EXTRACT_32BITS(pptr+1)),
bgp_vpn_rd_print(ndo, (u_char *)&route_target));
return 5 + (plen + 7) / 8;
trunc:
return -2;
}
static int
decode_labeled_vpn_prefix4(netdissect_options *ndo,
const u_char *pptr, char *buf, u_int buflen)
{
struct in_addr addr;
u_int plen;
ND_TCHECK(pptr[0]);
plen = pptr[0]; /* get prefix length */
if ((24+64) > plen)
return -1;
plen-=(24+64); /* adjust prefixlen - labellength - RD len*/
if (32 < plen)
return -1;
memset(&addr, 0, sizeof(addr));
ND_TCHECK2(pptr[12], (plen + 7) / 8);
memcpy(&addr, &pptr[12], (plen + 7) / 8);
if (plen % 8) {
((u_char *)&addr)[(plen + 7) / 8 - 1] &=
((0xff00 >> (plen % 8)) & 0xff);
}
/* the label may get offsetted by 4 bits so lets shift it right */
snprintf(buf, buflen, "RD: %s, %s/%d, label:%u %s",
bgp_vpn_rd_print(ndo, pptr+4),
ipaddr_string(ndo, &addr),
plen,
EXTRACT_24BITS(pptr+1)>>4,
((pptr[3]&1)==0) ? "(BOGUS: Bottom of Stack NOT set!)" : "(bottom)" );
return 12 + (plen + 7) / 8;
trunc:
return -2;
}
/*
* +-------------------------------+
* | |
* | RD:IPv4-address (12 octets) |
* | |
* +-------------------------------+
* | MDT Group-address (4 octets) |
* +-------------------------------+
*/
#define MDT_VPN_NLRI_LEN 16
static int
decode_mdt_vpn_nlri(netdissect_options *ndo,
const u_char *pptr, char *buf, u_int buflen)
{
const u_char *rd;
const u_char *vpn_ip;
ND_TCHECK(pptr[0]);
/* if the NLRI is not predefined length, quit.*/
if (*pptr != MDT_VPN_NLRI_LEN * 8)
return -1;
pptr++;
/* RD */
ND_TCHECK2(pptr[0], 8);
rd = pptr;
pptr+=8;
/* IPv4 address */
ND_TCHECK2(pptr[0], sizeof(struct in_addr));
vpn_ip = pptr;
pptr+=sizeof(struct in_addr);
/* MDT Group Address */
ND_TCHECK2(pptr[0], sizeof(struct in_addr));
snprintf(buf, buflen, "RD: %s, VPN IP Address: %s, MC Group Address: %s",
bgp_vpn_rd_print(ndo, rd), ipaddr_string(ndo, vpn_ip), ipaddr_string(ndo, pptr));
return MDT_VPN_NLRI_LEN + 1;
trunc:
return -2;
}
#define BGP_MULTICAST_VPN_ROUTE_TYPE_INTRA_AS_I_PMSI 1
#define BGP_MULTICAST_VPN_ROUTE_TYPE_INTER_AS_I_PMSI 2
#define BGP_MULTICAST_VPN_ROUTE_TYPE_S_PMSI 3
#define BGP_MULTICAST_VPN_ROUTE_TYPE_INTRA_AS_SEG_LEAF 4
#define BGP_MULTICAST_VPN_ROUTE_TYPE_SOURCE_ACTIVE 5
#define BGP_MULTICAST_VPN_ROUTE_TYPE_SHARED_TREE_JOIN 6
#define BGP_MULTICAST_VPN_ROUTE_TYPE_SOURCE_TREE_JOIN 7
static const struct tok bgp_multicast_vpn_route_type_values[] = {
{ BGP_MULTICAST_VPN_ROUTE_TYPE_INTRA_AS_I_PMSI, "Intra-AS I-PMSI"},
{ BGP_MULTICAST_VPN_ROUTE_TYPE_INTER_AS_I_PMSI, "Inter-AS I-PMSI"},
{ BGP_MULTICAST_VPN_ROUTE_TYPE_S_PMSI, "S-PMSI"},
{ BGP_MULTICAST_VPN_ROUTE_TYPE_INTRA_AS_SEG_LEAF, "Intra-AS Segment-Leaf"},
{ BGP_MULTICAST_VPN_ROUTE_TYPE_SOURCE_ACTIVE, "Source-Active"},
{ BGP_MULTICAST_VPN_ROUTE_TYPE_SHARED_TREE_JOIN, "Shared Tree Join"},
{ BGP_MULTICAST_VPN_ROUTE_TYPE_SOURCE_TREE_JOIN, "Source Tree Join"},
{ 0, NULL}
};
static int
decode_multicast_vpn(netdissect_options *ndo,
const u_char *pptr, char *buf, u_int buflen)
{
uint8_t route_type, route_length, addr_length, sg_length;
u_int offset;
ND_TCHECK2(pptr[0], 2);
route_type = *pptr++;
route_length = *pptr++;
snprintf(buf, buflen, "Route-Type: %s (%u), length: %u",
tok2str(bgp_multicast_vpn_route_type_values,
"Unknown", route_type),
route_type, route_length);
switch(route_type) {
case BGP_MULTICAST_VPN_ROUTE_TYPE_INTRA_AS_I_PMSI:
ND_TCHECK2(pptr[0], BGP_VPN_RD_LEN);
offset = strlen(buf);
snprintf(buf + offset, buflen - offset, ", RD: %s, Originator %s",
bgp_vpn_rd_print(ndo, pptr),
bgp_vpn_ip_print(ndo, pptr + BGP_VPN_RD_LEN,
(route_length - BGP_VPN_RD_LEN) << 3));
break;
case BGP_MULTICAST_VPN_ROUTE_TYPE_INTER_AS_I_PMSI:
ND_TCHECK2(pptr[0], BGP_VPN_RD_LEN + 4);
offset = strlen(buf);
snprintf(buf + offset, buflen - offset, ", RD: %s, Source-AS %s",
bgp_vpn_rd_print(ndo, pptr),
as_printf(ndo, astostr, sizeof(astostr),
EXTRACT_32BITS(pptr + BGP_VPN_RD_LEN)));
break;
case BGP_MULTICAST_VPN_ROUTE_TYPE_S_PMSI:
ND_TCHECK2(pptr[0], BGP_VPN_RD_LEN);
offset = strlen(buf);
snprintf(buf + offset, buflen - offset, ", RD: %s",
bgp_vpn_rd_print(ndo, pptr));
pptr += BGP_VPN_RD_LEN;
sg_length = bgp_vpn_sg_print(ndo, pptr, buf, buflen);
addr_length = route_length - sg_length;
ND_TCHECK2(pptr[0], addr_length);
offset = strlen(buf);
snprintf(buf + offset, buflen - offset, ", Originator %s",
bgp_vpn_ip_print(ndo, pptr, addr_length << 3));
break;
case BGP_MULTICAST_VPN_ROUTE_TYPE_SOURCE_ACTIVE:
ND_TCHECK2(pptr[0], BGP_VPN_RD_LEN);
offset = strlen(buf);
snprintf(buf + offset, buflen - offset, ", RD: %s",
bgp_vpn_rd_print(ndo, pptr));
pptr += BGP_VPN_RD_LEN;
bgp_vpn_sg_print(ndo, pptr, buf, buflen);
break;
case BGP_MULTICAST_VPN_ROUTE_TYPE_SHARED_TREE_JOIN: /* fall through */
case BGP_MULTICAST_VPN_ROUTE_TYPE_SOURCE_TREE_JOIN:
ND_TCHECK2(pptr[0], BGP_VPN_RD_LEN);
offset = strlen(buf);
snprintf(buf + offset, buflen - offset, ", RD: %s, Source-AS %s",
bgp_vpn_rd_print(ndo, pptr),
as_printf(ndo, astostr, sizeof(astostr),
EXTRACT_32BITS(pptr + BGP_VPN_RD_LEN)));
pptr += BGP_VPN_RD_LEN;
bgp_vpn_sg_print(ndo, pptr, buf, buflen);
break;
/*
* no per route-type printing yet.
*/
case BGP_MULTICAST_VPN_ROUTE_TYPE_INTRA_AS_SEG_LEAF:
default:
break;
}
return route_length + 2;
trunc:
return -2;
}
/*
* As I remember, some versions of systems have an snprintf() that
* returns -1 if the buffer would have overflowed. If the return
* value is negative, set buflen to 0, to indicate that we've filled
* the buffer up.
*
* If the return value is greater than buflen, that means that
* the buffer would have overflowed; again, set buflen to 0 in
* that case.
*/
#define UPDATE_BUF_BUFLEN(buf, buflen, stringlen) \
if (stringlen<0) \
buflen=0; \
else if ((u_int)stringlen>buflen) \
buflen=0; \
else { \
buflen-=stringlen; \
buf+=stringlen; \
}
static int
decode_labeled_vpn_l2(netdissect_options *ndo,
const u_char *pptr, char *buf, u_int buflen)
{
int plen,tlen,stringlen,tlv_type,tlv_len,ttlv_len;
ND_TCHECK2(pptr[0], 2);
plen=EXTRACT_16BITS(pptr);
tlen=plen;
pptr+=2;
/* Old and new L2VPN NLRI share AFI/SAFI
* -> Assume a 12 Byte-length NLRI is auto-discovery-only
* and > 17 as old format. Complain for the middle case
*/
if (plen==12) {
/* assume AD-only with RD, BGPNH */
ND_TCHECK2(pptr[0],12);
buf[0]='\0';
stringlen=snprintf(buf, buflen, "RD: %s, BGPNH: %s",
bgp_vpn_rd_print(ndo, pptr),
ipaddr_string(ndo, pptr+8)
);
UPDATE_BUF_BUFLEN(buf, buflen, stringlen);
pptr+=12;
tlen-=12;
return plen;
} else if (plen>17) {
/* assume old format */
/* RD, ID, LBLKOFF, LBLBASE */
ND_TCHECK2(pptr[0],15);
buf[0]='\0';
stringlen=snprintf(buf, buflen, "RD: %s, CE-ID: %u, Label-Block Offset: %u, Label Base %u",
bgp_vpn_rd_print(ndo, pptr),
EXTRACT_16BITS(pptr+8),
EXTRACT_16BITS(pptr+10),
EXTRACT_24BITS(pptr+12)>>4); /* the label is offsetted by 4 bits so lets shift it right */
UPDATE_BUF_BUFLEN(buf, buflen, stringlen);
pptr+=15;
tlen-=15;
/* ok now the variable part - lets read out TLVs*/
while (tlen>0) {
if (tlen < 3)
return -1;
ND_TCHECK2(pptr[0], 3);
tlv_type=*pptr++;
tlv_len=EXTRACT_16BITS(pptr);
ttlv_len=tlv_len;
pptr+=2;
switch(tlv_type) {
case 1:
if (buflen!=0) {
stringlen=snprintf(buf,buflen, "\n\t\tcircuit status vector (%u) length: %u: 0x",
tlv_type,
tlv_len);
UPDATE_BUF_BUFLEN(buf, buflen, stringlen);
}
ttlv_len=ttlv_len/8+1; /* how many bytes do we need to read ? */
while (ttlv_len>0) {
ND_TCHECK(pptr[0]);
if (buflen!=0) {
stringlen=snprintf(buf,buflen, "%02x",*pptr++);
UPDATE_BUF_BUFLEN(buf, buflen, stringlen);
}
ttlv_len--;
}
break;
default:
if (buflen!=0) {
stringlen=snprintf(buf,buflen, "\n\t\tunknown TLV #%u, length: %u",
tlv_type,
tlv_len);
UPDATE_BUF_BUFLEN(buf, buflen, stringlen);
}
break;
}
tlen-=(tlv_len<<3); /* the tlv-length is expressed in bits so lets shift it right */
}
return plen+2;
} else {
/* complain bitterly ? */
/* fall through */
goto trunc;
}
trunc:
return -2;
}
int
decode_prefix6(netdissect_options *ndo,
const u_char *pd, u_int itemlen, char *buf, u_int buflen)
{
struct in6_addr addr;
u_int plen, plenbytes;
ND_TCHECK(pd[0]);
ITEMCHECK(1);
plen = pd[0];
if (128 < plen)
return -1;
itemlen -= 1;
memset(&addr, 0, sizeof(addr));
plenbytes = (plen + 7) / 8;
ND_TCHECK2(pd[1], plenbytes);
ITEMCHECK(plenbytes);
memcpy(&addr, &pd[1], plenbytes);
if (plen % 8) {
addr.s6_addr[plenbytes - 1] &=
((0xff00 >> (plen % 8)) & 0xff);
}
snprintf(buf, buflen, "%s/%d", ip6addr_string(ndo, &addr), plen);
return 1 + plenbytes;
trunc:
return -2;
badtlv:
return -3;
}
static int
decode_labeled_prefix6(netdissect_options *ndo,
const u_char *pptr, u_int itemlen, char *buf, u_int buflen)
{
struct in6_addr addr;
u_int plen, plenbytes;
/* prefix length and label = 4 bytes */
ND_TCHECK2(pptr[0], 4);
ITEMCHECK(4);
plen = pptr[0]; /* get prefix length */
if (24 > plen)
return -1;
plen-=24; /* adjust prefixlen - labellength */
if (128 < plen)
return -1;
itemlen -= 4;
memset(&addr, 0, sizeof(addr));
plenbytes = (plen + 7) / 8;
ND_TCHECK2(pptr[4], plenbytes);
memcpy(&addr, &pptr[4], plenbytes);
if (plen % 8) {
addr.s6_addr[plenbytes - 1] &=
((0xff00 >> (plen % 8)) & 0xff);
}
/* the label may get offsetted by 4 bits so lets shift it right */
snprintf(buf, buflen, "%s/%d, label:%u %s",
ip6addr_string(ndo, &addr),
plen,
EXTRACT_24BITS(pptr+1)>>4,
((pptr[3]&1)==0) ? "(BOGUS: Bottom of Stack NOT set!)" : "(bottom)" );
return 4 + plenbytes;
trunc:
return -2;
badtlv:
return -3;
}
static int
decode_labeled_vpn_prefix6(netdissect_options *ndo,
const u_char *pptr, char *buf, u_int buflen)
{
struct in6_addr addr;
u_int plen;
ND_TCHECK(pptr[0]);
plen = pptr[0]; /* get prefix length */
if ((24+64) > plen)
return -1;
plen-=(24+64); /* adjust prefixlen - labellength - RD len*/
if (128 < plen)
return -1;
memset(&addr, 0, sizeof(addr));
ND_TCHECK2(pptr[12], (plen + 7) / 8);
memcpy(&addr, &pptr[12], (plen + 7) / 8);
if (plen % 8) {
addr.s6_addr[(plen + 7) / 8 - 1] &=
((0xff00 >> (plen % 8)) & 0xff);
}
/* the label may get offsetted by 4 bits so lets shift it right */
snprintf(buf, buflen, "RD: %s, %s/%d, label:%u %s",
bgp_vpn_rd_print(ndo, pptr+4),
ip6addr_string(ndo, &addr),
plen,
EXTRACT_24BITS(pptr+1)>>4,
((pptr[3]&1)==0) ? "(BOGUS: Bottom of Stack NOT set!)" : "(bottom)" );
return 12 + (plen + 7) / 8;
trunc:
return -2;
}
static int
decode_clnp_prefix(netdissect_options *ndo,
const u_char *pptr, char *buf, u_int buflen)
{
uint8_t addr[19];
u_int plen;
ND_TCHECK(pptr[0]);
plen = pptr[0]; /* get prefix length */
if (152 < plen)
return -1;
memset(&addr, 0, sizeof(addr));
ND_TCHECK2(pptr[4], (plen + 7) / 8);
memcpy(&addr, &pptr[4], (plen + 7) / 8);
if (plen % 8) {
addr[(plen + 7) / 8 - 1] &=
((0xff00 >> (plen % 8)) & 0xff);
}
snprintf(buf, buflen, "%s/%d",
isonsap_string(ndo, addr,(plen + 7) / 8),
plen);
return 1 + (plen + 7) / 8;
trunc:
return -2;
}
static int
decode_labeled_vpn_clnp_prefix(netdissect_options *ndo,
const u_char *pptr, char *buf, u_int buflen)
{
uint8_t addr[19];
u_int plen;
ND_TCHECK(pptr[0]);
plen = pptr[0]; /* get prefix length */
if ((24+64) > plen)
return -1;
plen-=(24+64); /* adjust prefixlen - labellength - RD len*/
if (152 < plen)
return -1;
memset(&addr, 0, sizeof(addr));
ND_TCHECK2(pptr[12], (plen + 7) / 8);
memcpy(&addr, &pptr[12], (plen + 7) / 8);
if (plen % 8) {
addr[(plen + 7) / 8 - 1] &=
((0xff00 >> (plen % 8)) & 0xff);
}
/* the label may get offsetted by 4 bits so lets shift it right */
snprintf(buf, buflen, "RD: %s, %s/%d, label:%u %s",
bgp_vpn_rd_print(ndo, pptr+4),
isonsap_string(ndo, addr,(plen + 7) / 8),
plen,
EXTRACT_24BITS(pptr+1)>>4,
((pptr[3]&1)==0) ? "(BOGUS: Bottom of Stack NOT set!)" : "(bottom)" );
return 12 + (plen + 7) / 8;
trunc:
return -2;
}
/*
* bgp_attr_get_as_size
*
* Try to find the size of the ASs encoded in an as-path. It is not obvious, as
* both Old speakers that do not support 4 byte AS, and the new speakers that do
* support, exchange AS-Path with the same path-attribute type value 0x02.
*/
static int
bgp_attr_get_as_size(netdissect_options *ndo,
uint8_t bgpa_type, const u_char *pptr, int len)
{
const u_char *tptr = pptr;
/*
* If the path attribute is the optional AS4 path type, then we already
* know, that ASs must be encoded in 4 byte format.
*/
if (bgpa_type == BGPTYPE_AS4_PATH) {
return 4;
}
/*
* Let us assume that ASs are of 2 bytes in size, and check if the AS-Path
* TLV is good. If not, ask the caller to try with AS encoded as 4 bytes
* each.
*/
while (tptr < pptr + len) {
ND_TCHECK(tptr[0]);
/*
* If we do not find a valid segment type, our guess might be wrong.
*/
if (tptr[0] < BGP_AS_SEG_TYPE_MIN || tptr[0] > BGP_AS_SEG_TYPE_MAX) {
goto trunc;
}
ND_TCHECK(tptr[1]);
tptr += 2 + tptr[1] * 2;
}
/*
* If we correctly reached end of the AS path attribute data content,
* then most likely ASs were indeed encoded as 2 bytes.
*/
if (tptr == pptr + len) {
return 2;
}
trunc:
/*
* We can come here, either we did not have enough data, or if we
* try to decode 4 byte ASs in 2 byte format. Either way, return 4,
* so that calller can try to decode each AS as of 4 bytes. If indeed
* there was not enough data, it will crib and end the parse anyways.
*/
return 4;
}
static int
bgp_attr_print(netdissect_options *ndo,
u_int atype, const u_char *pptr, u_int len)
{
int i;
uint16_t af;
uint8_t safi, snpa, nhlen;
union { /* copy buffer for bandwidth values */
float f;
uint32_t i;
} bw;
int advance;
u_int tlen;
const u_char *tptr;
char buf[MAXHOSTNAMELEN + 100];
int as_size;
tptr = pptr;
tlen=len;
switch (atype) {
case BGPTYPE_ORIGIN:
if (len != 1)
ND_PRINT((ndo, "invalid len"));
else {
ND_TCHECK(*tptr);
ND_PRINT((ndo, "%s", tok2str(bgp_origin_values,
"Unknown Origin Typecode",
tptr[0])));
}
break;
/*
* Process AS4 byte path and AS2 byte path attributes here.
*/
case BGPTYPE_AS4_PATH:
case BGPTYPE_AS_PATH:
if (len % 2) {
ND_PRINT((ndo, "invalid len"));
break;
}
if (!len) {
ND_PRINT((ndo, "empty"));
break;
}
/*
* BGP updates exchanged between New speakers that support 4
* byte AS, ASs are always encoded in 4 bytes. There is no
* definitive way to find this, just by the packet's
* contents. So, check for packet's TLV's sanity assuming
* 2 bytes first, and it does not pass, assume that ASs are
* encoded in 4 bytes format and move on.
*/
as_size = bgp_attr_get_as_size(ndo, atype, pptr, len);
while (tptr < pptr + len) {
ND_TCHECK(tptr[0]);
ND_PRINT((ndo, "%s", tok2str(bgp_as_path_segment_open_values,
"?", tptr[0])));
ND_TCHECK(tptr[1]);
for (i = 0; i < tptr[1] * as_size; i += as_size) {
ND_TCHECK2(tptr[2 + i], as_size);
ND_PRINT((ndo, "%s ",
as_printf(ndo, astostr, sizeof(astostr),
as_size == 2 ?
EXTRACT_16BITS(&tptr[2 + i]) :
EXTRACT_32BITS(&tptr[2 + i]))));
}
ND_TCHECK(tptr[0]);
ND_PRINT((ndo, "%s", tok2str(bgp_as_path_segment_close_values,
"?", tptr[0])));
ND_TCHECK(tptr[1]);
tptr += 2 + tptr[1] * as_size;
}
break;
case BGPTYPE_NEXT_HOP:
if (len != 4)
ND_PRINT((ndo, "invalid len"));
else {
ND_TCHECK2(tptr[0], 4);
ND_PRINT((ndo, "%s", ipaddr_string(ndo, tptr)));
}
break;
case BGPTYPE_MULTI_EXIT_DISC:
case BGPTYPE_LOCAL_PREF:
if (len != 4)
ND_PRINT((ndo, "invalid len"));
else {
ND_TCHECK2(tptr[0], 4);
ND_PRINT((ndo, "%u", EXTRACT_32BITS(tptr)));
}
break;
case BGPTYPE_ATOMIC_AGGREGATE:
if (len != 0)
ND_PRINT((ndo, "invalid len"));
break;
case BGPTYPE_AGGREGATOR:
/*
* Depending on the AS encoded is of 2 bytes or of 4 bytes,
* the length of this PA can be either 6 bytes or 8 bytes.
*/
if (len != 6 && len != 8) {
ND_PRINT((ndo, "invalid len"));
break;
}
ND_TCHECK2(tptr[0], len);
if (len == 6) {
ND_PRINT((ndo, " AS #%s, origin %s",
as_printf(ndo, astostr, sizeof(astostr), EXTRACT_16BITS(tptr)),
ipaddr_string(ndo, tptr + 2)));
} else {
ND_PRINT((ndo, " AS #%s, origin %s",
as_printf(ndo, astostr, sizeof(astostr),
EXTRACT_32BITS(tptr)), ipaddr_string(ndo, tptr + 4)));
}
break;
case BGPTYPE_AGGREGATOR4:
if (len != 8) {
ND_PRINT((ndo, "invalid len"));
break;
}
ND_TCHECK2(tptr[0], 8);
ND_PRINT((ndo, " AS #%s, origin %s",
as_printf(ndo, astostr, sizeof(astostr), EXTRACT_32BITS(tptr)),
ipaddr_string(ndo, tptr + 4)));
break;
case BGPTYPE_COMMUNITIES:
if (len % 4) {
ND_PRINT((ndo, "invalid len"));
break;
}
while (tlen>0) {
uint32_t comm;
ND_TCHECK2(tptr[0], 4);
comm = EXTRACT_32BITS(tptr);
switch (comm) {
case BGP_COMMUNITY_NO_EXPORT:
ND_PRINT((ndo, " NO_EXPORT"));
break;
case BGP_COMMUNITY_NO_ADVERT:
ND_PRINT((ndo, " NO_ADVERTISE"));
break;
case BGP_COMMUNITY_NO_EXPORT_SUBCONFED:
ND_PRINT((ndo, " NO_EXPORT_SUBCONFED"));
break;
default:
ND_PRINT((ndo, "%u:%u%s",
(comm >> 16) & 0xffff,
comm & 0xffff,
(tlen>4) ? ", " : ""));
break;
}
tlen -=4;
tptr +=4;
}
break;
case BGPTYPE_ORIGINATOR_ID:
if (len != 4) {
ND_PRINT((ndo, "invalid len"));
break;
}
ND_TCHECK2(tptr[0], 4);
ND_PRINT((ndo, "%s",ipaddr_string(ndo, tptr)));
break;
case BGPTYPE_CLUSTER_LIST:
if (len % 4) {
ND_PRINT((ndo, "invalid len"));
break;
}
while (tlen>0) {
ND_TCHECK2(tptr[0], 4);
ND_PRINT((ndo, "%s%s",
ipaddr_string(ndo, tptr),
(tlen>4) ? ", " : ""));
tlen -=4;
tptr +=4;
}
break;
case BGPTYPE_MP_REACH_NLRI:
ND_TCHECK2(tptr[0], 3);
af = EXTRACT_16BITS(tptr);
safi = tptr[2];
ND_PRINT((ndo, "\n\t AFI: %s (%u), %sSAFI: %s (%u)",
tok2str(af_values, "Unknown AFI", af),
af,
(safi>128) ? "vendor specific " : "", /* 128 is meanwhile wellknown */
tok2str(bgp_safi_values, "Unknown SAFI", safi),
safi));
switch(af<<8 | safi) {
case (AFNUM_INET<<8 | SAFNUM_UNICAST):
case (AFNUM_INET<<8 | SAFNUM_MULTICAST):
case (AFNUM_INET<<8 | SAFNUM_UNIMULTICAST):
case (AFNUM_INET<<8 | SAFNUM_LABUNICAST):
case (AFNUM_INET<<8 | SAFNUM_RT_ROUTING_INFO):
case (AFNUM_INET<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_INET<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_INET<<8 | SAFNUM_VPNUNIMULTICAST):
case (AFNUM_INET<<8 | SAFNUM_MULTICAST_VPN):
case (AFNUM_INET<<8 | SAFNUM_MDT):
case (AFNUM_INET6<<8 | SAFNUM_UNICAST):
case (AFNUM_INET6<<8 | SAFNUM_MULTICAST):
case (AFNUM_INET6<<8 | SAFNUM_UNIMULTICAST):
case (AFNUM_INET6<<8 | SAFNUM_LABUNICAST):
case (AFNUM_INET6<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_INET6<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_INET6<<8 | SAFNUM_VPNUNIMULTICAST):
case (AFNUM_NSAP<<8 | SAFNUM_UNICAST):
case (AFNUM_NSAP<<8 | SAFNUM_MULTICAST):
case (AFNUM_NSAP<<8 | SAFNUM_UNIMULTICAST):
case (AFNUM_NSAP<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_NSAP<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_NSAP<<8 | SAFNUM_VPNUNIMULTICAST):
case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_L2VPN<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNIMULTICAST):
case (AFNUM_VPLS<<8 | SAFNUM_VPLS):
break;
default:
ND_TCHECK2(tptr[0], tlen);
ND_PRINT((ndo, "\n\t no AFI %u / SAFI %u decoder", af, safi));
if (ndo->ndo_vflag <= 1)
print_unknown_data(ndo, tptr, "\n\t ", tlen);
goto done;
break;
}
tptr +=3;
ND_TCHECK(tptr[0]);
nhlen = tptr[0];
tlen = nhlen;
tptr++;
if (tlen) {
int nnh = 0;
ND_PRINT((ndo, "\n\t nexthop: "));
while (tlen > 0) {
if ( nnh++ > 0 ) {
ND_PRINT((ndo, ", " ));
}
switch(af<<8 | safi) {
case (AFNUM_INET<<8 | SAFNUM_UNICAST):
case (AFNUM_INET<<8 | SAFNUM_MULTICAST):
case (AFNUM_INET<<8 | SAFNUM_UNIMULTICAST):
case (AFNUM_INET<<8 | SAFNUM_LABUNICAST):
case (AFNUM_INET<<8 | SAFNUM_RT_ROUTING_INFO):
case (AFNUM_INET<<8 | SAFNUM_MULTICAST_VPN):
case (AFNUM_INET<<8 | SAFNUM_MDT):
if (tlen < (int)sizeof(struct in_addr)) {
ND_PRINT((ndo, "invalid len"));
tlen = 0;
} else {
ND_TCHECK2(tptr[0], sizeof(struct in_addr));
ND_PRINT((ndo, "%s",ipaddr_string(ndo, tptr)));
tlen -= sizeof(struct in_addr);
tptr += sizeof(struct in_addr);
}
break;
case (AFNUM_INET<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_INET<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_INET<<8 | SAFNUM_VPNUNIMULTICAST):
if (tlen < (int)(sizeof(struct in_addr)+BGP_VPN_RD_LEN)) {
ND_PRINT((ndo, "invalid len"));
tlen = 0;
} else {
ND_TCHECK2(tptr[0], sizeof(struct in_addr)+BGP_VPN_RD_LEN);
ND_PRINT((ndo, "RD: %s, %s",
bgp_vpn_rd_print(ndo, tptr),
ipaddr_string(ndo, tptr+BGP_VPN_RD_LEN)));
tlen -= (sizeof(struct in_addr)+BGP_VPN_RD_LEN);
tptr += (sizeof(struct in_addr)+BGP_VPN_RD_LEN);
}
break;
case (AFNUM_INET6<<8 | SAFNUM_UNICAST):
case (AFNUM_INET6<<8 | SAFNUM_MULTICAST):
case (AFNUM_INET6<<8 | SAFNUM_UNIMULTICAST):
case (AFNUM_INET6<<8 | SAFNUM_LABUNICAST):
if (tlen < (int)sizeof(struct in6_addr)) {
ND_PRINT((ndo, "invalid len"));
tlen = 0;
} else {
ND_TCHECK2(tptr[0], sizeof(struct in6_addr));
ND_PRINT((ndo, "%s", ip6addr_string(ndo, tptr)));
tlen -= sizeof(struct in6_addr);
tptr += sizeof(struct in6_addr);
}
break;
case (AFNUM_INET6<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_INET6<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_INET6<<8 | SAFNUM_VPNUNIMULTICAST):
if (tlen < (int)(sizeof(struct in6_addr)+BGP_VPN_RD_LEN)) {
ND_PRINT((ndo, "invalid len"));
tlen = 0;
} else {
ND_TCHECK2(tptr[0], sizeof(struct in6_addr)+BGP_VPN_RD_LEN);
ND_PRINT((ndo, "RD: %s, %s",
bgp_vpn_rd_print(ndo, tptr),
ip6addr_string(ndo, tptr+BGP_VPN_RD_LEN)));
tlen -= (sizeof(struct in6_addr)+BGP_VPN_RD_LEN);
tptr += (sizeof(struct in6_addr)+BGP_VPN_RD_LEN);
}
break;
case (AFNUM_VPLS<<8 | SAFNUM_VPLS):
case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_L2VPN<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNIMULTICAST):
if (tlen < (int)sizeof(struct in_addr)) {
ND_PRINT((ndo, "invalid len"));
tlen = 0;
} else {
ND_TCHECK2(tptr[0], sizeof(struct in_addr));
ND_PRINT((ndo, "%s", ipaddr_string(ndo, tptr)));
tlen -= (sizeof(struct in_addr));
tptr += (sizeof(struct in_addr));
}
break;
case (AFNUM_NSAP<<8 | SAFNUM_UNICAST):
case (AFNUM_NSAP<<8 | SAFNUM_MULTICAST):
case (AFNUM_NSAP<<8 | SAFNUM_UNIMULTICAST):
ND_TCHECK2(tptr[0], tlen);
ND_PRINT((ndo, "%s", isonsap_string(ndo, tptr, tlen)));
tptr += tlen;
tlen = 0;
break;
case (AFNUM_NSAP<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_NSAP<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_NSAP<<8 | SAFNUM_VPNUNIMULTICAST):
if (tlen < BGP_VPN_RD_LEN+1) {
ND_PRINT((ndo, "invalid len"));
tlen = 0;
} else {
ND_TCHECK2(tptr[0], tlen);
ND_PRINT((ndo, "RD: %s, %s",
bgp_vpn_rd_print(ndo, tptr),
isonsap_string(ndo, tptr+BGP_VPN_RD_LEN,tlen-BGP_VPN_RD_LEN)));
/* rfc986 mapped IPv4 address ? */
if (EXTRACT_32BITS(tptr+BGP_VPN_RD_LEN) == 0x47000601)
ND_PRINT((ndo, " = %s", ipaddr_string(ndo, tptr+BGP_VPN_RD_LEN+4)));
/* rfc1888 mapped IPv6 address ? */
else if (EXTRACT_24BITS(tptr+BGP_VPN_RD_LEN) == 0x350000)
ND_PRINT((ndo, " = %s", ip6addr_string(ndo, tptr+BGP_VPN_RD_LEN+3)));
tptr += tlen;
tlen = 0;
}
break;
default:
ND_TCHECK2(tptr[0], tlen);
ND_PRINT((ndo, "no AFI %u/SAFI %u decoder", af, safi));
if (ndo->ndo_vflag <= 1)
print_unknown_data(ndo, tptr, "\n\t ", tlen);
tptr += tlen;
tlen = 0;
goto done;
break;
}
}
}
ND_PRINT((ndo, ", nh-length: %u", nhlen));
tptr += tlen;
ND_TCHECK(tptr[0]);
snpa = tptr[0];
tptr++;
if (snpa) {
ND_PRINT((ndo, "\n\t %u SNPA", snpa));
for (/*nothing*/; snpa > 0; snpa--) {
ND_TCHECK(tptr[0]);
ND_PRINT((ndo, "\n\t %d bytes", tptr[0]));
tptr += tptr[0] + 1;
}
} else {
ND_PRINT((ndo, ", no SNPA"));
}
while (tptr < pptr + len) {
switch (af<<8 | safi) {
case (AFNUM_INET<<8 | SAFNUM_UNICAST):
case (AFNUM_INET<<8 | SAFNUM_MULTICAST):
case (AFNUM_INET<<8 | SAFNUM_UNIMULTICAST):
advance = decode_prefix4(ndo, tptr, len, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else if (advance == -3)
break; /* bytes left, but not enough */
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET<<8 | SAFNUM_LABUNICAST):
advance = decode_labeled_prefix4(ndo, tptr, len, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else if (advance == -3)
break; /* bytes left, but not enough */
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_INET<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_INET<<8 | SAFNUM_VPNUNIMULTICAST):
advance = decode_labeled_vpn_prefix4(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET<<8 | SAFNUM_RT_ROUTING_INFO):
advance = decode_rt_routing_info(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET<<8 | SAFNUM_MULTICAST_VPN): /* fall through */
case (AFNUM_INET6<<8 | SAFNUM_MULTICAST_VPN):
advance = decode_multicast_vpn(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET<<8 | SAFNUM_MDT):
advance = decode_mdt_vpn_nlri(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET6<<8 | SAFNUM_UNICAST):
case (AFNUM_INET6<<8 | SAFNUM_MULTICAST):
case (AFNUM_INET6<<8 | SAFNUM_UNIMULTICAST):
advance = decode_prefix6(ndo, tptr, len, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else if (advance == -3)
break; /* bytes left, but not enough */
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET6<<8 | SAFNUM_LABUNICAST):
advance = decode_labeled_prefix6(ndo, tptr, len, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else if (advance == -3)
break; /* bytes left, but not enough */
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET6<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_INET6<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_INET6<<8 | SAFNUM_VPNUNIMULTICAST):
advance = decode_labeled_vpn_prefix6(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_VPLS<<8 | SAFNUM_VPLS):
case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_L2VPN<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNIMULTICAST):
advance = decode_labeled_vpn_l2(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_NSAP<<8 | SAFNUM_UNICAST):
case (AFNUM_NSAP<<8 | SAFNUM_MULTICAST):
case (AFNUM_NSAP<<8 | SAFNUM_UNIMULTICAST):
advance = decode_clnp_prefix(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_NSAP<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_NSAP<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_NSAP<<8 | SAFNUM_VPNUNIMULTICAST):
advance = decode_labeled_vpn_clnp_prefix(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
default:
ND_TCHECK2(*tptr,tlen);
ND_PRINT((ndo, "\n\t no AFI %u / SAFI %u decoder", af, safi));
if (ndo->ndo_vflag <= 1)
print_unknown_data(ndo, tptr, "\n\t ", tlen);
advance = 0;
tptr = pptr + len;
break;
}
if (advance < 0)
break;
tptr += advance;
}
done:
break;
case BGPTYPE_MP_UNREACH_NLRI:
ND_TCHECK2(tptr[0], BGP_MP_NLRI_MINSIZE);
af = EXTRACT_16BITS(tptr);
safi = tptr[2];
ND_PRINT((ndo, "\n\t AFI: %s (%u), %sSAFI: %s (%u)",
tok2str(af_values, "Unknown AFI", af),
af,
(safi>128) ? "vendor specific " : "", /* 128 is meanwhile wellknown */
tok2str(bgp_safi_values, "Unknown SAFI", safi),
safi));
if (len == BGP_MP_NLRI_MINSIZE)
ND_PRINT((ndo, "\n\t End-of-Rib Marker (empty NLRI)"));
tptr += 3;
while (tptr < pptr + len) {
switch (af<<8 | safi) {
case (AFNUM_INET<<8 | SAFNUM_UNICAST):
case (AFNUM_INET<<8 | SAFNUM_MULTICAST):
case (AFNUM_INET<<8 | SAFNUM_UNIMULTICAST):
advance = decode_prefix4(ndo, tptr, len, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else if (advance == -3)
break; /* bytes left, but not enough */
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET<<8 | SAFNUM_LABUNICAST):
advance = decode_labeled_prefix4(ndo, tptr, len, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else if (advance == -3)
break; /* bytes left, but not enough */
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_INET<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_INET<<8 | SAFNUM_VPNUNIMULTICAST):
advance = decode_labeled_vpn_prefix4(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET6<<8 | SAFNUM_UNICAST):
case (AFNUM_INET6<<8 | SAFNUM_MULTICAST):
case (AFNUM_INET6<<8 | SAFNUM_UNIMULTICAST):
advance = decode_prefix6(ndo, tptr, len, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else if (advance == -3)
break; /* bytes left, but not enough */
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET6<<8 | SAFNUM_LABUNICAST):
advance = decode_labeled_prefix6(ndo, tptr, len, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else if (advance == -3)
break; /* bytes left, but not enough */
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET6<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_INET6<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_INET6<<8 | SAFNUM_VPNUNIMULTICAST):
advance = decode_labeled_vpn_prefix6(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_VPLS<<8 | SAFNUM_VPLS):
case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_L2VPN<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNIMULTICAST):
advance = decode_labeled_vpn_l2(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_NSAP<<8 | SAFNUM_UNICAST):
case (AFNUM_NSAP<<8 | SAFNUM_MULTICAST):
case (AFNUM_NSAP<<8 | SAFNUM_UNIMULTICAST):
advance = decode_clnp_prefix(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_NSAP<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_NSAP<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_NSAP<<8 | SAFNUM_VPNUNIMULTICAST):
advance = decode_labeled_vpn_clnp_prefix(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET<<8 | SAFNUM_MDT):
advance = decode_mdt_vpn_nlri(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET<<8 | SAFNUM_MULTICAST_VPN): /* fall through */
case (AFNUM_INET6<<8 | SAFNUM_MULTICAST_VPN):
advance = decode_multicast_vpn(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
default:
ND_TCHECK2(*(tptr-3),tlen);
ND_PRINT((ndo, "no AFI %u / SAFI %u decoder", af, safi));
if (ndo->ndo_vflag <= 1)
print_unknown_data(ndo, tptr-3, "\n\t ", tlen);
advance = 0;
tptr = pptr + len;
break;
}
if (advance < 0)
break;
tptr += advance;
}
break;
case BGPTYPE_EXTD_COMMUNITIES:
if (len % 8) {
ND_PRINT((ndo, "invalid len"));
break;
}
while (tlen>0) {
uint16_t extd_comm;
ND_TCHECK2(tptr[0], 2);
extd_comm=EXTRACT_16BITS(tptr);
ND_PRINT((ndo, "\n\t %s (0x%04x), Flags [%s]",
tok2str(bgp_extd_comm_subtype_values,
"unknown extd community typecode",
extd_comm),
extd_comm,
bittok2str(bgp_extd_comm_flag_values, "none", extd_comm)));
ND_TCHECK2(*(tptr+2), 6);
switch(extd_comm) {
case BGP_EXT_COM_RT_0:
case BGP_EXT_COM_RO_0:
case BGP_EXT_COM_L2VPN_RT_0:
ND_PRINT((ndo, ": %u:%u (= %s)",
EXTRACT_16BITS(tptr+2),
EXTRACT_32BITS(tptr+4),
ipaddr_string(ndo, tptr+4)));
break;
case BGP_EXT_COM_RT_1:
case BGP_EXT_COM_RO_1:
case BGP_EXT_COM_L2VPN_RT_1:
case BGP_EXT_COM_VRF_RT_IMP:
ND_PRINT((ndo, ": %s:%u",
ipaddr_string(ndo, tptr+2),
EXTRACT_16BITS(tptr+6)));
break;
case BGP_EXT_COM_RT_2:
case BGP_EXT_COM_RO_2:
ND_PRINT((ndo, ": %s:%u",
as_printf(ndo, astostr, sizeof(astostr),
EXTRACT_32BITS(tptr+2)), EXTRACT_16BITS(tptr+6)));
break;
case BGP_EXT_COM_LINKBAND:
bw.i = EXTRACT_32BITS(tptr+2);
ND_PRINT((ndo, ": bandwidth: %.3f Mbps",
bw.f*8/1000000));
break;
case BGP_EXT_COM_VPN_ORIGIN:
case BGP_EXT_COM_VPN_ORIGIN2:
case BGP_EXT_COM_VPN_ORIGIN3:
case BGP_EXT_COM_VPN_ORIGIN4:
case BGP_EXT_COM_OSPF_RID:
case BGP_EXT_COM_OSPF_RID2:
ND_PRINT((ndo, "%s", ipaddr_string(ndo, tptr+2)));
break;
case BGP_EXT_COM_OSPF_RTYPE:
case BGP_EXT_COM_OSPF_RTYPE2:
ND_PRINT((ndo, ": area:%s, router-type:%s, metric-type:%s%s",
ipaddr_string(ndo, tptr+2),
tok2str(bgp_extd_comm_ospf_rtype_values,
"unknown (0x%02x)",
*(tptr+6)),
(*(tptr+7) & BGP_OSPF_RTYPE_METRIC_TYPE) ? "E2" : "",
((*(tptr+6) == BGP_OSPF_RTYPE_EXT) || (*(tptr+6) == BGP_OSPF_RTYPE_NSSA)) ? "E1" : ""));
break;
case BGP_EXT_COM_L2INFO:
ND_PRINT((ndo, ": %s Control Flags [0x%02x]:MTU %u",
tok2str(l2vpn_encaps_values,
"unknown encaps",
*(tptr+2)),
*(tptr+3),
EXTRACT_16BITS(tptr+4)));
break;
case BGP_EXT_COM_SOURCE_AS:
ND_PRINT((ndo, ": AS %u", EXTRACT_16BITS(tptr+2)));
break;
default:
ND_TCHECK2(*tptr,8);
print_unknown_data(ndo, tptr, "\n\t ", 8);
break;
}
tlen -=8;
tptr +=8;
}
break;
case BGPTYPE_PMSI_TUNNEL:
{
uint8_t tunnel_type, flags;
ND_TCHECK2(tptr[0], 5);
tunnel_type = *(tptr+1);
flags = *tptr;
tlen = len;
ND_PRINT((ndo, "\n\t Tunnel-type %s (%u), Flags [%s], MPLS Label %u",
tok2str(bgp_pmsi_tunnel_values, "Unknown", tunnel_type),
tunnel_type,
bittok2str(bgp_pmsi_flag_values, "none", flags),
EXTRACT_24BITS(tptr+2)>>4));
tptr +=5;
tlen -= 5;
switch (tunnel_type) {
case BGP_PMSI_TUNNEL_PIM_SM: /* fall through */
case BGP_PMSI_TUNNEL_PIM_BIDIR:
ND_TCHECK2(tptr[0], 8);
ND_PRINT((ndo, "\n\t Sender %s, P-Group %s",
ipaddr_string(ndo, tptr),
ipaddr_string(ndo, tptr+4)));
break;
case BGP_PMSI_TUNNEL_PIM_SSM:
ND_TCHECK2(tptr[0], 8);
ND_PRINT((ndo, "\n\t Root-Node %s, P-Group %s",
ipaddr_string(ndo, tptr),
ipaddr_string(ndo, tptr+4)));
break;
case BGP_PMSI_TUNNEL_INGRESS:
ND_TCHECK2(tptr[0], 4);
ND_PRINT((ndo, "\n\t Tunnel-Endpoint %s",
ipaddr_string(ndo, tptr)));
break;
case BGP_PMSI_TUNNEL_LDP_P2MP: /* fall through */
case BGP_PMSI_TUNNEL_LDP_MP2MP:
ND_TCHECK2(tptr[0], 8);
ND_PRINT((ndo, "\n\t Root-Node %s, LSP-ID 0x%08x",
ipaddr_string(ndo, tptr),
EXTRACT_32BITS(tptr+4)));
break;
case BGP_PMSI_TUNNEL_RSVP_P2MP:
ND_TCHECK2(tptr[0], 8);
ND_PRINT((ndo, "\n\t Extended-Tunnel-ID %s, P2MP-ID 0x%08x",
ipaddr_string(ndo, tptr),
EXTRACT_32BITS(tptr+4)));
break;
default:
if (ndo->ndo_vflag <= 1) {
print_unknown_data(ndo, tptr, "\n\t ", tlen);
}
}
break;
}
case BGPTYPE_AIGP:
{
uint8_t type;
uint16_t length;
tlen = len;
while (tlen >= 3) {
ND_TCHECK2(tptr[0], 3);
type = *tptr;
length = EXTRACT_16BITS(tptr+1);
tptr += 3;
tlen -= 3;
ND_PRINT((ndo, "\n\t %s TLV (%u), length %u",
tok2str(bgp_aigp_values, "Unknown", type),
type, length));
if (length < 3)
goto trunc;
length -= 3;
/*
* Check if we can read the TLV data.
*/
ND_TCHECK2(tptr[3], length);
switch (type) {
case BGP_AIGP_TLV:
if (length < 8)
goto trunc;
ND_PRINT((ndo, ", metric %" PRIu64,
EXTRACT_64BITS(tptr)));
break;
default:
if (ndo->ndo_vflag <= 1) {
print_unknown_data(ndo, tptr,"\n\t ", length);
}
}
tptr += length;
tlen -= length;
}
break;
}
case BGPTYPE_ATTR_SET:
ND_TCHECK2(tptr[0], 4);
if (len < 4)
goto trunc;
ND_PRINT((ndo, "\n\t Origin AS: %s",
as_printf(ndo, astostr, sizeof(astostr), EXTRACT_32BITS(tptr))));
tptr+=4;
len -=4;
while (len) {
u_int aflags, alenlen, alen;
ND_TCHECK2(tptr[0], 2);
if (len < 2)
goto trunc;
aflags = *tptr;
atype = *(tptr + 1);
tptr += 2;
len -= 2;
alenlen = bgp_attr_lenlen(aflags, tptr);
ND_TCHECK2(tptr[0], alenlen);
if (len < alenlen)
goto trunc;
alen = bgp_attr_len(aflags, tptr);
tptr += alenlen;
len -= alenlen;
ND_PRINT((ndo, "\n\t %s (%u), length: %u",
tok2str(bgp_attr_values,
"Unknown Attribute", atype),
atype,
alen));
if (aflags) {
ND_PRINT((ndo, ", Flags [%s%s%s%s",
aflags & 0x80 ? "O" : "",
aflags & 0x40 ? "T" : "",
aflags & 0x20 ? "P" : "",
aflags & 0x10 ? "E" : ""));
if (aflags & 0xf)
ND_PRINT((ndo, "+%x", aflags & 0xf));
ND_PRINT((ndo, "]: "));
}
/* FIXME check for recursion */
if (!bgp_attr_print(ndo, atype, tptr, alen))
return 0;
tptr += alen;
len -= alen;
}
break;
case BGPTYPE_LARGE_COMMUNITY:
if (len == 0 || len % 12) {
ND_PRINT((ndo, "invalid len"));
break;
}
ND_PRINT((ndo, "\n\t "));
while (len > 0) {
ND_TCHECK2(*tptr, 12);
ND_PRINT((ndo, "%u:%u:%u%s",
EXTRACT_32BITS(tptr),
EXTRACT_32BITS(tptr + 4),
EXTRACT_32BITS(tptr + 8),
(len > 12) ? ", " : ""));
tptr += 12;
len -= 12;
}
break;
default:
ND_TCHECK2(*pptr,len);
ND_PRINT((ndo, "\n\t no Attribute %u decoder", atype)); /* we have no decoder for the attribute */
if (ndo->ndo_vflag <= 1)
print_unknown_data(ndo, pptr, "\n\t ", len);
break;
}
if (ndo->ndo_vflag > 1 && len) { /* omit zero length attributes*/
ND_TCHECK2(*pptr,len);
print_unknown_data(ndo, pptr, "\n\t ", len);
}
return 1;
trunc:
return 0;
}
static void
bgp_capabilities_print(netdissect_options *ndo,
const u_char *opt, int caps_len)
{
int cap_type, cap_len, tcap_len, cap_offset;
int i = 0;
while (i < caps_len) {
ND_TCHECK2(opt[i], BGP_CAP_HEADER_SIZE);
cap_type=opt[i];
cap_len=opt[i+1];
tcap_len=cap_len;
ND_PRINT((ndo, "\n\t %s (%u), length: %u",
tok2str(bgp_capcode_values, "Unknown",
cap_type),
cap_type,
cap_len));
ND_TCHECK2(opt[i+2], cap_len);
switch (cap_type) {
case BGP_CAPCODE_MP:
ND_PRINT((ndo, "\n\t\tAFI %s (%u), SAFI %s (%u)",
tok2str(af_values, "Unknown",
EXTRACT_16BITS(opt+i+2)),
EXTRACT_16BITS(opt+i+2),
tok2str(bgp_safi_values, "Unknown",
opt[i+5]),
opt[i+5]));
break;
case BGP_CAPCODE_RESTART:
ND_PRINT((ndo, "\n\t\tRestart Flags: [%s], Restart Time %us",
((opt[i+2])&0x80) ? "R" : "none",
EXTRACT_16BITS(opt+i+2)&0xfff));
tcap_len-=2;
cap_offset=4;
while(tcap_len>=4) {
ND_PRINT((ndo, "\n\t\t AFI %s (%u), SAFI %s (%u), Forwarding state preserved: %s",
tok2str(af_values,"Unknown",
EXTRACT_16BITS(opt+i+cap_offset)),
EXTRACT_16BITS(opt+i+cap_offset),
tok2str(bgp_safi_values,"Unknown",
opt[i+cap_offset+2]),
opt[i+cap_offset+2],
((opt[i+cap_offset+3])&0x80) ? "yes" : "no" ));
tcap_len-=4;
cap_offset+=4;
}
break;
case BGP_CAPCODE_RR:
case BGP_CAPCODE_RR_CISCO:
break;
case BGP_CAPCODE_AS_NEW:
/*
* Extract the 4 byte AS number encoded.
*/
if (cap_len == 4) {
ND_PRINT((ndo, "\n\t\t 4 Byte AS %s",
as_printf(ndo, astostr, sizeof(astostr),
EXTRACT_32BITS(opt + i + 2))));
}
break;
case BGP_CAPCODE_ADD_PATH:
cap_offset=2;
if (tcap_len == 0) {
ND_PRINT((ndo, " (bogus)")); /* length */
break;
}
while (tcap_len > 0) {
if (tcap_len < 4) {
ND_PRINT((ndo, "\n\t\t(invalid)"));
break;
}
ND_PRINT((ndo, "\n\t\tAFI %s (%u), SAFI %s (%u), Send/Receive: %s",
tok2str(af_values,"Unknown",EXTRACT_16BITS(opt+i+cap_offset)),
EXTRACT_16BITS(opt+i+cap_offset),
tok2str(bgp_safi_values,"Unknown",opt[i+cap_offset+2]),
opt[i+cap_offset+2],
tok2str(bgp_add_path_recvsend,"Bogus (0x%02x)",opt[i+cap_offset+3])
));
tcap_len-=4;
cap_offset+=4;
}
break;
default:
ND_PRINT((ndo, "\n\t\tno decoder for Capability %u",
cap_type));
if (ndo->ndo_vflag <= 1)
print_unknown_data(ndo, &opt[i+2], "\n\t\t", cap_len);
break;
}
if (ndo->ndo_vflag > 1 && cap_len > 0) {
print_unknown_data(ndo, &opt[i+2], "\n\t\t", cap_len);
}
i += BGP_CAP_HEADER_SIZE + cap_len;
}
return;
trunc:
ND_PRINT((ndo, "[|BGP]"));
}
static void
bgp_open_print(netdissect_options *ndo,
const u_char *dat, int length)
{
struct bgp_open bgpo;
struct bgp_opt bgpopt;
const u_char *opt;
int i;
ND_TCHECK2(dat[0], BGP_OPEN_SIZE);
memcpy(&bgpo, dat, BGP_OPEN_SIZE);
ND_PRINT((ndo, "\n\t Version %d, ", bgpo.bgpo_version));
ND_PRINT((ndo, "my AS %s, ",
as_printf(ndo, astostr, sizeof(astostr), ntohs(bgpo.bgpo_myas))));
ND_PRINT((ndo, "Holdtime %us, ", ntohs(bgpo.bgpo_holdtime)));
ND_PRINT((ndo, "ID %s", ipaddr_string(ndo, &bgpo.bgpo_id)));
ND_PRINT((ndo, "\n\t Optional parameters, length: %u", bgpo.bgpo_optlen));
/* some little sanity checking */
if (length < bgpo.bgpo_optlen+BGP_OPEN_SIZE)
return;
/* ugly! */
opt = &((const struct bgp_open *)dat)->bgpo_optlen;
opt++;
i = 0;
while (i < bgpo.bgpo_optlen) {
ND_TCHECK2(opt[i], BGP_OPT_SIZE);
memcpy(&bgpopt, &opt[i], BGP_OPT_SIZE);
if (i + 2 + bgpopt.bgpopt_len > bgpo.bgpo_optlen) {
ND_PRINT((ndo, "\n\t Option %d, length: %u", bgpopt.bgpopt_type, bgpopt.bgpopt_len));
break;
}
ND_PRINT((ndo, "\n\t Option %s (%u), length: %u",
tok2str(bgp_opt_values,"Unknown",
bgpopt.bgpopt_type),
bgpopt.bgpopt_type,
bgpopt.bgpopt_len));
/* now let's decode the options we know*/
switch(bgpopt.bgpopt_type) {
case BGP_OPT_CAP:
bgp_capabilities_print(ndo, &opt[i+BGP_OPT_SIZE],
bgpopt.bgpopt_len);
break;
case BGP_OPT_AUTH:
default:
ND_PRINT((ndo, "\n\t no decoder for option %u",
bgpopt.bgpopt_type));
break;
}
i += BGP_OPT_SIZE + bgpopt.bgpopt_len;
}
return;
trunc:
ND_PRINT((ndo, "[|BGP]"));
}
static void
bgp_update_print(netdissect_options *ndo,
const u_char *dat, int length)
{
struct bgp bgp;
const u_char *p;
int withdrawn_routes_len;
int len;
int i;
ND_TCHECK2(dat[0], BGP_SIZE);
if (length < BGP_SIZE)
goto trunc;
memcpy(&bgp, dat, BGP_SIZE);
p = dat + BGP_SIZE; /*XXX*/
length -= BGP_SIZE;
/* Unfeasible routes */
ND_TCHECK2(p[0], 2);
if (length < 2)
goto trunc;
withdrawn_routes_len = EXTRACT_16BITS(p);
p += 2;
length -= 2;
if (withdrawn_routes_len) {
/*
* Without keeping state from the original NLRI message,
* it's not possible to tell if this a v4 or v6 route,
* so only try to decode it if we're not v6 enabled.
*/
ND_TCHECK2(p[0], withdrawn_routes_len);
if (length < withdrawn_routes_len)
goto trunc;
ND_PRINT((ndo, "\n\t Withdrawn routes: %d bytes", withdrawn_routes_len));
p += withdrawn_routes_len;
length -= withdrawn_routes_len;
}
ND_TCHECK2(p[0], 2);
if (length < 2)
goto trunc;
len = EXTRACT_16BITS(p);
p += 2;
length -= 2;
if (withdrawn_routes_len == 0 && len == 0 && length == 0) {
/* No withdrawn routes, no path attributes, no NLRI */
ND_PRINT((ndo, "\n\t End-of-Rib Marker (empty NLRI)"));
return;
}
if (len) {
/* do something more useful!*/
while (len) {
int aflags, atype, alenlen, alen;
ND_TCHECK2(p[0], 2);
if (len < 2)
goto trunc;
if (length < 2)
goto trunc;
aflags = *p;
atype = *(p + 1);
p += 2;
len -= 2;
length -= 2;
alenlen = bgp_attr_lenlen(aflags, p);
ND_TCHECK2(p[0], alenlen);
if (len < alenlen)
goto trunc;
if (length < alenlen)
goto trunc;
alen = bgp_attr_len(aflags, p);
p += alenlen;
len -= alenlen;
length -= alenlen;
ND_PRINT((ndo, "\n\t %s (%u), length: %u",
tok2str(bgp_attr_values, "Unknown Attribute",
atype),
atype,
alen));
if (aflags) {
ND_PRINT((ndo, ", Flags [%s%s%s%s",
aflags & 0x80 ? "O" : "",
aflags & 0x40 ? "T" : "",
aflags & 0x20 ? "P" : "",
aflags & 0x10 ? "E" : ""));
if (aflags & 0xf)
ND_PRINT((ndo, "+%x", aflags & 0xf));
ND_PRINT((ndo, "]: "));
}
if (len < alen)
goto trunc;
if (length < alen)
goto trunc;
if (!bgp_attr_print(ndo, atype, p, alen))
goto trunc;
p += alen;
len -= alen;
length -= alen;
}
}
if (length) {
/*
* XXX - what if they're using the "Advertisement of
* Multiple Paths in BGP" feature:
*
* https://datatracker.ietf.org/doc/draft-ietf-idr-add-paths/
*
* http://tools.ietf.org/html/draft-ietf-idr-add-paths-06
*/
ND_PRINT((ndo, "\n\t Updated routes:"));
while (length) {
char buf[MAXHOSTNAMELEN + 100];
i = decode_prefix4(ndo, p, length, buf, sizeof(buf));
if (i == -1) {
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
break;
} else if (i == -2)
goto trunc;
else if (i == -3)
goto trunc; /* bytes left, but not enough */
else {
ND_PRINT((ndo, "\n\t %s", buf));
p += i;
length -= i;
}
}
}
return;
trunc:
ND_PRINT((ndo, "[|BGP]"));
}
static void
bgp_notification_print(netdissect_options *ndo,
const u_char *dat, int length)
{
struct bgp_notification bgpn;
const u_char *tptr;
uint8_t shutdown_comm_length;
uint8_t remainder_offset;
ND_TCHECK2(dat[0], BGP_NOTIFICATION_SIZE);
memcpy(&bgpn, dat, BGP_NOTIFICATION_SIZE);
/* some little sanity checking */
if (length<BGP_NOTIFICATION_SIZE)
return;
ND_PRINT((ndo, ", %s (%u)",
tok2str(bgp_notify_major_values, "Unknown Error",
bgpn.bgpn_major),
bgpn.bgpn_major));
switch (bgpn.bgpn_major) {
case BGP_NOTIFY_MAJOR_MSG:
ND_PRINT((ndo, ", subcode %s (%u)",
tok2str(bgp_notify_minor_msg_values, "Unknown",
bgpn.bgpn_minor),
bgpn.bgpn_minor));
break;
case BGP_NOTIFY_MAJOR_OPEN:
ND_PRINT((ndo, ", subcode %s (%u)",
tok2str(bgp_notify_minor_open_values, "Unknown",
bgpn.bgpn_minor),
bgpn.bgpn_minor));
break;
case BGP_NOTIFY_MAJOR_UPDATE:
ND_PRINT((ndo, ", subcode %s (%u)",
tok2str(bgp_notify_minor_update_values, "Unknown",
bgpn.bgpn_minor),
bgpn.bgpn_minor));
break;
case BGP_NOTIFY_MAJOR_FSM:
ND_PRINT((ndo, " subcode %s (%u)",
tok2str(bgp_notify_minor_fsm_values, "Unknown",
bgpn.bgpn_minor),
bgpn.bgpn_minor));
break;
case BGP_NOTIFY_MAJOR_CAP:
ND_PRINT((ndo, " subcode %s (%u)",
tok2str(bgp_notify_minor_cap_values, "Unknown",
bgpn.bgpn_minor),
bgpn.bgpn_minor));
break;
case BGP_NOTIFY_MAJOR_CEASE:
ND_PRINT((ndo, ", subcode %s (%u)",
tok2str(bgp_notify_minor_cease_values, "Unknown",
bgpn.bgpn_minor),
bgpn.bgpn_minor));
/* draft-ietf-idr-cease-subcode-02 mentions optionally 7 bytes
* for the maxprefix subtype, which may contain AFI, SAFI and MAXPREFIXES
*/
if(bgpn.bgpn_minor == BGP_NOTIFY_MINOR_CEASE_MAXPRFX && length >= BGP_NOTIFICATION_SIZE + 7) {
tptr = dat + BGP_NOTIFICATION_SIZE;
ND_TCHECK2(*tptr, 7);
ND_PRINT((ndo, ", AFI %s (%u), SAFI %s (%u), Max Prefixes: %u",
tok2str(af_values, "Unknown",
EXTRACT_16BITS(tptr)),
EXTRACT_16BITS(tptr),
tok2str(bgp_safi_values, "Unknown", *(tptr+2)),
*(tptr+2),
EXTRACT_32BITS(tptr+3)));
}
/*
* draft-ietf-idr-shutdown describes a method to send a communication
* intended for human consumption regarding the Administrative Shutdown
*/
if ((bgpn.bgpn_minor == BGP_NOTIFY_MINOR_CEASE_SHUT ||
bgpn.bgpn_minor == BGP_NOTIFY_MINOR_CEASE_RESET) &&
length >= BGP_NOTIFICATION_SIZE + 1) {
tptr = dat + BGP_NOTIFICATION_SIZE;
ND_TCHECK2(*tptr, 1);
shutdown_comm_length = *(tptr);
remainder_offset = 0;
/* garbage, hexdump it all */
if (shutdown_comm_length > BGP_NOTIFY_MINOR_CEASE_ADMIN_SHUTDOWN_LEN ||
shutdown_comm_length > length - (BGP_NOTIFICATION_SIZE + 1)) {
ND_PRINT((ndo, ", invalid Shutdown Communication length"));
}
else if (shutdown_comm_length == 0) {
ND_PRINT((ndo, ", empty Shutdown Communication"));
remainder_offset += 1;
}
/* a proper shutdown communication */
else {
ND_TCHECK2(*(tptr+1), shutdown_comm_length);
ND_PRINT((ndo, ", Shutdown Communication (length: %u): \"", shutdown_comm_length));
(void)fn_printn(ndo, tptr+1, shutdown_comm_length, NULL);
ND_PRINT((ndo, "\""));
remainder_offset += shutdown_comm_length + 1;
}
/* if there is trailing data, hexdump it */
if(length - (remainder_offset + BGP_NOTIFICATION_SIZE) > 0) {
ND_PRINT((ndo, ", Data: (length: %u)", length - (remainder_offset + BGP_NOTIFICATION_SIZE)));
hex_print(ndo, "\n\t\t", tptr + remainder_offset, length - (remainder_offset + BGP_NOTIFICATION_SIZE));
}
}
break;
default:
break;
}
return;
trunc:
ND_PRINT((ndo, "[|BGP]"));
}
static void
bgp_route_refresh_print(netdissect_options *ndo,
const u_char *pptr, int len)
{
const struct bgp_route_refresh *bgp_route_refresh_header;
ND_TCHECK2(pptr[0], BGP_ROUTE_REFRESH_SIZE);
/* some little sanity checking */
if (len<BGP_ROUTE_REFRESH_SIZE)
return;
bgp_route_refresh_header = (const struct bgp_route_refresh *)pptr;
ND_PRINT((ndo, "\n\t AFI %s (%u), SAFI %s (%u)",
tok2str(af_values,"Unknown",
/* this stinks but the compiler pads the structure
* weird */
EXTRACT_16BITS(&bgp_route_refresh_header->afi)),
EXTRACT_16BITS(&bgp_route_refresh_header->afi),
tok2str(bgp_safi_values,"Unknown",
bgp_route_refresh_header->safi),
bgp_route_refresh_header->safi));
if (ndo->ndo_vflag > 1) {
ND_TCHECK2(*pptr, len);
print_unknown_data(ndo, pptr, "\n\t ", len);
}
return;
trunc:
ND_PRINT((ndo, "[|BGP]"));
}
static int
bgp_header_print(netdissect_options *ndo,
const u_char *dat, int length)
{
struct bgp bgp;
ND_TCHECK2(dat[0], BGP_SIZE);
memcpy(&bgp, dat, BGP_SIZE);
ND_PRINT((ndo, "\n\t%s Message (%u), length: %u",
tok2str(bgp_msg_values, "Unknown", bgp.bgp_type),
bgp.bgp_type,
length));
switch (bgp.bgp_type) {
case BGP_OPEN:
bgp_open_print(ndo, dat, length);
break;
case BGP_UPDATE:
bgp_update_print(ndo, dat, length);
break;
case BGP_NOTIFICATION:
bgp_notification_print(ndo, dat, length);
break;
case BGP_KEEPALIVE:
break;
case BGP_ROUTE_REFRESH:
bgp_route_refresh_print(ndo, dat, length);
break;
default:
/* we have no decoder for the BGP message */
ND_TCHECK2(*dat, length);
ND_PRINT((ndo, "\n\t no Message %u decoder", bgp.bgp_type));
print_unknown_data(ndo, dat, "\n\t ", length);
break;
}
return 1;
trunc:
ND_PRINT((ndo, "[|BGP]"));
return 0;
}
void
bgp_print(netdissect_options *ndo,
const u_char *dat, int length)
{
const u_char *p;
const u_char *ep;
const u_char *start;
const u_char marker[] = {
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
};
struct bgp bgp;
uint16_t hlen;
ep = dat + length;
if (ndo->ndo_snapend < dat + length)
ep = ndo->ndo_snapend;
ND_PRINT((ndo, ": BGP"));
if (ndo->ndo_vflag < 1) /* lets be less chatty */
return;
p = dat;
start = p;
while (p < ep) {
if (!ND_TTEST2(p[0], 1))
break;
if (p[0] != 0xff) {
p++;
continue;
}
if (!ND_TTEST2(p[0], sizeof(marker)))
break;
if (memcmp(p, marker, sizeof(marker)) != 0) {
p++;
continue;
}
/* found BGP header */
ND_TCHECK2(p[0], BGP_SIZE); /*XXX*/
memcpy(&bgp, p, BGP_SIZE);
if (start != p)
ND_PRINT((ndo, " [|BGP]"));
hlen = ntohs(bgp.bgp_len);
if (hlen < BGP_SIZE) {
ND_PRINT((ndo, "\n[|BGP Bogus header length %u < %u]", hlen,
BGP_SIZE));
break;
}
if (ND_TTEST2(p[0], hlen)) {
if (!bgp_header_print(ndo, p, hlen))
return;
p += hlen;
start = p;
} else {
ND_PRINT((ndo, "\n[|BGP %s]",
tok2str(bgp_msg_values,
"Unknown Message Type",
bgp.bgp_type)));
break;
}
}
return;
trunc:
ND_PRINT((ndo, " [|BGP]"));
}
/*
* Local Variables:
* c-style: whitesmith
* c-basic-offset: 4
* End:
*/
| ./CrossVul/dataset_final_sorted/CWE-125/c/good_2722_0 |
crossvul-cpp_data_good_5330_0 | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% PPPP RRRR OOO FFFFF IIIII L EEEEE %
% P P R R O O F I L E %
% PPPP RRRR O O FFF I L EEE %
% P R R O O F I L E %
% P R R OOO F IIIII LLLLL EEEEE %
% %
% %
% MagickCore Image Profile 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/attribute.h"
#include "MagickCore/cache.h"
#include "MagickCore/color.h"
#include "MagickCore/colorspace-private.h"
#include "MagickCore/configure.h"
#include "MagickCore/exception.h"
#include "MagickCore/exception-private.h"
#include "MagickCore/image.h"
#include "MagickCore/linked-list.h"
#include "MagickCore/memory_.h"
#include "MagickCore/monitor.h"
#include "MagickCore/monitor-private.h"
#include "MagickCore/option.h"
#include "MagickCore/option-private.h"
#include "MagickCore/pixel-accessor.h"
#include "MagickCore/profile.h"
#include "MagickCore/profile-private.h"
#include "MagickCore/property.h"
#include "MagickCore/quantum.h"
#include "MagickCore/quantum-private.h"
#include "MagickCore/resource_.h"
#include "MagickCore/splay-tree.h"
#include "MagickCore/string_.h"
#include "MagickCore/thread-private.h"
#include "MagickCore/token.h"
#include "MagickCore/utility.h"
#if defined(MAGICKCORE_LCMS_DELEGATE)
#if defined(MAGICKCORE_HAVE_LCMS_LCMS2_H)
#include <wchar.h>
#include <lcms/lcms2.h>
#else
#include <wchar.h>
#include "lcms2.h"
#endif
#endif
/*
Forward declarations
*/
static MagickBooleanType
SetImageProfileInternal(Image *,const char *,const StringInfo *,
const MagickBooleanType,ExceptionInfo *);
static void
WriteTo8BimProfile(Image *,const char*,const StringInfo *);
/*
Typedef declarations
*/
struct _ProfileInfo
{
char
*name;
size_t
length;
unsigned char
*info;
size_t
signature;
};
typedef struct _CMSExceptionInfo
{
Image
*image;
ExceptionInfo
*exception;
} CMSExceptionInfo;
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% C l o n e I m a g e P r o f i l e s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% CloneImageProfiles() clones one or more image profiles.
%
% The format of the CloneImageProfiles method is:
%
% MagickBooleanType CloneImageProfiles(Image *image,
% const Image *clone_image)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o clone_image: the clone image.
%
*/
MagickExport MagickBooleanType CloneImageProfiles(Image *image,
const Image *clone_image)
{
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(clone_image != (const Image *) NULL);
assert(clone_image->signature == MagickCoreSignature);
if (clone_image->profiles != (void *) NULL)
{
if (image->profiles != (void *) NULL)
DestroyImageProfiles(image);
image->profiles=CloneSplayTree((SplayTreeInfo *) clone_image->profiles,
(void *(*)(void *)) ConstantString,(void *(*)(void *)) CloneStringInfo);
}
return(MagickTrue);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% D e l e t e I m a g e P r o f i l e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% DeleteImageProfile() deletes a profile from the image by its name.
%
% The format of the DeleteImageProfile method is:
%
% MagickBooleanTyupe DeleteImageProfile(Image *image,const char *name)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o name: the profile name.
%
*/
MagickExport MagickBooleanType DeleteImageProfile(Image *image,const char *name)
{
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
if (image->profiles == (SplayTreeInfo *) NULL)
return(MagickFalse);
WriteTo8BimProfile(image,name,(StringInfo *) NULL);
return(DeleteNodeFromSplayTree((SplayTreeInfo *) image->profiles,name));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% D e s t r o y I m a g e P r o f i l e s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% DestroyImageProfiles() releases memory associated with an image profile map.
%
% The format of the DestroyProfiles method is:
%
% void DestroyImageProfiles(Image *image)
%
% A description of each parameter follows:
%
% o image: the image.
%
*/
MagickExport void DestroyImageProfiles(Image *image)
{
if (image->profiles != (SplayTreeInfo *) NULL)
image->profiles=DestroySplayTree((SplayTreeInfo *) image->profiles);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% G e t I m a g e P r o f i l e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetImageProfile() gets a profile associated with an image by name.
%
% The format of the GetImageProfile method is:
%
% const StringInfo *GetImageProfile(const Image *image,const char *name)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o name: the profile name.
%
*/
MagickExport const StringInfo *GetImageProfile(const Image *image,
const char *name)
{
const StringInfo
*profile;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
if (image->profiles == (SplayTreeInfo *) NULL)
return((StringInfo *) NULL);
profile=(const StringInfo *) GetValueFromSplayTree((SplayTreeInfo *)
image->profiles,name);
return(profile);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% G e t N e x t I m a g e P r o f i l e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetNextImageProfile() gets the next profile name for an image.
%
% The format of the GetNextImageProfile method is:
%
% char *GetNextImageProfile(const Image *image)
%
% A description of each parameter follows:
%
% o hash_info: the hash info.
%
*/
MagickExport char *GetNextImageProfile(const Image *image)
{
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
if (image->profiles == (SplayTreeInfo *) NULL)
return((char *) NULL);
return((char *) GetNextKeyInSplayTree((SplayTreeInfo *) image->profiles));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% P r o f i l e I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ProfileImage() associates, applies, or removes an ICM, IPTC, or generic
% profile with / to / from an image. If the profile is NULL, it is removed
% from the image otherwise added or applied. Use a name of '*' and a profile
% of NULL to remove all profiles from the image.
%
% ICC and ICM profiles are handled as follows: If the image does not have
% an associated color profile, the one you provide is associated with the
% image and the image pixels are not transformed. Otherwise, the colorspace
% transform defined by the existing and new profile are applied to the image
% pixels and the new profile is associated with the image.
%
% The format of the ProfileImage method is:
%
% MagickBooleanType ProfileImage(Image *image,const char *name,
% const void *datum,const size_t length,const MagickBooleanType clone)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o name: Name of profile to add or remove: ICC, IPTC, or generic profile.
%
% o datum: the profile data.
%
% o length: the length of the profile.
%
% o clone: should be MagickFalse.
%
*/
#if defined(MAGICKCORE_LCMS_DELEGATE)
static unsigned short **DestroyPixelThreadSet(unsigned short **pixels)
{
register ssize_t
i;
assert(pixels != (unsigned short **) NULL);
for (i=0; i < (ssize_t) GetMagickResourceLimit(ThreadResource); i++)
if (pixels[i] != (unsigned short *) NULL)
pixels[i]=(unsigned short *) RelinquishMagickMemory(pixels[i]);
pixels=(unsigned short **) RelinquishMagickMemory(pixels);
return(pixels);
}
static unsigned short **AcquirePixelThreadSet(const size_t columns,
const size_t channels)
{
register ssize_t
i;
unsigned short
**pixels;
size_t
number_threads;
number_threads=(size_t) GetMagickResourceLimit(ThreadResource);
pixels=(unsigned short **) AcquireQuantumMemory(number_threads,
sizeof(*pixels));
if (pixels == (unsigned short **) NULL)
return((unsigned short **) NULL);
(void) ResetMagickMemory(pixels,0,number_threads*sizeof(*pixels));
for (i=0; i < (ssize_t) number_threads; i++)
{
pixels[i]=(unsigned short *) AcquireQuantumMemory(columns,channels*
sizeof(**pixels));
if (pixels[i] == (unsigned short *) NULL)
return(DestroyPixelThreadSet(pixels));
}
return(pixels);
}
static cmsHTRANSFORM *DestroyTransformThreadSet(cmsHTRANSFORM *transform)
{
register ssize_t
i;
assert(transform != (cmsHTRANSFORM *) NULL);
for (i=0; i < (ssize_t) GetMagickResourceLimit(ThreadResource); i++)
if (transform[i] != (cmsHTRANSFORM) NULL)
cmsDeleteTransform(transform[i]);
transform=(cmsHTRANSFORM *) RelinquishMagickMemory(transform);
return(transform);
}
static cmsHTRANSFORM *AcquireTransformThreadSet(Image *image,
const cmsHPROFILE source_profile,const cmsUInt32Number source_type,
const cmsHPROFILE target_profile,const cmsUInt32Number target_type,
const int intent,const cmsUInt32Number flags)
{
cmsHTRANSFORM
*transform;
register ssize_t
i;
size_t
number_threads;
number_threads=(size_t) GetMagickResourceLimit(ThreadResource);
transform=(cmsHTRANSFORM *) AcquireQuantumMemory(number_threads,
sizeof(*transform));
if (transform == (cmsHTRANSFORM *) NULL)
return((cmsHTRANSFORM *) NULL);
(void) ResetMagickMemory(transform,0,number_threads*sizeof(*transform));
for (i=0; i < (ssize_t) number_threads; i++)
{
transform[i]=cmsCreateTransformTHR((cmsContext) image,source_profile,
source_type,target_profile,target_type,intent,flags);
if (transform[i] == (cmsHTRANSFORM) NULL)
return(DestroyTransformThreadSet(transform));
}
return(transform);
}
#endif
#if defined(MAGICKCORE_LCMS_DELEGATE)
static void CMSExceptionHandler(cmsContext context,cmsUInt32Number severity,
const char *message)
{
CMSExceptionInfo
*cms_exception;
ExceptionInfo
*exception;
Image
*image;
cms_exception=(CMSExceptionInfo *) context;
if (cms_exception == (CMSExceptionInfo *) NULL)
return;
exception=cms_exception->exception;
if (exception == (ExceptionInfo *) NULL)
return;
image=cms_exception->image;
if (image == (Image *) NULL)
{
(void) ThrowMagickException(exception,GetMagickModule(),ImageWarning,
"UnableToTransformColorspace","`%s'","unknown context");
return;
}
if (image->debug != MagickFalse)
(void) LogMagickEvent(TransformEvent,GetMagickModule(),"lcms: #%u, %s",
severity,message != (char *) NULL ? message : "no message");
(void) ThrowMagickException(exception,GetMagickModule(),ImageWarning,
"UnableToTransformColorspace","`%s'",image->filename);
}
#endif
static MagickBooleanType SetsRGBImageProfile(Image *image,
ExceptionInfo *exception)
{
static unsigned char
sRGBProfile[] =
{
0x00, 0x00, 0x0c, 0x8c, 0x61, 0x72, 0x67, 0x6c, 0x02, 0x20, 0x00, 0x00,
0x6d, 0x6e, 0x74, 0x72, 0x52, 0x47, 0x42, 0x20, 0x58, 0x59, 0x5a, 0x20,
0x07, 0xde, 0x00, 0x01, 0x00, 0x06, 0x00, 0x16, 0x00, 0x0f, 0x00, 0x3a,
0x61, 0x63, 0x73, 0x70, 0x4d, 0x53, 0x46, 0x54, 0x00, 0x00, 0x00, 0x00,
0x49, 0x45, 0x43, 0x20, 0x73, 0x52, 0x47, 0x42, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf6, 0xd6,
0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0xd3, 0x2d, 0x61, 0x72, 0x67, 0x6c,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x11,
0x64, 0x65, 0x73, 0x63, 0x00, 0x00, 0x01, 0x50, 0x00, 0x00, 0x00, 0x99,
0x63, 0x70, 0x72, 0x74, 0x00, 0x00, 0x01, 0xec, 0x00, 0x00, 0x00, 0x67,
0x64, 0x6d, 0x6e, 0x64, 0x00, 0x00, 0x02, 0x54, 0x00, 0x00, 0x00, 0x70,
0x64, 0x6d, 0x64, 0x64, 0x00, 0x00, 0x02, 0xc4, 0x00, 0x00, 0x00, 0x88,
0x74, 0x65, 0x63, 0x68, 0x00, 0x00, 0x03, 0x4c, 0x00, 0x00, 0x00, 0x0c,
0x76, 0x75, 0x65, 0x64, 0x00, 0x00, 0x03, 0x58, 0x00, 0x00, 0x00, 0x67,
0x76, 0x69, 0x65, 0x77, 0x00, 0x00, 0x03, 0xc0, 0x00, 0x00, 0x00, 0x24,
0x6c, 0x75, 0x6d, 0x69, 0x00, 0x00, 0x03, 0xe4, 0x00, 0x00, 0x00, 0x14,
0x6d, 0x65, 0x61, 0x73, 0x00, 0x00, 0x03, 0xf8, 0x00, 0x00, 0x00, 0x24,
0x77, 0x74, 0x70, 0x74, 0x00, 0x00, 0x04, 0x1c, 0x00, 0x00, 0x00, 0x14,
0x62, 0x6b, 0x70, 0x74, 0x00, 0x00, 0x04, 0x30, 0x00, 0x00, 0x00, 0x14,
0x72, 0x58, 0x59, 0x5a, 0x00, 0x00, 0x04, 0x44, 0x00, 0x00, 0x00, 0x14,
0x67, 0x58, 0x59, 0x5a, 0x00, 0x00, 0x04, 0x58, 0x00, 0x00, 0x00, 0x14,
0x62, 0x58, 0x59, 0x5a, 0x00, 0x00, 0x04, 0x6c, 0x00, 0x00, 0x00, 0x14,
0x72, 0x54, 0x52, 0x43, 0x00, 0x00, 0x04, 0x80, 0x00, 0x00, 0x08, 0x0c,
0x67, 0x54, 0x52, 0x43, 0x00, 0x00, 0x04, 0x80, 0x00, 0x00, 0x08, 0x0c,
0x62, 0x54, 0x52, 0x43, 0x00, 0x00, 0x04, 0x80, 0x00, 0x00, 0x08, 0x0c,
0x64, 0x65, 0x73, 0x63, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3f,
0x73, 0x52, 0x47, 0x42, 0x20, 0x49, 0x45, 0x43, 0x36, 0x31, 0x39, 0x36,
0x36, 0x2d, 0x32, 0x2e, 0x31, 0x20, 0x28, 0x45, 0x71, 0x75, 0x69, 0x76,
0x61, 0x6c, 0x65, 0x6e, 0x74, 0x20, 0x74, 0x6f, 0x20, 0x77, 0x77, 0x77,
0x2e, 0x73, 0x72, 0x67, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x20, 0x31, 0x39,
0x39, 0x38, 0x20, 0x48, 0x50, 0x20, 0x70, 0x72, 0x6f, 0x66, 0x69, 0x6c,
0x65, 0x29, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x3f, 0x73, 0x52, 0x47, 0x42, 0x20, 0x49, 0x45, 0x43, 0x36, 0x31,
0x39, 0x36, 0x36, 0x2d, 0x32, 0x2e, 0x31, 0x20, 0x28, 0x45, 0x71, 0x75,
0x69, 0x76, 0x61, 0x6c, 0x65, 0x6e, 0x74, 0x20, 0x74, 0x6f, 0x20, 0x77,
0x77, 0x77, 0x2e, 0x73, 0x72, 0x67, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x20,
0x31, 0x39, 0x39, 0x38, 0x20, 0x48, 0x50, 0x20, 0x70, 0x72, 0x6f, 0x66,
0x69, 0x6c, 0x65, 0x29, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x74, 0x65, 0x78, 0x74, 0x00, 0x00, 0x00, 0x00, 0x43, 0x72, 0x65, 0x61,
0x74, 0x65, 0x64, 0x20, 0x62, 0x79, 0x20, 0x47, 0x72, 0x61, 0x65, 0x6d,
0x65, 0x20, 0x57, 0x2e, 0x20, 0x47, 0x69, 0x6c, 0x6c, 0x2e, 0x20, 0x52,
0x65, 0x6c, 0x65, 0x61, 0x73, 0x65, 0x64, 0x20, 0x69, 0x6e, 0x74, 0x6f,
0x20, 0x74, 0x68, 0x65, 0x20, 0x70, 0x75, 0x62, 0x6c, 0x69, 0x63, 0x20,
0x64, 0x6f, 0x6d, 0x61, 0x69, 0x6e, 0x2e, 0x20, 0x4e, 0x6f, 0x20, 0x57,
0x61, 0x72, 0x72, 0x61, 0x6e, 0x74, 0x79, 0x2c, 0x20, 0x55, 0x73, 0x65,
0x20, 0x61, 0x74, 0x20, 0x79, 0x6f, 0x75, 0x72, 0x20, 0x6f, 0x77, 0x6e,
0x20, 0x72, 0x69, 0x73, 0x6b, 0x2e, 0x00, 0x00, 0x64, 0x65, 0x73, 0x63,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x16, 0x49, 0x45, 0x43, 0x20,
0x68, 0x74, 0x74, 0x70, 0x3a, 0x2f, 0x2f, 0x77, 0x77, 0x77, 0x2e, 0x69,
0x65, 0x63, 0x2e, 0x63, 0x68, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x16, 0x49, 0x45, 0x43, 0x20, 0x68, 0x74, 0x74,
0x70, 0x3a, 0x2f, 0x2f, 0x77, 0x77, 0x77, 0x2e, 0x69, 0x65, 0x63, 0x2e,
0x63, 0x68, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x64, 0x65, 0x73, 0x63, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x2e,
0x49, 0x45, 0x43, 0x20, 0x36, 0x31, 0x39, 0x36, 0x36, 0x2d, 0x32, 0x2e,
0x31, 0x20, 0x44, 0x65, 0x66, 0x61, 0x75, 0x6c, 0x74, 0x20, 0x52, 0x47,
0x42, 0x20, 0x63, 0x6f, 0x6c, 0x6f, 0x75, 0x72, 0x20, 0x73, 0x70, 0x61,
0x63, 0x65, 0x20, 0x2d, 0x20, 0x73, 0x52, 0x47, 0x42, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x2e, 0x49, 0x45, 0x43,
0x20, 0x36, 0x31, 0x39, 0x36, 0x36, 0x2d, 0x32, 0x2e, 0x31, 0x20, 0x44,
0x65, 0x66, 0x61, 0x75, 0x6c, 0x74, 0x20, 0x52, 0x47, 0x42, 0x20, 0x63,
0x6f, 0x6c, 0x6f, 0x75, 0x72, 0x20, 0x73, 0x70, 0x61, 0x63, 0x65, 0x20,
0x2d, 0x20, 0x73, 0x52, 0x47, 0x42, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x73, 0x69, 0x67, 0x20, 0x00, 0x00, 0x00, 0x00,
0x43, 0x52, 0x54, 0x20, 0x64, 0x65, 0x73, 0x63, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x0d, 0x49, 0x45, 0x43, 0x36, 0x31, 0x39, 0x36, 0x36,
0x2d, 0x32, 0x2e, 0x31, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x0d, 0x49, 0x45, 0x43, 0x36, 0x31, 0x39, 0x36, 0x36,
0x2d, 0x32, 0x2e, 0x31, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x76, 0x69, 0x65, 0x77, 0x00, 0x00, 0x00, 0x00, 0x00, 0x13, 0xa4, 0x7c,
0x00, 0x14, 0x5f, 0x30, 0x00, 0x10, 0xce, 0x02, 0x00, 0x03, 0xed, 0xb2,
0x00, 0x04, 0x13, 0x0a, 0x00, 0x03, 0x5c, 0x67, 0x00, 0x00, 0x00, 0x01,
0x58, 0x59, 0x5a, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x4c, 0x0a, 0x3d,
0x00, 0x50, 0x00, 0x00, 0x00, 0x57, 0x1e, 0xb8, 0x6d, 0x65, 0x61, 0x73,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x02, 0x8f, 0x00, 0x00, 0x00, 0x02, 0x58, 0x59, 0x5a, 0x20,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf3, 0x51, 0x00, 0x01, 0x00, 0x00,
0x00, 0x01, 0x16, 0xcc, 0x58, 0x59, 0x5a, 0x20, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x58, 0x59, 0x5a, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x6f, 0xa0,
0x00, 0x00, 0x38, 0xf5, 0x00, 0x00, 0x03, 0x90, 0x58, 0x59, 0x5a, 0x20,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x62, 0x97, 0x00, 0x00, 0xb7, 0x87,
0x00, 0x00, 0x18, 0xd9, 0x58, 0x59, 0x5a, 0x20, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x24, 0x9f, 0x00, 0x00, 0x0f, 0x84, 0x00, 0x00, 0xb6, 0xc4,
0x63, 0x75, 0x72, 0x76, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00,
0x00, 0x00, 0x00, 0x05, 0x00, 0x0a, 0x00, 0x0f, 0x00, 0x14, 0x00, 0x19,
0x00, 0x1e, 0x00, 0x23, 0x00, 0x28, 0x00, 0x2d, 0x00, 0x32, 0x00, 0x37,
0x00, 0x3b, 0x00, 0x40, 0x00, 0x45, 0x00, 0x4a, 0x00, 0x4f, 0x00, 0x54,
0x00, 0x59, 0x00, 0x5e, 0x00, 0x63, 0x00, 0x68, 0x00, 0x6d, 0x00, 0x72,
0x00, 0x77, 0x00, 0x7c, 0x00, 0x81, 0x00, 0x86, 0x00, 0x8b, 0x00, 0x90,
0x00, 0x95, 0x00, 0x9a, 0x00, 0x9f, 0x00, 0xa4, 0x00, 0xa9, 0x00, 0xae,
0x00, 0xb2, 0x00, 0xb7, 0x00, 0xbc, 0x00, 0xc1, 0x00, 0xc6, 0x00, 0xcb,
0x00, 0xd0, 0x00, 0xd5, 0x00, 0xdb, 0x00, 0xe0, 0x00, 0xe5, 0x00, 0xeb,
0x00, 0xf0, 0x00, 0xf6, 0x00, 0xfb, 0x01, 0x01, 0x01, 0x07, 0x01, 0x0d,
0x01, 0x13, 0x01, 0x19, 0x01, 0x1f, 0x01, 0x25, 0x01, 0x2b, 0x01, 0x32,
0x01, 0x38, 0x01, 0x3e, 0x01, 0x45, 0x01, 0x4c, 0x01, 0x52, 0x01, 0x59,
0x01, 0x60, 0x01, 0x67, 0x01, 0x6e, 0x01, 0x75, 0x01, 0x7c, 0x01, 0x83,
0x01, 0x8b, 0x01, 0x92, 0x01, 0x9a, 0x01, 0xa1, 0x01, 0xa9, 0x01, 0xb1,
0x01, 0xb9, 0x01, 0xc1, 0x01, 0xc9, 0x01, 0xd1, 0x01, 0xd9, 0x01, 0xe1,
0x01, 0xe9, 0x01, 0xf2, 0x01, 0xfa, 0x02, 0x03, 0x02, 0x0c, 0x02, 0x14,
0x02, 0x1d, 0x02, 0x26, 0x02, 0x2f, 0x02, 0x38, 0x02, 0x41, 0x02, 0x4b,
0x02, 0x54, 0x02, 0x5d, 0x02, 0x67, 0x02, 0x71, 0x02, 0x7a, 0x02, 0x84,
0x02, 0x8e, 0x02, 0x98, 0x02, 0xa2, 0x02, 0xac, 0x02, 0xb6, 0x02, 0xc1,
0x02, 0xcb, 0x02, 0xd5, 0x02, 0xe0, 0x02, 0xeb, 0x02, 0xf5, 0x03, 0x00,
0x03, 0x0b, 0x03, 0x16, 0x03, 0x21, 0x03, 0x2d, 0x03, 0x38, 0x03, 0x43,
0x03, 0x4f, 0x03, 0x5a, 0x03, 0x66, 0x03, 0x72, 0x03, 0x7e, 0x03, 0x8a,
0x03, 0x96, 0x03, 0xa2, 0x03, 0xae, 0x03, 0xba, 0x03, 0xc7, 0x03, 0xd3,
0x03, 0xe0, 0x03, 0xec, 0x03, 0xf9, 0x04, 0x06, 0x04, 0x13, 0x04, 0x20,
0x04, 0x2d, 0x04, 0x3b, 0x04, 0x48, 0x04, 0x55, 0x04, 0x63, 0x04, 0x71,
0x04, 0x7e, 0x04, 0x8c, 0x04, 0x9a, 0x04, 0xa8, 0x04, 0xb6, 0x04, 0xc4,
0x04, 0xd3, 0x04, 0xe1, 0x04, 0xf0, 0x04, 0xfe, 0x05, 0x0d, 0x05, 0x1c,
0x05, 0x2b, 0x05, 0x3a, 0x05, 0x49, 0x05, 0x58, 0x05, 0x67, 0x05, 0x77,
0x05, 0x86, 0x05, 0x96, 0x05, 0xa6, 0x05, 0xb5, 0x05, 0xc5, 0x05, 0xd5,
0x05, 0xe5, 0x05, 0xf6, 0x06, 0x06, 0x06, 0x16, 0x06, 0x27, 0x06, 0x37,
0x06, 0x48, 0x06, 0x59, 0x06, 0x6a, 0x06, 0x7b, 0x06, 0x8c, 0x06, 0x9d,
0x06, 0xaf, 0x06, 0xc0, 0x06, 0xd1, 0x06, 0xe3, 0x06, 0xf5, 0x07, 0x07,
0x07, 0x19, 0x07, 0x2b, 0x07, 0x3d, 0x07, 0x4f, 0x07, 0x61, 0x07, 0x74,
0x07, 0x86, 0x07, 0x99, 0x07, 0xac, 0x07, 0xbf, 0x07, 0xd2, 0x07, 0xe5,
0x07, 0xf8, 0x08, 0x0b, 0x08, 0x1f, 0x08, 0x32, 0x08, 0x46, 0x08, 0x5a,
0x08, 0x6e, 0x08, 0x82, 0x08, 0x96, 0x08, 0xaa, 0x08, 0xbe, 0x08, 0xd2,
0x08, 0xe7, 0x08, 0xfb, 0x09, 0x10, 0x09, 0x25, 0x09, 0x3a, 0x09, 0x4f,
0x09, 0x64, 0x09, 0x79, 0x09, 0x8f, 0x09, 0xa4, 0x09, 0xba, 0x09, 0xcf,
0x09, 0xe5, 0x09, 0xfb, 0x0a, 0x11, 0x0a, 0x27, 0x0a, 0x3d, 0x0a, 0x54,
0x0a, 0x6a, 0x0a, 0x81, 0x0a, 0x98, 0x0a, 0xae, 0x0a, 0xc5, 0x0a, 0xdc,
0x0a, 0xf3, 0x0b, 0x0b, 0x0b, 0x22, 0x0b, 0x39, 0x0b, 0x51, 0x0b, 0x69,
0x0b, 0x80, 0x0b, 0x98, 0x0b, 0xb0, 0x0b, 0xc8, 0x0b, 0xe1, 0x0b, 0xf9,
0x0c, 0x12, 0x0c, 0x2a, 0x0c, 0x43, 0x0c, 0x5c, 0x0c, 0x75, 0x0c, 0x8e,
0x0c, 0xa7, 0x0c, 0xc0, 0x0c, 0xd9, 0x0c, 0xf3, 0x0d, 0x0d, 0x0d, 0x26,
0x0d, 0x40, 0x0d, 0x5a, 0x0d, 0x74, 0x0d, 0x8e, 0x0d, 0xa9, 0x0d, 0xc3,
0x0d, 0xde, 0x0d, 0xf8, 0x0e, 0x13, 0x0e, 0x2e, 0x0e, 0x49, 0x0e, 0x64,
0x0e, 0x7f, 0x0e, 0x9b, 0x0e, 0xb6, 0x0e, 0xd2, 0x0e, 0xee, 0x0f, 0x09,
0x0f, 0x25, 0x0f, 0x41, 0x0f, 0x5e, 0x0f, 0x7a, 0x0f, 0x96, 0x0f, 0xb3,
0x0f, 0xcf, 0x0f, 0xec, 0x10, 0x09, 0x10, 0x26, 0x10, 0x43, 0x10, 0x61,
0x10, 0x7e, 0x10, 0x9b, 0x10, 0xb9, 0x10, 0xd7, 0x10, 0xf5, 0x11, 0x13,
0x11, 0x31, 0x11, 0x4f, 0x11, 0x6d, 0x11, 0x8c, 0x11, 0xaa, 0x11, 0xc9,
0x11, 0xe8, 0x12, 0x07, 0x12, 0x26, 0x12, 0x45, 0x12, 0x64, 0x12, 0x84,
0x12, 0xa3, 0x12, 0xc3, 0x12, 0xe3, 0x13, 0x03, 0x13, 0x23, 0x13, 0x43,
0x13, 0x63, 0x13, 0x83, 0x13, 0xa4, 0x13, 0xc5, 0x13, 0xe5, 0x14, 0x06,
0x14, 0x27, 0x14, 0x49, 0x14, 0x6a, 0x14, 0x8b, 0x14, 0xad, 0x14, 0xce,
0x14, 0xf0, 0x15, 0x12, 0x15, 0x34, 0x15, 0x56, 0x15, 0x78, 0x15, 0x9b,
0x15, 0xbd, 0x15, 0xe0, 0x16, 0x03, 0x16, 0x26, 0x16, 0x49, 0x16, 0x6c,
0x16, 0x8f, 0x16, 0xb2, 0x16, 0xd6, 0x16, 0xfa, 0x17, 0x1d, 0x17, 0x41,
0x17, 0x65, 0x17, 0x89, 0x17, 0xae, 0x17, 0xd2, 0x17, 0xf7, 0x18, 0x1b,
0x18, 0x40, 0x18, 0x65, 0x18, 0x8a, 0x18, 0xaf, 0x18, 0xd5, 0x18, 0xfa,
0x19, 0x20, 0x19, 0x45, 0x19, 0x6b, 0x19, 0x91, 0x19, 0xb7, 0x19, 0xdd,
0x1a, 0x04, 0x1a, 0x2a, 0x1a, 0x51, 0x1a, 0x77, 0x1a, 0x9e, 0x1a, 0xc5,
0x1a, 0xec, 0x1b, 0x14, 0x1b, 0x3b, 0x1b, 0x63, 0x1b, 0x8a, 0x1b, 0xb2,
0x1b, 0xda, 0x1c, 0x02, 0x1c, 0x2a, 0x1c, 0x52, 0x1c, 0x7b, 0x1c, 0xa3,
0x1c, 0xcc, 0x1c, 0xf5, 0x1d, 0x1e, 0x1d, 0x47, 0x1d, 0x70, 0x1d, 0x99,
0x1d, 0xc3, 0x1d, 0xec, 0x1e, 0x16, 0x1e, 0x40, 0x1e, 0x6a, 0x1e, 0x94,
0x1e, 0xbe, 0x1e, 0xe9, 0x1f, 0x13, 0x1f, 0x3e, 0x1f, 0x69, 0x1f, 0x94,
0x1f, 0xbf, 0x1f, 0xea, 0x20, 0x15, 0x20, 0x41, 0x20, 0x6c, 0x20, 0x98,
0x20, 0xc4, 0x20, 0xf0, 0x21, 0x1c, 0x21, 0x48, 0x21, 0x75, 0x21, 0xa1,
0x21, 0xce, 0x21, 0xfb, 0x22, 0x27, 0x22, 0x55, 0x22, 0x82, 0x22, 0xaf,
0x22, 0xdd, 0x23, 0x0a, 0x23, 0x38, 0x23, 0x66, 0x23, 0x94, 0x23, 0xc2,
0x23, 0xf0, 0x24, 0x1f, 0x24, 0x4d, 0x24, 0x7c, 0x24, 0xab, 0x24, 0xda,
0x25, 0x09, 0x25, 0x38, 0x25, 0x68, 0x25, 0x97, 0x25, 0xc7, 0x25, 0xf7,
0x26, 0x27, 0x26, 0x57, 0x26, 0x87, 0x26, 0xb7, 0x26, 0xe8, 0x27, 0x18,
0x27, 0x49, 0x27, 0x7a, 0x27, 0xab, 0x27, 0xdc, 0x28, 0x0d, 0x28, 0x3f,
0x28, 0x71, 0x28, 0xa2, 0x28, 0xd4, 0x29, 0x06, 0x29, 0x38, 0x29, 0x6b,
0x29, 0x9d, 0x29, 0xd0, 0x2a, 0x02, 0x2a, 0x35, 0x2a, 0x68, 0x2a, 0x9b,
0x2a, 0xcf, 0x2b, 0x02, 0x2b, 0x36, 0x2b, 0x69, 0x2b, 0x9d, 0x2b, 0xd1,
0x2c, 0x05, 0x2c, 0x39, 0x2c, 0x6e, 0x2c, 0xa2, 0x2c, 0xd7, 0x2d, 0x0c,
0x2d, 0x41, 0x2d, 0x76, 0x2d, 0xab, 0x2d, 0xe1, 0x2e, 0x16, 0x2e, 0x4c,
0x2e, 0x82, 0x2e, 0xb7, 0x2e, 0xee, 0x2f, 0x24, 0x2f, 0x5a, 0x2f, 0x91,
0x2f, 0xc7, 0x2f, 0xfe, 0x30, 0x35, 0x30, 0x6c, 0x30, 0xa4, 0x30, 0xdb,
0x31, 0x12, 0x31, 0x4a, 0x31, 0x82, 0x31, 0xba, 0x31, 0xf2, 0x32, 0x2a,
0x32, 0x63, 0x32, 0x9b, 0x32, 0xd4, 0x33, 0x0d, 0x33, 0x46, 0x33, 0x7f,
0x33, 0xb8, 0x33, 0xf1, 0x34, 0x2b, 0x34, 0x65, 0x34, 0x9e, 0x34, 0xd8,
0x35, 0x13, 0x35, 0x4d, 0x35, 0x87, 0x35, 0xc2, 0x35, 0xfd, 0x36, 0x37,
0x36, 0x72, 0x36, 0xae, 0x36, 0xe9, 0x37, 0x24, 0x37, 0x60, 0x37, 0x9c,
0x37, 0xd7, 0x38, 0x14, 0x38, 0x50, 0x38, 0x8c, 0x38, 0xc8, 0x39, 0x05,
0x39, 0x42, 0x39, 0x7f, 0x39, 0xbc, 0x39, 0xf9, 0x3a, 0x36, 0x3a, 0x74,
0x3a, 0xb2, 0x3a, 0xef, 0x3b, 0x2d, 0x3b, 0x6b, 0x3b, 0xaa, 0x3b, 0xe8,
0x3c, 0x27, 0x3c, 0x65, 0x3c, 0xa4, 0x3c, 0xe3, 0x3d, 0x22, 0x3d, 0x61,
0x3d, 0xa1, 0x3d, 0xe0, 0x3e, 0x20, 0x3e, 0x60, 0x3e, 0xa0, 0x3e, 0xe0,
0x3f, 0x21, 0x3f, 0x61, 0x3f, 0xa2, 0x3f, 0xe2, 0x40, 0x23, 0x40, 0x64,
0x40, 0xa6, 0x40, 0xe7, 0x41, 0x29, 0x41, 0x6a, 0x41, 0xac, 0x41, 0xee,
0x42, 0x30, 0x42, 0x72, 0x42, 0xb5, 0x42, 0xf7, 0x43, 0x3a, 0x43, 0x7d,
0x43, 0xc0, 0x44, 0x03, 0x44, 0x47, 0x44, 0x8a, 0x44, 0xce, 0x45, 0x12,
0x45, 0x55, 0x45, 0x9a, 0x45, 0xde, 0x46, 0x22, 0x46, 0x67, 0x46, 0xab,
0x46, 0xf0, 0x47, 0x35, 0x47, 0x7b, 0x47, 0xc0, 0x48, 0x05, 0x48, 0x4b,
0x48, 0x91, 0x48, 0xd7, 0x49, 0x1d, 0x49, 0x63, 0x49, 0xa9, 0x49, 0xf0,
0x4a, 0x37, 0x4a, 0x7d, 0x4a, 0xc4, 0x4b, 0x0c, 0x4b, 0x53, 0x4b, 0x9a,
0x4b, 0xe2, 0x4c, 0x2a, 0x4c, 0x72, 0x4c, 0xba, 0x4d, 0x02, 0x4d, 0x4a,
0x4d, 0x93, 0x4d, 0xdc, 0x4e, 0x25, 0x4e, 0x6e, 0x4e, 0xb7, 0x4f, 0x00,
0x4f, 0x49, 0x4f, 0x93, 0x4f, 0xdd, 0x50, 0x27, 0x50, 0x71, 0x50, 0xbb,
0x51, 0x06, 0x51, 0x50, 0x51, 0x9b, 0x51, 0xe6, 0x52, 0x31, 0x52, 0x7c,
0x52, 0xc7, 0x53, 0x13, 0x53, 0x5f, 0x53, 0xaa, 0x53, 0xf6, 0x54, 0x42,
0x54, 0x8f, 0x54, 0xdb, 0x55, 0x28, 0x55, 0x75, 0x55, 0xc2, 0x56, 0x0f,
0x56, 0x5c, 0x56, 0xa9, 0x56, 0xf7, 0x57, 0x44, 0x57, 0x92, 0x57, 0xe0,
0x58, 0x2f, 0x58, 0x7d, 0x58, 0xcb, 0x59, 0x1a, 0x59, 0x69, 0x59, 0xb8,
0x5a, 0x07, 0x5a, 0x56, 0x5a, 0xa6, 0x5a, 0xf5, 0x5b, 0x45, 0x5b, 0x95,
0x5b, 0xe5, 0x5c, 0x35, 0x5c, 0x86, 0x5c, 0xd6, 0x5d, 0x27, 0x5d, 0x78,
0x5d, 0xc9, 0x5e, 0x1a, 0x5e, 0x6c, 0x5e, 0xbd, 0x5f, 0x0f, 0x5f, 0x61,
0x5f, 0xb3, 0x60, 0x05, 0x60, 0x57, 0x60, 0xaa, 0x60, 0xfc, 0x61, 0x4f,
0x61, 0xa2, 0x61, 0xf5, 0x62, 0x49, 0x62, 0x9c, 0x62, 0xf0, 0x63, 0x43,
0x63, 0x97, 0x63, 0xeb, 0x64, 0x40, 0x64, 0x94, 0x64, 0xe9, 0x65, 0x3d,
0x65, 0x92, 0x65, 0xe7, 0x66, 0x3d, 0x66, 0x92, 0x66, 0xe8, 0x67, 0x3d,
0x67, 0x93, 0x67, 0xe9, 0x68, 0x3f, 0x68, 0x96, 0x68, 0xec, 0x69, 0x43,
0x69, 0x9a, 0x69, 0xf1, 0x6a, 0x48, 0x6a, 0x9f, 0x6a, 0xf7, 0x6b, 0x4f,
0x6b, 0xa7, 0x6b, 0xff, 0x6c, 0x57, 0x6c, 0xaf, 0x6d, 0x08, 0x6d, 0x60,
0x6d, 0xb9, 0x6e, 0x12, 0x6e, 0x6b, 0x6e, 0xc4, 0x6f, 0x1e, 0x6f, 0x78,
0x6f, 0xd1, 0x70, 0x2b, 0x70, 0x86, 0x70, 0xe0, 0x71, 0x3a, 0x71, 0x95,
0x71, 0xf0, 0x72, 0x4b, 0x72, 0xa6, 0x73, 0x01, 0x73, 0x5d, 0x73, 0xb8,
0x74, 0x14, 0x74, 0x70, 0x74, 0xcc, 0x75, 0x28, 0x75, 0x85, 0x75, 0xe1,
0x76, 0x3e, 0x76, 0x9b, 0x76, 0xf8, 0x77, 0x56, 0x77, 0xb3, 0x78, 0x11,
0x78, 0x6e, 0x78, 0xcc, 0x79, 0x2a, 0x79, 0x89, 0x79, 0xe7, 0x7a, 0x46,
0x7a, 0xa5, 0x7b, 0x04, 0x7b, 0x63, 0x7b, 0xc2, 0x7c, 0x21, 0x7c, 0x81,
0x7c, 0xe1, 0x7d, 0x41, 0x7d, 0xa1, 0x7e, 0x01, 0x7e, 0x62, 0x7e, 0xc2,
0x7f, 0x23, 0x7f, 0x84, 0x7f, 0xe5, 0x80, 0x47, 0x80, 0xa8, 0x81, 0x0a,
0x81, 0x6b, 0x81, 0xcd, 0x82, 0x30, 0x82, 0x92, 0x82, 0xf4, 0x83, 0x57,
0x83, 0xba, 0x84, 0x1d, 0x84, 0x80, 0x84, 0xe3, 0x85, 0x47, 0x85, 0xab,
0x86, 0x0e, 0x86, 0x72, 0x86, 0xd7, 0x87, 0x3b, 0x87, 0x9f, 0x88, 0x04,
0x88, 0x69, 0x88, 0xce, 0x89, 0x33, 0x89, 0x99, 0x89, 0xfe, 0x8a, 0x64,
0x8a, 0xca, 0x8b, 0x30, 0x8b, 0x96, 0x8b, 0xfc, 0x8c, 0x63, 0x8c, 0xca,
0x8d, 0x31, 0x8d, 0x98, 0x8d, 0xff, 0x8e, 0x66, 0x8e, 0xce, 0x8f, 0x36,
0x8f, 0x9e, 0x90, 0x06, 0x90, 0x6e, 0x90, 0xd6, 0x91, 0x3f, 0x91, 0xa8,
0x92, 0x11, 0x92, 0x7a, 0x92, 0xe3, 0x93, 0x4d, 0x93, 0xb6, 0x94, 0x20,
0x94, 0x8a, 0x94, 0xf4, 0x95, 0x5f, 0x95, 0xc9, 0x96, 0x34, 0x96, 0x9f,
0x97, 0x0a, 0x97, 0x75, 0x97, 0xe0, 0x98, 0x4c, 0x98, 0xb8, 0x99, 0x24,
0x99, 0x90, 0x99, 0xfc, 0x9a, 0x68, 0x9a, 0xd5, 0x9b, 0x42, 0x9b, 0xaf,
0x9c, 0x1c, 0x9c, 0x89, 0x9c, 0xf7, 0x9d, 0x64, 0x9d, 0xd2, 0x9e, 0x40,
0x9e, 0xae, 0x9f, 0x1d, 0x9f, 0x8b, 0x9f, 0xfa, 0xa0, 0x69, 0xa0, 0xd8,
0xa1, 0x47, 0xa1, 0xb6, 0xa2, 0x26, 0xa2, 0x96, 0xa3, 0x06, 0xa3, 0x76,
0xa3, 0xe6, 0xa4, 0x56, 0xa4, 0xc7, 0xa5, 0x38, 0xa5, 0xa9, 0xa6, 0x1a,
0xa6, 0x8b, 0xa6, 0xfd, 0xa7, 0x6e, 0xa7, 0xe0, 0xa8, 0x52, 0xa8, 0xc4,
0xa9, 0x37, 0xa9, 0xa9, 0xaa, 0x1c, 0xaa, 0x8f, 0xab, 0x02, 0xab, 0x75,
0xab, 0xe9, 0xac, 0x5c, 0xac, 0xd0, 0xad, 0x44, 0xad, 0xb8, 0xae, 0x2d,
0xae, 0xa1, 0xaf, 0x16, 0xaf, 0x8b, 0xb0, 0x00, 0xb0, 0x75, 0xb0, 0xea,
0xb1, 0x60, 0xb1, 0xd6, 0xb2, 0x4b, 0xb2, 0xc2, 0xb3, 0x38, 0xb3, 0xae,
0xb4, 0x25, 0xb4, 0x9c, 0xb5, 0x13, 0xb5, 0x8a, 0xb6, 0x01, 0xb6, 0x79,
0xb6, 0xf0, 0xb7, 0x68, 0xb7, 0xe0, 0xb8, 0x59, 0xb8, 0xd1, 0xb9, 0x4a,
0xb9, 0xc2, 0xba, 0x3b, 0xba, 0xb5, 0xbb, 0x2e, 0xbb, 0xa7, 0xbc, 0x21,
0xbc, 0x9b, 0xbd, 0x15, 0xbd, 0x8f, 0xbe, 0x0a, 0xbe, 0x84, 0xbe, 0xff,
0xbf, 0x7a, 0xbf, 0xf5, 0xc0, 0x70, 0xc0, 0xec, 0xc1, 0x67, 0xc1, 0xe3,
0xc2, 0x5f, 0xc2, 0xdb, 0xc3, 0x58, 0xc3, 0xd4, 0xc4, 0x51, 0xc4, 0xce,
0xc5, 0x4b, 0xc5, 0xc8, 0xc6, 0x46, 0xc6, 0xc3, 0xc7, 0x41, 0xc7, 0xbf,
0xc8, 0x3d, 0xc8, 0xbc, 0xc9, 0x3a, 0xc9, 0xb9, 0xca, 0x38, 0xca, 0xb7,
0xcb, 0x36, 0xcb, 0xb6, 0xcc, 0x35, 0xcc, 0xb5, 0xcd, 0x35, 0xcd, 0xb5,
0xce, 0x36, 0xce, 0xb6, 0xcf, 0x37, 0xcf, 0xb8, 0xd0, 0x39, 0xd0, 0xba,
0xd1, 0x3c, 0xd1, 0xbe, 0xd2, 0x3f, 0xd2, 0xc1, 0xd3, 0x44, 0xd3, 0xc6,
0xd4, 0x49, 0xd4, 0xcb, 0xd5, 0x4e, 0xd5, 0xd1, 0xd6, 0x55, 0xd6, 0xd8,
0xd7, 0x5c, 0xd7, 0xe0, 0xd8, 0x64, 0xd8, 0xe8, 0xd9, 0x6c, 0xd9, 0xf1,
0xda, 0x76, 0xda, 0xfb, 0xdb, 0x80, 0xdc, 0x05, 0xdc, 0x8a, 0xdd, 0x10,
0xdd, 0x96, 0xde, 0x1c, 0xde, 0xa2, 0xdf, 0x29, 0xdf, 0xaf, 0xe0, 0x36,
0xe0, 0xbd, 0xe1, 0x44, 0xe1, 0xcc, 0xe2, 0x53, 0xe2, 0xdb, 0xe3, 0x63,
0xe3, 0xeb, 0xe4, 0x73, 0xe4, 0xfc, 0xe5, 0x84, 0xe6, 0x0d, 0xe6, 0x96,
0xe7, 0x1f, 0xe7, 0xa9, 0xe8, 0x32, 0xe8, 0xbc, 0xe9, 0x46, 0xe9, 0xd0,
0xea, 0x5b, 0xea, 0xe5, 0xeb, 0x70, 0xeb, 0xfb, 0xec, 0x86, 0xed, 0x11,
0xed, 0x9c, 0xee, 0x28, 0xee, 0xb4, 0xef, 0x40, 0xef, 0xcc, 0xf0, 0x58,
0xf0, 0xe5, 0xf1, 0x72, 0xf1, 0xff, 0xf2, 0x8c, 0xf3, 0x19, 0xf3, 0xa7,
0xf4, 0x34, 0xf4, 0xc2, 0xf5, 0x50, 0xf5, 0xde, 0xf6, 0x6d, 0xf6, 0xfb,
0xf7, 0x8a, 0xf8, 0x19, 0xf8, 0xa8, 0xf9, 0x38, 0xf9, 0xc7, 0xfa, 0x57,
0xfa, 0xe7, 0xfb, 0x77, 0xfc, 0x07, 0xfc, 0x98, 0xfd, 0x29, 0xfd, 0xba,
0xfe, 0x4b, 0xfe, 0xdc, 0xff, 0x6d, 0xff, 0xff
};
StringInfo
*profile;
MagickBooleanType
status;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (GetImageProfile(image,"icc") != (const StringInfo *) NULL)
return(MagickFalse);
profile=AcquireStringInfo(sizeof(sRGBProfile));
SetStringInfoDatum(profile,sRGBProfile);
status=SetImageProfile(image,"icc",profile,exception);
profile=DestroyStringInfo(profile);
return(status);
}
MagickExport MagickBooleanType ProfileImage(Image *image,const char *name,
const void *datum,const size_t length,ExceptionInfo *exception)
{
#define ProfileImageTag "Profile/Image"
#define ThrowProfileException(severity,tag,context) \
{ \
if (source_profile != (cmsHPROFILE) NULL) \
(void) cmsCloseProfile(source_profile); \
if (target_profile != (cmsHPROFILE) NULL) \
(void) cmsCloseProfile(target_profile); \
ThrowBinaryException(severity,tag,context); \
}
MagickBooleanType
status;
StringInfo
*profile;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(name != (const char *) NULL);
if ((datum == (const void *) NULL) || (length == 0))
{
char
*next;
/*
Delete image profile(s).
*/
ResetImageProfileIterator(image);
for (next=GetNextImageProfile(image); next != (const char *) NULL; )
{
if (IsOptionMember(next,name) != MagickFalse)
{
(void) DeleteImageProfile(image,next);
ResetImageProfileIterator(image);
}
next=GetNextImageProfile(image);
}
return(MagickTrue);
}
/*
Add a ICC, IPTC, or generic profile to the image.
*/
status=MagickTrue;
profile=AcquireStringInfo((size_t) length);
SetStringInfoDatum(profile,(unsigned char *) datum);
if ((LocaleCompare(name,"icc") != 0) && (LocaleCompare(name,"icm") != 0))
status=SetImageProfile(image,name,profile,exception);
else
{
const StringInfo
*icc_profile;
icc_profile=GetImageProfile(image,"icc");
if ((icc_profile != (const StringInfo *) NULL) &&
(CompareStringInfo(icc_profile,profile) == 0))
{
const char
*value;
value=GetImageProperty(image,"exif:ColorSpace",exception);
(void) value;
if (LocaleCompare(value,"1") != 0)
(void) SetsRGBImageProfile(image,exception);
value=GetImageProperty(image,"exif:InteroperabilityIndex",exception);
if (LocaleCompare(value,"R98.") != 0)
(void) SetsRGBImageProfile(image,exception);
/* Future.
value=GetImageProperty(image,"exif:InteroperabilityIndex",exception);
if (LocaleCompare(value,"R03.") != 0)
(void) SetAdobeRGB1998ImageProfile(image,exception);
*/
icc_profile=GetImageProfile(image,"icc");
}
if ((icc_profile != (const StringInfo *) NULL) &&
(CompareStringInfo(icc_profile,profile) == 0))
{
profile=DestroyStringInfo(profile);
return(MagickTrue);
}
#if !defined(MAGICKCORE_LCMS_DELEGATE)
(void) ThrowMagickException(exception,GetMagickModule(),
MissingDelegateWarning,"DelegateLibrarySupportNotBuiltIn",
"'%s' (LCMS)",image->filename);
#else
{
cmsHPROFILE
source_profile;
CMSExceptionInfo
cms_exception;
/*
Transform pixel colors as defined by the color profiles.
*/
cmsSetLogErrorHandler(CMSExceptionHandler);
cms_exception.image=image;
cms_exception.exception=exception;
(void) cms_exception;
source_profile=cmsOpenProfileFromMemTHR((cmsContext) &cms_exception,
GetStringInfoDatum(profile),(cmsUInt32Number)
GetStringInfoLength(profile));
if (source_profile == (cmsHPROFILE) NULL)
ThrowBinaryException(ResourceLimitError,
"ColorspaceColorProfileMismatch",name);
if ((cmsGetDeviceClass(source_profile) != cmsSigLinkClass) &&
(icc_profile == (StringInfo *) NULL))
status=SetImageProfile(image,name,profile,exception);
else
{
CacheView
*image_view;
ColorspaceType
source_colorspace,
target_colorspace;
cmsColorSpaceSignature
signature;
cmsHPROFILE
target_profile;
cmsHTRANSFORM
*magick_restrict transform;
cmsUInt32Number
flags,
source_type,
target_type;
int
intent;
MagickOffsetType
progress;
size_t
source_channels,
target_channels;
ssize_t
y;
unsigned short
**magick_restrict source_pixels,
**magick_restrict target_pixels;
target_profile=(cmsHPROFILE) NULL;
if (icc_profile != (StringInfo *) NULL)
{
target_profile=source_profile;
source_profile=cmsOpenProfileFromMemTHR((cmsContext)
&cms_exception,GetStringInfoDatum(icc_profile),
(cmsUInt32Number) GetStringInfoLength(icc_profile));
if (source_profile == (cmsHPROFILE) NULL)
ThrowProfileException(ResourceLimitError,
"ColorspaceColorProfileMismatch",name);
}
switch (cmsGetColorSpace(source_profile))
{
case cmsSigCmykData:
{
source_colorspace=CMYKColorspace;
source_type=(cmsUInt32Number) TYPE_CMYK_16;
source_channels=4;
break;
}
case cmsSigGrayData:
{
source_colorspace=GRAYColorspace;
source_type=(cmsUInt32Number) TYPE_GRAY_16;
source_channels=1;
break;
}
case cmsSigLabData:
{
source_colorspace=LabColorspace;
source_type=(cmsUInt32Number) TYPE_Lab_16;
source_channels=3;
break;
}
case cmsSigLuvData:
{
source_colorspace=YUVColorspace;
source_type=(cmsUInt32Number) TYPE_YUV_16;
source_channels=3;
break;
}
case cmsSigRgbData:
{
source_colorspace=sRGBColorspace;
source_type=(cmsUInt32Number) TYPE_RGB_16;
source_channels=3;
break;
}
case cmsSigXYZData:
{
source_colorspace=XYZColorspace;
source_type=(cmsUInt32Number) TYPE_XYZ_16;
source_channels=3;
break;
}
case cmsSigYCbCrData:
{
source_colorspace=YCbCrColorspace;
source_type=(cmsUInt32Number) TYPE_YCbCr_16;
source_channels=3;
break;
}
default:
{
source_colorspace=UndefinedColorspace;
source_type=(cmsUInt32Number) TYPE_RGB_16;
source_channels=3;
break;
}
}
signature=cmsGetPCS(source_profile);
if (target_profile != (cmsHPROFILE) NULL)
signature=cmsGetColorSpace(target_profile);
switch (signature)
{
case cmsSigCmykData:
{
target_colorspace=CMYKColorspace;
target_type=(cmsUInt32Number) TYPE_CMYK_16;
target_channels=4;
break;
}
case cmsSigLabData:
{
target_colorspace=LabColorspace;
target_type=(cmsUInt32Number) TYPE_Lab_16;
target_channels=3;
break;
}
case cmsSigGrayData:
{
target_colorspace=GRAYColorspace;
target_type=(cmsUInt32Number) TYPE_GRAY_16;
target_channels=1;
break;
}
case cmsSigLuvData:
{
target_colorspace=YUVColorspace;
target_type=(cmsUInt32Number) TYPE_YUV_16;
target_channels=3;
break;
}
case cmsSigRgbData:
{
target_colorspace=sRGBColorspace;
target_type=(cmsUInt32Number) TYPE_RGB_16;
target_channels=3;
break;
}
case cmsSigXYZData:
{
target_colorspace=XYZColorspace;
target_type=(cmsUInt32Number) TYPE_XYZ_16;
target_channels=3;
break;
}
case cmsSigYCbCrData:
{
target_colorspace=YCbCrColorspace;
target_type=(cmsUInt32Number) TYPE_YCbCr_16;
target_channels=3;
break;
}
default:
{
target_colorspace=UndefinedColorspace;
target_type=(cmsUInt32Number) TYPE_RGB_16;
target_channels=3;
break;
}
}
if ((source_colorspace == UndefinedColorspace) ||
(target_colorspace == UndefinedColorspace))
ThrowProfileException(ImageError,"ColorspaceColorProfileMismatch",
name);
if ((source_colorspace == GRAYColorspace) &&
(SetImageGray(image,exception) == MagickFalse))
ThrowProfileException(ImageError,"ColorspaceColorProfileMismatch",
name);
if ((source_colorspace == CMYKColorspace) &&
(image->colorspace != CMYKColorspace))
ThrowProfileException(ImageError,"ColorspaceColorProfileMismatch",
name);
if ((source_colorspace == XYZColorspace) &&
(image->colorspace != XYZColorspace))
ThrowProfileException(ImageError,"ColorspaceColorProfileMismatch",
name);
if ((source_colorspace == YCbCrColorspace) &&
(image->colorspace != YCbCrColorspace))
ThrowProfileException(ImageError,"ColorspaceColorProfileMismatch",
name);
if ((source_colorspace != CMYKColorspace) &&
(source_colorspace != LabColorspace) &&
(source_colorspace != XYZColorspace) &&
(source_colorspace != YCbCrColorspace) &&
(IssRGBCompatibleColorspace(image->colorspace) == MagickFalse))
ThrowProfileException(ImageError,"ColorspaceColorProfileMismatch",
name);
switch (image->rendering_intent)
{
case AbsoluteIntent: intent=INTENT_ABSOLUTE_COLORIMETRIC; break;
case PerceptualIntent: intent=INTENT_PERCEPTUAL; break;
case RelativeIntent: intent=INTENT_RELATIVE_COLORIMETRIC; break;
case SaturationIntent: intent=INTENT_SATURATION; break;
default: intent=INTENT_PERCEPTUAL; break;
}
flags=cmsFLAGS_HIGHRESPRECALC;
#if defined(cmsFLAGS_BLACKPOINTCOMPENSATION)
if (image->black_point_compensation != MagickFalse)
flags|=cmsFLAGS_BLACKPOINTCOMPENSATION;
#endif
transform=AcquireTransformThreadSet(image,source_profile,
source_type,target_profile,target_type,intent,flags);
if (transform == (cmsHTRANSFORM *) NULL)
ThrowProfileException(ImageError,"UnableToCreateColorTransform",
name);
/*
Transform image as dictated by the source & target image profiles.
*/
source_pixels=AcquirePixelThreadSet(image->columns,source_channels);
target_pixels=AcquirePixelThreadSet(image->columns,target_channels);
if ((source_pixels == (unsigned short **) NULL) ||
(target_pixels == (unsigned short **) NULL))
{
transform=DestroyTransformThreadSet(transform);
ThrowProfileException(ResourceLimitError,
"MemoryAllocationFailed",image->filename);
}
if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse)
{
target_pixels=DestroyPixelThreadSet(target_pixels);
source_pixels=DestroyPixelThreadSet(source_pixels);
transform=DestroyTransformThreadSet(transform);
if (source_profile != (cmsHPROFILE) NULL)
(void) cmsCloseProfile(source_profile);
if (target_profile != (cmsHPROFILE) NULL)
(void) cmsCloseProfile(target_profile);
return(MagickFalse);
}
if (target_colorspace == CMYKColorspace)
(void) SetImageColorspace(image,target_colorspace,exception);
progress=0;
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++)
{
const int
id = GetOpenMPThreadId();
MagickBooleanType
sync;
register ssize_t
x;
register Quantum
*magick_restrict q;
register unsigned short
*p;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,
exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
p=source_pixels[id];
for (x=0; x < (ssize_t) image->columns; x++)
{
*p++=ScaleQuantumToShort(GetPixelRed(image,q));
if (source_channels > 1)
{
*p++=ScaleQuantumToShort(GetPixelGreen(image,q));
*p++=ScaleQuantumToShort(GetPixelBlue(image,q));
}
if (source_channels > 3)
*p++=ScaleQuantumToShort(GetPixelBlack(image,q));
q+=GetPixelChannels(image);
}
cmsDoTransform(transform[id],source_pixels[id],target_pixels[id],
(unsigned int) image->columns);
p=target_pixels[id];
q-=GetPixelChannels(image)*image->columns;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (target_channels == 1)
SetPixelGray(image,ScaleShortToQuantum(*p),q);
else
SetPixelRed(image,ScaleShortToQuantum(*p),q);
p++;
if (target_channels > 1)
{
SetPixelGreen(image,ScaleShortToQuantum(*p),q);
p++;
SetPixelBlue(image,ScaleShortToQuantum(*p),q);
p++;
}
if (target_channels > 3)
{
SetPixelBlack(image,ScaleShortToQuantum(*p),q);
p++;
}
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_ProfileImage)
#endif
proceed=SetImageProgress(image,ProfileImageTag,progress++,
image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
image_view=DestroyCacheView(image_view);
(void) SetImageColorspace(image,target_colorspace,exception);
switch (signature)
{
case cmsSigRgbData:
{
image->type=image->alpha_trait == UndefinedPixelTrait ?
TrueColorType : TrueColorAlphaType;
break;
}
case cmsSigCmykData:
{
image->type=image->alpha_trait == UndefinedPixelTrait ?
ColorSeparationType : ColorSeparationAlphaType;
break;
}
case cmsSigGrayData:
{
image->type=image->alpha_trait == UndefinedPixelTrait ?
GrayscaleType : GrayscaleAlphaType;
break;
}
default:
break;
}
target_pixels=DestroyPixelThreadSet(target_pixels);
source_pixels=DestroyPixelThreadSet(source_pixels);
transform=DestroyTransformThreadSet(transform);
if ((status != MagickFalse) &&
(cmsGetDeviceClass(source_profile) != cmsSigLinkClass))
status=SetImageProfile(image,name,profile,exception);
if (target_profile != (cmsHPROFILE) NULL)
(void) cmsCloseProfile(target_profile);
}
(void) cmsCloseProfile(source_profile);
}
#endif
}
profile=DestroyStringInfo(profile);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e m o v e I m a g e P r o f i l e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% RemoveImageProfile() removes a named profile from the image and returns its
% value.
%
% The format of the RemoveImageProfile method is:
%
% void *RemoveImageProfile(Image *image,const char *name)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o name: the profile name.
%
*/
MagickExport StringInfo *RemoveImageProfile(Image *image,const char *name)
{
StringInfo
*profile;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
if (image->profiles == (SplayTreeInfo *) NULL)
return((StringInfo *) NULL);
WriteTo8BimProfile(image,name,(StringInfo *) NULL);
profile=(StringInfo *) RemoveNodeFromSplayTree((SplayTreeInfo *)
image->profiles,name);
return(profile);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e s e t P r o f i l e I t e r a t o r %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ResetImageProfileIterator() resets the image profile iterator. Use it in
% conjunction with GetNextImageProfile() to iterate over all the profiles
% associated with an image.
%
% The format of the ResetImageProfileIterator method is:
%
% ResetImageProfileIterator(Image *image)
%
% A description of each parameter follows:
%
% o image: the image.
%
*/
MagickExport void ResetImageProfileIterator(const Image *image)
{
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
if (image->profiles == (SplayTreeInfo *) NULL)
return;
ResetSplayTreeIterator((SplayTreeInfo *) image->profiles);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S e t I m a g e P r o f i l e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% SetImageProfile() adds a named profile to the image. If a profile with the
% same name already exists, it is replaced. This method differs from the
% ProfileImage() method in that it does not apply CMS color profiles.
%
% The format of the SetImageProfile method is:
%
% MagickBooleanType SetImageProfile(Image *image,const char *name,
% const StringInfo *profile)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o name: the profile name, for example icc, exif, and 8bim (8bim is the
% Photoshop wrapper for iptc profiles).
%
% o profile: A StringInfo structure that contains the named profile.
%
*/
static void *DestroyProfile(void *profile)
{
return((void *) DestroyStringInfo((StringInfo *) profile));
}
static inline const unsigned char *ReadResourceByte(const unsigned char *p,
unsigned char *quantum)
{
*quantum=(*p++);
return(p);
}
static inline const unsigned char *ReadResourceLong(const unsigned char *p,
unsigned int *quantum)
{
*quantum=(unsigned int) (*p++) << 24;
*quantum|=(unsigned int) (*p++) << 16;
*quantum|=(unsigned int) (*p++) << 8;
*quantum|=(unsigned int) (*p++) << 0;
return(p);
}
static inline const unsigned char *ReadResourceShort(const unsigned char *p,
unsigned short *quantum)
{
*quantum=(unsigned short) (*p++) << 8;
*quantum|=(unsigned short) (*p++);
return(p);
}
static inline void WriteResourceLong(unsigned char *p,
const unsigned int quantum)
{
unsigned char
buffer[4];
buffer[0]=(unsigned char) (quantum >> 24);
buffer[1]=(unsigned char) (quantum >> 16);
buffer[2]=(unsigned char) (quantum >> 8);
buffer[3]=(unsigned char) quantum;
(void) CopyMagickMemory(p,buffer,4);
}
static void WriteTo8BimProfile(Image *image,const char *name,
const StringInfo *profile)
{
const unsigned char
*datum,
*q;
register const unsigned char
*p;
size_t
length;
StringInfo
*profile_8bim;
ssize_t
count;
unsigned char
length_byte;
unsigned int
value;
unsigned short
id,
profile_id;
if (LocaleCompare(name,"icc") == 0)
profile_id=0x040f;
else
if (LocaleCompare(name,"iptc") == 0)
profile_id=0x0404;
else
if (LocaleCompare(name,"xmp") == 0)
profile_id=0x0424;
else
return;
profile_8bim=(StringInfo *) GetValueFromSplayTree((SplayTreeInfo *)
image->profiles,"8bim");
if (profile_8bim == (StringInfo *) NULL)
return;
datum=GetStringInfoDatum(profile_8bim);
length=GetStringInfoLength(profile_8bim);
for (p=datum; p < (datum+length-16); )
{
q=p;
if (LocaleNCompare((char *) p,"8BIM",4) != 0)
break;
p+=4;
p=ReadResourceShort(p,&id);
p=ReadResourceByte(p,&length_byte);
p+=length_byte;
if (((length_byte+1) & 0x01) != 0)
p++;
if (p > (datum+length-4))
break;
p=ReadResourceLong(p,&value);
count=(ssize_t) value;
if ((count & 0x01) != 0)
count++;
if ((count < 0) || (p > (datum+length-count)) ||
(count > (ssize_t) length))
break;
if (id != profile_id)
p+=count;
else
{
size_t
extent,
offset;
ssize_t
extract_count;
StringInfo
*extract_profile;
extract_count=0;
extent=(datum+length)-(p+count);
if (profile == (StringInfo *) NULL)
{
offset=(q-datum);
extract_profile=AcquireStringInfo(offset+extent);
(void) CopyMagickMemory(extract_profile->datum,datum,offset);
}
else
{
offset=(p-datum);
extract_count=profile->length;
if ((extract_count & 0x01) != 0)
extract_count++;
extract_profile=AcquireStringInfo(offset+extract_count+extent);
(void) CopyMagickMemory(extract_profile->datum,datum,offset-4);
WriteResourceLong(extract_profile->datum+offset-4,
(unsigned int)profile->length);
(void) CopyMagickMemory(extract_profile->datum+offset,
profile->datum,profile->length);
}
(void) CopyMagickMemory(extract_profile->datum+offset+extract_count,
p+count,extent);
(void) AddValueToSplayTree((SplayTreeInfo *) image->profiles,
ConstantString("8bim"),CloneStringInfo(extract_profile));
extract_profile=DestroyStringInfo(extract_profile);
break;
}
}
}
static void GetProfilesFromResourceBlock(Image *image,
const StringInfo *resource_block,ExceptionInfo *exception)
{
const unsigned char
*datum;
register const unsigned char
*p;
size_t
length;
ssize_t
count;
StringInfo
*profile;
unsigned char
length_byte;
unsigned int
value;
unsigned short
id;
datum=GetStringInfoDatum(resource_block);
length=GetStringInfoLength(resource_block);
for (p=datum; p < (datum+length-16); )
{
if (LocaleNCompare((char *) p,"8BIM",4) != 0)
break;
p+=4;
p=ReadResourceShort(p,&id);
p=ReadResourceByte(p,&length_byte);
p+=length_byte;
if (((length_byte+1) & 0x01) != 0)
p++;
if (p > (datum+length-4))
break;
p=ReadResourceLong(p,&value);
count=(ssize_t) value;
if ((p > (datum+length-count)) || (count > (ssize_t) length) ||
(count < 0))
break;
switch (id)
{
case 0x03ed:
{
unsigned int
resolution;
unsigned short
units;
/*
Resolution.
*/
p=ReadResourceLong(p,&resolution);
image->resolution.x=((double) resolution)/65536.0;
p=ReadResourceShort(p,&units)+2;
p=ReadResourceLong(p,&resolution)+4;
image->resolution.y=((double) resolution)/65536.0;
/*
Values are always stored as pixels per inch.
*/
if ((ResolutionType) units != PixelsPerCentimeterResolution)
image->units=PixelsPerInchResolution;
else
{
image->units=PixelsPerCentimeterResolution;
image->resolution.x/=2.54;
image->resolution.y/=2.54;
}
break;
}
case 0x0404:
{
/*
IPTC Profile
*/
profile=AcquireStringInfo(count);
SetStringInfoDatum(profile,p);
(void) SetImageProfileInternal(image,"iptc",profile,MagickTrue,
exception);
profile=DestroyStringInfo(profile);
p+=count;
break;
}
case 0x040c:
{
/*
Thumbnail.
*/
p+=count;
break;
}
case 0x040f:
{
/*
ICC Profile.
*/
profile=AcquireStringInfo(count);
SetStringInfoDatum(profile,p);
(void) SetImageProfileInternal(image,"icc",profile,MagickTrue,
exception);
profile=DestroyStringInfo(profile);
p+=count;
break;
}
case 0x0422:
{
/*
EXIF Profile.
*/
profile=AcquireStringInfo(count);
SetStringInfoDatum(profile,p);
(void) SetImageProfileInternal(image,"exif",profile,MagickTrue,
exception);
profile=DestroyStringInfo(profile);
p+=count;
break;
}
case 0x0424:
{
/*
XMP Profile.
*/
profile=AcquireStringInfo(count);
SetStringInfoDatum(profile,p);
(void) SetImageProfileInternal(image,"xmp",profile,MagickTrue,
exception);
profile=DestroyStringInfo(profile);
p+=count;
break;
}
default:
{
p+=count;
break;
}
}
if ((count & 0x01) != 0)
p++;
}
}
static MagickBooleanType SetImageProfileInternal(Image *image,const char *name,
const StringInfo *profile,const MagickBooleanType recursive,
ExceptionInfo *exception)
{
char
key[MagickPathExtent],
property[MagickPathExtent];
MagickBooleanType
status;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
if (image->profiles == (SplayTreeInfo *) NULL)
image->profiles=NewSplayTree(CompareSplayTreeString,RelinquishMagickMemory,
DestroyProfile);
(void) CopyMagickString(key,name,MagickPathExtent);
LocaleLower(key);
status=AddValueToSplayTree((SplayTreeInfo *) image->profiles,
ConstantString(key),CloneStringInfo(profile));
if (status != MagickFalse)
{
if (LocaleCompare(name,"8bim") == 0)
GetProfilesFromResourceBlock(image,profile,exception);
else if (recursive == MagickFalse)
WriteTo8BimProfile(image,name,profile);
}
/*
Inject profile into image properties.
*/
(void) FormatLocaleString(property,MagickPathExtent,"%s:*",name);
(void) GetImageProperty(image,property,exception);
return(status);
}
MagickExport MagickBooleanType SetImageProfile(Image *image,const char *name,
const StringInfo *profile,ExceptionInfo *exception)
{
return(SetImageProfileInternal(image,name,profile,MagickFalse,exception));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S y n c I m a g e P r o f i l e s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% SyncImageProfiles() synchronizes image properties with the image profiles.
% Currently we only support updating the EXIF resolution and orientation.
%
% The format of the SyncImageProfiles method is:
%
% MagickBooleanType SyncImageProfiles(Image *image)
%
% A description of each parameter follows:
%
% o image: the image.
%
*/
static inline int ReadProfileByte(unsigned char **p,size_t *length)
{
int
c;
if (*length < 1)
return(EOF);
c=(int) (*(*p)++);
(*length)--;
return(c);
}
static inline signed short ReadProfileShort(const EndianType endian,
unsigned char *buffer)
{
union
{
unsigned int
unsigned_value;
signed int
signed_value;
} quantum;
unsigned short
value;
if (endian == LSBEndian)
{
value=(unsigned short) buffer[1] << 8;
value|=(unsigned short) buffer[0];
quantum.unsigned_value=value & 0xffff;
return(quantum.signed_value);
}
value=(unsigned short) buffer[0] << 8;
value|=(unsigned short) buffer[1];
quantum.unsigned_value=value & 0xffff;
return(quantum.signed_value);
}
static inline signed int ReadProfileLong(const EndianType endian,
unsigned char *buffer)
{
union
{
unsigned int
unsigned_value;
signed int
signed_value;
} quantum;
unsigned int
value;
if (endian == LSBEndian)
{
value=(unsigned int) buffer[3] << 24;
value|=(unsigned int) buffer[2] << 16;
value|=(unsigned int) buffer[1] << 8;
value|=(unsigned int) buffer[0];
quantum.unsigned_value=value & 0xffffffff;
return(quantum.signed_value);
}
value=(unsigned int) buffer[0] << 24;
value|=(unsigned int) buffer[1] << 16;
value|=(unsigned int) buffer[2] << 8;
value|=(unsigned int) buffer[3];
quantum.unsigned_value=value & 0xffffffff;
return(quantum.signed_value);
}
static inline signed int ReadProfileMSBLong(unsigned char **p,size_t *length)
{
signed int
value;
if (*length < 4)
return(0);
value=ReadProfileLong(MSBEndian,*p);
(*length)-=4;
*p+=4;
return(value);
}
static inline signed short ReadProfileMSBShort(unsigned char **p,
size_t *length)
{
signed short
value;
if (*length < 2)
return(0);
value=ReadProfileShort(MSBEndian,*p);
(*length)-=2;
*p+=2;
return(value);
}
static inline void WriteProfileLong(const EndianType endian,
const size_t value,unsigned char *p)
{
unsigned char
buffer[4];
if (endian == LSBEndian)
{
buffer[0]=(unsigned char) value;
buffer[1]=(unsigned char) (value >> 8);
buffer[2]=(unsigned char) (value >> 16);
buffer[3]=(unsigned char) (value >> 24);
(void) CopyMagickMemory(p,buffer,4);
return;
}
buffer[0]=(unsigned char) (value >> 24);
buffer[1]=(unsigned char) (value >> 16);
buffer[2]=(unsigned char) (value >> 8);
buffer[3]=(unsigned char) value;
(void) CopyMagickMemory(p,buffer,4);
}
static void WriteProfileShort(const EndianType endian,
const unsigned short value,unsigned char *p)
{
unsigned char
buffer[2];
if (endian == LSBEndian)
{
buffer[0]=(unsigned char) value;
buffer[1]=(unsigned char) (value >> 8);
(void) CopyMagickMemory(p,buffer,2);
return;
}
buffer[0]=(unsigned char) (value >> 8);
buffer[1]=(unsigned char) value;
(void) CopyMagickMemory(p,buffer,2);
}
static MagickBooleanType Sync8BimProfile(Image *image,StringInfo *profile)
{
size_t
length;
ssize_t
count;
unsigned char
*p;
unsigned short
id;
length=GetStringInfoLength(profile);
p=GetStringInfoDatum(profile);
while (length != 0)
{
if (ReadProfileByte(&p,&length) != 0x38)
continue;
if (ReadProfileByte(&p,&length) != 0x42)
continue;
if (ReadProfileByte(&p,&length) != 0x49)
continue;
if (ReadProfileByte(&p,&length) != 0x4D)
continue;
if (length < 7)
return(MagickFalse);
id=ReadProfileMSBShort(&p,&length);
count=(ssize_t) ReadProfileByte(&p,&length);
if ((count > (ssize_t) length) || (count < 0))
return(MagickFalse);
p+=count;
if ((*p & 0x01) == 0)
(void) ReadProfileByte(&p,&length);
count=(ssize_t) ReadProfileMSBLong(&p,&length);
if ((count > (ssize_t) length) || (count < 0))
return(MagickFalse);
if ((id == 0x3ED) && (count == 16))
{
if (image->units == PixelsPerCentimeterResolution)
WriteProfileLong(MSBEndian, (unsigned int) (image->resolution.x*2.54*
65536.0),p);
else
WriteProfileLong(MSBEndian, (unsigned int) (image->resolution.x*
65536.0),p);
WriteProfileShort(MSBEndian,(unsigned short) image->units,p+4);
if (image->units == PixelsPerCentimeterResolution)
WriteProfileLong(MSBEndian, (unsigned int) (image->resolution.y*2.54*
65536.0),p+8);
else
WriteProfileLong(MSBEndian, (unsigned int) (image->resolution.y*
65536.0),p+8);
WriteProfileShort(MSBEndian,(unsigned short) image->units,p+12);
}
p+=count;
length-=count;
}
return(MagickTrue);
}
MagickBooleanType SyncExifProfile(Image *image,StringInfo *profile)
{
#define MaxDirectoryStack 16
#define EXIF_DELIMITER "\n"
#define EXIF_NUM_FORMATS 12
#define TAG_EXIF_OFFSET 0x8769
#define TAG_INTEROP_OFFSET 0xa005
typedef struct _DirectoryInfo
{
unsigned char
*directory;
size_t
entry;
} DirectoryInfo;
DirectoryInfo
directory_stack[MaxDirectoryStack];
EndianType
endian;
size_t
entry,
length,
number_entries;
ssize_t
id,
level,
offset;
static int
format_bytes[] = {0, 1, 1, 2, 4, 8, 1, 1, 2, 4, 8, 4, 8};
unsigned char
*directory,
*exif;
/*
Set EXIF resolution tag.
*/
length=GetStringInfoLength(profile);
exif=GetStringInfoDatum(profile);
if (length < 16)
return(MagickFalse);
id=(ssize_t) ReadProfileShort(LSBEndian,exif);
if ((id != 0x4949) && (id != 0x4D4D))
{
while (length != 0)
{
if (ReadProfileByte(&exif,&length) != 0x45)
continue;
if (ReadProfileByte(&exif,&length) != 0x78)
continue;
if (ReadProfileByte(&exif,&length) != 0x69)
continue;
if (ReadProfileByte(&exif,&length) != 0x66)
continue;
if (ReadProfileByte(&exif,&length) != 0x00)
continue;
if (ReadProfileByte(&exif,&length) != 0x00)
continue;
break;
}
if (length < 16)
return(MagickFalse);
id=(ssize_t) ReadProfileShort(LSBEndian,exif);
}
endian=LSBEndian;
if (id == 0x4949)
endian=LSBEndian;
else
if (id == 0x4D4D)
endian=MSBEndian;
else
return(MagickFalse);
if (ReadProfileShort(endian,exif+2) != 0x002a)
return(MagickFalse);
/*
This the offset to the first IFD.
*/
offset=(ssize_t) ReadProfileLong(endian,exif+4);
if ((offset < 0) || (size_t) offset >= length)
return(MagickFalse);
directory=exif+offset;
level=0;
entry=0;
do
{
if (level > 0)
{
level--;
directory=directory_stack[level].directory;
entry=directory_stack[level].entry;
}
if ((directory < exif) || (directory > (exif+length-2)))
break;
/*
Determine how many entries there are in the current IFD.
*/
number_entries=ReadProfileShort(endian,directory);
for ( ; entry < number_entries; entry++)
{
int
components;
register unsigned char
*p,
*q;
size_t
number_bytes;
ssize_t
format,
tag_value;
q=(unsigned char *) (directory+2+(12*entry));
if (q > (exif+length-12))
break; /* corrupt EXIF */
tag_value=(ssize_t) ReadProfileShort(endian,q);
format=(ssize_t) ReadProfileShort(endian,q+2);
if ((format < 0) || ((format-1) >= EXIF_NUM_FORMATS))
break;
components=(ssize_t) ReadProfileLong(endian,q+4);
if (components < 0)
break; /* corrupt EXIF */
number_bytes=(size_t) components*format_bytes[format];
if ((ssize_t) number_bytes < components)
break; /* prevent overflow */
if (number_bytes <= 4)
p=q+8;
else
{
/*
The directory entry contains an offset.
*/
offset=(ssize_t) ReadProfileLong(endian,q+8);
if ((size_t) (offset+number_bytes) > length)
continue;
if (~length < number_bytes)
continue; /* prevent overflow */
p=(unsigned char *) (exif+offset);
}
switch (tag_value)
{
case 0x011a:
{
(void) WriteProfileLong(endian,(size_t) (image->resolution.x+0.5),p);
(void) WriteProfileLong(endian,1UL,p+4);
break;
}
case 0x011b:
{
(void) WriteProfileLong(endian,(size_t) (image->resolution.y+0.5),p);
(void) WriteProfileLong(endian,1UL,p+4);
break;
}
case 0x0112:
{
if (number_bytes == 4)
{
(void) WriteProfileLong(endian,(size_t) image->orientation,p);
break;
}
(void) WriteProfileShort(endian,(unsigned short) image->orientation,
p);
break;
}
case 0x0128:
{
if (number_bytes == 4)
{
(void) WriteProfileLong(endian,(size_t) (image->units+1),p);
break;
}
(void) WriteProfileShort(endian,(unsigned short) (image->units+1),p);
break;
}
default:
break;
}
if ((tag_value == TAG_EXIF_OFFSET) || (tag_value == TAG_INTEROP_OFFSET))
{
offset=(ssize_t) ReadProfileLong(endian,p);
if (((size_t) offset < length) && (level < (MaxDirectoryStack-2)))
{
directory_stack[level].directory=directory;
entry++;
directory_stack[level].entry=entry;
level++;
directory_stack[level].directory=exif+offset;
directory_stack[level].entry=0;
level++;
if ((directory+2+(12*number_entries)) > (exif+length))
break;
offset=(ssize_t) ReadProfileLong(endian,directory+2+(12*
number_entries));
if ((offset != 0) && ((size_t) offset < length) &&
(level < (MaxDirectoryStack-2)))
{
directory_stack[level].directory=exif+offset;
directory_stack[level].entry=0;
level++;
}
}
break;
}
}
} while (level > 0);
return(MagickTrue);
}
MagickPrivate MagickBooleanType SyncImageProfiles(Image *image)
{
MagickBooleanType
status;
StringInfo
*profile;
status=MagickTrue;
profile=(StringInfo *) GetImageProfile(image,"8BIM");
if (profile != (StringInfo *) NULL)
if (Sync8BimProfile(image,profile) == MagickFalse)
status=MagickFalse;
profile=(StringInfo *) GetImageProfile(image,"EXIF");
if (profile != (StringInfo *) NULL)
if (SyncExifProfile(image,profile) == MagickFalse)
status=MagickFalse;
return(status);
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/good_5330_0 |
crossvul-cpp_data_good_2725_0 | /*
* Copyright: (c) 2000 United States Government as represented by the
* Secretary of the Navy. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* 3. The 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 ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
/* \summary: AFS RX printer */
/*
* This code unmangles RX packets. RX is the mutant form of RPC that AFS
* uses to communicate between clients and servers.
*
* In this code, I mainly concern myself with decoding the AFS calls, not
* with the guts of RX, per se.
*
* Bah. If I never look at rx_packet.h again, it will be too soon.
*
* Ken Hornstein <kenh@cmf.nrl.navy.mil>
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <netdissect-stdinc.h>
#include "netdissect.h"
#include "addrtoname.h"
#include "extract.h"
#include "ip.h"
#define FS_RX_PORT 7000
#define CB_RX_PORT 7001
#define PROT_RX_PORT 7002
#define VLDB_RX_PORT 7003
#define KAUTH_RX_PORT 7004
#define VOL_RX_PORT 7005
#define ERROR_RX_PORT 7006 /* Doesn't seem to be used */
#define BOS_RX_PORT 7007
#define AFSNAMEMAX 256
#define AFSOPAQUEMAX 1024
#define PRNAMEMAX 64
#define VLNAMEMAX 65
#define KANAMEMAX 64
#define BOSNAMEMAX 256
#define PRSFS_READ 1 /* Read files */
#define PRSFS_WRITE 2 /* Write files */
#define PRSFS_INSERT 4 /* Insert files into a directory */
#define PRSFS_LOOKUP 8 /* Lookup files into a directory */
#define PRSFS_DELETE 16 /* Delete files */
#define PRSFS_LOCK 32 /* Lock files */
#define PRSFS_ADMINISTER 64 /* Change ACL's */
struct rx_header {
uint32_t epoch;
uint32_t cid;
uint32_t callNumber;
uint32_t seq;
uint32_t serial;
uint8_t type;
#define RX_PACKET_TYPE_DATA 1
#define RX_PACKET_TYPE_ACK 2
#define RX_PACKET_TYPE_BUSY 3
#define RX_PACKET_TYPE_ABORT 4
#define RX_PACKET_TYPE_ACKALL 5
#define RX_PACKET_TYPE_CHALLENGE 6
#define RX_PACKET_TYPE_RESPONSE 7
#define RX_PACKET_TYPE_DEBUG 8
#define RX_PACKET_TYPE_PARAMS 9
#define RX_PACKET_TYPE_VERSION 13
uint8_t flags;
#define RX_CLIENT_INITIATED 1
#define RX_REQUEST_ACK 2
#define RX_LAST_PACKET 4
#define RX_MORE_PACKETS 8
#define RX_FREE_PACKET 16
#define RX_SLOW_START_OK 32
#define RX_JUMBO_PACKET 32
uint8_t userStatus;
uint8_t securityIndex;
uint16_t spare; /* How clever: even though the AFS */
uint16_t serviceId; /* header files indicate that the */
}; /* serviceId is first, it's really */
/* encoded _after_ the spare field */
/* I wasted a day figuring that out! */
#define NUM_RX_FLAGS 7
#define RX_MAXACKS 255
struct rx_ackPacket {
uint16_t bufferSpace; /* Number of packet buffers available */
uint16_t maxSkew; /* Max diff between ack'd packet and */
/* highest packet received */
uint32_t firstPacket; /* The first packet in ack list */
uint32_t previousPacket; /* Previous packet recv'd (obsolete) */
uint32_t serial; /* # of packet that prompted the ack */
uint8_t reason; /* Reason for acknowledgement */
uint8_t nAcks; /* Number of acknowledgements */
uint8_t acks[RX_MAXACKS]; /* Up to RX_MAXACKS acknowledgements */
};
/*
* Values for the acks array
*/
#define RX_ACK_TYPE_NACK 0 /* Don't have this packet */
#define RX_ACK_TYPE_ACK 1 /* I have this packet */
static const struct tok rx_types[] = {
{ RX_PACKET_TYPE_DATA, "data" },
{ RX_PACKET_TYPE_ACK, "ack" },
{ RX_PACKET_TYPE_BUSY, "busy" },
{ RX_PACKET_TYPE_ABORT, "abort" },
{ RX_PACKET_TYPE_ACKALL, "ackall" },
{ RX_PACKET_TYPE_CHALLENGE, "challenge" },
{ RX_PACKET_TYPE_RESPONSE, "response" },
{ RX_PACKET_TYPE_DEBUG, "debug" },
{ RX_PACKET_TYPE_PARAMS, "params" },
{ RX_PACKET_TYPE_VERSION, "version" },
{ 0, NULL },
};
static const struct double_tok {
int flag; /* Rx flag */
int packetType; /* Packet type */
const char *s; /* Flag string */
} rx_flags[] = {
{ RX_CLIENT_INITIATED, 0, "client-init" },
{ RX_REQUEST_ACK, 0, "req-ack" },
{ RX_LAST_PACKET, 0, "last-pckt" },
{ RX_MORE_PACKETS, 0, "more-pckts" },
{ RX_FREE_PACKET, 0, "free-pckt" },
{ RX_SLOW_START_OK, RX_PACKET_TYPE_ACK, "slow-start" },
{ RX_JUMBO_PACKET, RX_PACKET_TYPE_DATA, "jumbogram" }
};
static const struct tok fs_req[] = {
{ 130, "fetch-data" },
{ 131, "fetch-acl" },
{ 132, "fetch-status" },
{ 133, "store-data" },
{ 134, "store-acl" },
{ 135, "store-status" },
{ 136, "remove-file" },
{ 137, "create-file" },
{ 138, "rename" },
{ 139, "symlink" },
{ 140, "link" },
{ 141, "makedir" },
{ 142, "rmdir" },
{ 143, "oldsetlock" },
{ 144, "oldextlock" },
{ 145, "oldrellock" },
{ 146, "get-stats" },
{ 147, "give-cbs" },
{ 148, "get-vlinfo" },
{ 149, "get-vlstats" },
{ 150, "set-vlstats" },
{ 151, "get-rootvl" },
{ 152, "check-token" },
{ 153, "get-time" },
{ 154, "nget-vlinfo" },
{ 155, "bulk-stat" },
{ 156, "setlock" },
{ 157, "extlock" },
{ 158, "rellock" },
{ 159, "xstat-ver" },
{ 160, "get-xstat" },
{ 161, "dfs-lookup" },
{ 162, "dfs-flushcps" },
{ 163, "dfs-symlink" },
{ 220, "residency" },
{ 65536, "inline-bulk-status" },
{ 65537, "fetch-data-64" },
{ 65538, "store-data-64" },
{ 65539, "give-up-all-cbs" },
{ 65540, "get-caps" },
{ 65541, "cb-rx-conn-addr" },
{ 0, NULL },
};
static const struct tok cb_req[] = {
{ 204, "callback" },
{ 205, "initcb" },
{ 206, "probe" },
{ 207, "getlock" },
{ 208, "getce" },
{ 209, "xstatver" },
{ 210, "getxstat" },
{ 211, "initcb2" },
{ 212, "whoareyou" },
{ 213, "initcb3" },
{ 214, "probeuuid" },
{ 215, "getsrvprefs" },
{ 216, "getcellservdb" },
{ 217, "getlocalcell" },
{ 218, "getcacheconf" },
{ 65536, "getce64" },
{ 65537, "getcellbynum" },
{ 65538, "tellmeaboutyourself" },
{ 0, NULL },
};
static const struct tok pt_req[] = {
{ 500, "new-user" },
{ 501, "where-is-it" },
{ 502, "dump-entry" },
{ 503, "add-to-group" },
{ 504, "name-to-id" },
{ 505, "id-to-name" },
{ 506, "delete" },
{ 507, "remove-from-group" },
{ 508, "get-cps" },
{ 509, "new-entry" },
{ 510, "list-max" },
{ 511, "set-max" },
{ 512, "list-entry" },
{ 513, "change-entry" },
{ 514, "list-elements" },
{ 515, "same-mbr-of" },
{ 516, "set-fld-sentry" },
{ 517, "list-owned" },
{ 518, "get-cps2" },
{ 519, "get-host-cps" },
{ 520, "update-entry" },
{ 521, "list-entries" },
{ 530, "list-super-groups" },
{ 0, NULL },
};
static const struct tok vldb_req[] = {
{ 501, "create-entry" },
{ 502, "delete-entry" },
{ 503, "get-entry-by-id" },
{ 504, "get-entry-by-name" },
{ 505, "get-new-volume-id" },
{ 506, "replace-entry" },
{ 507, "update-entry" },
{ 508, "setlock" },
{ 509, "releaselock" },
{ 510, "list-entry" },
{ 511, "list-attrib" },
{ 512, "linked-list" },
{ 513, "get-stats" },
{ 514, "probe" },
{ 515, "get-addrs" },
{ 516, "change-addr" },
{ 517, "create-entry-n" },
{ 518, "get-entry-by-id-n" },
{ 519, "get-entry-by-name-n" },
{ 520, "replace-entry-n" },
{ 521, "list-entry-n" },
{ 522, "list-attrib-n" },
{ 523, "linked-list-n" },
{ 524, "update-entry-by-name" },
{ 525, "create-entry-u" },
{ 526, "get-entry-by-id-u" },
{ 527, "get-entry-by-name-u" },
{ 528, "replace-entry-u" },
{ 529, "list-entry-u" },
{ 530, "list-attrib-u" },
{ 531, "linked-list-u" },
{ 532, "regaddr" },
{ 533, "get-addrs-u" },
{ 534, "list-attrib-n2" },
{ 0, NULL },
};
static const struct tok kauth_req[] = {
{ 1, "auth-old" },
{ 21, "authenticate" },
{ 22, "authenticate-v2" },
{ 2, "change-pw" },
{ 3, "get-ticket-old" },
{ 23, "get-ticket" },
{ 4, "set-pw" },
{ 5, "set-fields" },
{ 6, "create-user" },
{ 7, "delete-user" },
{ 8, "get-entry" },
{ 9, "list-entry" },
{ 10, "get-stats" },
{ 11, "debug" },
{ 12, "get-pw" },
{ 13, "get-random-key" },
{ 14, "unlock" },
{ 15, "lock-status" },
{ 0, NULL },
};
static const struct tok vol_req[] = {
{ 100, "create-volume" },
{ 101, "delete-volume" },
{ 102, "restore" },
{ 103, "forward" },
{ 104, "end-trans" },
{ 105, "clone" },
{ 106, "set-flags" },
{ 107, "get-flags" },
{ 108, "trans-create" },
{ 109, "dump" },
{ 110, "get-nth-volume" },
{ 111, "set-forwarding" },
{ 112, "get-name" },
{ 113, "get-status" },
{ 114, "sig-restore" },
{ 115, "list-partitions" },
{ 116, "list-volumes" },
{ 117, "set-id-types" },
{ 118, "monitor" },
{ 119, "partition-info" },
{ 120, "reclone" },
{ 121, "list-one-volume" },
{ 122, "nuke" },
{ 123, "set-date" },
{ 124, "x-list-volumes" },
{ 125, "x-list-one-volume" },
{ 126, "set-info" },
{ 127, "x-list-partitions" },
{ 128, "forward-multiple" },
{ 65536, "convert-ro" },
{ 65537, "get-size" },
{ 65538, "dump-v2" },
{ 0, NULL },
};
static const struct tok bos_req[] = {
{ 80, "create-bnode" },
{ 81, "delete-bnode" },
{ 82, "set-status" },
{ 83, "get-status" },
{ 84, "enumerate-instance" },
{ 85, "get-instance-info" },
{ 86, "get-instance-parm" },
{ 87, "add-superuser" },
{ 88, "delete-superuser" },
{ 89, "list-superusers" },
{ 90, "list-keys" },
{ 91, "add-key" },
{ 92, "delete-key" },
{ 93, "set-cell-name" },
{ 94, "get-cell-name" },
{ 95, "get-cell-host" },
{ 96, "add-cell-host" },
{ 97, "delete-cell-host" },
{ 98, "set-t-status" },
{ 99, "shutdown-all" },
{ 100, "restart-all" },
{ 101, "startup-all" },
{ 102, "set-noauth-flag" },
{ 103, "re-bozo" },
{ 104, "restart" },
{ 105, "start-bozo-install" },
{ 106, "uninstall" },
{ 107, "get-dates" },
{ 108, "exec" },
{ 109, "prune" },
{ 110, "set-restart-time" },
{ 111, "get-restart-time" },
{ 112, "start-bozo-log" },
{ 113, "wait-all" },
{ 114, "get-instance-strings" },
{ 115, "get-restricted" },
{ 116, "set-restricted" },
{ 0, NULL },
};
static const struct tok ubik_req[] = {
{ 10000, "vote-beacon" },
{ 10001, "vote-debug-old" },
{ 10002, "vote-sdebug-old" },
{ 10003, "vote-getsyncsite" },
{ 10004, "vote-debug" },
{ 10005, "vote-sdebug" },
{ 10006, "vote-xdebug" },
{ 10007, "vote-xsdebug" },
{ 20000, "disk-begin" },
{ 20001, "disk-commit" },
{ 20002, "disk-lock" },
{ 20003, "disk-write" },
{ 20004, "disk-getversion" },
{ 20005, "disk-getfile" },
{ 20006, "disk-sendfile" },
{ 20007, "disk-abort" },
{ 20008, "disk-releaselocks" },
{ 20009, "disk-truncate" },
{ 20010, "disk-probe" },
{ 20011, "disk-writev" },
{ 20012, "disk-interfaceaddr" },
{ 20013, "disk-setversion" },
{ 0, NULL },
};
#define VOTE_LOW 10000
#define VOTE_HIGH 10007
#define DISK_LOW 20000
#define DISK_HIGH 20013
static const struct tok cb_types[] = {
{ 1, "exclusive" },
{ 2, "shared" },
{ 3, "dropped" },
{ 0, NULL },
};
static const struct tok ubik_lock_types[] = {
{ 1, "read" },
{ 2, "write" },
{ 3, "wait" },
{ 0, NULL },
};
static const char *voltype[] = { "read-write", "read-only", "backup" };
static const struct tok afs_fs_errors[] = {
{ 101, "salvage volume" },
{ 102, "no such vnode" },
{ 103, "no such volume" },
{ 104, "volume exist" },
{ 105, "no service" },
{ 106, "volume offline" },
{ 107, "voline online" },
{ 108, "diskfull" },
{ 109, "diskquota exceeded" },
{ 110, "volume busy" },
{ 111, "volume moved" },
{ 112, "AFS IO error" },
{ 0xffffff9c, "restarting fileserver" }, /* -100, sic! */
{ 0, NULL }
};
/*
* Reasons for acknowledging a packet
*/
static const struct tok rx_ack_reasons[] = {
{ 1, "ack requested" },
{ 2, "duplicate packet" },
{ 3, "out of sequence" },
{ 4, "exceeds window" },
{ 5, "no buffer space" },
{ 6, "ping" },
{ 7, "ping response" },
{ 8, "delay" },
{ 9, "idle" },
{ 0, NULL },
};
/*
* Cache entries we keep around so we can figure out the RX opcode
* numbers for replies. This allows us to make sense of RX reply packets.
*/
struct rx_cache_entry {
uint32_t callnum; /* Call number (net order) */
struct in_addr client; /* client IP address (net order) */
struct in_addr server; /* server IP address (net order) */
int dport; /* server port (host order) */
u_short serviceId; /* Service identifier (net order) */
uint32_t opcode; /* RX opcode (host order) */
};
#define RX_CACHE_SIZE 64
static struct rx_cache_entry rx_cache[RX_CACHE_SIZE];
static int rx_cache_next = 0;
static int rx_cache_hint = 0;
static void rx_cache_insert(netdissect_options *, const u_char *, const struct ip *, int);
static int rx_cache_find(const struct rx_header *, const struct ip *,
int, int32_t *);
static void fs_print(netdissect_options *, const u_char *, int);
static void fs_reply_print(netdissect_options *, const u_char *, int, int32_t);
static void acl_print(netdissect_options *, u_char *, int, u_char *);
static void cb_print(netdissect_options *, const u_char *, int);
static void cb_reply_print(netdissect_options *, const u_char *, int, int32_t);
static void prot_print(netdissect_options *, const u_char *, int);
static void prot_reply_print(netdissect_options *, const u_char *, int, int32_t);
static void vldb_print(netdissect_options *, const u_char *, int);
static void vldb_reply_print(netdissect_options *, const u_char *, int, int32_t);
static void kauth_print(netdissect_options *, const u_char *, int);
static void kauth_reply_print(netdissect_options *, const u_char *, int, int32_t);
static void vol_print(netdissect_options *, const u_char *, int);
static void vol_reply_print(netdissect_options *, const u_char *, int, int32_t);
static void bos_print(netdissect_options *, const u_char *, int);
static void bos_reply_print(netdissect_options *, const u_char *, int, int32_t);
static void ubik_print(netdissect_options *, const u_char *);
static void ubik_reply_print(netdissect_options *, const u_char *, int, int32_t);
static void rx_ack_print(netdissect_options *, const u_char *, int);
static int is_ubik(uint32_t);
/*
* Handle the rx-level packet. See if we know what port it's going to so
* we can peek at the afs call inside
*/
void
rx_print(netdissect_options *ndo,
register const u_char *bp, int length, int sport, int dport,
const u_char *bp2)
{
register const struct rx_header *rxh;
int i;
int32_t opcode;
if (ndo->ndo_snapend - bp < (int)sizeof (struct rx_header)) {
ND_PRINT((ndo, " [|rx] (%d)", length));
return;
}
rxh = (const struct rx_header *) bp;
ND_PRINT((ndo, " rx %s", tok2str(rx_types, "type %d", rxh->type)));
if (ndo->ndo_vflag) {
int firstflag = 0;
if (ndo->ndo_vflag > 1)
ND_PRINT((ndo, " cid %08x call# %d",
(int) EXTRACT_32BITS(&rxh->cid),
(int) EXTRACT_32BITS(&rxh->callNumber)));
ND_PRINT((ndo, " seq %d ser %d",
(int) EXTRACT_32BITS(&rxh->seq),
(int) EXTRACT_32BITS(&rxh->serial)));
if (ndo->ndo_vflag > 2)
ND_PRINT((ndo, " secindex %d serviceid %hu",
(int) rxh->securityIndex,
EXTRACT_16BITS(&rxh->serviceId)));
if (ndo->ndo_vflag > 1)
for (i = 0; i < NUM_RX_FLAGS; i++) {
if (rxh->flags & rx_flags[i].flag &&
(!rx_flags[i].packetType ||
rxh->type == rx_flags[i].packetType)) {
if (!firstflag) {
firstflag = 1;
ND_PRINT((ndo, " "));
} else {
ND_PRINT((ndo, ","));
}
ND_PRINT((ndo, "<%s>", rx_flags[i].s));
}
}
}
/*
* Try to handle AFS calls that we know about. Check the destination
* port and make sure it's a data packet. Also, make sure the
* seq number is 1 (because otherwise it's a continuation packet,
* and we can't interpret that). Also, seems that reply packets
* do not have the client-init flag set, so we check for that
* as well.
*/
if (rxh->type == RX_PACKET_TYPE_DATA &&
EXTRACT_32BITS(&rxh->seq) == 1 &&
rxh->flags & RX_CLIENT_INITIATED) {
/*
* Insert this call into the call cache table, so we
* have a chance to print out replies
*/
rx_cache_insert(ndo, bp, (const struct ip *) bp2, dport);
switch (dport) {
case FS_RX_PORT: /* AFS file service */
fs_print(ndo, bp, length);
break;
case CB_RX_PORT: /* AFS callback service */
cb_print(ndo, bp, length);
break;
case PROT_RX_PORT: /* AFS protection service */
prot_print(ndo, bp, length);
break;
case VLDB_RX_PORT: /* AFS VLDB service */
vldb_print(ndo, bp, length);
break;
case KAUTH_RX_PORT: /* AFS Kerberos auth service */
kauth_print(ndo, bp, length);
break;
case VOL_RX_PORT: /* AFS Volume service */
vol_print(ndo, bp, length);
break;
case BOS_RX_PORT: /* AFS BOS service */
bos_print(ndo, bp, length);
break;
default:
;
}
/*
* If it's a reply (client-init is _not_ set, but seq is one)
* then look it up in the cache. If we find it, call the reply
* printing functions Note that we handle abort packets here,
* because printing out the return code can be useful at times.
*/
} else if (((rxh->type == RX_PACKET_TYPE_DATA &&
EXTRACT_32BITS(&rxh->seq) == 1) ||
rxh->type == RX_PACKET_TYPE_ABORT) &&
(rxh->flags & RX_CLIENT_INITIATED) == 0 &&
rx_cache_find(rxh, (const struct ip *) bp2,
sport, &opcode)) {
switch (sport) {
case FS_RX_PORT: /* AFS file service */
fs_reply_print(ndo, bp, length, opcode);
break;
case CB_RX_PORT: /* AFS callback service */
cb_reply_print(ndo, bp, length, opcode);
break;
case PROT_RX_PORT: /* AFS PT service */
prot_reply_print(ndo, bp, length, opcode);
break;
case VLDB_RX_PORT: /* AFS VLDB service */
vldb_reply_print(ndo, bp, length, opcode);
break;
case KAUTH_RX_PORT: /* AFS Kerberos auth service */
kauth_reply_print(ndo, bp, length, opcode);
break;
case VOL_RX_PORT: /* AFS Volume service */
vol_reply_print(ndo, bp, length, opcode);
break;
case BOS_RX_PORT: /* AFS BOS service */
bos_reply_print(ndo, bp, length, opcode);
break;
default:
;
}
/*
* If it's an RX ack packet, then use the appropriate ack decoding
* function (there isn't any service-specific information in the
* ack packet, so we can use one for all AFS services)
*/
} else if (rxh->type == RX_PACKET_TYPE_ACK)
rx_ack_print(ndo, bp, length);
ND_PRINT((ndo, " (%d)", length));
}
/*
* Insert an entry into the cache. Taken from print-nfs.c
*/
static void
rx_cache_insert(netdissect_options *ndo,
const u_char *bp, const struct ip *ip, int dport)
{
struct rx_cache_entry *rxent;
const struct rx_header *rxh = (const struct rx_header *) bp;
if (ndo->ndo_snapend - bp + 1 <= (int)(sizeof(struct rx_header) + sizeof(int32_t)))
return;
rxent = &rx_cache[rx_cache_next];
if (++rx_cache_next >= RX_CACHE_SIZE)
rx_cache_next = 0;
rxent->callnum = rxh->callNumber;
UNALIGNED_MEMCPY(&rxent->client, &ip->ip_src, sizeof(uint32_t));
UNALIGNED_MEMCPY(&rxent->server, &ip->ip_dst, sizeof(uint32_t));
rxent->dport = dport;
rxent->serviceId = rxh->serviceId;
rxent->opcode = EXTRACT_32BITS(bp + sizeof(struct rx_header));
}
/*
* Lookup an entry in the cache. Also taken from print-nfs.c
*
* Note that because this is a reply, we're looking at the _source_
* port.
*/
static int
rx_cache_find(const struct rx_header *rxh, const struct ip *ip, int sport,
int32_t *opcode)
{
int i;
struct rx_cache_entry *rxent;
uint32_t clip;
uint32_t sip;
UNALIGNED_MEMCPY(&clip, &ip->ip_dst, sizeof(uint32_t));
UNALIGNED_MEMCPY(&sip, &ip->ip_src, sizeof(uint32_t));
/* Start the search where we last left off */
i = rx_cache_hint;
do {
rxent = &rx_cache[i];
if (rxent->callnum == rxh->callNumber &&
rxent->client.s_addr == clip &&
rxent->server.s_addr == sip &&
rxent->serviceId == rxh->serviceId &&
rxent->dport == sport) {
/* We got a match! */
rx_cache_hint = i;
*opcode = rxent->opcode;
return(1);
}
if (++i >= RX_CACHE_SIZE)
i = 0;
} while (i != rx_cache_hint);
/* Our search failed */
return(0);
}
/*
* These extrememly grody macros handle the printing of various AFS stuff.
*/
#define FIDOUT() { unsigned long n1, n2, n3; \
ND_TCHECK2(bp[0], sizeof(int32_t) * 3); \
n1 = EXTRACT_32BITS(bp); \
bp += sizeof(int32_t); \
n2 = EXTRACT_32BITS(bp); \
bp += sizeof(int32_t); \
n3 = EXTRACT_32BITS(bp); \
bp += sizeof(int32_t); \
ND_PRINT((ndo, " fid %d/%d/%d", (int) n1, (int) n2, (int) n3)); \
}
#define STROUT(MAX) { unsigned int _i; \
ND_TCHECK2(bp[0], sizeof(int32_t)); \
_i = EXTRACT_32BITS(bp); \
if (_i > (MAX)) \
goto trunc; \
bp += sizeof(int32_t); \
ND_PRINT((ndo, " \"")); \
if (fn_printn(ndo, bp, _i, ndo->ndo_snapend)) \
goto trunc; \
ND_PRINT((ndo, "\"")); \
bp += ((_i + sizeof(int32_t) - 1) / sizeof(int32_t)) * sizeof(int32_t); \
}
#define INTOUT() { int _i; \
ND_TCHECK2(bp[0], sizeof(int32_t)); \
_i = (int) EXTRACT_32BITS(bp); \
bp += sizeof(int32_t); \
ND_PRINT((ndo, " %d", _i)); \
}
#define UINTOUT() { unsigned long _i; \
ND_TCHECK2(bp[0], sizeof(int32_t)); \
_i = EXTRACT_32BITS(bp); \
bp += sizeof(int32_t); \
ND_PRINT((ndo, " %lu", _i)); \
}
#define UINT64OUT() { uint64_t _i; \
ND_TCHECK2(bp[0], sizeof(uint64_t)); \
_i = EXTRACT_64BITS(bp); \
bp += sizeof(uint64_t); \
ND_PRINT((ndo, " %" PRIu64, _i)); \
}
#define DATEOUT() { time_t _t; struct tm *tm; char str[256]; \
ND_TCHECK2(bp[0], sizeof(int32_t)); \
_t = (time_t) EXTRACT_32BITS(bp); \
bp += sizeof(int32_t); \
tm = localtime(&_t); \
strftime(str, 256, "%Y/%m/%d %H:%M:%S", tm); \
ND_PRINT((ndo, " %s", str)); \
}
#define STOREATTROUT() { unsigned long mask, _i; \
ND_TCHECK2(bp[0], (sizeof(int32_t)*6)); \
mask = EXTRACT_32BITS(bp); bp += sizeof(int32_t); \
if (mask) ND_PRINT((ndo, " StoreStatus")); \
if (mask & 1) { ND_PRINT((ndo, " date")); DATEOUT(); } \
else bp += sizeof(int32_t); \
_i = EXTRACT_32BITS(bp); bp += sizeof(int32_t); \
if (mask & 2) ND_PRINT((ndo, " owner %lu", _i)); \
_i = EXTRACT_32BITS(bp); bp += sizeof(int32_t); \
if (mask & 4) ND_PRINT((ndo, " group %lu", _i)); \
_i = EXTRACT_32BITS(bp); bp += sizeof(int32_t); \
if (mask & 8) ND_PRINT((ndo, " mode %lo", _i & 07777)); \
_i = EXTRACT_32BITS(bp); bp += sizeof(int32_t); \
if (mask & 16) ND_PRINT((ndo, " segsize %lu", _i)); \
/* undocumented in 3.3 docu */ \
if (mask & 1024) ND_PRINT((ndo, " fsync")); \
}
#define UBIK_VERSIONOUT() {int32_t epoch; int32_t counter; \
ND_TCHECK2(bp[0], sizeof(int32_t) * 2); \
epoch = EXTRACT_32BITS(bp); \
bp += sizeof(int32_t); \
counter = EXTRACT_32BITS(bp); \
bp += sizeof(int32_t); \
ND_PRINT((ndo, " %d.%d", epoch, counter)); \
}
#define AFSUUIDOUT() {uint32_t temp; int _i; \
ND_TCHECK2(bp[0], 11*sizeof(uint32_t)); \
temp = EXTRACT_32BITS(bp); \
bp += sizeof(uint32_t); \
ND_PRINT((ndo, " %08x", temp)); \
temp = EXTRACT_32BITS(bp); \
bp += sizeof(uint32_t); \
ND_PRINT((ndo, "%04x", temp)); \
temp = EXTRACT_32BITS(bp); \
bp += sizeof(uint32_t); \
ND_PRINT((ndo, "%04x", temp)); \
for (_i = 0; _i < 8; _i++) { \
temp = EXTRACT_32BITS(bp); \
bp += sizeof(uint32_t); \
ND_PRINT((ndo, "%02x", (unsigned char) temp)); \
} \
}
/*
* This is the sickest one of all
*/
#define VECOUT(MAX) { u_char *sp; \
u_char s[AFSNAMEMAX]; \
int k; \
if ((MAX) + 1 > sizeof(s)) \
goto trunc; \
ND_TCHECK2(bp[0], (MAX) * sizeof(int32_t)); \
sp = s; \
for (k = 0; k < (MAX); k++) { \
*sp++ = (u_char) EXTRACT_32BITS(bp); \
bp += sizeof(int32_t); \
} \
s[(MAX)] = '\0'; \
ND_PRINT((ndo, " \"")); \
fn_print(ndo, s, NULL); \
ND_PRINT((ndo, "\"")); \
}
#define DESTSERVEROUT() { unsigned long n1, n2, n3; \
ND_TCHECK2(bp[0], sizeof(int32_t) * 3); \
n1 = EXTRACT_32BITS(bp); \
bp += sizeof(int32_t); \
n2 = EXTRACT_32BITS(bp); \
bp += sizeof(int32_t); \
n3 = EXTRACT_32BITS(bp); \
bp += sizeof(int32_t); \
ND_PRINT((ndo, " server %d:%d:%d", (int) n1, (int) n2, (int) n3)); \
}
/*
* Handle calls to the AFS file service (fs)
*/
static void
fs_print(netdissect_options *ndo,
register const u_char *bp, int length)
{
int fs_op;
unsigned long i;
if (length <= (int)sizeof(struct rx_header))
return;
if (ndo->ndo_snapend - bp + 1 <= (int)(sizeof(struct rx_header) + sizeof(int32_t))) {
goto trunc;
}
/*
* Print out the afs call we're invoking. The table used here was
* gleaned from fsint/afsint.xg
*/
fs_op = EXTRACT_32BITS(bp + sizeof(struct rx_header));
ND_PRINT((ndo, " fs call %s", tok2str(fs_req, "op#%d", fs_op)));
/*
* Print out arguments to some of the AFS calls. This stuff is
* all from afsint.xg
*/
bp += sizeof(struct rx_header) + 4;
/*
* Sigh. This is gross. Ritchie forgive me.
*/
switch (fs_op) {
case 130: /* Fetch data */
FIDOUT();
ND_PRINT((ndo, " offset"));
UINTOUT();
ND_PRINT((ndo, " length"));
UINTOUT();
break;
case 131: /* Fetch ACL */
case 132: /* Fetch Status */
case 143: /* Old set lock */
case 144: /* Old extend lock */
case 145: /* Old release lock */
case 156: /* Set lock */
case 157: /* Extend lock */
case 158: /* Release lock */
FIDOUT();
break;
case 135: /* Store status */
FIDOUT();
STOREATTROUT();
break;
case 133: /* Store data */
FIDOUT();
STOREATTROUT();
ND_PRINT((ndo, " offset"));
UINTOUT();
ND_PRINT((ndo, " length"));
UINTOUT();
ND_PRINT((ndo, " flen"));
UINTOUT();
break;
case 134: /* Store ACL */
{
char a[AFSOPAQUEMAX+1];
FIDOUT();
ND_TCHECK2(bp[0], 4);
i = EXTRACT_32BITS(bp);
bp += sizeof(int32_t);
ND_TCHECK2(bp[0], i);
i = min(AFSOPAQUEMAX, i);
strncpy(a, (const char *) bp, i);
a[i] = '\0';
acl_print(ndo, (u_char *) a, sizeof(a), (u_char *) a + i);
break;
}
case 137: /* Create file */
case 141: /* MakeDir */
FIDOUT();
STROUT(AFSNAMEMAX);
STOREATTROUT();
break;
case 136: /* Remove file */
case 142: /* Remove directory */
FIDOUT();
STROUT(AFSNAMEMAX);
break;
case 138: /* Rename file */
ND_PRINT((ndo, " old"));
FIDOUT();
STROUT(AFSNAMEMAX);
ND_PRINT((ndo, " new"));
FIDOUT();
STROUT(AFSNAMEMAX);
break;
case 139: /* Symlink */
FIDOUT();
STROUT(AFSNAMEMAX);
ND_PRINT((ndo, " link to"));
STROUT(AFSNAMEMAX);
break;
case 140: /* Link */
FIDOUT();
STROUT(AFSNAMEMAX);
ND_PRINT((ndo, " link to"));
FIDOUT();
break;
case 148: /* Get volume info */
STROUT(AFSNAMEMAX);
break;
case 149: /* Get volume stats */
case 150: /* Set volume stats */
ND_PRINT((ndo, " volid"));
UINTOUT();
break;
case 154: /* New get volume info */
ND_PRINT((ndo, " volname"));
STROUT(AFSNAMEMAX);
break;
case 155: /* Bulk stat */
case 65536: /* Inline bulk stat */
{
unsigned long j;
ND_TCHECK2(bp[0], 4);
j = EXTRACT_32BITS(bp);
bp += sizeof(int32_t);
for (i = 0; i < j; i++) {
FIDOUT();
if (i != j - 1)
ND_PRINT((ndo, ","));
}
if (j == 0)
ND_PRINT((ndo, " <none!>"));
}
case 65537: /* Fetch data 64 */
FIDOUT();
ND_PRINT((ndo, " offset"));
UINT64OUT();
ND_PRINT((ndo, " length"));
UINT64OUT();
break;
case 65538: /* Store data 64 */
FIDOUT();
STOREATTROUT();
ND_PRINT((ndo, " offset"));
UINT64OUT();
ND_PRINT((ndo, " length"));
UINT64OUT();
ND_PRINT((ndo, " flen"));
UINT64OUT();
break;
case 65541: /* CallBack rx conn address */
ND_PRINT((ndo, " addr"));
UINTOUT();
default:
;
}
return;
trunc:
ND_PRINT((ndo, " [|fs]"));
}
/*
* Handle replies to the AFS file service
*/
static void
fs_reply_print(netdissect_options *ndo,
register const u_char *bp, int length, int32_t opcode)
{
unsigned long i;
const struct rx_header *rxh;
if (length <= (int)sizeof(struct rx_header))
return;
rxh = (const struct rx_header *) bp;
/*
* Print out the afs call we're invoking. The table used here was
* gleaned from fsint/afsint.xg
*/
ND_PRINT((ndo, " fs reply %s", tok2str(fs_req, "op#%d", opcode)));
bp += sizeof(struct rx_header);
/*
* If it was a data packet, interpret the response
*/
if (rxh->type == RX_PACKET_TYPE_DATA) {
switch (opcode) {
case 131: /* Fetch ACL */
{
char a[AFSOPAQUEMAX+1];
ND_TCHECK2(bp[0], 4);
i = EXTRACT_32BITS(bp);
bp += sizeof(int32_t);
ND_TCHECK2(bp[0], i);
i = min(AFSOPAQUEMAX, i);
strncpy(a, (const char *) bp, i);
a[i] = '\0';
acl_print(ndo, (u_char *) a, sizeof(a), (u_char *) a + i);
break;
}
case 137: /* Create file */
case 141: /* MakeDir */
ND_PRINT((ndo, " new"));
FIDOUT();
break;
case 151: /* Get root volume */
ND_PRINT((ndo, " root volume"));
STROUT(AFSNAMEMAX);
break;
case 153: /* Get time */
DATEOUT();
break;
default:
;
}
} else if (rxh->type == RX_PACKET_TYPE_ABORT) {
/*
* Otherwise, just print out the return code
*/
ND_TCHECK2(bp[0], sizeof(int32_t));
i = (int) EXTRACT_32BITS(bp);
bp += sizeof(int32_t);
ND_PRINT((ndo, " error %s", tok2str(afs_fs_errors, "#%d", i)));
} else {
ND_PRINT((ndo, " strange fs reply of type %d", rxh->type));
}
return;
trunc:
ND_PRINT((ndo, " [|fs]"));
}
/*
* Print out an AFS ACL string. An AFS ACL is a string that has the
* following format:
*
* <positive> <negative>
* <uid1> <aclbits1>
* ....
*
* "positive" and "negative" are integers which contain the number of
* positive and negative ACL's in the string. The uid/aclbits pair are
* ASCII strings containing the UID/PTS record and an ASCII number
* representing a logical OR of all the ACL permission bits
*/
static void
acl_print(netdissect_options *ndo,
u_char *s, int maxsize, u_char *end)
{
int pos, neg, acl;
int n, i;
char *user;
char fmt[1024];
if ((user = (char *)malloc(maxsize)) == NULL)
return;
if (sscanf((char *) s, "%d %d\n%n", &pos, &neg, &n) != 2)
goto finish;
s += n;
if (s > end)
goto finish;
/*
* This wacky order preserves the order used by the "fs" command
*/
#define ACLOUT(acl) \
ND_PRINT((ndo, "%s%s%s%s%s%s%s", \
acl & PRSFS_READ ? "r" : "", \
acl & PRSFS_LOOKUP ? "l" : "", \
acl & PRSFS_INSERT ? "i" : "", \
acl & PRSFS_DELETE ? "d" : "", \
acl & PRSFS_WRITE ? "w" : "", \
acl & PRSFS_LOCK ? "k" : "", \
acl & PRSFS_ADMINISTER ? "a" : ""));
for (i = 0; i < pos; i++) {
snprintf(fmt, sizeof(fmt), "%%%ds %%d\n%%n", maxsize - 1);
if (sscanf((char *) s, fmt, user, &acl, &n) != 2)
goto finish;
s += n;
ND_PRINT((ndo, " +{"));
fn_print(ndo, (u_char *)user, NULL);
ND_PRINT((ndo, " "));
ACLOUT(acl);
ND_PRINT((ndo, "}"));
if (s > end)
goto finish;
}
for (i = 0; i < neg; i++) {
snprintf(fmt, sizeof(fmt), "%%%ds %%d\n%%n", maxsize - 1);
if (sscanf((char *) s, fmt, user, &acl, &n) != 2)
goto finish;
s += n;
ND_PRINT((ndo, " -{"));
fn_print(ndo, (u_char *)user, NULL);
ND_PRINT((ndo, " "));
ACLOUT(acl);
ND_PRINT((ndo, "}"));
if (s > end)
goto finish;
}
finish:
free(user);
return;
}
#undef ACLOUT
/*
* Handle calls to the AFS callback service
*/
static void
cb_print(netdissect_options *ndo,
register const u_char *bp, int length)
{
int cb_op;
unsigned long i;
if (length <= (int)sizeof(struct rx_header))
return;
if (ndo->ndo_snapend - bp + 1 <= (int)(sizeof(struct rx_header) + sizeof(int32_t))) {
goto trunc;
}
/*
* Print out the afs call we're invoking. The table used here was
* gleaned from fsint/afscbint.xg
*/
cb_op = EXTRACT_32BITS(bp + sizeof(struct rx_header));
ND_PRINT((ndo, " cb call %s", tok2str(cb_req, "op#%d", cb_op)));
bp += sizeof(struct rx_header) + 4;
/*
* Print out the afs call we're invoking. The table used here was
* gleaned from fsint/afscbint.xg
*/
switch (cb_op) {
case 204: /* Callback */
{
unsigned long j, t;
ND_TCHECK2(bp[0], 4);
j = EXTRACT_32BITS(bp);
bp += sizeof(int32_t);
for (i = 0; i < j; i++) {
FIDOUT();
if (i != j - 1)
ND_PRINT((ndo, ","));
}
if (j == 0)
ND_PRINT((ndo, " <none!>"));
j = EXTRACT_32BITS(bp);
bp += sizeof(int32_t);
if (j != 0)
ND_PRINT((ndo, ";"));
for (i = 0; i < j; i++) {
ND_PRINT((ndo, " ver"));
INTOUT();
ND_PRINT((ndo, " expires"));
DATEOUT();
ND_TCHECK2(bp[0], 4);
t = EXTRACT_32BITS(bp);
bp += sizeof(int32_t);
tok2str(cb_types, "type %d", t);
}
}
case 214: {
ND_PRINT((ndo, " afsuuid"));
AFSUUIDOUT();
break;
}
default:
;
}
return;
trunc:
ND_PRINT((ndo, " [|cb]"));
}
/*
* Handle replies to the AFS Callback Service
*/
static void
cb_reply_print(netdissect_options *ndo,
register const u_char *bp, int length, int32_t opcode)
{
const struct rx_header *rxh;
if (length <= (int)sizeof(struct rx_header))
return;
rxh = (const struct rx_header *) bp;
/*
* Print out the afs call we're invoking. The table used here was
* gleaned from fsint/afscbint.xg
*/
ND_PRINT((ndo, " cb reply %s", tok2str(cb_req, "op#%d", opcode)));
bp += sizeof(struct rx_header);
/*
* If it was a data packet, interpret the response.
*/
if (rxh->type == RX_PACKET_TYPE_DATA)
switch (opcode) {
case 213: /* InitCallBackState3 */
AFSUUIDOUT();
break;
default:
;
}
else {
/*
* Otherwise, just print out the return code
*/
ND_PRINT((ndo, " errcode"));
INTOUT();
}
return;
trunc:
ND_PRINT((ndo, " [|cb]"));
}
/*
* Handle calls to the AFS protection database server
*/
static void
prot_print(netdissect_options *ndo,
register const u_char *bp, int length)
{
unsigned long i;
int pt_op;
if (length <= (int)sizeof(struct rx_header))
return;
if (ndo->ndo_snapend - bp + 1 <= (int)(sizeof(struct rx_header) + sizeof(int32_t))) {
goto trunc;
}
/*
* Print out the afs call we're invoking. The table used here was
* gleaned from ptserver/ptint.xg
*/
pt_op = EXTRACT_32BITS(bp + sizeof(struct rx_header));
ND_PRINT((ndo, " pt"));
if (is_ubik(pt_op)) {
ubik_print(ndo, bp);
return;
}
ND_PRINT((ndo, " call %s", tok2str(pt_req, "op#%d", pt_op)));
/*
* Decode some of the arguments to the PT calls
*/
bp += sizeof(struct rx_header) + 4;
switch (pt_op) {
case 500: /* I New User */
STROUT(PRNAMEMAX);
ND_PRINT((ndo, " id"));
INTOUT();
ND_PRINT((ndo, " oldid"));
INTOUT();
break;
case 501: /* Where is it */
case 506: /* Delete */
case 508: /* Get CPS */
case 512: /* List entry */
case 514: /* List elements */
case 517: /* List owned */
case 518: /* Get CPS2 */
case 519: /* Get host CPS */
case 530: /* List super groups */
ND_PRINT((ndo, " id"));
INTOUT();
break;
case 502: /* Dump entry */
ND_PRINT((ndo, " pos"));
INTOUT();
break;
case 503: /* Add to group */
case 507: /* Remove from group */
case 515: /* Is a member of? */
ND_PRINT((ndo, " uid"));
INTOUT();
ND_PRINT((ndo, " gid"));
INTOUT();
break;
case 504: /* Name to ID */
{
unsigned long j;
ND_TCHECK2(bp[0], 4);
j = EXTRACT_32BITS(bp);
bp += sizeof(int32_t);
/*
* Who designed this chicken-shit protocol?
*
* Each character is stored as a 32-bit
* integer!
*/
for (i = 0; i < j; i++) {
VECOUT(PRNAMEMAX);
}
if (j == 0)
ND_PRINT((ndo, " <none!>"));
}
break;
case 505: /* Id to name */
{
unsigned long j;
ND_PRINT((ndo, " ids:"));
ND_TCHECK2(bp[0], 4);
i = EXTRACT_32BITS(bp);
bp += sizeof(int32_t);
for (j = 0; j < i; j++)
INTOUT();
if (j == 0)
ND_PRINT((ndo, " <none!>"));
}
break;
case 509: /* New entry */
STROUT(PRNAMEMAX);
ND_PRINT((ndo, " flag"));
INTOUT();
ND_PRINT((ndo, " oid"));
INTOUT();
break;
case 511: /* Set max */
ND_PRINT((ndo, " id"));
INTOUT();
ND_PRINT((ndo, " gflag"));
INTOUT();
break;
case 513: /* Change entry */
ND_PRINT((ndo, " id"));
INTOUT();
STROUT(PRNAMEMAX);
ND_PRINT((ndo, " oldid"));
INTOUT();
ND_PRINT((ndo, " newid"));
INTOUT();
break;
case 520: /* Update entry */
ND_PRINT((ndo, " id"));
INTOUT();
STROUT(PRNAMEMAX);
break;
default:
;
}
return;
trunc:
ND_PRINT((ndo, " [|pt]"));
}
/*
* Handle replies to the AFS protection service
*/
static void
prot_reply_print(netdissect_options *ndo,
register const u_char *bp, int length, int32_t opcode)
{
const struct rx_header *rxh;
unsigned long i;
if (length < (int)sizeof(struct rx_header))
return;
rxh = (const struct rx_header *) bp;
/*
* Print out the afs call we're invoking. The table used here was
* gleaned from ptserver/ptint.xg. Check to see if it's a
* Ubik call, however.
*/
ND_PRINT((ndo, " pt"));
if (is_ubik(opcode)) {
ubik_reply_print(ndo, bp, length, opcode);
return;
}
ND_PRINT((ndo, " reply %s", tok2str(pt_req, "op#%d", opcode)));
bp += sizeof(struct rx_header);
/*
* If it was a data packet, interpret the response
*/
if (rxh->type == RX_PACKET_TYPE_DATA)
switch (opcode) {
case 504: /* Name to ID */
{
unsigned long j;
ND_PRINT((ndo, " ids:"));
ND_TCHECK2(bp[0], 4);
i = EXTRACT_32BITS(bp);
bp += sizeof(int32_t);
for (j = 0; j < i; j++)
INTOUT();
if (j == 0)
ND_PRINT((ndo, " <none!>"));
}
break;
case 505: /* ID to name */
{
unsigned long j;
ND_TCHECK2(bp[0], 4);
j = EXTRACT_32BITS(bp);
bp += sizeof(int32_t);
/*
* Who designed this chicken-shit protocol?
*
* Each character is stored as a 32-bit
* integer!
*/
for (i = 0; i < j; i++) {
VECOUT(PRNAMEMAX);
}
if (j == 0)
ND_PRINT((ndo, " <none!>"));
}
break;
case 508: /* Get CPS */
case 514: /* List elements */
case 517: /* List owned */
case 518: /* Get CPS2 */
case 519: /* Get host CPS */
{
unsigned long j;
ND_TCHECK2(bp[0], 4);
j = EXTRACT_32BITS(bp);
bp += sizeof(int32_t);
for (i = 0; i < j; i++) {
INTOUT();
}
if (j == 0)
ND_PRINT((ndo, " <none!>"));
}
break;
case 510: /* List max */
ND_PRINT((ndo, " maxuid"));
INTOUT();
ND_PRINT((ndo, " maxgid"));
INTOUT();
break;
default:
;
}
else {
/*
* Otherwise, just print out the return code
*/
ND_PRINT((ndo, " errcode"));
INTOUT();
}
return;
trunc:
ND_PRINT((ndo, " [|pt]"));
}
/*
* Handle calls to the AFS volume location database service
*/
static void
vldb_print(netdissect_options *ndo,
register const u_char *bp, int length)
{
int vldb_op;
unsigned long i;
if (length <= (int)sizeof(struct rx_header))
return;
if (ndo->ndo_snapend - bp + 1 <= (int)(sizeof(struct rx_header) + sizeof(int32_t))) {
goto trunc;
}
/*
* Print out the afs call we're invoking. The table used here was
* gleaned from vlserver/vldbint.xg
*/
vldb_op = EXTRACT_32BITS(bp + sizeof(struct rx_header));
ND_PRINT((ndo, " vldb"));
if (is_ubik(vldb_op)) {
ubik_print(ndo, bp);
return;
}
ND_PRINT((ndo, " call %s", tok2str(vldb_req, "op#%d", vldb_op)));
/*
* Decode some of the arguments to the VLDB calls
*/
bp += sizeof(struct rx_header) + 4;
switch (vldb_op) {
case 501: /* Create new volume */
case 517: /* Create entry N */
VECOUT(VLNAMEMAX);
break;
case 502: /* Delete entry */
case 503: /* Get entry by ID */
case 507: /* Update entry */
case 508: /* Set lock */
case 509: /* Release lock */
case 518: /* Get entry by ID N */
ND_PRINT((ndo, " volid"));
INTOUT();
ND_TCHECK2(bp[0], sizeof(int32_t));
i = EXTRACT_32BITS(bp);
bp += sizeof(int32_t);
if (i <= 2)
ND_PRINT((ndo, " type %s", voltype[i]));
break;
case 504: /* Get entry by name */
case 519: /* Get entry by name N */
case 524: /* Update entry by name */
case 527: /* Get entry by name U */
STROUT(VLNAMEMAX);
break;
case 505: /* Get new vol id */
ND_PRINT((ndo, " bump"));
INTOUT();
break;
case 506: /* Replace entry */
case 520: /* Replace entry N */
ND_PRINT((ndo, " volid"));
INTOUT();
ND_TCHECK2(bp[0], sizeof(int32_t));
i = EXTRACT_32BITS(bp);
bp += sizeof(int32_t);
if (i <= 2)
ND_PRINT((ndo, " type %s", voltype[i]));
VECOUT(VLNAMEMAX);
break;
case 510: /* List entry */
case 521: /* List entry N */
ND_PRINT((ndo, " index"));
INTOUT();
break;
default:
;
}
return;
trunc:
ND_PRINT((ndo, " [|vldb]"));
}
/*
* Handle replies to the AFS volume location database service
*/
static void
vldb_reply_print(netdissect_options *ndo,
register const u_char *bp, int length, int32_t opcode)
{
const struct rx_header *rxh;
unsigned long i;
if (length < (int)sizeof(struct rx_header))
return;
rxh = (const struct rx_header *) bp;
/*
* Print out the afs call we're invoking. The table used here was
* gleaned from vlserver/vldbint.xg. Check to see if it's a
* Ubik call, however.
*/
ND_PRINT((ndo, " vldb"));
if (is_ubik(opcode)) {
ubik_reply_print(ndo, bp, length, opcode);
return;
}
ND_PRINT((ndo, " reply %s", tok2str(vldb_req, "op#%d", opcode)));
bp += sizeof(struct rx_header);
/*
* If it was a data packet, interpret the response
*/
if (rxh->type == RX_PACKET_TYPE_DATA)
switch (opcode) {
case 510: /* List entry */
ND_PRINT((ndo, " count"));
INTOUT();
ND_PRINT((ndo, " nextindex"));
INTOUT();
case 503: /* Get entry by id */
case 504: /* Get entry by name */
{ unsigned long nservers, j;
VECOUT(VLNAMEMAX);
ND_TCHECK2(bp[0], sizeof(int32_t));
bp += sizeof(int32_t);
ND_PRINT((ndo, " numservers"));
ND_TCHECK2(bp[0], sizeof(int32_t));
nservers = EXTRACT_32BITS(bp);
bp += sizeof(int32_t);
ND_PRINT((ndo, " %lu", nservers));
ND_PRINT((ndo, " servers"));
for (i = 0; i < 8; i++) {
ND_TCHECK2(bp[0], sizeof(int32_t));
if (i < nservers)
ND_PRINT((ndo, " %s",
intoa(((const struct in_addr *) bp)->s_addr)));
bp += sizeof(int32_t);
}
ND_PRINT((ndo, " partitions"));
for (i = 0; i < 8; i++) {
ND_TCHECK2(bp[0], sizeof(int32_t));
j = EXTRACT_32BITS(bp);
if (i < nservers && j <= 26)
ND_PRINT((ndo, " %c", 'a' + (int)j));
else if (i < nservers)
ND_PRINT((ndo, " %lu", j));
bp += sizeof(int32_t);
}
ND_TCHECK2(bp[0], 8 * sizeof(int32_t));
bp += 8 * sizeof(int32_t);
ND_PRINT((ndo, " rwvol"));
UINTOUT();
ND_PRINT((ndo, " rovol"));
UINTOUT();
ND_PRINT((ndo, " backup"));
UINTOUT();
}
break;
case 505: /* Get new volume ID */
ND_PRINT((ndo, " newvol"));
UINTOUT();
break;
case 521: /* List entry */
case 529: /* List entry U */
ND_PRINT((ndo, " count"));
INTOUT();
ND_PRINT((ndo, " nextindex"));
INTOUT();
case 518: /* Get entry by ID N */
case 519: /* Get entry by name N */
{ unsigned long nservers, j;
VECOUT(VLNAMEMAX);
ND_PRINT((ndo, " numservers"));
ND_TCHECK2(bp[0], sizeof(int32_t));
nservers = EXTRACT_32BITS(bp);
bp += sizeof(int32_t);
ND_PRINT((ndo, " %lu", nservers));
ND_PRINT((ndo, " servers"));
for (i = 0; i < 13; i++) {
ND_TCHECK2(bp[0], sizeof(int32_t));
if (i < nservers)
ND_PRINT((ndo, " %s",
intoa(((const struct in_addr *) bp)->s_addr)));
bp += sizeof(int32_t);
}
ND_PRINT((ndo, " partitions"));
for (i = 0; i < 13; i++) {
ND_TCHECK2(bp[0], sizeof(int32_t));
j = EXTRACT_32BITS(bp);
if (i < nservers && j <= 26)
ND_PRINT((ndo, " %c", 'a' + (int)j));
else if (i < nservers)
ND_PRINT((ndo, " %lu", j));
bp += sizeof(int32_t);
}
ND_TCHECK2(bp[0], 13 * sizeof(int32_t));
bp += 13 * sizeof(int32_t);
ND_PRINT((ndo, " rwvol"));
UINTOUT();
ND_PRINT((ndo, " rovol"));
UINTOUT();
ND_PRINT((ndo, " backup"));
UINTOUT();
}
break;
case 526: /* Get entry by ID U */
case 527: /* Get entry by name U */
{ unsigned long nservers, j;
VECOUT(VLNAMEMAX);
ND_PRINT((ndo, " numservers"));
ND_TCHECK2(bp[0], sizeof(int32_t));
nservers = EXTRACT_32BITS(bp);
bp += sizeof(int32_t);
ND_PRINT((ndo, " %lu", nservers));
ND_PRINT((ndo, " servers"));
for (i = 0; i < 13; i++) {
if (i < nservers) {
ND_PRINT((ndo, " afsuuid"));
AFSUUIDOUT();
} else {
ND_TCHECK2(bp[0], 44);
bp += 44;
}
}
ND_TCHECK2(bp[0], 4 * 13);
bp += 4 * 13;
ND_PRINT((ndo, " partitions"));
for (i = 0; i < 13; i++) {
ND_TCHECK2(bp[0], sizeof(int32_t));
j = EXTRACT_32BITS(bp);
if (i < nservers && j <= 26)
ND_PRINT((ndo, " %c", 'a' + (int)j));
else if (i < nservers)
ND_PRINT((ndo, " %lu", j));
bp += sizeof(int32_t);
}
ND_TCHECK2(bp[0], 13 * sizeof(int32_t));
bp += 13 * sizeof(int32_t);
ND_PRINT((ndo, " rwvol"));
UINTOUT();
ND_PRINT((ndo, " rovol"));
UINTOUT();
ND_PRINT((ndo, " backup"));
UINTOUT();
}
default:
;
}
else {
/*
* Otherwise, just print out the return code
*/
ND_PRINT((ndo, " errcode"));
INTOUT();
}
return;
trunc:
ND_PRINT((ndo, " [|vldb]"));
}
/*
* Handle calls to the AFS Kerberos Authentication service
*/
static void
kauth_print(netdissect_options *ndo,
register const u_char *bp, int length)
{
int kauth_op;
if (length <= (int)sizeof(struct rx_header))
return;
if (ndo->ndo_snapend - bp + 1 <= (int)(sizeof(struct rx_header) + sizeof(int32_t))) {
goto trunc;
}
/*
* Print out the afs call we're invoking. The table used here was
* gleaned from kauth/kauth.rg
*/
kauth_op = EXTRACT_32BITS(bp + sizeof(struct rx_header));
ND_PRINT((ndo, " kauth"));
if (is_ubik(kauth_op)) {
ubik_print(ndo, bp);
return;
}
ND_PRINT((ndo, " call %s", tok2str(kauth_req, "op#%d", kauth_op)));
/*
* Decode some of the arguments to the KA calls
*/
bp += sizeof(struct rx_header) + 4;
switch (kauth_op) {
case 1: /* Authenticate old */
case 21: /* Authenticate */
case 22: /* Authenticate-V2 */
case 2: /* Change PW */
case 5: /* Set fields */
case 6: /* Create user */
case 7: /* Delete user */
case 8: /* Get entry */
case 14: /* Unlock */
case 15: /* Lock status */
ND_PRINT((ndo, " principal"));
STROUT(KANAMEMAX);
STROUT(KANAMEMAX);
break;
case 3: /* GetTicket-old */
case 23: /* GetTicket */
{
int i;
ND_PRINT((ndo, " kvno"));
INTOUT();
ND_PRINT((ndo, " domain"));
STROUT(KANAMEMAX);
ND_TCHECK2(bp[0], sizeof(int32_t));
i = (int) EXTRACT_32BITS(bp);
bp += sizeof(int32_t);
ND_TCHECK2(bp[0], i);
bp += i;
ND_PRINT((ndo, " principal"));
STROUT(KANAMEMAX);
STROUT(KANAMEMAX);
break;
}
case 4: /* Set Password */
ND_PRINT((ndo, " principal"));
STROUT(KANAMEMAX);
STROUT(KANAMEMAX);
ND_PRINT((ndo, " kvno"));
INTOUT();
break;
case 12: /* Get password */
ND_PRINT((ndo, " name"));
STROUT(KANAMEMAX);
break;
default:
;
}
return;
trunc:
ND_PRINT((ndo, " [|kauth]"));
}
/*
* Handle replies to the AFS Kerberos Authentication Service
*/
static void
kauth_reply_print(netdissect_options *ndo,
register const u_char *bp, int length, int32_t opcode)
{
const struct rx_header *rxh;
if (length <= (int)sizeof(struct rx_header))
return;
rxh = (const struct rx_header *) bp;
/*
* Print out the afs call we're invoking. The table used here was
* gleaned from kauth/kauth.rg
*/
ND_PRINT((ndo, " kauth"));
if (is_ubik(opcode)) {
ubik_reply_print(ndo, bp, length, opcode);
return;
}
ND_PRINT((ndo, " reply %s", tok2str(kauth_req, "op#%d", opcode)));
bp += sizeof(struct rx_header);
/*
* If it was a data packet, interpret the response.
*/
if (rxh->type == RX_PACKET_TYPE_DATA)
/* Well, no, not really. Leave this for later */
;
else {
/*
* Otherwise, just print out the return code
*/
ND_PRINT((ndo, " errcode"));
INTOUT();
}
return;
trunc:
ND_PRINT((ndo, " [|kauth]"));
}
/*
* Handle calls to the AFS Volume location service
*/
static void
vol_print(netdissect_options *ndo,
register const u_char *bp, int length)
{
int vol_op;
if (length <= (int)sizeof(struct rx_header))
return;
if (ndo->ndo_snapend - bp + 1 <= (int)(sizeof(struct rx_header) + sizeof(int32_t))) {
goto trunc;
}
/*
* Print out the afs call we're invoking. The table used here was
* gleaned from volser/volint.xg
*/
vol_op = EXTRACT_32BITS(bp + sizeof(struct rx_header));
ND_PRINT((ndo, " vol call %s", tok2str(vol_req, "op#%d", vol_op)));
bp += sizeof(struct rx_header) + 4;
switch (vol_op) {
case 100: /* Create volume */
ND_PRINT((ndo, " partition"));
UINTOUT();
ND_PRINT((ndo, " name"));
STROUT(AFSNAMEMAX);
ND_PRINT((ndo, " type"));
UINTOUT();
ND_PRINT((ndo, " parent"));
UINTOUT();
break;
case 101: /* Delete volume */
case 107: /* Get flags */
ND_PRINT((ndo, " trans"));
UINTOUT();
break;
case 102: /* Restore */
ND_PRINT((ndo, " totrans"));
UINTOUT();
ND_PRINT((ndo, " flags"));
UINTOUT();
break;
case 103: /* Forward */
ND_PRINT((ndo, " fromtrans"));
UINTOUT();
ND_PRINT((ndo, " fromdate"));
DATEOUT();
DESTSERVEROUT();
ND_PRINT((ndo, " desttrans"));
INTOUT();
break;
case 104: /* End trans */
ND_PRINT((ndo, " trans"));
UINTOUT();
break;
case 105: /* Clone */
ND_PRINT((ndo, " trans"));
UINTOUT();
ND_PRINT((ndo, " purgevol"));
UINTOUT();
ND_PRINT((ndo, " newtype"));
UINTOUT();
ND_PRINT((ndo, " newname"));
STROUT(AFSNAMEMAX);
break;
case 106: /* Set flags */
ND_PRINT((ndo, " trans"));
UINTOUT();
ND_PRINT((ndo, " flags"));
UINTOUT();
break;
case 108: /* Trans create */
ND_PRINT((ndo, " vol"));
UINTOUT();
ND_PRINT((ndo, " partition"));
UINTOUT();
ND_PRINT((ndo, " flags"));
UINTOUT();
break;
case 109: /* Dump */
case 655537: /* Get size */
ND_PRINT((ndo, " fromtrans"));
UINTOUT();
ND_PRINT((ndo, " fromdate"));
DATEOUT();
break;
case 110: /* Get n-th volume */
ND_PRINT((ndo, " index"));
UINTOUT();
break;
case 111: /* Set forwarding */
ND_PRINT((ndo, " tid"));
UINTOUT();
ND_PRINT((ndo, " newsite"));
UINTOUT();
break;
case 112: /* Get name */
case 113: /* Get status */
ND_PRINT((ndo, " tid"));
break;
case 114: /* Signal restore */
ND_PRINT((ndo, " name"));
STROUT(AFSNAMEMAX);
ND_PRINT((ndo, " type"));
UINTOUT();
ND_PRINT((ndo, " pid"));
UINTOUT();
ND_PRINT((ndo, " cloneid"));
UINTOUT();
break;
case 116: /* List volumes */
ND_PRINT((ndo, " partition"));
UINTOUT();
ND_PRINT((ndo, " flags"));
UINTOUT();
break;
case 117: /* Set id types */
ND_PRINT((ndo, " tid"));
UINTOUT();
ND_PRINT((ndo, " name"));
STROUT(AFSNAMEMAX);
ND_PRINT((ndo, " type"));
UINTOUT();
ND_PRINT((ndo, " pid"));
UINTOUT();
ND_PRINT((ndo, " clone"));
UINTOUT();
ND_PRINT((ndo, " backup"));
UINTOUT();
break;
case 119: /* Partition info */
ND_PRINT((ndo, " name"));
STROUT(AFSNAMEMAX);
break;
case 120: /* Reclone */
ND_PRINT((ndo, " tid"));
UINTOUT();
break;
case 121: /* List one volume */
case 122: /* Nuke volume */
case 124: /* Extended List volumes */
case 125: /* Extended List one volume */
case 65536: /* Convert RO to RW volume */
ND_PRINT((ndo, " partid"));
UINTOUT();
ND_PRINT((ndo, " volid"));
UINTOUT();
break;
case 123: /* Set date */
ND_PRINT((ndo, " tid"));
UINTOUT();
ND_PRINT((ndo, " date"));
DATEOUT();
break;
case 126: /* Set info */
ND_PRINT((ndo, " tid"));
UINTOUT();
break;
case 128: /* Forward multiple */
ND_PRINT((ndo, " fromtrans"));
UINTOUT();
ND_PRINT((ndo, " fromdate"));
DATEOUT();
{
unsigned long i, j;
ND_TCHECK2(bp[0], 4);
j = EXTRACT_32BITS(bp);
bp += sizeof(int32_t);
for (i = 0; i < j; i++) {
DESTSERVEROUT();
if (i != j - 1)
ND_PRINT((ndo, ","));
}
if (j == 0)
ND_PRINT((ndo, " <none!>"));
}
break;
case 65538: /* Dump version 2 */
ND_PRINT((ndo, " fromtrans"));
UINTOUT();
ND_PRINT((ndo, " fromdate"));
DATEOUT();
ND_PRINT((ndo, " flags"));
UINTOUT();
break;
default:
;
}
return;
trunc:
ND_PRINT((ndo, " [|vol]"));
}
/*
* Handle replies to the AFS Volume Service
*/
static void
vol_reply_print(netdissect_options *ndo,
register const u_char *bp, int length, int32_t opcode)
{
const struct rx_header *rxh;
if (length <= (int)sizeof(struct rx_header))
return;
rxh = (const struct rx_header *) bp;
/*
* Print out the afs call we're invoking. The table used here was
* gleaned from volser/volint.xg
*/
ND_PRINT((ndo, " vol reply %s", tok2str(vol_req, "op#%d", opcode)));
bp += sizeof(struct rx_header);
/*
* If it was a data packet, interpret the response.
*/
if (rxh->type == RX_PACKET_TYPE_DATA) {
switch (opcode) {
case 100: /* Create volume */
ND_PRINT((ndo, " volid"));
UINTOUT();
ND_PRINT((ndo, " trans"));
UINTOUT();
break;
case 104: /* End transaction */
UINTOUT();
break;
case 105: /* Clone */
ND_PRINT((ndo, " newvol"));
UINTOUT();
break;
case 107: /* Get flags */
UINTOUT();
break;
case 108: /* Transaction create */
ND_PRINT((ndo, " trans"));
UINTOUT();
break;
case 110: /* Get n-th volume */
ND_PRINT((ndo, " volume"));
UINTOUT();
ND_PRINT((ndo, " partition"));
UINTOUT();
break;
case 112: /* Get name */
STROUT(AFSNAMEMAX);
break;
case 113: /* Get status */
ND_PRINT((ndo, " volid"));
UINTOUT();
ND_PRINT((ndo, " nextuniq"));
UINTOUT();
ND_PRINT((ndo, " type"));
UINTOUT();
ND_PRINT((ndo, " parentid"));
UINTOUT();
ND_PRINT((ndo, " clone"));
UINTOUT();
ND_PRINT((ndo, " backup"));
UINTOUT();
ND_PRINT((ndo, " restore"));
UINTOUT();
ND_PRINT((ndo, " maxquota"));
UINTOUT();
ND_PRINT((ndo, " minquota"));
UINTOUT();
ND_PRINT((ndo, " owner"));
UINTOUT();
ND_PRINT((ndo, " create"));
DATEOUT();
ND_PRINT((ndo, " access"));
DATEOUT();
ND_PRINT((ndo, " update"));
DATEOUT();
ND_PRINT((ndo, " expire"));
DATEOUT();
ND_PRINT((ndo, " backup"));
DATEOUT();
ND_PRINT((ndo, " copy"));
DATEOUT();
break;
case 115: /* Old list partitions */
break;
case 116: /* List volumes */
case 121: /* List one volume */
{
unsigned long i, j;
ND_TCHECK2(bp[0], 4);
j = EXTRACT_32BITS(bp);
bp += sizeof(int32_t);
for (i = 0; i < j; i++) {
ND_PRINT((ndo, " name"));
VECOUT(32);
ND_PRINT((ndo, " volid"));
UINTOUT();
ND_PRINT((ndo, " type"));
bp += sizeof(int32_t) * 21;
if (i != j - 1)
ND_PRINT((ndo, ","));
}
if (j == 0)
ND_PRINT((ndo, " <none!>"));
}
break;
default:
;
}
} else {
/*
* Otherwise, just print out the return code
*/
ND_PRINT((ndo, " errcode"));
INTOUT();
}
return;
trunc:
ND_PRINT((ndo, " [|vol]"));
}
/*
* Handle calls to the AFS BOS service
*/
static void
bos_print(netdissect_options *ndo,
register const u_char *bp, int length)
{
int bos_op;
if (length <= (int)sizeof(struct rx_header))
return;
if (ndo->ndo_snapend - bp + 1 <= (int)(sizeof(struct rx_header) + sizeof(int32_t))) {
goto trunc;
}
/*
* Print out the afs call we're invoking. The table used here was
* gleaned from bozo/bosint.xg
*/
bos_op = EXTRACT_32BITS(bp + sizeof(struct rx_header));
ND_PRINT((ndo, " bos call %s", tok2str(bos_req, "op#%d", bos_op)));
/*
* Decode some of the arguments to the BOS calls
*/
bp += sizeof(struct rx_header) + 4;
switch (bos_op) {
case 80: /* Create B node */
ND_PRINT((ndo, " type"));
STROUT(BOSNAMEMAX);
ND_PRINT((ndo, " instance"));
STROUT(BOSNAMEMAX);
break;
case 81: /* Delete B node */
case 83: /* Get status */
case 85: /* Get instance info */
case 87: /* Add super user */
case 88: /* Delete super user */
case 93: /* Set cell name */
case 96: /* Add cell host */
case 97: /* Delete cell host */
case 104: /* Restart */
case 106: /* Uninstall */
case 108: /* Exec */
case 112: /* Getlog */
case 114: /* Get instance strings */
STROUT(BOSNAMEMAX);
break;
case 82: /* Set status */
case 98: /* Set T status */
STROUT(BOSNAMEMAX);
ND_PRINT((ndo, " status"));
INTOUT();
break;
case 86: /* Get instance parm */
STROUT(BOSNAMEMAX);
ND_PRINT((ndo, " num"));
INTOUT();
break;
case 84: /* Enumerate instance */
case 89: /* List super users */
case 90: /* List keys */
case 91: /* Add key */
case 92: /* Delete key */
case 95: /* Get cell host */
INTOUT();
break;
case 105: /* Install */
STROUT(BOSNAMEMAX);
ND_PRINT((ndo, " size"));
INTOUT();
ND_PRINT((ndo, " flags"));
INTOUT();
ND_PRINT((ndo, " date"));
INTOUT();
break;
default:
;
}
return;
trunc:
ND_PRINT((ndo, " [|bos]"));
}
/*
* Handle replies to the AFS BOS Service
*/
static void
bos_reply_print(netdissect_options *ndo,
register const u_char *bp, int length, int32_t opcode)
{
const struct rx_header *rxh;
if (length <= (int)sizeof(struct rx_header))
return;
rxh = (const struct rx_header *) bp;
/*
* Print out the afs call we're invoking. The table used here was
* gleaned from volser/volint.xg
*/
ND_PRINT((ndo, " bos reply %s", tok2str(bos_req, "op#%d", opcode)));
bp += sizeof(struct rx_header);
/*
* If it was a data packet, interpret the response.
*/
if (rxh->type == RX_PACKET_TYPE_DATA)
/* Well, no, not really. Leave this for later */
;
else {
/*
* Otherwise, just print out the return code
*/
ND_PRINT((ndo, " errcode"));
INTOUT();
}
return;
trunc:
ND_PRINT((ndo, " [|bos]"));
}
/*
* Check to see if this is a Ubik opcode.
*/
static int
is_ubik(uint32_t opcode)
{
if ((opcode >= VOTE_LOW && opcode <= VOTE_HIGH) ||
(opcode >= DISK_LOW && opcode <= DISK_HIGH))
return(1);
else
return(0);
}
/*
* Handle Ubik opcodes to any one of the replicated database services
*/
static void
ubik_print(netdissect_options *ndo,
register const u_char *bp)
{
int ubik_op;
int32_t temp;
/*
* Print out the afs call we're invoking. The table used here was
* gleaned from ubik/ubik_int.xg
*/
ubik_op = EXTRACT_32BITS(bp + sizeof(struct rx_header));
ND_PRINT((ndo, " ubik call %s", tok2str(ubik_req, "op#%d", ubik_op)));
/*
* Decode some of the arguments to the Ubik calls
*/
bp += sizeof(struct rx_header) + 4;
switch (ubik_op) {
case 10000: /* Beacon */
ND_TCHECK2(bp[0], 4);
temp = EXTRACT_32BITS(bp);
bp += sizeof(int32_t);
ND_PRINT((ndo, " syncsite %s", temp ? "yes" : "no"));
ND_PRINT((ndo, " votestart"));
DATEOUT();
ND_PRINT((ndo, " dbversion"));
UBIK_VERSIONOUT();
ND_PRINT((ndo, " tid"));
UBIK_VERSIONOUT();
break;
case 10003: /* Get sync site */
ND_PRINT((ndo, " site"));
UINTOUT();
break;
case 20000: /* Begin */
case 20001: /* Commit */
case 20007: /* Abort */
case 20008: /* Release locks */
case 20010: /* Writev */
ND_PRINT((ndo, " tid"));
UBIK_VERSIONOUT();
break;
case 20002: /* Lock */
ND_PRINT((ndo, " tid"));
UBIK_VERSIONOUT();
ND_PRINT((ndo, " file"));
INTOUT();
ND_PRINT((ndo, " pos"));
INTOUT();
ND_PRINT((ndo, " length"));
INTOUT();
ND_TCHECK_32BITS(bp);
temp = EXTRACT_32BITS(bp);
bp += sizeof(int32_t);
tok2str(ubik_lock_types, "type %d", temp);
break;
case 20003: /* Write */
ND_PRINT((ndo, " tid"));
UBIK_VERSIONOUT();
ND_PRINT((ndo, " file"));
INTOUT();
ND_PRINT((ndo, " pos"));
INTOUT();
break;
case 20005: /* Get file */
ND_PRINT((ndo, " file"));
INTOUT();
break;
case 20006: /* Send file */
ND_PRINT((ndo, " file"));
INTOUT();
ND_PRINT((ndo, " length"));
INTOUT();
ND_PRINT((ndo, " dbversion"));
UBIK_VERSIONOUT();
break;
case 20009: /* Truncate */
ND_PRINT((ndo, " tid"));
UBIK_VERSIONOUT();
ND_PRINT((ndo, " file"));
INTOUT();
ND_PRINT((ndo, " length"));
INTOUT();
break;
case 20012: /* Set version */
ND_PRINT((ndo, " tid"));
UBIK_VERSIONOUT();
ND_PRINT((ndo, " oldversion"));
UBIK_VERSIONOUT();
ND_PRINT((ndo, " newversion"));
UBIK_VERSIONOUT();
break;
default:
;
}
return;
trunc:
ND_PRINT((ndo, " [|ubik]"));
}
/*
* Handle Ubik replies to any one of the replicated database services
*/
static void
ubik_reply_print(netdissect_options *ndo,
register const u_char *bp, int length, int32_t opcode)
{
const struct rx_header *rxh;
if (length < (int)sizeof(struct rx_header))
return;
rxh = (const struct rx_header *) bp;
/*
* Print out the ubik call we're invoking. This table was gleaned
* from ubik/ubik_int.xg
*/
ND_PRINT((ndo, " ubik reply %s", tok2str(ubik_req, "op#%d", opcode)));
bp += sizeof(struct rx_header);
/*
* If it was a data packet, print out the arguments to the Ubik calls
*/
if (rxh->type == RX_PACKET_TYPE_DATA)
switch (opcode) {
case 10000: /* Beacon */
ND_PRINT((ndo, " vote no"));
break;
case 20004: /* Get version */
ND_PRINT((ndo, " dbversion"));
UBIK_VERSIONOUT();
break;
default:
;
}
/*
* Otherwise, print out "yes" it it was a beacon packet (because
* that's how yes votes are returned, go figure), otherwise
* just print out the error code.
*/
else
switch (opcode) {
case 10000: /* Beacon */
ND_PRINT((ndo, " vote yes until"));
DATEOUT();
break;
default:
ND_PRINT((ndo, " errcode"));
INTOUT();
}
return;
trunc:
ND_PRINT((ndo, " [|ubik]"));
}
/*
* Handle RX ACK packets.
*/
static void
rx_ack_print(netdissect_options *ndo,
register const u_char *bp, int length)
{
const struct rx_ackPacket *rxa;
int i, start, last;
uint32_t firstPacket;
if (length < (int)sizeof(struct rx_header))
return;
bp += sizeof(struct rx_header);
/*
* This may seem a little odd .... the rx_ackPacket structure
* contains an array of individual packet acknowledgements
* (used for selective ack/nack), but since it's variable in size,
* we don't want to truncate based on the size of the whole
* rx_ackPacket structure.
*/
ND_TCHECK2(bp[0], sizeof(struct rx_ackPacket) - RX_MAXACKS);
rxa = (const struct rx_ackPacket *) bp;
bp += (sizeof(struct rx_ackPacket) - RX_MAXACKS);
/*
* Print out a few useful things from the ack packet structure
*/
if (ndo->ndo_vflag > 2)
ND_PRINT((ndo, " bufspace %d maxskew %d",
(int) EXTRACT_16BITS(&rxa->bufferSpace),
(int) EXTRACT_16BITS(&rxa->maxSkew)));
firstPacket = EXTRACT_32BITS(&rxa->firstPacket);
ND_PRINT((ndo, " first %d serial %d reason %s",
firstPacket, EXTRACT_32BITS(&rxa->serial),
tok2str(rx_ack_reasons, "#%d", (int) rxa->reason)));
/*
* Okay, now we print out the ack array. The way _this_ works
* is that we start at "first", and step through the ack array.
* If we have a contiguous range of acks/nacks, try to
* collapse them into a range.
*
* If you're really clever, you might have noticed that this
* doesn't seem quite correct. Specifically, due to structure
* padding, sizeof(struct rx_ackPacket) - RX_MAXACKS won't actually
* yield the start of the ack array (because RX_MAXACKS is 255
* and the structure will likely get padded to a 2 or 4 byte
* boundary). However, this is the way it's implemented inside
* of AFS - the start of the extra fields are at
* sizeof(struct rx_ackPacket) - RX_MAXACKS + nAcks, which _isn't_
* the exact start of the ack array. Sigh. That's why we aren't
* using bp, but instead use rxa->acks[]. But nAcks gets added
* to bp after this, so bp ends up at the right spot. Go figure.
*/
if (rxa->nAcks != 0) {
ND_TCHECK2(bp[0], rxa->nAcks);
/*
* Sigh, this is gross, but it seems to work to collapse
* ranges correctly.
*/
for (i = 0, start = last = -2; i < rxa->nAcks; i++)
if (rxa->acks[i] == RX_ACK_TYPE_ACK) {
/*
* I figured this deserved _some_ explanation.
* First, print "acked" and the packet seq
* number if this is the first time we've
* seen an acked packet.
*/
if (last == -2) {
ND_PRINT((ndo, " acked %d", firstPacket + i));
start = i;
}
/*
* Otherwise, if there is a skip in
* the range (such as an nacked packet in
* the middle of some acked packets),
* then print the current packet number
* seperated from the last number by
* a comma.
*/
else if (last != i - 1) {
ND_PRINT((ndo, ",%d", firstPacket + i));
start = i;
}
/*
* We always set last to the value of
* the last ack we saw. Conversely, start
* is set to the value of the first ack
* we saw in a range.
*/
last = i;
/*
* Okay, this bit a code gets executed when
* we hit a nack ... in _this_ case we
* want to print out the range of packets
* that were acked, so we need to print
* the _previous_ packet number seperated
* from the first by a dash (-). Since we
* already printed the first packet above,
* just print the final packet. Don't
* do this if there will be a single-length
* range.
*/
} else if (last == i - 1 && start != last)
ND_PRINT((ndo, "-%d", firstPacket + i - 1));
/*
* So, what's going on here? We ran off the end of the
* ack list, and if we got a range we need to finish it up.
* So we need to determine if the last packet in the list
* was an ack (if so, then last will be set to it) and
* we need to see if the last range didn't start with the
* last packet (because if it _did_, then that would mean
* that the packet number has already been printed and
* we don't need to print it again).
*/
if (last == i - 1 && start != last)
ND_PRINT((ndo, "-%d", firstPacket + i - 1));
/*
* Same as above, just without comments
*/
for (i = 0, start = last = -2; i < rxa->nAcks; i++)
if (rxa->acks[i] == RX_ACK_TYPE_NACK) {
if (last == -2) {
ND_PRINT((ndo, " nacked %d", firstPacket + i));
start = i;
} else if (last != i - 1) {
ND_PRINT((ndo, ",%d", firstPacket + i));
start = i;
}
last = i;
} else if (last == i - 1 && start != last)
ND_PRINT((ndo, "-%d", firstPacket + i - 1));
if (last == i - 1 && start != last)
ND_PRINT((ndo, "-%d", firstPacket + i - 1));
bp += rxa->nAcks;
}
/*
* These are optional fields; depending on your version of AFS,
* you may or may not see them
*/
#define TRUNCRET(n) if (ndo->ndo_snapend - bp + 1 <= n) return;
if (ndo->ndo_vflag > 1) {
TRUNCRET(4);
ND_PRINT((ndo, " ifmtu"));
INTOUT();
TRUNCRET(4);
ND_PRINT((ndo, " maxmtu"));
INTOUT();
TRUNCRET(4);
ND_PRINT((ndo, " rwind"));
INTOUT();
TRUNCRET(4);
ND_PRINT((ndo, " maxpackets"));
INTOUT();
}
return;
trunc:
ND_PRINT((ndo, " [|ack]"));
}
#undef TRUNCRET
| ./CrossVul/dataset_final_sorted/CWE-125/c/good_2725_0 |
crossvul-cpp_data_bad_351_11 | /*
* card-piv.c: Support for PIV-II from NIST SP800-73
* card-default.c: Support for cards with no driver
*
* Copyright (C) 2001, 2002 Juha Yrjölä <juha.yrjola@iki.fi>
* Copyright (C) 2005-2016 Douglas E. Engert <deengert@gmail.com>
* Copyright (C) 2006, Identity Alliance, Thomas Harning <thomas.harning@identityalliance.com>
* Copyright (C) 2007, EMC, Russell Larner <rlarner@rsa.com>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.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 <ctype.h>
#include <fcntl.h>
#include <limits.h>
#include <stdlib.h>
#include <string.h>
#ifdef _WIN32
#include <io.h>
#else
#include <unistd.h>
#endif
#ifdef ENABLE_OPENSSL
/* openssl only needed for card administration */
#include <openssl/evp.h>
#include <openssl/bio.h>
#include <openssl/pem.h>
#include <openssl/rand.h>
#include <openssl/rsa.h>
#endif /* ENABLE_OPENSSL */
#include "internal.h"
#include "asn1.h"
#include "cardctl.h"
#ifdef ENABLE_ZLIB
#include "compression.h"
#endif
enum {
PIV_OBJ_CCC = 0,
PIV_OBJ_CHUI,
/* PIV_OBJ_UCHUI is not in new with 800-73-2 */
PIV_OBJ_X509_PIV_AUTH,
PIV_OBJ_CHF,
PIV_OBJ_PI,
PIV_OBJ_CHFI,
PIV_OBJ_X509_DS,
PIV_OBJ_X509_KM,
PIV_OBJ_X509_CARD_AUTH,
PIV_OBJ_SEC_OBJ,
PIV_OBJ_DISCOVERY,
PIV_OBJ_HISTORY,
PIV_OBJ_RETIRED_X509_1,
PIV_OBJ_RETIRED_X509_2,
PIV_OBJ_RETIRED_X509_3,
PIV_OBJ_RETIRED_X509_4,
PIV_OBJ_RETIRED_X509_5,
PIV_OBJ_RETIRED_X509_6,
PIV_OBJ_RETIRED_X509_7,
PIV_OBJ_RETIRED_X509_8,
PIV_OBJ_RETIRED_X509_9,
PIV_OBJ_RETIRED_X509_10,
PIV_OBJ_RETIRED_X509_11,
PIV_OBJ_RETIRED_X509_12,
PIV_OBJ_RETIRED_X509_13,
PIV_OBJ_RETIRED_X509_14,
PIV_OBJ_RETIRED_X509_15,
PIV_OBJ_RETIRED_X509_16,
PIV_OBJ_RETIRED_X509_17,
PIV_OBJ_RETIRED_X509_18,
PIV_OBJ_RETIRED_X509_19,
PIV_OBJ_RETIRED_X509_20,
PIV_OBJ_IRIS_IMAGE,
PIV_OBJ_9B03,
PIV_OBJ_9A06,
PIV_OBJ_9C06,
PIV_OBJ_9D06,
PIV_OBJ_9E06,
PIV_OBJ_8206,
PIV_OBJ_8306,
PIV_OBJ_8406,
PIV_OBJ_8506,
PIV_OBJ_8606,
PIV_OBJ_8706,
PIV_OBJ_8806,
PIV_OBJ_8906,
PIV_OBJ_8A06,
PIV_OBJ_8B06,
PIV_OBJ_8C06,
PIV_OBJ_8D06,
PIV_OBJ_8E06,
PIV_OBJ_8F06,
PIV_OBJ_9006,
PIV_OBJ_9106,
PIV_OBJ_9206,
PIV_OBJ_9306,
PIV_OBJ_9406,
PIV_OBJ_9506,
PIV_OBJ_LAST_ENUM
};
/*
* Flags in the piv_obj_cache:
* PIV_OBJ_CACHE_VALID means the data in the cache can be used.
* It might have zero length indicating that the object was not found.
* PIV_OBJ_CACHE_NOT_PRESENT means do not even try to read the object.
* These objects will only be present if the history object says
* they are on the card, or the discovery or history object in not present.
* If the file lilsted in the history object offCardCertURL was found,
* its certs will be read into the cache and PIV_OBJ_CACHE_VALID set
* and PIV_OBJ_CACHE_NOT_PRESENT unset.
*/
#define PIV_OBJ_CACHE_VALID 1
#define PIV_OBJ_CACHE_NOT_PRESENT 8
typedef struct piv_obj_cache {
u8* obj_data;
size_t obj_len;
u8* internal_obj_data; /* like a cert in the object */
size_t internal_obj_len;
int flags;
} piv_obj_cache_t;
enum {
PIV_STATE_NORMAL = 0,
PIV_STATE_MATCH,
PIV_STATE_INIT
};
typedef struct piv_private_data {
sc_file_t *aid_file;
int enumtag;
int selected_obj; /* The index into the piv_objects last selected */
int return_only_cert; /* return the cert from the object */
int rwb_state; /* first time -1, 0, in middle, 1 at eof */
int operation; /* saved from set_security_env */
int algorithm; /* saved from set_security_env */
int key_ref; /* saved from set_security_env and */
int alg_id; /* used in decrypt, signature, derive */
int key_size; /* RSA: modulus_bits EC: field_length in bits */
u8* w_buf; /* write_binary buffer */
size_t w_buf_len; /* length of w_buff */
piv_obj_cache_t obj_cache[PIV_OBJ_LAST_ENUM];
int keysWithOnCardCerts;
int keysWithOffCardCerts;
char * offCardCertURL;
int pin_preference; /* set from Discovery object */
int logged_in;
int pstate;
int pin_cmd_verify;
int context_specific;
int pin_cmd_noparse;
unsigned int pin_cmd_verify_sw1;
unsigned int pin_cmd_verify_sw2;
int tries_left; /* SC_PIN_CMD_GET_INFO tries_left from last */
unsigned int card_issues; /* card_issues flags for this card */
int object_test_verify; /* Can test this object to set verification state of card */
int yubico_version; /* 3 byte version number of NEO or Yubikey4 as integer */
} piv_private_data_t;
#define PIV_DATA(card) ((piv_private_data_t*)card->drv_data)
struct piv_aid {
int enumtag;
size_t len_short; /* min length without version */
size_t len_long; /* With version and other stuff */
u8 *value;
};
/*
* The Generic entry should be the "A0 00 00 03 08 00 00 10 00 "
* NIST published this on 10/6/2005
* 800-73-2 Part 1 now refers to version "02 00"
* i.e. "A0 00 00 03 08 00 00 01 00 02 00".
* but we don't need the version number. but could get it from the PIX.
*
* 800-73-3 Part 1 now refers to "01 00" i.e. going back to 800-73-1.
* The main differences between 73-1, and 73-3 are the addition of the
* key History object and keys, as well as Discovery and Iris objects.
* These can be discovered by trying GET DATA
*/
/* all have same AID */
static struct piv_aid piv_aids[] = {
{SC_CARD_TYPE_PIV_II_GENERIC, /* TODO not really card type but what PIV AID is supported */
9, 9, (u8 *) "\xA0\x00\x00\x03\x08\x00\x00\x10\x00" },
{0, 9, 0, NULL }
};
/* card_issues - bugs in PIV implementations requires special handling */
#define CI_VERIFY_630X 0x00000001U /* VERIFY tries left returns 630X rather then 63CX */
#define CI_VERIFY_LC0_FAIL 0x00000002U /* VERIFY Lc=0 never returns 90 00 if PIN not needed */
/* will also test after first PIN verify if protected object can be used instead */
#define CI_CANT_USE_GETDATA_FOR_STATE 0x00000008U /* No object to test verification inplace of VERIFY Lc=0 */
#define CI_LEAKS_FILE_NOT_FOUND 0x00000010U /* GET DATA of empty object returns 6A 82 even if PIN not verified */
#define CI_DISCOVERY_USELESS 0x00000020U /* Discovery can not be used to query active AID */
#define CI_PIV_AID_LOSE_STATE 0x00000040U /* PIV AID can lose the login state run with out it*/
#define CI_OTHER_AID_LOSE_STATE 0x00000100U /* Other drivers match routines may reset our security state and lose AID!!! */
#define CI_NFC_EXPOSE_TOO_MUCH 0x00000200U /* PIN, crypto and objects exposed over NFS in violation of 800-73-3 */
#define CI_NO_RSA2048 0x00010000U /* does not have RSA 2048 */
#define CI_NO_EC384 0x00020000U /* does not have EC 384 */
/*
* Flags in the piv_object:
* PIV_OBJECT_NOT_PRESENT: the presents of the object is
* indicated by the History object.
*/
#define PIV_OBJECT_TYPE_CERT 1
#define PIV_OBJECT_TYPE_PUBKEY 2
#define PIV_OBJECT_NOT_PRESENT 4
struct piv_object {
int enumtag;
const char * name;
const char * oidstring;
size_t tag_len;
u8 tag_value[3];
u8 containerid[2]; /* will use as relative paths for simulation */
int flags; /* object has some internal object like a cert */
};
/* Must be in order, and one per enumerated PIV_OBJ */
static const struct piv_object piv_objects[] = {
{ PIV_OBJ_CCC, "Card Capability Container",
"2.16.840.1.101.3.7.1.219.0", 3, "\x5F\xC1\x07", "\xDB\x00", 0},
{ PIV_OBJ_CHUI, "Card Holder Unique Identifier",
"2.16.840.1.101.3.7.2.48.0", 3, "\x5F\xC1\x02", "\x30\x00", 0},
{ PIV_OBJ_X509_PIV_AUTH, "X.509 Certificate for PIV Authentication",
"2.16.840.1.101.3.7.2.1.1", 3, "\x5F\xC1\x05", "\x01\x01", PIV_OBJECT_TYPE_CERT} ,
{ PIV_OBJ_CHF, "Card Holder Fingerprints",
"2.16.840.1.101.3.7.2.96.16", 3, "\x5F\xC1\x03", "\x60\x10", 0},
{ PIV_OBJ_PI, "Printed Information",
"2.16.840.1.101.3.7.2.48.1", 3, "\x5F\xC1\x09", "\x30\x01", 0},
{ PIV_OBJ_CHFI, "Cardholder Facial Images",
"2.16.840.1.101.3.7.2.96.48", 3, "\x5F\xC1\x08", "\x60\x30", 0},
{ PIV_OBJ_X509_DS, "X.509 Certificate for Digital Signature",
"2.16.840.1.101.3.7.2.1.0", 3, "\x5F\xC1\x0A", "\x01\x00", PIV_OBJECT_TYPE_CERT},
{ PIV_OBJ_X509_KM, "X.509 Certificate for Key Management",
"2.16.840.1.101.3.7.2.1.2", 3, "\x5F\xC1\x0B", "\x01\x02", PIV_OBJECT_TYPE_CERT},
{ PIV_OBJ_X509_CARD_AUTH, "X.509 Certificate for Card Authentication",
"2.16.840.1.101.3.7.2.5.0", 3, "\x5F\xC1\x01", "\x05\x00", PIV_OBJECT_TYPE_CERT},
{ PIV_OBJ_SEC_OBJ, "Security Object",
"2.16.840.1.101.3.7.2.144.0", 3, "\x5F\xC1\x06", "\x90\x00", 0},
{ PIV_OBJ_DISCOVERY, "Discovery Object",
"2.16.840.1.101.3.7.2.96.80", 1, "\x7E", "\x60\x50", 0},
{ PIV_OBJ_HISTORY, "Key History Object",
"2.16.840.1.101.3.7.2.96.96", 3, "\x5F\xC1\x0C", "\x60\x60", 0},
/* 800-73-3, 21 new objects, 20 history certificates */
{ PIV_OBJ_RETIRED_X509_1, "Retired X.509 Certificate for Key Management 1",
"2.16.840.1.101.3.7.2.16.1", 3, "\x5F\xC1\x0D", "\x10\x01",
PIV_OBJECT_NOT_PRESENT|PIV_OBJECT_TYPE_CERT},
{ PIV_OBJ_RETIRED_X509_2, "Retired X.509 Certificate for Key Management 2",
"2.16.840.1.101.3.7.2.16.2", 3, "\x5F\xC1\x0E", "\x10\x02",
PIV_OBJECT_NOT_PRESENT|PIV_OBJECT_TYPE_CERT},
{ PIV_OBJ_RETIRED_X509_3, "Retired X.509 Certificate for Key Management 3",
"2.16.840.1.101.3.7.2.16.3", 3, "\x5F\xC1\x0F", "\x10\x03",
PIV_OBJECT_NOT_PRESENT|PIV_OBJECT_TYPE_CERT},
{ PIV_OBJ_RETIRED_X509_4, "Retired X.509 Certificate for Key Management 4",
"2.16.840.1.101.3.7.2.16.4", 3, "\x5F\xC1\x10", "\x10\x04",
PIV_OBJECT_NOT_PRESENT|PIV_OBJECT_TYPE_CERT},
{ PIV_OBJ_RETIRED_X509_5, "Retired X.509 Certificate for Key Management 5",
"2.16.840.1.101.3.7.2.16.5", 3, "\x5F\xC1\x11", "\x10\x05",
PIV_OBJECT_NOT_PRESENT|PIV_OBJECT_TYPE_CERT},
{ PIV_OBJ_RETIRED_X509_6, "Retired X.509 Certificate for Key Management 6",
"2.16.840.1.101.3.7.2.16.6", 3, "\x5F\xC1\x12", "\x10\x06",
PIV_OBJECT_NOT_PRESENT|PIV_OBJECT_TYPE_CERT},
{ PIV_OBJ_RETIRED_X509_7, "Retired X.509 Certificate for Key Management 7",
"2.16.840.1.101.3.7.2.16.7", 3, "\x5F\xC1\x13", "\x10\x07",
PIV_OBJECT_NOT_PRESENT|PIV_OBJECT_TYPE_CERT},
{ PIV_OBJ_RETIRED_X509_8, "Retired X.509 Certificate for Key Management 8",
"2.16.840.1.101.3.7.2.16.8", 3, "\x5F\xC1\x14", "\x10\x08",
PIV_OBJECT_NOT_PRESENT|PIV_OBJECT_TYPE_CERT},
{ PIV_OBJ_RETIRED_X509_9, "Retired X.509 Certificate for Key Management 9",
"2.16.840.1.101.3.7.2.16.9", 3, "\x5F\xC1\x15", "\x10\x09",
PIV_OBJECT_NOT_PRESENT|PIV_OBJECT_TYPE_CERT},
{ PIV_OBJ_RETIRED_X509_10, "Retired X.509 Certificate for Key Management 10",
"2.16.840.1.101.3.7.2.16.10", 3, "\x5F\xC1\x16", "\x10\x0A",
PIV_OBJECT_NOT_PRESENT|PIV_OBJECT_TYPE_CERT},
{ PIV_OBJ_RETIRED_X509_11, "Retired X.509 Certificate for Key Management 11",
"2.16.840.1.101.3.7.2.16.11", 3, "\x5F\xC1\x17", "\x10\x0B",
PIV_OBJECT_NOT_PRESENT|PIV_OBJECT_TYPE_CERT},
{ PIV_OBJ_RETIRED_X509_12, "Retired X.509 Certificate for Key Management 12",
"2.16.840.1.101.3.7.2.16.12", 3, "\x5F\xC1\x18", "\x10\x0C",
PIV_OBJECT_NOT_PRESENT|PIV_OBJECT_TYPE_CERT},
{ PIV_OBJ_RETIRED_X509_13, "Retired X.509 Certificate for Key Management 13",
"2.16.840.1.101.3.7.2.16.13", 3, "\x5F\xC1\x19", "\x10\x0D",
PIV_OBJECT_NOT_PRESENT|PIV_OBJECT_TYPE_CERT},
{ PIV_OBJ_RETIRED_X509_14, "Retired X.509 Certificate for Key Management 14",
"2.16.840.1.101.3.7.2.16.14", 3, "\x5F\xC1\x1A", "\x10\x0E",
PIV_OBJECT_NOT_PRESENT|PIV_OBJECT_TYPE_CERT},
{ PIV_OBJ_RETIRED_X509_15, "Retired X.509 Certificate for Key Management 15",
"2.16.840.1.101.3.7.2.16.15", 3, "\x5F\xC1\x1B", "\x10\x0F",
PIV_OBJECT_NOT_PRESENT|PIV_OBJECT_TYPE_CERT},
{ PIV_OBJ_RETIRED_X509_16, "Retired X.509 Certificate for Key Management 16",
"2.16.840.1.101.3.7.2.16.16", 3, "\x5F\xC1\x1C", "\x10\x10",
PIV_OBJECT_NOT_PRESENT|PIV_OBJECT_TYPE_CERT},
{ PIV_OBJ_RETIRED_X509_17, "Retired X.509 Certificate for Key Management 17",
"2.16.840.1.101.3.7.2.16.17", 3, "\x5F\xC1\x1D", "\x10\x11",
PIV_OBJECT_NOT_PRESENT|PIV_OBJECT_TYPE_CERT},
{ PIV_OBJ_RETIRED_X509_18, "Retired X.509 Certificate for Key Management 18",
"2.16.840.1.101.3.7.2.16.18", 3, "\x5F\xC1\x1E", "\x10\x12",
PIV_OBJECT_NOT_PRESENT|PIV_OBJECT_TYPE_CERT},
{ PIV_OBJ_RETIRED_X509_19, "Retired X.509 Certificate for Key Management 19",
"2.16.840.1.101.3.7.2.16.19", 3, "\x5F\xC1\x1F", "\x10\x13",
PIV_OBJECT_NOT_PRESENT|PIV_OBJECT_TYPE_CERT},
{ PIV_OBJ_RETIRED_X509_20, "Retired X.509 Certificate for Key Management 20",
"2.16.840.1.101.3.7.2.16.20", 3, "\x5F\xC1\x20", "\x10\x14",
PIV_OBJECT_NOT_PRESENT|PIV_OBJECT_TYPE_CERT},
{ PIV_OBJ_IRIS_IMAGE, "Cardholder Iris Images",
"2.16.840.1.101.3.7.2.16.21", 3, "\x5F\xC1\x21", "\x10\x15", 0},
/* following not standard , to be used by piv-tool only for testing */
{ PIV_OBJ_9B03, "3DES-ECB ADM",
"2.16.840.1.101.3.7.2.9999.3", 2, "\x9B\x03", "\x9B\x03", 0},
/* Only used when signing a cert req, usually from engine
* after piv-tool generated the key and saved the pub key
* to a file. Note RSA key can be 1024, 2048 or 3072
* but still use the "9x06" name.
*/
{ PIV_OBJ_9A06, "RSA 9A Pub key from last genkey",
"2.16.840.1.101.3.7.2.9999.20", 2, "\x9A\x06", "\x9A\x06", PIV_OBJECT_TYPE_PUBKEY},
{ PIV_OBJ_9C06, "Pub 9C key from last genkey",
"2.16.840.1.101.3.7.2.9999.21", 2, "\x9C\x06", "\x9C\x06", PIV_OBJECT_TYPE_PUBKEY},
{ PIV_OBJ_9D06, "Pub 9D key from last genkey",
"2.16.840.1.101.3.7.2.9999.22", 2, "\x9D\x06", "\x9D\x06", PIV_OBJECT_TYPE_PUBKEY},
{ PIV_OBJ_9E06, "Pub 9E key from last genkey",
"2.16.840.1.101.3.7.2.9999.23", 2, "\x9E\x06", "\x9E\x06", PIV_OBJECT_TYPE_PUBKEY},
{ PIV_OBJ_8206, "Pub 82 key ",
"2.16.840.1.101.3.7.2.9999.101", 2, "\x82\x06", "\x82\x06", PIV_OBJECT_TYPE_PUBKEY},
{ PIV_OBJ_8306, "Pub 83 key ",
"2.16.840.1.101.3.7.2.9999.102", 2, "\x83\x06", "\x83\x06", PIV_OBJECT_TYPE_PUBKEY},
{ PIV_OBJ_8406, "Pub 84 key ",
"2.16.840.1.101.3.7.2.9999.103", 2, "\x84\x06", "\x84\x06", PIV_OBJECT_TYPE_PUBKEY},
{ PIV_OBJ_8506, "Pub 85 key ",
"2.16.840.1.101.3.7.2.9999.104", 2, "\x85\x06", "\x85\x06", PIV_OBJECT_TYPE_PUBKEY},
{ PIV_OBJ_8606, "Pub 86 key ",
"2.16.840.1.101.3.7.2.9999.105", 2, "\x86\x06", "\x86\x06", PIV_OBJECT_TYPE_PUBKEY},
{ PIV_OBJ_8706, "Pub 87 key ",
"2.16.840.1.101.3.7.2.9999.106", 2, "\x87\x06", "\x87\x06", PIV_OBJECT_TYPE_PUBKEY},
{ PIV_OBJ_8806, "Pub 88 key ",
"2.16.840.1.101.3.7.2.9999.107", 2, "\x88\x06", "\x88\x06", PIV_OBJECT_TYPE_PUBKEY},
{ PIV_OBJ_8906, "Pub 89 key ",
"2.16.840.1.101.3.7.2.9999.108", 2, "\x89\x06", "\x89\x06", PIV_OBJECT_TYPE_PUBKEY},
{ PIV_OBJ_8A06, "Pub 8A key ",
"2.16.840.1.101.3.7.2.9999.109", 2, "\x8A\x06", "\x8A\x06", PIV_OBJECT_TYPE_PUBKEY},
{ PIV_OBJ_8B06, "Pub 8B key ",
"2.16.840.1.101.3.7.2.9999.110", 2, "\x8B\x06", "\x8B\x06", PIV_OBJECT_TYPE_PUBKEY},
{ PIV_OBJ_8C06, "Pub 8C key ",
"2.16.840.1.101.3.7.2.9999.111", 2, "\x8C\x06", "\x8C\x06", PIV_OBJECT_TYPE_PUBKEY},
{ PIV_OBJ_8D06, "Pub 8D key ",
"2.16.840.1.101.3.7.2.9999.112", 2, "\x8D\x06", "\x8D\x06", PIV_OBJECT_TYPE_PUBKEY},
{ PIV_OBJ_8E06, "Pub 8E key ",
"2.16.840.1.101.3.7.2.9999.113", 2, "\x8E\x06", "\x8E\x06", PIV_OBJECT_TYPE_PUBKEY},
{ PIV_OBJ_8F06, "Pub 8F key ",
"2.16.840.1.101.3.7.2.9999.114", 2, "\x8F\x06", "\x8F\x06", PIV_OBJECT_TYPE_PUBKEY},
{ PIV_OBJ_9006, "Pub 90 key ",
"2.16.840.1.101.3.7.2.9999.115", 2, "\x90\x06", "\x90\x06", PIV_OBJECT_TYPE_PUBKEY},
{ PIV_OBJ_9106, "Pub 91 key ",
"2.16.840.1.101.3.7.2.9999.116", 2, "\x91\x06", "\x91\x06", PIV_OBJECT_TYPE_PUBKEY},
{ PIV_OBJ_9206, "Pub 92 key ",
"2.16.840.1.101.3.7.2.9999.117", 2, "\x92\x06", "\x92\x06", PIV_OBJECT_TYPE_PUBKEY},
{ PIV_OBJ_9306, "Pub 93 key ",
"2.16.840.1.101.3.7.2.9999.118", 2, "\x93\x06", "\x93\x06", PIV_OBJECT_TYPE_PUBKEY},
{ PIV_OBJ_9406, "Pub 94 key ",
"2.16.840.1.101.3.7.2.9999.119", 2, "\x94\x06", "\x94\x06", PIV_OBJECT_TYPE_PUBKEY},
{ PIV_OBJ_9506, "Pub 95 key ",
"2.16.840.1.101.3.7.2.9999.120", 2, "\x95\x06", "\x95\x06", PIV_OBJECT_TYPE_PUBKEY},
{ PIV_OBJ_LAST_ENUM, "", "", 0, "", "", 0}
};
static struct sc_card_operations piv_ops;
static struct sc_card_driver piv_drv = {
"Personal Identity Verification Card",
"PIV-II",
&piv_ops,
NULL, 0, NULL
};
static int piv_match_card_continued(sc_card_t *card);
static int
piv_find_obj_by_containerid(sc_card_t *card, const u8 * str)
{
int i;
LOG_FUNC_CALLED(card->ctx);
sc_log(card->ctx, "str=0x%02X%02X\n", str[0], str[1]);
for (i = 0; piv_objects[i].enumtag < PIV_OBJ_LAST_ENUM; i++) {
if ( str[0] == piv_objects[i].containerid[0] && str[1] == piv_objects[i].containerid[1])
LOG_FUNC_RETURN(card->ctx, i);
}
LOG_FUNC_RETURN(card->ctx, -1);
}
/*
* If ptr == NULL, just return the size of the tag and length and data
* otherwise, store tag and length at **ptr, and increment
*/
static size_t
put_tag_and_len(unsigned int tag, size_t len, u8 **ptr)
{
int i;
u8 *p;
if (len < 128) {
i = 2;
} else if (len < 256) {
i = 3;
} else {
i = 4;
}
if (ptr) {
p = *ptr;
*p++ = (u8)tag;
switch (i) {
case 2:
*p++ = len;
break;
case 3:
*p++ = 0x81;
*p++ = len;
break;
case 4:
*p++ = 0x82;
*p++ = (u8) (len >> 8);
*p++ = (u8) (len & 0xff);
break;
}
*ptr = p;
} else {
i += len;
}
return i;
}
/*
* Send a command and receive data. There is always something to send.
* Used by GET DATA, PUT DATA, GENERAL AUTHENTICATE
* and GENERATE ASYMMETRIC KEY PAIR.
* GET DATA may call to get the first 128 bytes to get the length from the tag.
*
* A caller may provide a buffer, and length to read. If not provided,
* an internal 4096 byte buffer is used, and a copy is returned to the
* caller. that need to be freed by the caller.
*/
static int piv_general_io(sc_card_t *card, int ins, int p1, int p2,
const u8 * sendbuf, size_t sendbuflen, u8 ** recvbuf,
size_t * recvbuflen)
{
int r;
sc_apdu_t apdu;
u8 rbufinitbuf[4096];
u8 *rbuf;
size_t rbuflen;
unsigned int cla_out, tag_out;
const u8 *body;
size_t bodylen;
int find_len = 0;
piv_private_data_t * priv = PIV_DATA(card);
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
sc_log(card->ctx,
"%02x %02x %02x %"SC_FORMAT_LEN_SIZE_T"u : %"SC_FORMAT_LEN_SIZE_T"u %"SC_FORMAT_LEN_SIZE_T"u",
ins, p1, p2, sendbuflen, card->max_send_size,
card->max_recv_size);
rbuf = rbufinitbuf;
rbuflen = sizeof(rbufinitbuf);
/* if caller provided a buffer and length */
if (recvbuf && *recvbuf && recvbuflen && *recvbuflen) {
rbuf = *recvbuf;
rbuflen = *recvbuflen;
}
r = sc_lock(card);
if (r != SC_SUCCESS)
LOG_FUNC_RETURN(card->ctx, r);
sc_format_apdu(card, &apdu,
recvbuf ? SC_APDU_CASE_4_SHORT: SC_APDU_CASE_3_SHORT,
ins, p1, p2);
apdu.flags |= SC_APDU_FLAGS_CHAINING;
/* if looking for length of object, dont try and read the rest of buffer here */
if (rbuflen == 8 && card->reader->active_protocol == SC_PROTO_T1) {
apdu.flags |= SC_APDU_FLAGS_NO_GET_RESP;
find_len = 1;
}
apdu.lc = sendbuflen;
apdu.datalen = sendbuflen;
apdu.data = sendbuf;
if (recvbuf) {
apdu.resp = rbuf;
apdu.le = (rbuflen > 256) ? 256 : rbuflen;
apdu.resplen = rbuflen;
} else {
apdu.resp = rbuf;
apdu.le = 0;
apdu.resplen = 0;
}
sc_log(card->ctx,
"calling sc_transmit_apdu flags=%lx le=%"SC_FORMAT_LEN_SIZE_T"u, resplen=%"SC_FORMAT_LEN_SIZE_T"u, resp=%p",
apdu.flags, apdu.le, apdu.resplen, apdu.resp);
/* with new adpu.c and chaining, this actually reads the whole object */
r = sc_transmit_apdu(card, &apdu);
sc_log(card->ctx,
"DEE r=%d apdu.resplen=%"SC_FORMAT_LEN_SIZE_T"u sw1=%02x sw2=%02x",
r, apdu.resplen, apdu.sw1, apdu.sw2);
if (r < 0) {
sc_log(card->ctx, "Transmit failed");
goto err;
}
if (!(find_len && apdu.sw1 == 0x61))
r = sc_check_sw(card, apdu.sw1, apdu.sw2);
/* TODO: - DEE look later at tag vs size read too */
if (r < 0) {
sc_log(card->ctx, "Card returned error ");
goto err;
}
/*
* See how much we read and make sure it is asn1
* if not, return 0 indicating no data found
*/
rbuflen = 0; /* in case rseplen < 3 i.e. not parseable */
/* we may only be using get data to test the security status of the card, so zero length is OK */
if ( recvbuflen && recvbuf && apdu.resplen > 3 && priv->pin_cmd_noparse != 1) {
*recvbuflen = 0;
/* we should have all the tag data, so we have to tell sc_asn1_find_tag
* the buffer is bigger, so it will not produce "ASN1.tag too long!" */
body = rbuf;
if (sc_asn1_read_tag(&body, 0xffff, &cla_out, &tag_out, &bodylen) != SC_SUCCESS
|| body == NULL) {
/* only early beta cards had this problem */
sc_log(card->ctx, "***** received buffer tag MISSING ");
body = rbuf;
/* some readers/cards might return 6c 00 */
if (apdu.sw1 == 0x61 || apdu.sw2 == 0x6c )
bodylen = 12000;
else
bodylen = apdu.resplen;
}
rbuflen = body - rbuf + bodylen;
/* if using internal buffer, alloc new one */
if (rbuf == rbufinitbuf) {
*recvbuf = malloc(rbuflen);
if (*recvbuf == NULL) {
r = SC_ERROR_OUT_OF_MEMORY;
goto err;
}
memcpy(*recvbuf, rbuf, rbuflen); /* copy tag too */
}
}
if (recvbuflen) {
*recvbuflen = rbuflen;
r = *recvbuflen;
}
err:
sc_unlock(card);
LOG_FUNC_RETURN(card->ctx, r);
}
/* Add the PIV-II operations */
/* Should use our own keydata, actually should be common to all cards */
/* RSA and EC are added. */
static int piv_generate_key(sc_card_t *card,
sc_cardctl_piv_genkey_info_t *keydata)
{
int r;
u8 *rbuf = NULL;
size_t rbuflen = 0;
u8 *p;
const u8 *tag;
u8 tagbuf[16];
u8 outdata[3]; /* we could also add tag 81 for exponent */
size_t taglen, i;
size_t out_len;
size_t in_len;
unsigned int cla_out, tag_out;
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
keydata->exponent = 0;
keydata->pubkey = NULL;
keydata->pubkey_len = 0;
keydata->ecparam = NULL; /* will show size as we only support 2 curves */
keydata->ecparam_len = 0;
keydata->ecpoint = NULL;
keydata->ecpoint_len = 0;
out_len = 3;
outdata[0] = 0x80;
outdata[1] = 0x01;
outdata[2] = keydata->key_algid;
switch (keydata->key_algid) {
case 0x05: keydata->key_bits = 3072; break;
case 0x06: keydata->key_bits = 1024; break;
case 0x07: keydata->key_bits = 2048; break;
/* TODO: - DEE For EC, also set the curve parameter as the OID */
case 0x11: keydata->key_bits = 0;
keydata->ecparam =0; /* we only support prime256v1 for 11 */
keydata->ecparam_len =0;
break;
case 0x14: keydata->key_bits = 0;
keydata->ecparam = 0; /* we only support secp384r1 */
keydata->ecparam_len = 0;
break;
default:
LOG_FUNC_RETURN(card->ctx, SC_ERROR_INVALID_ARGUMENTS);
}
p = tagbuf;
put_tag_and_len(0xAC, out_len, &p);
memcpy(p, outdata, out_len);
p+=out_len;
r = piv_general_io(card, 0x47, 0x00, keydata->key_num,
tagbuf, p - tagbuf, &rbuf, &rbuflen);
if (r >= 0) {
const u8 *cp;
keydata->exponent = 0;
/* expected tag is 7f49. */
/* we will whatever tag is present */
cp = rbuf;
in_len = rbuflen;
r = sc_asn1_read_tag(&cp, rbuflen, &cla_out, &tag_out, &in_len);
if (cp == NULL) {
r = SC_ERROR_ASN1_OBJECT_NOT_FOUND;
}
if (r != SC_SUCCESS) {
sc_log(card->ctx, "Tag buffer not found");
goto err;
}
/* if RSA vs EC */
if (keydata->key_bits > 0 ) {
tag = sc_asn1_find_tag(card->ctx, cp, in_len, 0x82, &taglen);
if (tag != NULL && taglen <= 4) {
keydata->exponent = 0;
for (i = 0; i < taglen;i++)
keydata->exponent = (keydata->exponent<<8) + tag[i];
}
tag = sc_asn1_find_tag(card->ctx, cp, in_len, 0x81, &taglen);
if (tag != NULL && taglen > 0) {
keydata->pubkey = malloc(taglen);
if (keydata->pubkey == NULL)
LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY);
keydata->pubkey_len = taglen;
memcpy (keydata->pubkey, tag, taglen);
}
}
else { /* must be EC */
tag = sc_asn1_find_tag(card->ctx, cp, in_len, 0x86, &taglen);
if (tag != NULL && taglen > 0) {
keydata->ecpoint = malloc(taglen);
if (keydata->ecpoint == NULL)
LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY);
keydata->ecpoint_len = taglen;
memcpy (keydata->ecpoint, tag, taglen);
}
}
/* TODO: -DEE Could add key to cache so could use engine to generate key,
* and sign req in single operation */
r = 0;
}
err:
if (rbuf)
free(rbuf);
LOG_FUNC_RETURN(card->ctx, r);
}
static int piv_select_aid(sc_card_t* card, u8* aid, size_t aidlen, u8* response, size_t *responselen)
{
sc_apdu_t apdu;
int r;
LOG_FUNC_CALLED(card->ctx);
sc_log(card->ctx,
"Got args: aid=%p, aidlen=%"SC_FORMAT_LEN_SIZE_T"u, response=%p, responselen=%"SC_FORMAT_LEN_SIZE_T"u",
aid, aidlen, response, responselen ? *responselen : 0);
sc_format_apdu(card, &apdu,
response == NULL ? SC_APDU_CASE_3_SHORT : SC_APDU_CASE_4_SHORT, 0xA4, 0x04, 0x00);
apdu.lc = aidlen;
apdu.data = aid;
apdu.datalen = aidlen;
apdu.resp = response;
apdu.resplen = responselen ? *responselen : 0;
apdu.le = response == NULL ? 0 : 256; /* could be 21 for fci */
r = sc_transmit_apdu(card, &apdu);
if (responselen)
*responselen = apdu.resplen;
LOG_TEST_RET(card->ctx, r, "PIV select failed");
LOG_FUNC_RETURN(card->ctx, sc_check_sw(card, apdu.sw1, apdu.sw2));
}
/* find the PIV AID on the card. If card->type already filled in,
* then look for specific AID only
* Assumes that priv may not be present
*/
static int piv_find_aid(sc_card_t * card, sc_file_t *aid_file)
{
sc_apdu_t apdu;
u8 rbuf[SC_MAX_APDU_BUFFER_SIZE];
int r,i;
const u8 *tag;
size_t taglen;
const u8 *pix;
size_t pixlen;
size_t resplen = sizeof(rbuf);
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
/* first see if the default application will return a template
* that we know about.
*/
r = piv_select_aid(card, piv_aids[0].value, piv_aids[0].len_short, rbuf, &resplen);
if (r >= 0 && resplen > 2 ) {
tag = sc_asn1_find_tag(card->ctx, rbuf, resplen, 0x61, &taglen);
if (tag != NULL) {
pix = sc_asn1_find_tag(card->ctx, tag, taglen, 0x4F, &pixlen);
if (pix != NULL ) {
sc_log(card->ctx, "found PIX");
/* early cards returned full AID, rather then just the pix */
for (i = 0; piv_aids[i].len_long != 0; i++) {
if ((pixlen >= 6 && memcmp(pix, piv_aids[i].value + 5,
piv_aids[i].len_long - 5 ) == 0)
|| ((pixlen >= piv_aids[i].len_short &&
memcmp(pix, piv_aids[i].value,
piv_aids[i].len_short) == 0))) {
if (card->type > SC_CARD_TYPE_PIV_II_BASE &&
card->type < SC_CARD_TYPE_PIV_II_BASE+1000 &&
card->type == piv_aids[i].enumtag) {
LOG_FUNC_RETURN(card->ctx, i);
} else {
LOG_FUNC_RETURN(card->ctx, i);
}
}
}
}
}
}
/* for testing, we can force the use of a specific AID
* by using the card= parameter in conf file
*/
for (i = 0; piv_aids[i].len_long != 0; i++) {
if (card->type > SC_CARD_TYPE_PIV_II_BASE &&
card->type < SC_CARD_TYPE_PIV_II_BASE+1000 &&
card->type != piv_aids[i].enumtag) {
continue;
}
sc_format_apdu(card, &apdu, SC_APDU_CASE_4_SHORT, 0xA4, 0x04, 0x00);
apdu.lc = piv_aids[i].len_long;
apdu.data = piv_aids[i].value;
apdu.datalen = apdu.lc;
apdu.resp = rbuf;
apdu.resplen = sizeof(rbuf);
apdu.le = 256;
r = sc_transmit_apdu(card, &apdu);
LOG_TEST_RET(card->ctx, r, "APDU transmit failed");
r = sc_check_sw(card, apdu.sw1, apdu.sw2);
if (r) {
if (card->type != 0 && card->type == piv_aids[i].enumtag)
LOG_FUNC_RETURN(card->ctx, (r < 0)? r: i);
continue;
}
if ( apdu.resplen == 0 && r == 0) {
/* could be the MSU card */
continue; /* other cards will return a FCI */
}
if (apdu.resp[0] != 0x6f || apdu.resp[1] > apdu.resplen - 2 )
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, SC_ERROR_NO_CARD_SUPPORT);
card->ops->process_fci(card, aid_file, apdu.resp+2, apdu.resp[1]);
LOG_FUNC_RETURN(card->ctx, i);
}
LOG_FUNC_RETURN(card->ctx, SC_ERROR_NO_CARD_SUPPORT);
}
/*
* Read a DER encoded object from a file. Allocate and return the buf.
* Used to read the file defined in offCardCertURL from a cache.
* Also used for testing of History and Discovery objects from a file
* when testing with a card that does not support these new objects.
*/
static int piv_read_obj_from_file(sc_card_t * card, char * filename,
u8 **buf, size_t *buf_len)
{
int r;
int f = -1;
size_t len;
u8 tagbuf[16];
size_t rbuflen;
const u8 * body;
unsigned int cla_out, tag_out;
size_t bodylen;
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
*buf = NULL;
*buf_len = 0;
f = open(filename, O_RDONLY);
if (f < 0) {
sc_log(card->ctx, "Unable to load PIV off card file: \"%s\"",filename);
r = SC_ERROR_FILE_NOT_FOUND;
goto err;
}
len = read(f, tagbuf, sizeof(tagbuf)); /* get tag and length */
if (len < 2 || len > sizeof(tagbuf)) {
sc_log(card->ctx, "Problem with \"%s\"",filename);
r = SC_ERROR_DATA_OBJECT_NOT_FOUND;
goto err;
}
body = tagbuf;
if (sc_asn1_read_tag(&body, 0xfffff, &cla_out, &tag_out, &bodylen) != SC_SUCCESS
|| body == NULL) {
sc_log(card->ctx, "DER problem");
r = SC_ERROR_INVALID_ASN1_OBJECT;
goto err;
}
rbuflen = body - tagbuf + bodylen;
*buf = malloc(rbuflen);
if (!*buf) {
r = SC_ERROR_OUT_OF_MEMORY;
goto err;
}
memcpy(*buf, tagbuf, len); /* copy first or only part */
if (rbuflen > len + sizeof(tagbuf)) {
len = read(f, *buf + sizeof(tagbuf), rbuflen - sizeof(tagbuf)); /* read rest */
if (len != rbuflen - sizeof(tagbuf)) {
r = SC_ERROR_INVALID_ASN1_OBJECT;
free (*buf);
*buf = NULL;
goto err;
}
}
r = rbuflen;
*buf_len = rbuflen;
err:
if (f >= 0)
close(f);
LOG_FUNC_RETURN(card->ctx, r);
}
/* the tag is the PIV_OBJ_* */
static int
piv_get_data(sc_card_t * card, int enumtag, u8 **buf, size_t *buf_len)
{
u8 *p;
int r = 0;
u8 tagbuf[8];
size_t tag_len;
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
sc_log(card->ctx, "#%d", enumtag);
sc_lock(card); /* do check len and get data in same transaction */
/* assert(enumtag >= 0 && enumtag < PIV_OBJ_LAST_ENUM); */
tag_len = piv_objects[enumtag].tag_len;
p = tagbuf;
put_tag_and_len(0x5c, tag_len, &p);
memcpy(p, piv_objects[enumtag].tag_value, tag_len);
p += tag_len;
if (*buf_len == 1 && *buf == NULL) { /* we need to get the length */
u8 rbufinitbuf[8]; /* tag of 53 with 82 xx xx will fit in 4 */
u8 *rbuf;
size_t rbuflen;
size_t bodylen;
unsigned int cla_out, tag_out;
const u8 *body;
sc_log(card->ctx, "get len of #%d", enumtag);
rbuf = rbufinitbuf;
rbuflen = sizeof(rbufinitbuf);
r = piv_general_io(card, 0xCB, 0x3F, 0xFF, tagbuf, p - tagbuf, &rbuf, &rbuflen);
if (r > 0) {
body = rbuf;
if (sc_asn1_read_tag(&body, 0xffff, &cla_out, &tag_out, &bodylen) != SC_SUCCESS
|| body == NULL) {
sc_log(card->ctx, "***** received buffer tag MISSING ");
r = SC_ERROR_FILE_NOT_FOUND;
goto err;
}
*buf_len = r;
} else if ( r == 0 ) {
r = SC_ERROR_FILE_NOT_FOUND;
goto err;
} else {
goto err;
}
}
sc_log(card->ctx,
"buffer for #%d *buf=0x%p len=%"SC_FORMAT_LEN_SIZE_T"u",
enumtag, *buf, *buf_len);
if (*buf == NULL && *buf_len > 0) {
*buf = malloc(*buf_len);
if (*buf == NULL ) {
r = SC_ERROR_OUT_OF_MEMORY;
goto err;
}
}
r = piv_general_io(card, 0xCB, 0x3F, 0xFF, tagbuf, p - tagbuf, buf, buf_len);
err:
sc_unlock(card);
LOG_FUNC_RETURN(card->ctx, r);
}
static int
piv_get_cached_data(sc_card_t * card, int enumtag, u8 **buf, size_t *buf_len)
{
piv_private_data_t * priv = PIV_DATA(card);
int r;
u8 *rbuf = NULL;
size_t rbuflen;
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
sc_log(card->ctx, "#%d", enumtag);
assert(enumtag >= 0 && enumtag < PIV_OBJ_LAST_ENUM);
/* see if we have it cached */
if (priv->obj_cache[enumtag].flags & PIV_OBJ_CACHE_VALID) {
sc_log(card->ctx,
"found #%d %p:%"SC_FORMAT_LEN_SIZE_T"u %p:%"SC_FORMAT_LEN_SIZE_T"u",
enumtag,
priv->obj_cache[enumtag].obj_data,
priv->obj_cache[enumtag].obj_len,
priv->obj_cache[enumtag].internal_obj_data,
priv->obj_cache[enumtag].internal_obj_len);
if (priv->obj_cache[enumtag].obj_len == 0) {
r = SC_ERROR_FILE_NOT_FOUND;
sc_log(card->ctx, "#%d found but len=0", enumtag);
goto err;
}
*buf = priv->obj_cache[enumtag].obj_data;
*buf_len = priv->obj_cache[enumtag].obj_len;
r = *buf_len;
goto ok;
}
/*
* If we know it can not be on the card i.e. History object
* has been read, and we know what other certs may or
* may not be on the card. We can avoid extra overhead
*/
if (priv->obj_cache[enumtag].flags & PIV_OBJ_CACHE_NOT_PRESENT) {
sc_log(card->ctx, "no_obj #%d", enumtag);
r = SC_ERROR_FILE_NOT_FOUND;
goto err;
}
/* Not cached, try to get it, piv_get_data will allocate a buf */
sc_log(card->ctx, "get #%d", enumtag);
rbuflen = 1;
r = piv_get_data(card, enumtag, &rbuf, &rbuflen);
if (r > 0) {
priv->obj_cache[enumtag].flags |= PIV_OBJ_CACHE_VALID;
priv->obj_cache[enumtag].obj_len = r;
priv->obj_cache[enumtag].obj_data = rbuf;
*buf = rbuf;
*buf_len = r;
sc_log(card->ctx,
"added #%d %p:%"SC_FORMAT_LEN_SIZE_T"u %p:%"SC_FORMAT_LEN_SIZE_T"u",
enumtag,
priv->obj_cache[enumtag].obj_data,
priv->obj_cache[enumtag].obj_len,
priv->obj_cache[enumtag].internal_obj_data,
priv->obj_cache[enumtag].internal_obj_len);
} else if (r == 0 || r == SC_ERROR_FILE_NOT_FOUND) {
r = SC_ERROR_FILE_NOT_FOUND;
priv->obj_cache[enumtag].flags |= PIV_OBJ_CACHE_VALID;
priv->obj_cache[enumtag].obj_len = 0;
} else if ( r < 0) {
goto err;
}
ok:
err:
LOG_FUNC_RETURN(card->ctx, r);
}
static int
piv_cache_internal_data(sc_card_t *card, int enumtag)
{
piv_private_data_t * priv = PIV_DATA(card);
const u8* tag;
const u8* body;
size_t taglen;
size_t bodylen;
int compressed = 0;
/* if already cached */
if (priv->obj_cache[enumtag].internal_obj_data && priv->obj_cache[enumtag].internal_obj_len) {
sc_log(card->ctx,
"#%d found internal %p:%"SC_FORMAT_LEN_SIZE_T"u",
enumtag,
priv->obj_cache[enumtag].internal_obj_data,
priv->obj_cache[enumtag].internal_obj_len);
LOG_FUNC_RETURN(card->ctx, SC_SUCCESS);
}
body = sc_asn1_find_tag(card->ctx,
priv->obj_cache[enumtag].obj_data,
priv->obj_cache[enumtag].obj_len,
0x53, &bodylen);
if (body == NULL)
LOG_FUNC_RETURN(card->ctx, SC_ERROR_OBJECT_NOT_VALID);
/* get the certificate out */
if (piv_objects[enumtag].flags & PIV_OBJECT_TYPE_CERT) {
tag = sc_asn1_find_tag(card->ctx, body, bodylen, 0x71, &taglen);
/* 800-72-1 not clear if this is 80 or 01 Sent comment to NIST for 800-72-2 */
/* 800-73-3 says it is 01, keep dual test so old cards still work */
if (tag && (((*tag) & 0x80) || ((*tag) & 0x01)))
compressed = 1;
tag = sc_asn1_find_tag(card->ctx, body, bodylen, 0x70, &taglen);
if (tag == NULL)
LOG_FUNC_RETURN(card->ctx, SC_ERROR_OBJECT_NOT_VALID);
if (taglen == 0)
LOG_FUNC_RETURN(card->ctx, SC_ERROR_FILE_NOT_FOUND);
if(compressed) {
#ifdef ENABLE_ZLIB
size_t len;
u8* newBuf = NULL;
if(SC_SUCCESS != sc_decompress_alloc(&newBuf, &len, tag, taglen, COMPRESSION_AUTO))
LOG_FUNC_RETURN(card->ctx, SC_ERROR_OBJECT_NOT_VALID);
priv->obj_cache[enumtag].internal_obj_data = newBuf;
priv->obj_cache[enumtag].internal_obj_len = len;
#else
sc_log(card->ctx, "PIV compression not supported, no zlib");
LOG_FUNC_RETURN(card->ctx, SC_ERROR_NOT_SUPPORTED);
#endif
}
else {
if (!(priv->obj_cache[enumtag].internal_obj_data = malloc(taglen)))
LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY);
memcpy(priv->obj_cache[enumtag].internal_obj_data, tag, taglen);
priv->obj_cache[enumtag].internal_obj_len = taglen;
}
/* convert pub key to internal */
/* TODO: -DEE need to fix ... would only be used if we cache the pub key, but we don't today */
}
else if (piv_objects[enumtag].flags & PIV_OBJECT_TYPE_PUBKEY) {
tag = sc_asn1_find_tag(card->ctx, body, bodylen, *body, &taglen);
if (tag == NULL)
LOG_FUNC_RETURN(card->ctx, SC_ERROR_OBJECT_NOT_VALID);
if (taglen == 0)
LOG_FUNC_RETURN(card->ctx, SC_ERROR_FILE_NOT_FOUND);
if (!(priv->obj_cache[enumtag].internal_obj_data = malloc(taglen)))
LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY);
memcpy(priv->obj_cache[enumtag].internal_obj_data, tag, taglen);
priv->obj_cache[enumtag].internal_obj_len = taglen;
}
else {
LOG_FUNC_RETURN(card->ctx, SC_ERROR_INTERNAL);
}
sc_log(card->ctx, "added #%d internal %p:%"SC_FORMAT_LEN_SIZE_T"u",
enumtag,
priv->obj_cache[enumtag].internal_obj_data,
priv->obj_cache[enumtag].internal_obj_len);
LOG_FUNC_RETURN(card->ctx, SC_SUCCESS);
}
/*
* Callers of this may be expecting a certificate,
* select file will have saved the object type for us
* as well as set that we want the cert from the object.
*/
static int
piv_read_binary(sc_card_t *card, unsigned int idx, unsigned char *buf, size_t count, unsigned long flags)
{
piv_private_data_t * priv = PIV_DATA(card);
int enumtag;
int r;
u8 *rbuf = NULL;
size_t rbuflen = 0;
const u8 *body;
size_t bodylen;
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
if (priv->selected_obj < 0)
LOG_FUNC_RETURN(card->ctx, SC_ERROR_INTERNAL);
enumtag = piv_objects[priv->selected_obj].enumtag;
if (priv->rwb_state == -1) {
r = piv_get_cached_data(card, enumtag, &rbuf, &rbuflen);
if (r >=0) {
/* an object with no data will be considered not found */
/* Discovery tag = 0x73, all others are 0x53 */
if (!rbuf || rbuf[0] == 0x00 || ((rbuf[0]&0xDF) == 0x53 && rbuf[1] == 0x00)) {
r = SC_ERROR_FILE_NOT_FOUND;
goto err;
}
sc_log(card->ctx,
"DEE rbuf=%p,rbuflen=%"SC_FORMAT_LEN_SIZE_T"u,",
rbuf, rbuflen);
body = sc_asn1_find_tag(card->ctx, rbuf, rbuflen, rbuf[0], &bodylen);
if (body == NULL) {
/* if missing, assume its the body */
/* DEE bug in the beta card */
sc_log(card->ctx, " ***** tag 0x53 MISSING");
r = SC_ERROR_INVALID_DATA;
goto err;
}
if (bodylen > body - rbuf + rbuflen) {
sc_log(card->ctx,
" ***** tag length > then data: %"SC_FORMAT_LEN_SIZE_T"u>%"SC_FORMAT_LEN_PTRDIFF_T"u+%"SC_FORMAT_LEN_SIZE_T"u",
bodylen, body - rbuf, rbuflen);
r = SC_ERROR_INVALID_DATA;
goto err;
}
/* if cached obj has internal interesting data (cert or pub key) */
if (priv->return_only_cert || piv_objects[enumtag].flags & PIV_OBJECT_TYPE_PUBKEY) {
r = piv_cache_internal_data(card, enumtag);
if (r < 0)
goto err;
}
}
priv->rwb_state = 0;
}
if (priv->return_only_cert || piv_objects[enumtag].flags & PIV_OBJECT_TYPE_PUBKEY) {
rbuf = priv->obj_cache[enumtag].internal_obj_data;
rbuflen = priv->obj_cache[enumtag].internal_obj_len;
} else {
rbuf = priv->obj_cache[enumtag].obj_data;
rbuflen = priv->obj_cache[enumtag].obj_len;
}
/* rbuf rbuflen has pointer and length to cached data */
if ( rbuflen < idx + count)
count = rbuflen - idx;
if (count <= 0) {
r = 0;
priv->rwb_state = 1;
} else {
memcpy(buf, rbuf + idx, count);
r = count;
}
err:
LOG_FUNC_RETURN(card->ctx, r);
}
/*
* the tag is the PIV_OBJ_*
* The buf should have the 0x53 tag+len+tags and data
*/
static int
piv_put_data(sc_card_t *card, int tag, const u8 *buf, size_t buf_len)
{
int r;
u8 * sbuf;
size_t sbuflen;
u8 * p;
size_t tag_len;
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
tag_len = piv_objects[tag].tag_len;
sbuflen = put_tag_and_len(0x5c, tag_len, NULL) + buf_len;
if (!(sbuf = malloc(sbuflen)))
LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY);
p = sbuf;
put_tag_and_len(0x5c, tag_len, &p);
memcpy(p, piv_objects[tag].tag_value, tag_len);
p += tag_len;
memcpy(p, buf, buf_len);
p += buf_len;
r = piv_general_io(card, 0xDB, 0x3F, 0xFF, sbuf, p - sbuf, NULL, NULL);
if (sbuf)
free(sbuf);
LOG_FUNC_RETURN(card->ctx, r);
}
static int
piv_write_certificate(sc_card_t *card, const u8* buf, size_t count, unsigned long flags)
{
piv_private_data_t * priv = PIV_DATA(card);
int enumtag;
int r = SC_SUCCESS;
u8 *sbuf = NULL;
u8 *p;
size_t sbuflen;
size_t taglen;
sc_log(card->ctx, "DEE cert len=%"SC_FORMAT_LEN_SIZE_T"u", count);
taglen = put_tag_and_len(0x70, count, NULL)
+ put_tag_and_len(0x71, 1, NULL)
+ put_tag_and_len(0xFE, 0, NULL);
sbuflen = put_tag_and_len(0x53, taglen, NULL);
sbuf = malloc(sbuflen);
if (sbuf == NULL)
LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY);
p = sbuf;
put_tag_and_len(0x53, taglen, &p);
put_tag_and_len(0x70, count, &p);
memcpy(p, buf, count);
p += count;
put_tag_and_len(0x71, 1, &p);
/* Use 01 as per NIST 800-73-3 */
*p++ = (flags)? 0x01:0x00; /* certinfo, i.e. gzipped? */
put_tag_and_len(0xFE,0,&p); /* LRC tag */
sc_log(card->ctx, "DEE buf %p len %"SC_FORMAT_LEN_PTRDIFF_T"u %"SC_FORMAT_LEN_SIZE_T"u",
sbuf, p - sbuf, sbuflen);
enumtag = piv_objects[priv->selected_obj].enumtag;
r = piv_put_data(card, enumtag, sbuf, sbuflen);
if (sbuf)
free(sbuf);
LOG_FUNC_RETURN(card->ctx, r);
}
/*
* For certs we need to add the 0x53 tag and other specific tags,
* and call the piv_put_data
* Note: the select file will have saved the object type for us
* Write is used by piv-tool, so we will use flags:
* length << 8 | 8bits:
* object xxxx0000
* uncompressed cert xxx00001
* compressed cert xxx10001
* pubkey xxxx0010
*
* to indicate we are writing a cert and if is compressed
* or if we are writing a pubkey in to the cache.
* if its not a cert or pubkey its an object.
*
* Therefore when idx=0, we will get the length of the object
* and allocate a buffer, so we can support partial writes.
* When the last chuck of the data is sent, we will write it.
*/
static int piv_write_binary(sc_card_t *card, unsigned int idx,
const u8 *buf, size_t count, unsigned long flags)
{
piv_private_data_t * priv = PIV_DATA(card);
int r;
int enumtag;
LOG_FUNC_CALLED(card->ctx);
if (priv->selected_obj < 0)
LOG_FUNC_RETURN(card->ctx, SC_ERROR_INTERNAL);
enumtag = piv_objects[priv->selected_obj].enumtag;
if (priv->rwb_state == 1) /* trying to write at end */
LOG_FUNC_RETURN(card->ctx, SC_SUCCESS);
if (priv->rwb_state == -1) {
/* if cached, remove old entry */
if (priv->obj_cache[enumtag].flags & PIV_OBJ_CACHE_VALID) {
priv->obj_cache[enumtag].flags = 0;
if (priv->obj_cache[enumtag].obj_data) {
free(priv->obj_cache[enumtag].obj_data);
priv->obj_cache[enumtag].obj_data = NULL;
priv->obj_cache[enumtag].obj_len = 0;
}
if (priv->obj_cache[enumtag].internal_obj_data) {
free(priv->obj_cache[enumtag].internal_obj_data);
priv->obj_cache[enumtag].internal_obj_data = NULL;
priv->obj_cache[enumtag].internal_obj_len = 0;
}
}
if (idx != 0)
LOG_FUNC_RETURN(card->ctx, SC_ERROR_NO_CARD_SUPPORT);
priv->w_buf_len = flags>>8;
if (priv->w_buf_len == 0)
LOG_FUNC_RETURN(card->ctx, SC_ERROR_INTERNAL);
priv->w_buf = malloc(priv->w_buf_len);
priv-> rwb_state = 0;
}
/* on each pass make sure we have w_buf */
if (priv->w_buf == NULL)
LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY);
if (idx + count > priv->w_buf_len)
LOG_FUNC_RETURN(card->ctx, SC_ERROR_OBJECT_NOT_VALID);
memcpy(priv->w_buf + idx, buf, count); /* copy one chunk */
/* if this was not the last chunk, return to get rest */
if (idx + count < priv->w_buf_len)
LOG_FUNC_RETURN(card->ctx, count);
priv-> rwb_state = 1; /* at end of object */
switch (flags & 0x0f) {
case 1:
r = piv_write_certificate(card, priv->w_buf, priv->w_buf_len, flags & 0x10);
break;
case 2: /* pubkey to be added to cache, it should have 0x53 and 0x99 tags. */
/* TODO: -DEE this is not fully implemented and not used */
r = priv->w_buf_len;
break;
default:
r = piv_put_data(card, enumtag, priv->w_buf, priv->w_buf_len);
break;
}
/* if it worked, will cache it */
if (r >= 0 && priv->w_buf) {
priv->obj_cache[enumtag].flags |= PIV_OBJ_CACHE_VALID;
priv->obj_cache[enumtag].obj_data = priv->w_buf;
priv->obj_cache[enumtag].obj_len = priv->w_buf_len;
} else {
if (priv->w_buf)
free(priv->w_buf);
}
priv->w_buf = NULL;
priv->w_buf_len = 0;
LOG_FUNC_RETURN(card->ctx, (r < 0)? r : (int)count);
}
/*
* Card initialization is NOT standard.
* Some cards use mutual or external authentication using 3des or aes key. We
* will read in the key from a file either binary or hex encoded.
* This is only needed during initialization/personalization of the card
*/
#ifdef ENABLE_OPENSSL
static const EVP_CIPHER *get_cipher_for_algo(int alg_id)
{
switch (alg_id) {
case 0x0: return EVP_des_ede3_ecb();
case 0x1: return EVP_des_ede3_ecb(); /* 2TDES */
case 0x3: return EVP_des_ede3_ecb();
case 0x8: return EVP_aes_128_ecb();
case 0xA: return EVP_aes_192_ecb();
case 0xC: return EVP_aes_256_ecb();
default: return NULL;
}
}
static int get_keylen(unsigned int alg_id, size_t *size)
{
switch(alg_id) {
case 0x01: *size = 192/8; /* 2TDES still has 3 single des keys phase out by 12/31/2010 */
break;
case 0x00:
case 0x03: *size = 192/8;
break;
case 0x08: *size = 128/8;
break;
case 0x0A: *size = 192/8;
break;
case 0x0C: *size = 256/8;
break;
default:
return SC_ERROR_INVALID_ARGUMENTS;
}
return SC_SUCCESS;
}
static int piv_get_key(sc_card_t *card, unsigned int alg_id, u8 **key, size_t *len)
{
int r;
size_t fsize;
FILE *f = NULL;
char * keyfilename = NULL;
size_t expected_keylen;
size_t keylen;
u8 * keybuf = NULL;
u8 * tkey = NULL;
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
keyfilename = (char *)getenv("PIV_EXT_AUTH_KEY");
if (keyfilename == NULL) {
sc_log(card->ctx,
"Unable to get PIV_EXT_AUTH_KEY=(null) for general_external_authenticate");
r = SC_ERROR_FILE_NOT_FOUND;
goto err;
}
r = get_keylen(alg_id, &expected_keylen);
if(r) {
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "Invalid cipher selector, none found for: %02x", alg_id);
r = SC_ERROR_INVALID_ARGUMENTS;
goto err;
}
f = fopen(keyfilename, "rb");
if (!f) {
sc_log(card->ctx, " Unable to load key from file\n");
r = SC_ERROR_FILE_NOT_FOUND;
goto err;
}
if (0 > fseek(f, 0L, SEEK_END))
r = SC_ERROR_INTERNAL;
fsize = ftell(f);
if (0 > (long) fsize)
r = SC_ERROR_INTERNAL;
if (0 > fseek(f, 0L, SEEK_SET))
r = SC_ERROR_INTERNAL;
if(r) {
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "Could not read %s\n", keyfilename);
goto err;
}
keybuf = malloc(fsize+1); /* if not binary, need null to make it a string */
if (!keybuf) {
sc_log(card->ctx, " Unable to allocate key memory");
r = SC_ERROR_OUT_OF_MEMORY;
goto err;
}
keybuf[fsize] = 0x00; /* in case it is text need null */
if (fread(keybuf, 1, fsize, f) != fsize) {
sc_log(card->ctx, " Unable to read key\n");
r = SC_ERROR_WRONG_LENGTH;
goto err;
}
tkey = malloc(expected_keylen);
if (!tkey) {
sc_log(card->ctx, " Unable to allocate key memory");
r = SC_ERROR_OUT_OF_MEMORY;
goto err;
}
if (fsize == expected_keylen) { /* it must be binary */
memcpy(tkey, keybuf, expected_keylen);
} else {
/* if the key-length is larger then binary length, we assume hex encoded */
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "Treating key as hex-encoded!\n");
sc_right_trim(keybuf, fsize);
keylen = expected_keylen;
r = sc_hex_to_bin((char *)keybuf, tkey, &keylen);
if (keylen !=expected_keylen || r != 0 ) {
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "Error formatting key\n");
if (r == 0)
r = SC_ERROR_INCOMPATIBLE_KEY;
goto err;
}
}
*key = tkey;
tkey = NULL;
*len = expected_keylen;
r = SC_SUCCESS;
err:
if (f)
fclose(f);
if (keybuf) {
free(keybuf);
}
if (tkey) {
free(tkey);
}
LOG_FUNC_RETURN(card->ctx, r);
return r;
}
#endif
/*
* will only deal with 3des for now
* assumptions include:
* size of encrypted data is same as unencrypted
* challenges, nonces etc from card are less then 114 (keeps tags simple)
*/
static int piv_general_mutual_authenticate(sc_card_t *card,
unsigned int key_ref, unsigned int alg_id)
{
int r;
#ifdef ENABLE_OPENSSL
int N;
int locked = 0;
u8 *rbuf = NULL;
size_t rbuflen;
u8 *nonce = NULL;
size_t nonce_len;
u8 *p;
u8 *key = NULL;
size_t keylen;
u8 *plain_text = NULL;
size_t plain_text_len = 0;
u8 *tmp;
size_t tmplen, tmplen2;
u8 *built = NULL;
size_t built_len;
const u8 *body = NULL;
size_t body_len;
const u8 *witness_data = NULL;
size_t witness_len;
const u8 *challenge_response = NULL;
size_t challenge_response_len;
u8 *decrypted_reponse = NULL;
size_t decrypted_reponse_len;
EVP_CIPHER_CTX * ctx = NULL;
u8 sbuf[255];
const EVP_CIPHER *cipher;
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
ctx = EVP_CIPHER_CTX_new();
if (ctx == NULL) {
r = SC_ERROR_OUT_OF_MEMORY;
goto err;
}
cipher = get_cipher_for_algo(alg_id);
if(!cipher) {
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "Invalid cipher selector, none found for: %02x\n", alg_id);
r = SC_ERROR_INVALID_ARGUMENTS;
goto err;
}
r = piv_get_key(card, alg_id, &key, &keylen);
if (r) {
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "Error getting General Auth key\n");
goto err;
}
r = sc_lock(card);
if (r != SC_SUCCESS) {
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "sc_lock failed\n");
goto err; /* cleanup */
}
locked = 1;
p = sbuf;
*p++ = 0x7C;
*p++ = 0x02;
*p++ = 0x80;
*p++ = 0x00;
/* get the encrypted nonce */
r = piv_general_io(card, 0x87, alg_id, key_ref, sbuf, p - sbuf, &rbuf, &rbuflen);
if (r < 0) goto err;
/* Remove the encompassing outer TLV of 0x7C and get the data */
body = sc_asn1_find_tag(card->ctx, rbuf,
r, 0x7C, &body_len);
if (!body) {
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "Invalid Witness Data response of NULL\n");
r = SC_ERROR_INVALID_DATA;
goto err;
}
/* Get the witness data indicated by the TAG 0x80 */
witness_data = sc_asn1_find_tag(card->ctx, body,
body_len, 0x80, &witness_len);
if (!witness_len) {
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "Invalid Challenge Data none found in TLV\n");
r = SC_ERROR_INVALID_DATA;
goto err;
}
/* Allocate an output buffer for openssl */
plain_text = malloc(witness_len);
if (!plain_text) {
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "Could not allocate buffer for plain text\n");
r = SC_ERROR_INTERNAL;
goto err;
}
/* decrypt the data from the card */
if (!EVP_DecryptInit(ctx, cipher, key, NULL)) {
/* may fail if des parity of key is wrong. depends on OpenSSL options */
r = SC_ERROR_INTERNAL;
goto err;
}
EVP_CIPHER_CTX_set_padding(ctx,0);
p = plain_text;
if (!EVP_DecryptUpdate(ctx, p, &N, witness_data, witness_len)) {
r = SC_ERROR_INTERNAL;
goto err;
}
plain_text_len = tmplen = N;
p += tmplen;
if(!EVP_DecryptFinal(ctx, p, &N)) {
r = SC_ERROR_INTERNAL;
goto err;
}
tmplen = N;
plain_text_len += tmplen;
if (plain_text_len != witness_len) {
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,
"Encrypted and decrypted lengths do not match: %"SC_FORMAT_LEN_SIZE_T"u:%"SC_FORMAT_LEN_SIZE_T"u\n",
witness_len, plain_text_len);
r = SC_ERROR_INTERNAL;
goto err;
}
/* Build a response to the card of:
* [GEN AUTH][ 80<decrypted witness>81 <challenge> ]
* Start by computing the nonce for <challenge> the
* nonce length should match the witness length of
* the card.
*/
nonce = malloc(witness_len);
if(!nonce) {
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,
"OOM allocating nonce (%"SC_FORMAT_LEN_SIZE_T"u : %"SC_FORMAT_LEN_SIZE_T"u)\n",
witness_len, plain_text_len);
r = SC_ERROR_INTERNAL;
goto err;
}
nonce_len = witness_len;
r = RAND_bytes(nonce, witness_len);
if(!r) {
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,
"Generating random for nonce (%"SC_FORMAT_LEN_SIZE_T"u : %"SC_FORMAT_LEN_SIZE_T"u)\n",
witness_len, plain_text_len);
r = SC_ERROR_INTERNAL;
goto err;
}
/* nonce for challenge */
tmplen = put_tag_and_len(0x81, witness_len, NULL);
/* plain text witness keep a length separate for the 0x7C tag */
tmplen += put_tag_and_len(0x80, witness_len, NULL);
tmplen2 = tmplen;
/* outside 7C tag with 81:80 as innards */
tmplen = put_tag_and_len(0x7C, tmplen, NULL);
built_len = tmplen;
/* Build the response buffer */
p = built = malloc(built_len);
if(!built) {
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "OOM Building witness response and challenge\n");
r = SC_ERROR_INTERNAL;
goto err;
}
p = built;
/* Start with the 7C Tag */
put_tag_and_len(0x7C, tmplen2, &p);
/* Add the DECRYPTED witness, tag 0x80 */
put_tag_and_len(0x80, witness_len, &p);
memcpy(p, plain_text, witness_len);
p += witness_len;
/* Add the challenge, tag 0x81 */
put_tag_and_len(0x81, witness_len, &p);
memcpy(p, nonce, witness_len);
/* Don't leak rbuf from above */
free(rbuf);
rbuf = NULL;
/* Send constructed data */
r = piv_general_io(card, 0x87, alg_id, key_ref, built,built_len, &rbuf, &rbuflen);
if (r < 0) goto err;
/* Remove the encompassing outer TLV of 0x7C and get the data */
body = sc_asn1_find_tag(card->ctx, rbuf,
r, 0x7C, &body_len);
if(!body) {
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "Could not find outer tag 0x7C in response");
r = SC_ERROR_INVALID_DATA;
goto err;
}
/* SP800-73 not clear if 80 or 82 */
challenge_response = sc_asn1_find_tag(card->ctx, body,
body_len, 0x82, &challenge_response_len);
if(!challenge_response) {
challenge_response = sc_asn1_find_tag(card->ctx, body,
body_len, 0x80, &challenge_response_len);
if(!challenge_response) {
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "Could not find tag 0x82 or 0x80 in response");
r = SC_ERROR_INVALID_DATA;
goto err;
}
}
/* Decrypt challenge and check against nonce */
decrypted_reponse = malloc(challenge_response_len);
if(!decrypted_reponse) {
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "OOM Allocating decryption buffer");
r = SC_ERROR_INVALID_DATA;
goto err;
}
EVP_CIPHER_CTX_cleanup(ctx);
if (!EVP_DecryptInit(ctx, cipher, key, NULL)) {
r = SC_ERROR_INTERNAL;
goto err;
}
EVP_CIPHER_CTX_set_padding(ctx,0);
tmp = decrypted_reponse;
if (!EVP_DecryptUpdate(ctx, tmp, &N, challenge_response, challenge_response_len)) {
r = SC_ERROR_INTERNAL;
goto err;
}
decrypted_reponse_len = tmplen = N;
tmp += tmplen;
if(!EVP_DecryptFinal(ctx, tmp, &N)) {
r = SC_ERROR_INTERNAL;
goto err;
}
tmplen = N;
decrypted_reponse_len += tmplen;
if (decrypted_reponse_len != nonce_len || memcmp(nonce, decrypted_reponse, nonce_len) != 0) {
sc_log(card->ctx,
"mutual authentication failed, card returned wrong value %"SC_FORMAT_LEN_SIZE_T"u:%"SC_FORMAT_LEN_SIZE_T"u",
decrypted_reponse_len, nonce_len);
r = SC_ERROR_DECRYPT_FAILED;
goto err;
}
r = SC_SUCCESS;
err:
if (ctx)
EVP_CIPHER_CTX_free(ctx);
if (locked)
sc_unlock(card);
if (rbuf)
free(rbuf);
if (decrypted_reponse)
free(decrypted_reponse);
if (built)
free(built);
if (plain_text)
free(plain_text);
if (nonce)
free(nonce);
if (key)
free(key);
#else
sc_log(card->ctx, "OpenSSL Required");
r = SC_ERROR_NOT_SUPPORTED;
#endif /* ENABLE_OPENSSL */
LOG_FUNC_RETURN(card->ctx, r);
}
/* Currently only used for card administration */
static int piv_general_external_authenticate(sc_card_t *card,
unsigned int key_ref, unsigned int alg_id)
{
int r;
#ifdef ENABLE_OPENSSL
int tmplen;
int outlen;
int locked = 0;
u8 *p;
u8 *rbuf = NULL;
u8 *key = NULL;
u8 *cypher_text = NULL;
u8 *output_buf = NULL;
const u8 *body = NULL;
const u8 *challenge_data = NULL;
size_t rbuflen;
size_t body_len;
size_t output_len;
size_t challenge_len;
size_t keylen = 0;
size_t cypher_text_len = 0;
u8 sbuf[255];
EVP_CIPHER_CTX * ctx = NULL;
const EVP_CIPHER *cipher;
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
ctx = EVP_CIPHER_CTX_new();
if (ctx == NULL) {
r = SC_ERROR_OUT_OF_MEMORY;
goto err;
}
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "Selected cipher for algorithm id: %02x\n", alg_id);
cipher = get_cipher_for_algo(alg_id);
if(!cipher) {
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "Invalid cipher selector, none found for: %02x\n", alg_id);
r = SC_ERROR_INVALID_ARGUMENTS;
goto err;
}
r = piv_get_key(card, alg_id, &key, &keylen);
if (r) {
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "Error getting General Auth key\n");
goto err;
}
r = sc_lock(card);
if (r != SC_SUCCESS) {
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "sc_lock failed\n");
goto err; /* cleanup */
}
locked = 1;
p = sbuf;
*p++ = 0x7C;
*p++ = 0x02;
*p++ = 0x81;
*p++ = 0x00;
/* get a challenge */
r = piv_general_io(card, 0x87, alg_id, key_ref, sbuf, p - sbuf, &rbuf, &rbuflen);
if (r < 0) {
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "Error getting Challenge\n");
goto err;
}
/*
* the value here corresponds with the response size, so we use this
* to alloc the response buffer, rather than re-computing it.
*/
output_len = r;
/* Remove the encompassing outer TLV of 0x7C and get the data */
body = sc_asn1_find_tag(card->ctx, rbuf,
r, 0x7C, &body_len);
if (!body) {
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "Invalid Challenge Data response of NULL\n");
r = SC_ERROR_INVALID_DATA;
goto err;
}
/* Get the challenge data indicated by the TAG 0x81 */
challenge_data = sc_asn1_find_tag(card->ctx, body,
body_len, 0x81, &challenge_len);
if (!challenge_data) {
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "Invalid Challenge Data none found in TLV\n");
r = SC_ERROR_INVALID_DATA;
goto err;
}
/* Store this to sanity check that plaintext length and cyphertext lengths match */
/* TODO is this required */
tmplen = challenge_len;
/* Encrypt the challenge with the secret */
if (!EVP_EncryptInit(ctx, cipher, key, NULL)) {
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "Encrypt fail\n");
r = SC_ERROR_INTERNAL;
goto err;
}
cypher_text = malloc(challenge_len);
if (!cypher_text) {
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "Could not allocate buffer for cipher text\n");
r = SC_ERROR_INTERNAL;
goto err;
}
EVP_CIPHER_CTX_set_padding(ctx,0);
if (!EVP_EncryptUpdate(ctx, cypher_text, &outlen, challenge_data, challenge_len)) {
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "Encrypt update fail\n");
r = SC_ERROR_INTERNAL;
goto err;
}
cypher_text_len += outlen;
if (!EVP_EncryptFinal(ctx, cypher_text + cypher_text_len, &outlen)) {
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "Final fail\n");
r = SC_ERROR_INTERNAL;
goto err;
}
cypher_text_len += outlen;
/*
* Actually perform the sanity check on lengths plaintext length vs
* encrypted length
*/
if (cypher_text_len != (size_t)tmplen) {
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "Length test fail\n");
r = SC_ERROR_INTERNAL;
goto err;
}
output_buf = malloc(output_len);
if(!output_buf) {
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "Could not allocate output buffer: %s\n",
strerror(errno));
r = SC_ERROR_INTERNAL;
goto err;
}
p = output_buf;
/*
* Build: 7C<len>[82<len><challenge>]
* Start off by capturing the data of the response:
* - 82<len><encrypted challenege response>
* Build the outside TLV (7C)
* Advance past that tag + len
* Build the body (82)
* memcopy the body past the 7C<len> portion
* Transmit
*/
tmplen = put_tag_and_len(0x82, cypher_text_len, NULL);
tmplen = put_tag_and_len(0x7C, tmplen, &p);
/* Build the 0x82 TLV and append to the 7C<len> tag */
tmplen += put_tag_and_len(0x82, cypher_text_len, &p);
memcpy(p, cypher_text, cypher_text_len);
p += cypher_text_len;
tmplen += cypher_text_len;
/* Sanity check the lengths again */
if(output_len != (size_t)tmplen) {
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "Allocated and computed lengths do not match! "
"Expected %"SC_FORMAT_LEN_SIZE_T"d, found: %d\n", output_len, tmplen);
r = SC_ERROR_INTERNAL;
goto err;
}
r = piv_general_io(card, 0x87, alg_id, key_ref, output_buf, output_len, NULL, NULL);
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "Got response challenge\n");
err:
if (ctx)
EVP_CIPHER_CTX_free(ctx);
if (locked)
sc_unlock(card);
if (key) {
sc_mem_clear(key, keylen);
free(key);
}
if (rbuf)
free(rbuf);
if (cypher_text)
free(cypher_text);
if (output_buf)
free(output_buf);
#else
sc_log(card->ctx, "OpenSSL Required");
r = SC_ERROR_NOT_SUPPORTED;
#endif /* ENABLE_OPENSSL */
LOG_FUNC_RETURN(card->ctx, r);
}
static int
piv_get_serial_nr_from_CHUI(sc_card_t* card, sc_serial_number_t* serial)
{
int r;
int i;
u8 gbits;
u8 *rbuf = NULL;
const u8 *body;
const u8 *fascn;
const u8 *guid;
size_t rbuflen = 0, bodylen, fascnlen, guidlen;
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
if (card->serialnr.len) {
*serial = card->serialnr;
LOG_FUNC_RETURN(card->ctx, SC_SUCCESS);
}
/*
* 800-73-3 Part 1 and CIO Council docs say for PIV Compatible cards
* the FASC-N Agency code should be 9999 and there should be a GUID
* based on RFC 4122. If GUID present and not zero
* we will use the GUID as the serial number.
*/
r = piv_get_cached_data(card, PIV_OBJ_CHUI, &rbuf, &rbuflen);
LOG_TEST_RET(card->ctx, r, "Failure retrieving CHUI");
r = SC_ERROR_INTERNAL;
if (rbuflen != 0) {
body = sc_asn1_find_tag(card->ctx, rbuf, rbuflen, 0x53, &bodylen); /* Pass the outer wrapper asn1 */
if (body != NULL && bodylen != 0) {
fascn = sc_asn1_find_tag(card->ctx, body, bodylen, 0x30, &fascnlen); /* Find the FASC-N data */
guid = sc_asn1_find_tag(card->ctx, body, bodylen, 0x34, &guidlen);
gbits = 0; /* if guid is valid, gbits will not be zero */
if (guid && guidlen == 16) {
for (i = 0; i < 16; i++) {
gbits = gbits | guid[i]; /* if all are zero, gbits will be zero */
}
}
sc_log(card->ctx,
"fascn=%p,fascnlen=%"SC_FORMAT_LEN_SIZE_T"u,guid=%p,guidlen=%"SC_FORMAT_LEN_SIZE_T"u,gbits=%2.2x",
fascn, fascnlen, guid, guidlen, gbits);
if (fascn && fascnlen == 25) {
/* test if guid and the fascn starts with ;9999 (in ISO 4bit + parity code) */
if (!(gbits && fascn[0] == 0xD4 && fascn[1] == 0xE7
&& fascn[2] == 0x39 && (fascn[3] | 0x7F) == 0xFF)) {
serial->len = fascnlen < SC_MAX_SERIALNR ? fascnlen : SC_MAX_SERIALNR;
memcpy (serial->value, fascn, serial->len);
r = SC_SUCCESS;
gbits = 0; /* set to skip using guid below */
}
}
if (guid && gbits) {
serial->len = guidlen < SC_MAX_SERIALNR ? guidlen : SC_MAX_SERIALNR;
memcpy (serial->value, guid, serial->len);
r = SC_SUCCESS;
}
}
}
card->serialnr = *serial;
LOG_FUNC_RETURN(card->ctx, r);
}
/*
* If the object can not be present on the card, because the History
* object is not present or the History object says its not present,
* return 1. If object may be present return 0.
* Cuts down on overhead, by not showing non existent objects to pkcs11
* The path for the object is passed in and the first 2 bytes are used.
* Note: If the History or Discovery object is not found the
* PIV_OBJ_CACHE_NOT_PRESENT is set, as older cards do not have these.
* pkcs15-piv.c calls this via cardctl.
*/
static int piv_is_object_present(sc_card_t *card, u8 *ptr)
{
piv_private_data_t * priv = PIV_DATA(card);
int r = 0;
int enumtag;
enumtag = piv_find_obj_by_containerid(card, ptr);
if (enumtag >= 0 && priv->obj_cache[enumtag].flags & PIV_OBJ_CACHE_NOT_PRESENT)
r = 1;
LOG_FUNC_RETURN(card->ctx, r);
}
/*
* NIST 800-73-3 allows the default pin to be the PIV application 0x80
* or the global pin for the card 0x00. Look at Discovery object to get this.
* called by pkcs15-piv.c via cardctl when setting up the pins.
*/
static int piv_get_pin_preference(sc_card_t *card, int *ptr)
{
piv_private_data_t * priv = PIV_DATA(card);
*ptr = priv->pin_preference;
LOG_FUNC_RETURN(card->ctx, SC_SUCCESS);
}
static int piv_card_ctl(sc_card_t *card, unsigned long cmd, void *ptr)
{
piv_private_data_t * priv = PIV_DATA(card);
u8 * opts; /* A or M, key_ref, alg_id */
LOG_FUNC_CALLED(card->ctx);
sc_log(card->ctx, "cmd=%ld ptr=%p", cmd, ptr);
if (priv == NULL) {
LOG_FUNC_RETURN(card->ctx, SC_ERROR_INTERNAL);
}
switch(cmd) {
case SC_CARDCTL_PIV_AUTHENTICATE:
opts = (u8 *)ptr;
switch (*opts) {
case 'A':
return piv_general_external_authenticate(card,
*(opts+1), *(opts+2));
break;
case 'M':
return piv_general_mutual_authenticate(card,
*(opts+1), *(opts+2));
break;
}
break;
case SC_CARDCTL_PIV_GENERATE_KEY:
return piv_generate_key(card,
(sc_cardctl_piv_genkey_info_t *) ptr);
break;
case SC_CARDCTL_GET_SERIALNR:
return piv_get_serial_nr_from_CHUI(card, (sc_serial_number_t *) ptr);
break;
case SC_CARDCTL_PIV_PIN_PREFERENCE:
return piv_get_pin_preference(card, ptr);
break;
case SC_CARDCTL_PIV_OBJECT_PRESENT:
return piv_is_object_present(card, ptr);
break;
}
LOG_FUNC_RETURN(card->ctx, SC_ERROR_NOT_SUPPORTED);
}
static int piv_get_challenge(sc_card_t *card, u8 *rnd, size_t len)
{
/* Dynamic Authentication Template (Challenge) */
u8 sbuf[] = {0x7c, 0x02, 0x81, 0x00};
u8 *rbuf = NULL;
const u8 *p;
size_t rbuf_len = 0, out_len = 0;
int r;
unsigned int tag, cla;
LOG_FUNC_CALLED(card->ctx);
/* NIST 800-73-3 says use 9B, previous verisons used 00 */
r = piv_general_io(card, 0x87, 0x00, 0x9B, sbuf, sizeof sbuf, &rbuf, &rbuf_len);
LOG_TEST_GOTO_ERR(card->ctx, r, "GENERAL AUTHENTICATE failed");
p = rbuf;
r = sc_asn1_read_tag(&p, rbuf_len, &cla, &tag, &out_len);
if (r < 0 || (cla|tag) != 0x7C) {
LOG_TEST_GOTO_ERR(card->ctx, SC_ERROR_INVALID_DATA, "Can't find Dynamic Authentication Template");
}
rbuf_len = out_len;
r = sc_asn1_read_tag(&p, rbuf_len, &cla, &tag, &out_len);
if (r < 0 || (cla|tag) != 0x81) {
LOG_TEST_GOTO_ERR(card->ctx, SC_ERROR_INVALID_DATA, "Can't find Challenge");
}
if (len < out_len) {
out_len = len;
}
memcpy(rnd, p, out_len);
r = (int) out_len;
err:
free(rbuf);
LOG_FUNC_RETURN(card->ctx, r);
}
static int
piv_set_security_env(sc_card_t *card, const sc_security_env_t *env, int se_num)
{
piv_private_data_t * priv = PIV_DATA(card);
int r = 0;
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
sc_log(card->ctx,
"flags=%08lx op=%d alg=%d algf=%08x algr=%08x kr0=%02x, krfl=%"SC_FORMAT_LEN_SIZE_T"u",
env->flags, env->operation, env->algorithm, env->algorithm_flags,
env->algorithm_ref, env->key_ref[0], env->key_ref_len);
priv->operation = env->operation;
priv->algorithm = env->algorithm;
if (env->algorithm == SC_ALGORITHM_RSA) {
priv->alg_id = 0x06; /* Say it is RSA, set 5, 6, 7 later */
} else if (env->algorithm == SC_ALGORITHM_EC) {
if (env->flags & SC_SEC_ENV_ALG_REF_PRESENT) {
switch (env->algorithm_ref) {
case 256:
priv->alg_id = 0x11; /* Say it is EC 256 */
priv->key_size = 256;
break;
case 384:
priv->alg_id = 0x14;
priv->key_size = 384;
break;
default:
r = SC_ERROR_NO_CARD_SUPPORT;
}
} else
r = SC_ERROR_NO_CARD_SUPPORT;
} else
r = SC_ERROR_NO_CARD_SUPPORT;
priv->key_ref = env->key_ref[0];
LOG_FUNC_RETURN(card->ctx, r);
}
static int piv_restore_security_env(sc_card_t *card, int se_num)
{
LOG_FUNC_CALLED(card->ctx);
LOG_FUNC_RETURN(card->ctx, SC_SUCCESS);
}
static int piv_validate_general_authentication(sc_card_t *card,
const u8 * data, size_t datalen,
u8 * out, size_t outlen)
{
piv_private_data_t * priv = PIV_DATA(card);
int r;
u8 *p;
const u8 *tag;
size_t taglen;
const u8 *body;
size_t bodylen;
unsigned int real_alg_id;
u8 sbuf[4096]; /* needs work. for 3072 keys, needs 384+10 or so */
u8 *rbuf = NULL;
size_t rbuflen = 0;
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
/* should assume large send data */
p = sbuf;
put_tag_and_len(0x7c, (2 + put_tag_and_len(0, datalen, NULL)) , &p);
put_tag_and_len(0x82, 0, &p);
if (priv->operation == SC_SEC_OPERATION_DERIVE
&& priv->algorithm == SC_ALGORITHM_EC)
put_tag_and_len(0x85, datalen, &p);
else
put_tag_and_len(0x81, datalen, &p);
memcpy(p, data, datalen);
p += datalen;
/*
* alg_id=06 is a place holder for all RSA keys.
* Derive the real alg_id based on the size of the
* the data, as we are always using raw mode.
* Non RSA keys needs some work in thia area.
*/
real_alg_id = priv->alg_id;
if (priv->alg_id == 0x06) {
switch (datalen) {
case 128: real_alg_id = 0x06; break;
case 256: real_alg_id = 0x07; break;
case 384: real_alg_id = 0x05; break;
default:
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, SC_ERROR_NO_CARD_SUPPORT);
}
}
/* EC alg_id was already set */
r = piv_general_io(card, 0x87, real_alg_id, priv->key_ref,
sbuf, p - sbuf, &rbuf, &rbuflen);
if ( r >= 0) {
body = sc_asn1_find_tag(card->ctx, rbuf, rbuflen, 0x7c, &bodylen);
if (body) {
tag = sc_asn1_find_tag(card->ctx, body, bodylen, 0x82, &taglen);
if (tag) {
memcpy(out, tag, taglen);
r = taglen;
}
} else
r = SC_ERROR_INVALID_DATA;
}
if (rbuf)
free(rbuf);
LOG_FUNC_RETURN(card->ctx, r);
}
static int
piv_compute_signature(sc_card_t *card, const u8 * data, size_t datalen,
u8 * out, size_t outlen)
{
piv_private_data_t * priv = PIV_DATA(card);
int r;
int i;
size_t nLen;
u8 rbuf[128]; /* For EC conversions 384 will fit */
size_t rbuflen = sizeof(rbuf);
const u8 * body;
size_t bodylen;
const u8 * tag;
size_t taglen;
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
/* The PIV returns a DER SEQUENCE{INTEGER, INTEGER}
* Which may have leading 00 to force positive
* TODO: -DEE should check if PKCS15 want the same
* But PKCS11 just wants 2* filed_length in bytes
* So we have to strip out the integers
* if present and pad on left if too short.
*/
if (priv->alg_id == 0x11 || priv->alg_id == 0x14 ) {
nLen = (priv->key_size + 7) / 8;
if (outlen < 2*nLen) {
sc_log(card->ctx,
" output too small for EC signature %"SC_FORMAT_LEN_SIZE_T"u < %"SC_FORMAT_LEN_SIZE_T"u",
outlen, 2 * nLen);
r = SC_ERROR_INVALID_DATA;
goto err;
}
memset(out, 0, outlen);
r = piv_validate_general_authentication(card, data, datalen, rbuf, rbuflen);
if (r < 0)
goto err;
if ( r >= 0) {
body = sc_asn1_find_tag(card->ctx, rbuf, rbuflen, 0x30, &bodylen);
for (i = 0; i<2; i++) {
if (body) {
tag = sc_asn1_find_tag(card->ctx, body, bodylen, 0x02, &taglen);
if (tag) {
bodylen -= taglen - (tag - body);
body = tag + taglen;
if (taglen > nLen) { /* drop leading 00 if present */
if (*tag != 0x00) {
r = SC_ERROR_INVALID_DATA;
goto err;
}
tag++;
taglen--;
}
memcpy(out + nLen*i + nLen - taglen , tag, taglen);
} else {
r = SC_ERROR_INVALID_DATA;
goto err;
}
} else {
r = SC_ERROR_INVALID_DATA;
goto err;
}
}
r = 2 * nLen;
}
} else { /* RSA is all set */
r = piv_validate_general_authentication(card, data, datalen, out, outlen);
}
err:
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, r);
}
static int
piv_decipher(sc_card_t *card, const u8 * data, size_t datalen, u8 * out, size_t outlen)
{
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, piv_validate_general_authentication(card, data, datalen, out, outlen));
}
/*
* the PIV-II does not always support files, but we will simulate
* files and reading/writing using get/put_data
* The path is the containerID number
* We can use this to determine the type of data requested, like a cert
* or pub key.
* We only support write from the piv_tool with file_out==NULL
* All other requests should be to read.
* Only if file_out != null, will we read to get length.
*/
static int piv_select_file(sc_card_t *card, const sc_path_t *in_path,
sc_file_t **file_out)
{
piv_private_data_t * priv = PIV_DATA(card);
int r;
int i;
const u8 *path;
int pathlen;
sc_file_t *file = NULL;
u8 * rbuf = NULL;
size_t rbuflen = 0;
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
path = in_path->value;
pathlen = in_path->len;
/* only support single EF in current application */
/*
* PIV emulates files, and only does so because sc_pkcs15_* uses
* select_file and read_binary. The emulation adds path emulated structures
* so piv_select_file will find it.
* there is no dir. Only direct access to emulated files
* thus opensc-tool and opensc-explorer can not read the emulated files
*/
if (memcmp(path, "\x3F\x00", 2) == 0) {
if (pathlen > 2) {
path += 2;
pathlen -= 2;
}
}
i = piv_find_obj_by_containerid(card, path);
if (i < 0)
LOG_FUNC_RETURN(card->ctx, SC_ERROR_FILE_NOT_FOUND);
/*
* pkcs15 will use a 2 byte path or a 4 byte path
* with cece added to path to request only the cert from the cert obj
* PIV "Container ID" is used as the path, and are two bytes long
*/
priv->return_only_cert = (pathlen == 4 && path[2] == 0xce && path[3] == 0xce);
priv->selected_obj = i;
priv->rwb_state = -1;
/* make it look like the file was found. */
/* We don't want to read it now unless we need the length */
if (file_out) {
/* we need to read it now, to get length into cache */
r = piv_get_cached_data(card, i, &rbuf, &rbuflen);
if (r < 0)
LOG_FUNC_RETURN(card->ctx, SC_ERROR_FILE_NOT_FOUND);
/* get the cert or the pub key out and into the cache too */
if (priv->return_only_cert || piv_objects[i].flags & PIV_OBJECT_TYPE_PUBKEY) {
r = piv_cache_internal_data(card, i);
if (r < 0)
LOG_FUNC_RETURN(card->ctx, r);
}
file = sc_file_new();
if (file == NULL)
LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY);
file->path = *in_path;
/* this could be like the FCI */
file->type = SC_FILE_TYPE_DF;
file->shareable = 0;
file->ef_structure = 0;
if (priv->return_only_cert)
file->size = priv->obj_cache[i].internal_obj_len;
else
file->size = priv->obj_cache[i].obj_len;
file->id = (piv_objects[i].containerid[0]<<8) + piv_objects[i].containerid[1];
*file_out = file;
}
LOG_FUNC_RETURN(card->ctx, SC_SUCCESS);
}
static int piv_parse_discovery(sc_card_t *card, u8 * rbuf, size_t rbuflen, int aid_only)
{
piv_private_data_t * priv = PIV_DATA(card);
int r = 0;
const u8 * body;
size_t bodylen;
const u8 * aid;
size_t aidlen;
const u8 * pinp;
size_t pinplen;
unsigned int cla_out, tag_out;
if (rbuflen != 0) {
body = rbuf;
if ((r = sc_asn1_read_tag(&body, rbuflen, &cla_out, &tag_out, &bodylen)) != SC_SUCCESS) {
sc_log(card->ctx, "DER problem %d",r);
r = SC_ERROR_INVALID_ASN1_OBJECT;
goto err;
}
sc_log(card->ctx,
"Discovery 0x%2.2x 0x%2.2x %p:%"SC_FORMAT_LEN_SIZE_T"u",
cla_out, tag_out, body, bodylen);
if ( cla_out+tag_out == 0x7E && body != NULL && bodylen != 0) {
aidlen = 0;
aid = sc_asn1_find_tag(card->ctx, body, bodylen, 0x4F, &aidlen);
sc_log(card->ctx, "Discovery aid=%p:%"SC_FORMAT_LEN_SIZE_T"u",
aid, aidlen);
if (aid == NULL || aidlen < piv_aids[0].len_short ||
memcmp(aid,piv_aids[0].value,piv_aids[0].len_short) != 0) { /*TODO look at long */
sc_log(card->ctx, "Discovery object not PIV");
r = SC_ERROR_INVALID_CARD; /* This is an error */
goto err;
}
if (aid_only == 0) {
pinp = sc_asn1_find_tag(card->ctx, body, bodylen, 0x5F2F, &pinplen);
sc_log(card->ctx,
"Discovery pinp=%p:%"SC_FORMAT_LEN_SIZE_T"u",
pinp, pinplen);
if (pinp && pinplen == 2) {
sc_log(card->ctx, "Discovery pinp flags=0x%2.2x 0x%2.2x",*pinp, *(pinp+1));
r = SC_SUCCESS;
if (*pinp == 0x60 && *(pinp+1) == 0x20) { /* use Global pin */
sc_log(card->ctx, "Pin Preference - Global");
priv->pin_preference = 0x00;
}
}
}
}
}
err:
LOG_FUNC_RETURN(card->ctx, r);
}
/* normal way to get the discovery object via cache */
static int piv_process_discovery(sc_card_t *card)
{
int r;
u8 * rbuf = NULL;
size_t rbuflen = 0;
r = piv_get_cached_data(card, PIV_OBJ_DISCOVERY, &rbuf, &rbuflen);
/* Note rbuf and rbuflen are now pointers into cache */
if (r < 0)
goto err;
sc_log(card->ctx, "Discovery = %p:%"SC_FORMAT_LEN_SIZE_T"u", rbuf,
rbuflen);
/* the object is now cached, see what we have */
r = piv_parse_discovery(card, rbuf, rbuflen, 0);
err:
LOG_FUNC_RETURN(card->ctx, r);
}
static int piv_find_discovery(sc_card_t *card)
{
int r = 0;
u8 rbuf[256];
size_t rbuflen = sizeof(rbuf);
u8 * arbuf = rbuf;
piv_private_data_t * priv = PIV_DATA(card);
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
/*
* During piv_match or piv_card_reader_lock_obtained,
* we use the discovery object to test if card present, and
* if PIV AID is active. So we can not use the cache
*/
/* If not valid, read, cache and test */
if (!(priv->obj_cache[PIV_OBJ_DISCOVERY].flags & PIV_OBJ_CACHE_VALID)) {
r = piv_process_discovery(card);
} else {
/* if already in cache,force read */
r = piv_get_data(card, PIV_OBJ_DISCOVERY, &arbuf, &rbuflen);
if (r >= 0)
/* make sure it is PIV AID */
r = piv_parse_discovery(card, rbuf, rbuflen, 1);
}
LOG_FUNC_RETURN(card->ctx, r);
}
/*
* The history object lists what retired keys and certs are on the card
* or listed in the offCardCertURL. The user may have read the offCardURL file,
* ahead of time, and if so will use it for the certs listed.
* TODO: -DEE
* If the offCardCertURL is not cached by the user, should we wget it here?
* Its may be out of scope to have OpenSC read the URL.
*/
static int
piv_process_history(sc_card_t *card)
{
piv_private_data_t * priv = PIV_DATA(card);
int r;
int i;
int enumtag;
u8 * rbuf = NULL;
size_t rbuflen = 0;
const u8 * body;
size_t bodylen;
const u8 * num;
size_t numlen;
const u8 * url = NULL;
size_t urllen;
u8 * ocfhfbuf = NULL;
unsigned int cla_out, tag_out;
size_t ocfhflen;
const u8 * seq;
const u8 * seqtag;
size_t seqlen;
const u8 * keyref;
size_t keyreflen;
const u8 * cert;
size_t certlen;
size_t certobjlen, i2;
u8 * certobj;
u8 * cp;
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
r = piv_get_cached_data(card, PIV_OBJ_HISTORY, &rbuf, &rbuflen);
if (r == SC_ERROR_FILE_NOT_FOUND)
r = 0; /* OK if not found */
if (r <= 0) {
priv->obj_cache[PIV_OBJ_HISTORY].flags |= PIV_OBJ_CACHE_NOT_PRESENT;
goto err; /* no file, must be pre 800-73-3 card and not on card */
}
/* the object is now cached, see what we have */
if (rbuflen != 0) {
body = rbuf;
if ((r = sc_asn1_read_tag(&body, rbuflen, &cla_out, &tag_out, &bodylen)) != SC_SUCCESS) {
sc_log(card->ctx, "DER problem %d",r);
r = SC_ERROR_INVALID_ASN1_OBJECT;
goto err;
}
if ( cla_out+tag_out == 0x53 && body != NULL && bodylen != 0) {
numlen = 0;
num = sc_asn1_find_tag(card->ctx, body, bodylen, 0xC1, &numlen);
if (num) {
if (numlen != 1 || *num > PIV_OBJ_RETIRED_X509_20-PIV_OBJ_RETIRED_X509_1+1) {
r = SC_ERROR_INTERNAL; /* TODO some other error */
goto err;
}
priv->keysWithOnCardCerts = *num;
}
numlen = 0;
num = sc_asn1_find_tag(card->ctx, body, bodylen, 0xC2, &numlen);
if (num) {
if (numlen != 1 || *num > PIV_OBJ_RETIRED_X509_20-PIV_OBJ_RETIRED_X509_1+1) {
r = SC_ERROR_INTERNAL; /* TODO some other error */
goto err;
}
priv->keysWithOffCardCerts = *num;
}
url = sc_asn1_find_tag(card->ctx, body, bodylen, 0xF3, &urllen);
if (url) {
priv->offCardCertURL = calloc(1,urllen+1);
if (priv->offCardCertURL == NULL)
LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY);
memcpy(priv->offCardCertURL, url, urllen);
}
}
else {
sc_log(card->ctx, "Problem with History object\n");
goto err;
}
}
sc_log(card->ctx, "History on=%d off=%d URL=%s",
priv->keysWithOnCardCerts, priv->keysWithOffCardCerts,
priv->offCardCertURL ? priv->offCardCertURL:"NONE");
/* now mark what objects are on the card */
for (i=0; i<priv->keysWithOnCardCerts; i++)
priv->obj_cache[PIV_OBJ_RETIRED_X509_1+i].flags &= ~PIV_OBJ_CACHE_NOT_PRESENT;
/*
* If user has gotten copy of the file from the offCardCertsURL,
* we will read in and add the certs to the cache as listed on
* the card. some of the certs may be on the card as well.
*
* Get file name from url. verify that the filename is valid
* The URL ends in a SHA1 string. We will use this as the filename
* in the directory used for the PKCS15 cache
*/
r = 0;
if (priv->offCardCertURL) {
char * fp;
char filename[PATH_MAX];
if (strncmp("http://", priv->offCardCertURL, 7)) {
r = SC_ERROR_INVALID_DATA;
goto err;
}
/* find the last / so we have the filename part */
fp = strrchr(priv->offCardCertURL + 7,'/');
if (fp == NULL) {
r = SC_ERROR_INVALID_DATA;
goto err;
}
fp++;
/* Use the same directory as used for other OpenSC cached items */
r = sc_get_cache_dir(card->ctx, filename, sizeof(filename) - strlen(fp) - 2);
if (r != SC_SUCCESS)
goto err;
#ifdef _WIN32
strcat(filename,"\\");
#else
strcat(filename,"/");
#endif
strcat(filename,fp);
r = piv_read_obj_from_file(card, filename,
&ocfhfbuf, &ocfhflen);
if (r == SC_ERROR_FILE_NOT_FOUND) {
r = 0;
goto err;
}
/*
* Its a seq of seq of a key ref and cert
*/
body = ocfhfbuf;
if (sc_asn1_read_tag(&body, ocfhflen, &cla_out,
&tag_out, &bodylen) != SC_SUCCESS
|| cla_out+tag_out != 0x30) {
sc_log(card->ctx, "DER problem");
r = SC_ERROR_INVALID_ASN1_OBJECT;
goto err;
}
seq = body;
while (bodylen > 0) {
seqtag = seq;
if (sc_asn1_read_tag(&seq, bodylen, &cla_out,
&tag_out, &seqlen) != SC_SUCCESS
|| cla_out+tag_out != 0x30) {
sc_log(card->ctx, "DER problem");
r = SC_ERROR_INVALID_ASN1_OBJECT;
goto err;
}
keyref = sc_asn1_find_tag(card->ctx, seq, seqlen, 0x04, &keyreflen);
if (!keyref || keyreflen != 1 ||
(*keyref < 0x82 || *keyref > 0x95)) {
sc_log(card->ctx, "DER problem");
r = SC_ERROR_INVALID_ASN1_OBJECT;
goto err;
}
cert = keyref + keyreflen;
certlen = seqlen - (cert - seq);
enumtag = PIV_OBJ_RETIRED_X509_1 + *keyref - 0x82;
/* now add the cert like another object */
i2 = put_tag_and_len(0x70,certlen, NULL)
+ put_tag_and_len(0x71, 1, NULL)
+ put_tag_and_len(0xFE, 0, NULL);
certobjlen = put_tag_and_len(0x53, i2, NULL);
certobj = malloc(certobjlen);
if (certobj == NULL) {
r = SC_ERROR_OUT_OF_MEMORY;
goto err;
}
cp = certobj;
put_tag_and_len(0x53, i2, &cp);
put_tag_and_len(0x70,certlen, &cp);
memcpy(cp, cert, certlen);
cp += certlen;
put_tag_and_len(0x71, 1,&cp);
*cp++ = 0x00;
put_tag_and_len(0xFE, 0, &cp);
priv->obj_cache[enumtag].obj_data = certobj;
priv->obj_cache[enumtag].obj_len = certobjlen;
priv->obj_cache[enumtag].flags |= PIV_OBJ_CACHE_VALID;
priv->obj_cache[enumtag].flags &= ~PIV_OBJ_CACHE_NOT_PRESENT;
r = piv_cache_internal_data(card, enumtag);
sc_log(card->ctx, "got internal r=%d",r);
certobj = NULL;
sc_log(card->ctx,
"Added from off card file #%d %p:%"SC_FORMAT_LEN_SIZE_T"u 0x%02X",
enumtag,
priv->obj_cache[enumtag].obj_data,
priv->obj_cache[enumtag].obj_len, *keyref);
bodylen -= (seqlen + seq - seqtag);
seq += seqlen;
}
}
err:
if (ocfhfbuf)
free(ocfhfbuf);
LOG_FUNC_RETURN(card->ctx, r);
}
static int
piv_finish(sc_card_t *card)
{
piv_private_data_t * priv = PIV_DATA(card);
int i;
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
if (priv) {
sc_file_free(priv->aid_file);
if (priv->w_buf)
free(priv->w_buf);
if (priv->offCardCertURL)
free(priv->offCardCertURL);
for (i = 0; i < PIV_OBJ_LAST_ENUM - 1; i++) {
sc_log(card->ctx,
"DEE freeing #%d, 0x%02x %p:%"SC_FORMAT_LEN_SIZE_T"u %p:%"SC_FORMAT_LEN_SIZE_T"u",
i, priv->obj_cache[i].flags,
priv->obj_cache[i].obj_data,
priv->obj_cache[i].obj_len,
priv->obj_cache[i].internal_obj_data,
priv->obj_cache[i].internal_obj_len);
if (priv->obj_cache[i].obj_data)
free(priv->obj_cache[i].obj_data);
if (priv->obj_cache[i].internal_obj_data)
free(priv->obj_cache[i].internal_obj_data);
}
free(priv);
card->drv_data = NULL; /* priv */
}
return 0;
}
static int piv_match_card(sc_card_t *card)
{
int r = 0;
/* piv_match_card may be called with card->type, set by opensc.conf */
/* user provide card type must be one we know */
switch (card->type) {
case -1:
case SC_CARD_TYPE_PIV_II_GENERIC:
case SC_CARD_TYPE_PIV_II_HIST:
case SC_CARD_TYPE_PIV_II_NEO:
case SC_CARD_TYPE_PIV_II_YUBIKEY4:
case SC_CARD_TYPE_PIV_II_GI_DE:
break;
default:
return 0; /* can not handle the card */
}
/* its one we know, or we can test for it in piv_init */
/*
* We will call piv_match_card_continued here then
* again in piv_init to avoid any issues with passing
* anything from piv_match_card
* to piv_init as had been done in the past
*/
r = piv_match_card_continued(card);
if (r == 1) {
/* clean up what we left in card */
sc_unlock(card);
piv_finish(card);
}
return r;
}
static int piv_match_card_continued(sc_card_t *card)
{
int i;
int type = -1;
piv_private_data_t *priv = NULL;
int saved_type = card->type;
/* Since we send an APDU, the card's logout function may be called...
* however it may be in dirty memory */
card->ops->logout = NULL;
/* piv_match_card may be called with card->type, set by opensc.conf */
/* user provide card type must be one we know */
switch (card->type) {
case -1:
case SC_CARD_TYPE_PIV_II_GENERIC:
case SC_CARD_TYPE_PIV_II_HIST:
case SC_CARD_TYPE_PIV_II_NEO:
case SC_CARD_TYPE_PIV_II_YUBIKEY4:
case SC_CARD_TYPE_PIV_II_GI_DE:
type = card->type;
break;
default:
return 0; /* can not handle the card */
}
if (type == -1) {
/*
*try to identify card by ATR or historical data in ATR
* currently all PIV card will respond to piv_find_aid
* the same. But in future may need to know card type first,
* so do it here.
*/
if (card->reader->atr_info.hist_bytes != NULL) {
if (card->reader->atr_info.hist_bytes_len == 8 &&
!(memcmp(card->reader->atr_info.hist_bytes, "Yubikey4", 8))) {
type = SC_CARD_TYPE_PIV_II_YUBIKEY4;
}
else if (card->reader->atr_info.hist_bytes_len >= 7 &&
!(memcmp(card->reader->atr_info.hist_bytes, "Yubikey", 7))) {
type = SC_CARD_TYPE_PIV_II_NEO;
}
/*
* https://csrc.nist.gov/csrc/media/projects/cryptographic-module-validation-program/documents/security-policies/140sp1239.pdf
* lists 2 ATRS with historical bytes:
* 73 66 74 65 2D 63 64 30 38 30
* 73 66 74 65 20 63 64 31 34 34
* will check for 73 66 74 65
*/
else if (card->reader->atr_info.hist_bytes_len >= 4 &&
!(memcmp(card->reader->atr_info.hist_bytes, "sfte", 4))) {
type = SC_CARD_TYPE_PIV_II_GI_DE;
}
else if (card->reader->atr_info.hist_bytes[0] == 0x80u) { /* compact TLV */
size_t datalen;
const u8 *data = sc_compacttlv_find_tag(card->reader->atr_info.hist_bytes + 1,
card->reader->atr_info.hist_bytes_len - 1,
0xF0, &datalen);
if (data != NULL) {
int k;
for (k = 0; piv_aids[k].len_long != 0; k++) {
if (datalen == piv_aids[k].len_long
&& !memcmp(data, piv_aids[k].value, datalen)) {
type = SC_CARD_TYPE_PIV_II_HIST;
break;
}
}
}
}
}
if (type == -1)
type = SC_CARD_TYPE_PIV_II_GENERIC;
}
/* allocate and init basic fields */
priv = calloc(1, sizeof(piv_private_data_t));
if (!priv)
LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY);
if (card->type == -1)
card->type = type;
card->drv_data = priv; /* will free if no match, or pass on to piv_init */
priv->aid_file = sc_file_new();
priv->selected_obj = -1;
priv->pin_preference = 0x80; /* 800-73-3 part 1, table 3 */
priv->logged_in = SC_PIN_STATE_UNKNOWN;
priv->tries_left = 10; /* will assume OK at start */
priv->pstate = PIV_STATE_MATCH;
/* Some objects will only be present if History object says so */
for (i=0; i < PIV_OBJ_LAST_ENUM -1; i++)
if(piv_objects[i].flags & PIV_OBJECT_NOT_PRESENT)
priv->obj_cache[i].flags |= PIV_OBJ_CACHE_NOT_PRESENT;
sc_lock(card);
/*
* detect if active AID is PIV. NIST 800-73 says Only one PIV application per card
* and PIV must be the default application
* This can avoid doing doing a select_aid and losing the login state on some cards
* We may get interference on some cards by other drivers trying SELECT_AID before
* we get to see if PIV application is still active.
* putting PIV driver first might help.
* This may fail if the wrong AID is active
*/
i = piv_find_discovery(card);
if (i < 0) {
/* Detect by selecting applet */
sc_file_t aidfile;
i = piv_find_aid(card, &aidfile);
}
if (i >= 0) {
/*
* We now know PIV AID is active, test DISCOVERY object
* Some CAC cards with PIV don't support DISCOVERY and return
* SC_ERROR_INCORRECT_PARAMETERS. Any error other then
* SC_ERROR_FILE_NOT_FOUND means we cannot use discovery
* to test for active AID.
*/
int i7e = piv_find_discovery(card);
if (i7e != 0 && i7e != SC_ERROR_FILE_NOT_FOUND) {
priv->card_issues |= CI_DISCOVERY_USELESS;
priv->obj_cache[PIV_OBJ_DISCOVERY].flags |= PIV_OBJ_CACHE_NOT_PRESENT;
}
}
if (i < 0) {
/* don't match. Does not have a PIV applet. */
sc_unlock(card);
piv_finish(card);
card->type = saved_type;
return 0;
}
/* Matched, caller will use or free priv and sc_lock as needed */
priv->pstate=PIV_STATE_INIT;
return 1; /* match */
}
static int piv_init(sc_card_t *card)
{
int r = 0;
piv_private_data_t * priv = NULL;
sc_apdu_t apdu;
unsigned long flags;
unsigned long ext_flags;
u8 yubico_version_buf[3];
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
/* continue the matching get a lock and the priv */
r = piv_match_card_continued(card);
if (r != 1) {
sc_log(card->ctx,"piv_match_card_continued failed");
piv_finish(card);
/* tell sc_connect_card to try other drivers */
LOG_FUNC_RETURN(card->ctx, SC_ERROR_INVALID_CARD);
}
priv = PIV_DATA(card);
/* can not force the PIV driver to use non-PIV cards as tested in piv_card_match_continued */
if (!priv || card->type == -1)
LOG_FUNC_RETURN(card->ctx, SC_ERROR_INVALID_CARD);
sc_log(card->ctx,
"Max send = %"SC_FORMAT_LEN_SIZE_T"u recv = %"SC_FORMAT_LEN_SIZE_T"u card->type = %d",
card->max_send_size, card->max_recv_size, card->type);
card->cla = 0x00;
if(card->name == NULL)
card->name = card->driver->name;
/*
* Set card_issues based on card type either set by piv_match_card or by opensc.conf
*/
switch(card->type) {
case SC_CARD_TYPE_PIV_II_NEO:
case SC_CARD_TYPE_PIV_II_YUBIKEY4:
sc_format_apdu(card, &apdu, SC_APDU_CASE_2_SHORT, 0xFD, 0x00, 0x00);
apdu.lc = 0;
apdu.data = NULL;
apdu.datalen = 0;
apdu.resp = yubico_version_buf;
apdu.resplen = sizeof(yubico_version_buf);
apdu.le = apdu.resplen;
r = sc_transmit_apdu(card, &apdu);
priv->yubico_version = (yubico_version_buf[0]<<16) | (yubico_version_buf[1] <<8) | yubico_version_buf[2];
sc_log(card->ctx, "Yubico card->type=%d, r=0x%08x version=0x%08x", card->type, r, priv->yubico_version);
break;
}
/*
* Set card_issues flags based card->type and version numbers if available.
*
* YubiKey NEO, Yubikey 4 and other devices with PIV applets, have compliance
* issues with the NIST 800-73-3 specs. The OpenSC developers do not have
* access to all the different devices or versions of the devices.
* Vendor and user input is welcome on any compliance issues.
*
* For the Yubico devices The assumption is also made that if a bug is
* fixed in a Yubico version that means it is fixed on both NEO and Yubikey 4.
*
* The flags CI_CANT_USE_GETDATA_FOR_STATE and CI_DISCOVERY_USELESS
* may be set earlier or later then in the following code.
*/
switch(card->type) {
case SC_CARD_TYPE_PIV_II_NEO:
priv->card_issues |= CI_NO_EC384
| CI_VERIFY_630X
| CI_OTHER_AID_LOSE_STATE
| CI_LEAKS_FILE_NOT_FOUND
| CI_NFC_EXPOSE_TOO_MUCH;
if (priv->yubico_version < 0x00040302)
priv->card_issues |= CI_VERIFY_LC0_FAIL;
break;
case SC_CARD_TYPE_PIV_II_YUBIKEY4:
priv->card_issues |= CI_OTHER_AID_LOSE_STATE
| CI_LEAKS_FILE_NOT_FOUND;
if (priv->yubico_version < 0x00040302)
priv->card_issues |= CI_VERIFY_LC0_FAIL;
break;
case SC_CARD_TYPE_PIV_II_HIST:
priv->card_issues |= 0;
break;
case SC_CARD_TYPE_PIV_II_GI_DE:
priv->card_issues |= CI_VERIFY_LC0_FAIL
| CI_PIV_AID_LOSE_STATE
| CI_OTHER_AID_LOSE_STATE;;
/* TODO may need more research */
break;
case SC_CARD_TYPE_PIV_II_GENERIC:
priv->card_issues |= CI_VERIFY_LC0_FAIL
| CI_OTHER_AID_LOSE_STATE;
/* TODO may need more research */
break;
default:
priv->card_issues = 0; /* opensc.conf may have it wrong, continue anyway */
sc_log(card->ctx, "Unknown PIV card->type %d", card->type);
card->type = SC_CARD_TYPE_PIV_II_BASE;
}
sc_log(card->ctx, "PIV card-type=%d card_issues=0x%08x", card->type, priv->card_issues);
priv->enumtag = piv_aids[0].enumtag;
/* PKCS#11 may try to generate session keys, and get confused
* if SC_ALGORITHM_ONBOARD_KEY_GEN is present
* piv-tool can still do this, just don't tell PKCS#11
*/
flags = SC_ALGORITHM_RSA_RAW;
_sc_card_add_rsa_alg(card, 1024, flags, 0); /* mandatory */
_sc_card_add_rsa_alg(card, 2048, flags, 0); /* optional */
_sc_card_add_rsa_alg(card, 3072, flags, 0); /* optional */
flags = SC_ALGORITHM_ECDSA_RAW | SC_ALGORITHM_ECDH_CDH_RAW | SC_ALGORITHM_ECDSA_HASH_NONE;
ext_flags = SC_ALGORITHM_EXT_EC_NAMEDCURVE | SC_ALGORITHM_EXT_EC_UNCOMPRESES;
_sc_card_add_ec_alg(card, 256, flags, ext_flags, NULL);
if (!(priv->card_issues & CI_NO_EC384))
_sc_card_add_ec_alg(card, 384, flags, ext_flags, NULL);
/* TODO may turn off SC_CARD_CAP_ISO7816_PIN_INFO later */
card->caps |= SC_CARD_CAP_RNG | SC_CARD_CAP_ISO7816_PIN_INFO;
/*
* 800-73-3 cards may have a history object and/or a discovery object
* We want to process them now as this has information on what
* keys and certs the card has and how the pin might be used.
* If they fail, ignore it there are optional and introduced in
* NIST 800-73-3 and NIST 800-73-2 so some older cards may
* not handle the request.
*/
piv_process_history(card);
piv_process_discovery(card);
priv->pstate=PIV_STATE_NORMAL;
sc_unlock(card) ; /* obtained in piv_match */
LOG_FUNC_RETURN(card->ctx, SC_SUCCESS);
}
static int piv_check_sw(struct sc_card *card, unsigned int sw1, unsigned int sw2)
{
struct sc_card_driver *iso_drv = sc_get_iso7816_driver();
int r;
piv_private_data_t * priv = PIV_DATA(card);
/* may be called before piv_init has allocated priv */
if (priv) {
/* need to save sw1 and sw2 if trying to determine card_state from pin_cmd */
if (priv->pin_cmd_verify) {
priv->pin_cmd_verify_sw1 = sw1;
priv->pin_cmd_verify_sw2 = sw2;
} else {
/* a command has completed and it is not verify */
/* If we are in a context_specific sequence, unlock */
if (priv->context_specific) {
sc_log(card->ctx,"Clearing CONTEXT_SPECIFIC lock");
priv->context_specific = 0;
sc_unlock(card);
}
}
if (priv->card_issues & CI_VERIFY_630X) {
/* Handle the Yubikey NEO or any other PIV card which returns in response to a verify
* 63 0X rather than 63 CX indicate the number of remaining PIN retries.
* Perhaps they misread the spec and thought 0xCX meant "clear" or "don't care", not a literal 0xC!
*/
if (priv->pin_cmd_verify && sw1 == 0x63U) {
priv->pin_cmd_verify_sw2 |= 0xC0U; /* make it easier to test in other code */
if ((sw2 & ~0x0fU) == 0x00U) {
sc_log(card->ctx, "Verification failed (remaining tries: %d)", (sw2 & 0x0f));
return SC_ERROR_PIN_CODE_INCORRECT;
/* this is what the iso_check_sw returns for 63 C0 */
}
}
}
}
r = iso_drv->ops->check_sw(card, sw1, sw2);
return r;
}
static int
piv_check_protected_objects(sc_card_t *card)
{
int r = 0;
int i;
piv_private_data_t * priv = PIV_DATA(card);
u8 buf[8]; /* tag of 53 with 82 xx xx will fit in 4 */
u8 * rbuf;
size_t buf_len;
static int protected_objects[] = {PIV_OBJ_PI, PIV_OBJ_CHF, PIV_OBJ_IRIS_IMAGE};
LOG_FUNC_CALLED(card->ctx);
/*
* routine only called from piv_pin_cmd after verify lc=0 did not return 90 00
* We will test for a protected object using GET DATA.
*
* Based on observations, of cards using the GET DATA APDU,
* SC_ERROR_SECURITY_STATUS_NOT_SATISFIED means the PIN not verified,
* SC_SUCCESS means PIN has been verified even if it has length 0
* SC_ERROR_FILE_NOT_FOUND (which is the bug) does not tell us anything
* about the state of the PIN and we will try the next object.
*
* If we can't determine the security state from this process,
* set card_issues CI_CANT_USE_GETDATA_FOR_STATE
* and return SC_ERROR_PIN_CODE_INCORRECT
* The circumvention is to add a dummy Printed Info object in the card.
* so we will have an object to test.
*
* We save the object's number to use in the future.
*
*/
if (priv->object_test_verify == 0) {
for (i = 0; i < (int)(sizeof(protected_objects)/sizeof(int)); i++) {
buf_len = sizeof(buf);
priv->pin_cmd_noparse = 1; /* tell piv_general_io dont need to parse at all. */
rbuf = buf;
r = piv_get_data(card, protected_objects[i], &rbuf, &buf_len);
priv->pin_cmd_noparse = 0;
/* TODO may need to check sw1 and sw2 to see what really happened */
if (r >= 0 || r == SC_ERROR_SECURITY_STATUS_NOT_SATISFIED) {
/* we can use this object next time if needed */
priv->object_test_verify = protected_objects[i];
break;
}
}
if (priv->object_test_verify == 0) {
/*
* none of the objects returned acceptable sw1, sw2
*/
sc_log(card->ctx, "No protected objects found, setting CI_CANT_USE_GETDATA_FOR_STATE");
priv->card_issues |= CI_CANT_USE_GETDATA_FOR_STATE;
r = SC_ERROR_PIN_CODE_INCORRECT;
}
} else {
/* use the one object we found earlier. Test is security status has changed */
buf_len = sizeof(buf);
priv->pin_cmd_noparse = 1; /* tell piv_general_io dont need to parse at all. */
rbuf = buf;
r = piv_get_data(card, priv->object_test_verify, &rbuf, &buf_len);
priv->pin_cmd_noparse = 0;
}
if (r == SC_ERROR_FILE_NOT_FOUND)
r = SC_ERROR_PIN_CODE_INCORRECT;
else if (r == SC_ERROR_SECURITY_STATUS_NOT_SATISFIED)
r = SC_ERROR_PIN_CODE_INCORRECT;
else if (r > 0)
r = SC_SUCCESS;
sc_log(card->ctx, "object_test_verify=%d, card_issues = 0x%08x", priv->object_test_verify, priv->card_issues);
LOG_FUNC_RETURN(card->ctx, r);
}
static int
piv_pin_cmd(sc_card_t *card, struct sc_pin_cmd_data *data, int *tries_left)
{
int r = 0;
piv_private_data_t * priv = PIV_DATA(card);
/* Extra validation of (new) PIN during a PIN change request, to
* ensure it's not outside the FIPS 201 4.1.6.1 (numeric only) and
* FIPS 140-2 (6 character minimum) requirements.
*/
struct sc_card_driver *iso_drv = sc_get_iso7816_driver();
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
sc_log(card->ctx, "piv_pin_cmd tries_left=%d, logged_in=%d", priv->tries_left, priv->logged_in);
if (data->cmd == SC_PIN_CMD_CHANGE) {
int i = 0;
if (data->pin2.len < 6) {
return SC_ERROR_INVALID_PIN_LENGTH;
}
for(i=0; i < data->pin2.len; ++i) {
if (!isdigit(data->pin2.data[i])) {
return SC_ERROR_INVALID_DATA;
}
}
}
priv->pin_cmd_verify_sw1 = 0x00U;
if (data->cmd == SC_PIN_CMD_GET_INFO) { /* fill in what we think it should be */
data->pin1.logged_in = priv->logged_in;
data->pin1.tries_left = priv->tries_left;
if (tries_left)
*tries_left = priv->tries_left;
/*
* If called to check on the login state for a context specific login
* return not logged in. Needed because of logic in e6f7373ef066
*/
if (data->pin_type == SC_AC_CONTEXT_SPECIFIC) {
data->pin1.logged_in = 0;
LOG_FUNC_RETURN(card->ctx, SC_SUCCESS);
}
if (priv->logged_in == SC_PIN_STATE_LOGGED_IN) {
/* Avoid status requests when the user is logged in to handle NIST
* 800-73-4 Part 2:
* The PKI cryptographic function (see Table 4b) is protected with
* a “PIN Always” or “OCC Always” access rule. In other words, the
* PIN or OCC data must be submitted and verified every time
* immediately before a digital signature key operation. This
* ensures cardholder participation every time the private key is
* used for digital signature generation */
LOG_FUNC_RETURN(card->ctx, SC_SUCCESS);
}
}
/*
* If this was for a CKU_CONTEXT_SPECFIC login, lock the card one more time.
* to avoid any interference from other applications.
* Sc_unlock will be called at a later time after the next card command
* that should be a crypto operation. If its not then it is a error by the
* calling application.
*/
if (data->cmd == SC_PIN_CMD_VERIFY && data->pin_type == SC_AC_CONTEXT_SPECIFIC) {
priv->context_specific = 1;
sc_log(card->ctx,"Starting CONTEXT_SPECIFIC verify");
sc_lock(card);
}
priv->pin_cmd_verify = 1; /* tell piv_check_sw its a verify to save sw1, sw2 */
r = iso_drv->ops->pin_cmd(card, data, tries_left);
priv->pin_cmd_verify = 0;
/* if verify failed, release the lock */
if (data->cmd == SC_PIN_CMD_VERIFY && r < 0 && priv->context_specific) {
sc_log(card->ctx,"Clearing CONTEXT_SPECIFIC");
priv->context_specific = 0;
sc_unlock(card);
}
/* if access to applet is know to be reset by other driver we select_aid and try again */
if ( priv->card_issues & CI_OTHER_AID_LOSE_STATE && priv->pin_cmd_verify_sw1 == 0x6DU) {
sc_log(card->ctx, "AID may be lost doing piv_find_aid and retry pin_cmd");
piv_find_aid(card, priv->aid_file); /* return not tested */
priv->pin_cmd_verify = 1; /* tell piv_check_sw its a verify to save sw1, sw2 */
r = iso_drv->ops->pin_cmd(card, data, tries_left);
priv->pin_cmd_verify = 0;
}
/* If verify worked, we are logged_in */
if (data->cmd == SC_PIN_CMD_VERIFY) {
if (r >= 0)
priv->logged_in = SC_PIN_STATE_LOGGED_IN;
else
priv->logged_in = SC_PIN_STATE_LOGGED_OUT;
}
/* Some cards never return 90 00 for SC_PIN_CMD_GET_INFO even if the card state is verified */
/* PR 797 has changed the return codes from pin_cmd, and added a data->pin1.logged_in flag */
if (data->cmd == SC_PIN_CMD_GET_INFO) {
if (priv->card_issues & CI_CANT_USE_GETDATA_FOR_STATE) {
sc_log(card->ctx, "CI_CANT_USE_GETDATA_FOR_STATE set, assume logged_in=%d", priv->logged_in);
data->pin1.logged_in = priv->logged_in; /* use what ever we saw last */
} else if (priv->card_issues & CI_VERIFY_LC0_FAIL
&& priv->pin_cmd_verify_sw1 == 0x63U ) { /* can not use modified return codes from iso->drv->pin_cmd */
/* try another method, looking at a protected object this may require adding one of these to NEO */
r = piv_check_protected_objects(card);
if (r == SC_SUCCESS)
data->pin1.logged_in = SC_PIN_STATE_LOGGED_IN;
else if (r == SC_ERROR_PIN_CODE_INCORRECT) {
if (priv->card_issues & CI_CANT_USE_GETDATA_FOR_STATE) { /* we still can not determine login state */
data->pin1.logged_in = priv->logged_in; /* may have be set from SC_PIN_CMD_VERIFY */
/* TODO a reset may have logged us out. need to detect resets */
} else {
data->pin1.logged_in = SC_PIN_STATE_LOGGED_OUT;
}
r = SC_SUCCESS;
}
}
priv->logged_in = data->pin1.logged_in;
priv->tries_left = data->pin1.tries_left;
}
sc_log(card->ctx, "piv_pin_cmd tries_left=%d, logged_in=%d",priv->tries_left, priv->logged_in);
LOG_FUNC_RETURN(card->ctx, r);
}
static int piv_logout(sc_card_t *card)
{
int r = SC_ERROR_NOT_SUPPORTED; /* TODO Some PIV cards may support a logout */
/* piv_private_data_t * priv = PIV_DATA(card); */
LOG_FUNC_CALLED(card->ctx);
/* TODO 800-73-3 does not define a logout, 800-73-4 does */
LOG_FUNC_RETURN(card->ctx, r);
}
/*
* Called when a sc_lock gets a reader lock and PCSC SCardBeginTransaction
* If SCardBeginTransaction may pass back tha a card reset was seen since
* the last transaction completed.
* There may have been one or more resets, by other card drivers in different
* processes, and they may have taken action already
* and changed the AID and or may have sent a VERIFY with PIN
* So test the state of the card.
* this is very similar to what the piv_match routine does,
*/
static int piv_card_reader_lock_obtained(sc_card_t *card, int was_reset)
{
int r = 0;
u8 temp[256];
size_t templen = sizeof(temp);
piv_private_data_t * priv = PIV_DATA(card); /* may be null */
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
/* We have a PCSC transaction and sc_lock */
if (priv == NULL || priv->pstate == PIV_STATE_MATCH) {
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,
priv ? "PIV_STATE_MATCH" : "priv==NULL");
r = 0; /* do nothing, piv_match will take care of it */
goto err;
}
/* make sure our application is active */
/* first see if AID is active AID by reading discovery object '7E' */
/* If not try selecting AID */
/* but if card does not support DISCOVERY object we can not use it */
if (priv->card_issues & CI_DISCOVERY_USELESS) {
r = SC_ERROR_NO_CARD_SUPPORT;
} else {
r = piv_find_discovery(card);
}
if (r < 0) {
if (was_reset > 0 || !(priv->card_issues & CI_PIV_AID_LOSE_STATE)) {
r = piv_select_aid(card, piv_aids[0].value, piv_aids[0].len_short, temp, &templen);
} else {
r = 0; /* cant do anything with this card, hope there was no interference */
}
}
if (r < 0) /* bad error return will show up in sc_lock as error*/
goto err;
if (was_reset > 0)
priv->logged_in = SC_PIN_STATE_UNKNOWN;
r = 0;
err:
LOG_FUNC_RETURN(card->ctx, r);
}
static struct sc_card_driver * sc_get_driver(void)
{
struct sc_card_driver *iso_drv = sc_get_iso7816_driver();
piv_ops = *iso_drv->ops;
piv_ops.match_card = piv_match_card;
piv_ops.init = piv_init;
piv_ops.finish = piv_finish;
piv_ops.select_file = piv_select_file; /* must use get/put, could emulate? */
piv_ops.get_challenge = piv_get_challenge;
piv_ops.logout = piv_logout;
piv_ops.read_binary = piv_read_binary;
piv_ops.write_binary = piv_write_binary;
piv_ops.set_security_env = piv_set_security_env;
piv_ops.restore_security_env = piv_restore_security_env;
piv_ops.compute_signature = piv_compute_signature;
piv_ops.decipher = piv_decipher;
piv_ops.check_sw = piv_check_sw;
piv_ops.card_ctl = piv_card_ctl;
piv_ops.pin_cmd = piv_pin_cmd;
piv_ops.card_reader_lock_obtained = piv_card_reader_lock_obtained;
return &piv_drv;
}
#if 1
struct sc_card_driver * sc_get_piv_driver(void)
{
return sc_get_driver();
}
#endif
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_351_11 |
crossvul-cpp_data_bad_2661_0 | /* $NetBSD: print-telnet.c,v 1.2 1999/10/11 12:40:12 sjg Exp $ */
/*-
* Copyright (c) 1997, 1998 The NetBSD Foundation, Inc.
* All rights reserved.
*
* This code is derived from software contributed to The NetBSD Foundation
* by Simon J. Gerraty.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by the NetBSD
* Foundation, Inc. and its contributors.
* 4. Neither the name of The NetBSD Foundation 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 NETBSD FOUNDATION, INC. AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
/*
* @(#)Copyright (c) 1994, Simon J. Gerraty.
*
* This is free software. It comes with NO WARRANTY.
* Permission to use, modify and distribute this source code
* is granted subject to the following conditions.
* 1/ that the above copyright notice and this notice
* are preserved in all copies.
*/
/* \summary: Telnet option printer */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <netdissect-stdinc.h>
#include <stdio.h>
#include "netdissect.h"
static const char tstr[] = " [|telnet]";
#define TELCMDS
#define TELOPTS
/* NetBSD: telnet.h,v 1.9 2001/06/11 01:50:50 wiz Exp */
/*
* Definitions for the TELNET protocol.
*/
#define IAC 255 /* interpret as command: */
#define DONT 254 /* you are not to use option */
#define DO 253 /* please, you use option */
#define WONT 252 /* I won't use option */
#define WILL 251 /* I will use option */
#define SB 250 /* interpret as subnegotiation */
#define GA 249 /* you may reverse the line */
#define EL 248 /* erase the current line */
#define EC 247 /* erase the current character */
#define AYT 246 /* are you there */
#define AO 245 /* abort output--but let prog finish */
#define IP 244 /* interrupt process--permanently */
#define BREAK 243 /* break */
#define DM 242 /* data mark--for connect. cleaning */
#define NOP 241 /* nop */
#define SE 240 /* end sub negotiation */
#define EOR 239 /* end of record (transparent mode) */
#define ABORT 238 /* Abort process */
#define SUSP 237 /* Suspend process */
#define xEOF 236 /* End of file: EOF is already used... */
#define SYNCH 242 /* for telfunc calls */
#ifdef TELCMDS
static const char *telcmds[] = {
"EOF", "SUSP", "ABORT", "EOR",
"SE", "NOP", "DMARK", "BRK", "IP", "AO", "AYT", "EC",
"EL", "GA", "SB", "WILL", "WONT", "DO", "DONT", "IAC", 0,
};
#else
extern char *telcmds[];
#endif
#define TELCMD_FIRST xEOF
#define TELCMD_LAST IAC
#define TELCMD_OK(x) ((unsigned int)(x) <= TELCMD_LAST && \
(unsigned int)(x) >= TELCMD_FIRST)
#define TELCMD(x) telcmds[(x)-TELCMD_FIRST]
/* telnet options */
#define TELOPT_BINARY 0 /* 8-bit data path */
#define TELOPT_ECHO 1 /* echo */
#define TELOPT_RCP 2 /* prepare to reconnect */
#define TELOPT_SGA 3 /* suppress go ahead */
#define TELOPT_NAMS 4 /* approximate message size */
#define TELOPT_STATUS 5 /* give status */
#define TELOPT_TM 6 /* timing mark */
#define TELOPT_RCTE 7 /* remote controlled transmission and echo */
#define TELOPT_NAOL 8 /* negotiate about output line width */
#define TELOPT_NAOP 9 /* negotiate about output page size */
#define TELOPT_NAOCRD 10 /* negotiate about CR disposition */
#define TELOPT_NAOHTS 11 /* negotiate about horizontal tabstops */
#define TELOPT_NAOHTD 12 /* negotiate about horizontal tab disposition */
#define TELOPT_NAOFFD 13 /* negotiate about formfeed disposition */
#define TELOPT_NAOVTS 14 /* negotiate about vertical tab stops */
#define TELOPT_NAOVTD 15 /* negotiate about vertical tab disposition */
#define TELOPT_NAOLFD 16 /* negotiate about output LF disposition */
#define TELOPT_XASCII 17 /* extended ascic character set */
#define TELOPT_LOGOUT 18 /* force logout */
#define TELOPT_BM 19 /* byte macro */
#define TELOPT_DET 20 /* data entry terminal */
#define TELOPT_SUPDUP 21 /* supdup protocol */
#define TELOPT_SUPDUPOUTPUT 22 /* supdup output */
#define TELOPT_SNDLOC 23 /* send location */
#define TELOPT_TTYPE 24 /* terminal type */
#define TELOPT_EOR 25 /* end or record */
#define TELOPT_TUID 26 /* TACACS user identification */
#define TELOPT_OUTMRK 27 /* output marking */
#define TELOPT_TTYLOC 28 /* terminal location number */
#define TELOPT_3270REGIME 29 /* 3270 regime */
#define TELOPT_X3PAD 30 /* X.3 PAD */
#define TELOPT_NAWS 31 /* window size */
#define TELOPT_TSPEED 32 /* terminal speed */
#define TELOPT_LFLOW 33 /* remote flow control */
#define TELOPT_LINEMODE 34 /* Linemode option */
#define TELOPT_XDISPLOC 35 /* X Display Location */
#define TELOPT_OLD_ENVIRON 36 /* Old - Environment variables */
#define TELOPT_AUTHENTICATION 37/* Authenticate */
#define TELOPT_ENCRYPT 38 /* Encryption option */
#define TELOPT_NEW_ENVIRON 39 /* New - Environment variables */
#define TELOPT_EXOPL 255 /* extended-options-list */
#define NTELOPTS (1+TELOPT_NEW_ENVIRON)
#ifdef TELOPTS
static const char *telopts[NTELOPTS+1] = {
"BINARY", "ECHO", "RCP", "SUPPRESS GO AHEAD", "NAME",
"STATUS", "TIMING MARK", "RCTE", "NAOL", "NAOP",
"NAOCRD", "NAOHTS", "NAOHTD", "NAOFFD", "NAOVTS",
"NAOVTD", "NAOLFD", "EXTEND ASCII", "LOGOUT", "BYTE MACRO",
"DATA ENTRY TERMINAL", "SUPDUP", "SUPDUP OUTPUT",
"SEND LOCATION", "TERMINAL TYPE", "END OF RECORD",
"TACACS UID", "OUTPUT MARKING", "TTYLOC",
"3270 REGIME", "X.3 PAD", "NAWS", "TSPEED", "LFLOW",
"LINEMODE", "XDISPLOC", "OLD-ENVIRON", "AUTHENTICATION",
"ENCRYPT", "NEW-ENVIRON",
0,
};
#define TELOPT_FIRST TELOPT_BINARY
#define TELOPT_LAST TELOPT_NEW_ENVIRON
#define TELOPT_OK(x) ((unsigned int)(x) <= TELOPT_LAST)
#define TELOPT(x) telopts[(x)-TELOPT_FIRST]
#endif
/* sub-option qualifiers */
#define TELQUAL_IS 0 /* option is... */
#define TELQUAL_SEND 1 /* send option */
#define TELQUAL_INFO 2 /* ENVIRON: informational version of IS */
#define TELQUAL_REPLY 2 /* AUTHENTICATION: client version of IS */
#define TELQUAL_NAME 3 /* AUTHENTICATION: client version of IS */
#define LFLOW_OFF 0 /* Disable remote flow control */
#define LFLOW_ON 1 /* Enable remote flow control */
#define LFLOW_RESTART_ANY 2 /* Restart output on any char */
#define LFLOW_RESTART_XON 3 /* Restart output only on XON */
/*
* LINEMODE suboptions
*/
#define LM_MODE 1
#define LM_FORWARDMASK 2
#define LM_SLC 3
#define MODE_EDIT 0x01
#define MODE_TRAPSIG 0x02
#define MODE_ACK 0x04
#define MODE_SOFT_TAB 0x08
#define MODE_LIT_ECHO 0x10
#define MODE_MASK 0x1f
#define SLC_SYNCH 1
#define SLC_BRK 2
#define SLC_IP 3
#define SLC_AO 4
#define SLC_AYT 5
#define SLC_EOR 6
#define SLC_ABORT 7
#define SLC_EOF 8
#define SLC_SUSP 9
#define SLC_EC 10
#define SLC_EL 11
#define SLC_EW 12
#define SLC_RP 13
#define SLC_LNEXT 14
#define SLC_XON 15
#define SLC_XOFF 16
#define SLC_FORW1 17
#define SLC_FORW2 18
#define SLC_MCL 19
#define SLC_MCR 20
#define SLC_MCWL 21
#define SLC_MCWR 22
#define SLC_MCBOL 23
#define SLC_MCEOL 24
#define SLC_INSRT 25
#define SLC_OVER 26
#define SLC_ECR 27
#define SLC_EWR 28
#define SLC_EBOL 29
#define SLC_EEOL 30
#define NSLC 30
/*
* For backwards compatibility, we define SLC_NAMES to be the
* list of names if SLC_NAMES is not defined.
*/
#define SLC_NAMELIST "0", "SYNCH", "BRK", "IP", "AO", "AYT", "EOR", \
"ABORT", "EOF", "SUSP", "EC", "EL", "EW", "RP", \
"LNEXT", "XON", "XOFF", "FORW1", "FORW2", \
"MCL", "MCR", "MCWL", "MCWR", "MCBOL", \
"MCEOL", "INSRT", "OVER", "ECR", "EWR", \
"EBOL", "EEOL", \
0,
#ifdef SLC_NAMES
const char *slc_names[] = {
SLC_NAMELIST
};
#else
extern char *slc_names[];
#define SLC_NAMES SLC_NAMELIST
#endif
#define SLC_NAME_OK(x) ((unsigned int)(x) <= NSLC)
#define SLC_NAME(x) slc_names[x]
#define SLC_NOSUPPORT 0
#define SLC_CANTCHANGE 1
#define SLC_VARIABLE 2
#define SLC_DEFAULT 3
#define SLC_LEVELBITS 0x03
#define SLC_FUNC 0
#define SLC_FLAGS 1
#define SLC_VALUE 2
#define SLC_ACK 0x80
#define SLC_FLUSHIN 0x40
#define SLC_FLUSHOUT 0x20
#define OLD_ENV_VAR 1
#define OLD_ENV_VALUE 0
#define NEW_ENV_VAR 0
#define NEW_ENV_VALUE 1
#define ENV_ESC 2
#define ENV_USERVAR 3
/*
* AUTHENTICATION suboptions
*/
/*
* Who is authenticating who ...
*/
#define AUTH_WHO_CLIENT 0 /* Client authenticating server */
#define AUTH_WHO_SERVER 1 /* Server authenticating client */
#define AUTH_WHO_MASK 1
#define AUTHTYPE_NULL 0
#define AUTHTYPE_KERBEROS_V4 1
#define AUTHTYPE_KERBEROS_V5 2
#define AUTHTYPE_SPX 3
#define AUTHTYPE_MINK 4
#define AUTHTYPE_CNT 5
#define AUTHTYPE_TEST 99
#ifdef AUTH_NAMES
const char *authtype_names[] = {
"NULL", "KERBEROS_V4", "KERBEROS_V5", "SPX", "MINK", 0,
};
#else
extern char *authtype_names[];
#endif
#define AUTHTYPE_NAME_OK(x) ((unsigned int)(x) < AUTHTYPE_CNT)
#define AUTHTYPE_NAME(x) authtype_names[x]
/*
* ENCRYPTion suboptions
*/
#define ENCRYPT_IS 0 /* I pick encryption type ... */
#define ENCRYPT_SUPPORT 1 /* I support encryption types ... */
#define ENCRYPT_REPLY 2 /* Initial setup response */
#define ENCRYPT_START 3 /* Am starting to send encrypted */
#define ENCRYPT_END 4 /* Am ending encrypted */
#define ENCRYPT_REQSTART 5 /* Request you start encrypting */
#define ENCRYPT_REQEND 6 /* Request you send encrypting */
#define ENCRYPT_ENC_KEYID 7
#define ENCRYPT_DEC_KEYID 8
#define ENCRYPT_CNT 9
#define ENCTYPE_ANY 0
#define ENCTYPE_DES_CFB64 1
#define ENCTYPE_DES_OFB64 2
#define ENCTYPE_CNT 3
#ifdef ENCRYPT_NAMES
const char *encrypt_names[] = {
"IS", "SUPPORT", "REPLY", "START", "END",
"REQUEST-START", "REQUEST-END", "ENC-KEYID", "DEC-KEYID",
0,
};
const char *enctype_names[] = {
"ANY", "DES_CFB64", "DES_OFB64", 0,
};
#else
extern char *encrypt_names[];
extern char *enctype_names[];
#endif
#define ENCRYPT_NAME_OK(x) ((unsigned int)(x) < ENCRYPT_CNT)
#define ENCRYPT_NAME(x) encrypt_names[x]
#define ENCTYPE_NAME_OK(x) ((unsigned int)(x) < ENCTYPE_CNT)
#define ENCTYPE_NAME(x) enctype_names[x]
/* normal */
static const char *cmds[] = {
"IS", "SEND", "INFO",
};
/* 37: Authentication */
static const char *authcmd[] = {
"IS", "SEND", "REPLY", "NAME",
};
static const char *authtype[] = {
"NULL", "KERBEROS_V4", "KERBEROS_V5", "SPX", "MINK",
"SRP", "RSA", "SSL", NULL, NULL,
"LOKI", "SSA", "KEA_SJ", "KEA_SJ_INTEG", "DSS",
"NTLM",
};
/* 38: Encryption */
static const char *enccmd[] = {
"IS", "SUPPORT", "REPLY", "START", "END",
"REQUEST-START", "REQUEST-END", "END_KEYID", "DEC_KEYID",
};
static const char *enctype[] = {
"NULL", "DES_CFB64", "DES_OFB64", "DES3_CFB64", "DES3_OFB64",
NULL, "CAST5_40_CFB64", "CAST5_40_OFB64", "CAST128_CFB64", "CAST128_OFB64",
};
#define STR_OR_ID(x, tab) \
(((x) < sizeof(tab)/sizeof(tab[0]) && tab[(x)]) ? tab[(x)] : numstr(x))
static char *
numstr(int x)
{
static char buf[20];
snprintf(buf, sizeof(buf), "%#x", x);
return buf;
}
/* sp points to IAC byte */
static int
telnet_parse(netdissect_options *ndo, const u_char *sp, u_int length, int print)
{
int i, x;
u_int c;
const u_char *osp, *p;
#define FETCH(c, sp, length) \
do { \
if (length < 1) \
goto pktend; \
ND_TCHECK(*sp); \
c = *sp++; \
length--; \
} while (0)
osp = sp;
FETCH(c, sp, length);
if (c != IAC)
goto pktend;
FETCH(c, sp, length);
if (c == IAC) { /* <IAC><IAC>! */
if (print)
ND_PRINT((ndo, "IAC IAC"));
goto done;
}
i = c - TELCMD_FIRST;
if (i < 0 || i > IAC - TELCMD_FIRST)
goto pktend;
switch (c) {
case DONT:
case DO:
case WONT:
case WILL:
case SB:
/* DONT/DO/WONT/WILL x */
FETCH(x, sp, length);
if (x >= 0 && x < NTELOPTS) {
if (print)
ND_PRINT((ndo, "%s %s", telcmds[i], telopts[x]));
} else {
if (print)
ND_PRINT((ndo, "%s %#x", telcmds[i], x));
}
if (c != SB)
break;
/* IAC SB .... IAC SE */
p = sp;
while (length > (u_int)(p + 1 - sp)) {
ND_TCHECK2(*p, 2);
if (p[0] == IAC && p[1] == SE)
break;
p++;
}
if (*p != IAC)
goto pktend;
switch (x) {
case TELOPT_AUTHENTICATION:
if (p <= sp)
break;
FETCH(c, sp, length);
if (print)
ND_PRINT((ndo, " %s", STR_OR_ID(c, authcmd)));
if (p <= sp)
break;
FETCH(c, sp, length);
if (print)
ND_PRINT((ndo, " %s", STR_OR_ID(c, authtype)));
break;
case TELOPT_ENCRYPT:
if (p <= sp)
break;
FETCH(c, sp, length);
if (print)
ND_PRINT((ndo, " %s", STR_OR_ID(c, enccmd)));
if (p <= sp)
break;
FETCH(c, sp, length);
if (print)
ND_PRINT((ndo, " %s", STR_OR_ID(c, enctype)));
break;
default:
if (p <= sp)
break;
FETCH(c, sp, length);
if (print)
ND_PRINT((ndo, " %s", STR_OR_ID(c, cmds)));
break;
}
while (p > sp) {
FETCH(x, sp, length);
if (print)
ND_PRINT((ndo, " %#x", x));
}
/* terminating IAC SE */
if (print)
ND_PRINT((ndo, " SE"));
sp += 2;
break;
default:
if (print)
ND_PRINT((ndo, "%s", telcmds[i]));
goto done;
}
done:
return sp - osp;
trunc:
ND_PRINT((ndo, "%s", tstr));
pktend:
return -1;
#undef FETCH
}
void
telnet_print(netdissect_options *ndo, const u_char *sp, u_int length)
{
int first = 1;
const u_char *osp;
int l;
osp = sp;
ND_TCHECK(*sp);
while (length > 0 && *sp == IAC) {
/*
* Parse the Telnet command without printing it,
* to determine its length.
*/
l = telnet_parse(ndo, sp, length, 0);
if (l < 0)
break;
/*
* now print it
*/
if (ndo->ndo_Xflag && 2 < ndo->ndo_vflag) {
if (first)
ND_PRINT((ndo, "\nTelnet:"));
hex_print_with_offset(ndo, "\n", sp, l, sp - osp);
if (l > 8)
ND_PRINT((ndo, "\n\t\t\t\t"));
else
ND_PRINT((ndo, "%*s\t", (8 - l) * 3, ""));
} else
ND_PRINT((ndo, "%s", (first) ? " [telnet " : ", "));
(void)telnet_parse(ndo, sp, length, 1);
first = 0;
sp += l;
length -= l;
ND_TCHECK(*sp);
}
if (!first) {
if (ndo->ndo_Xflag && 2 < ndo->ndo_vflag)
ND_PRINT((ndo, "\n"));
else
ND_PRINT((ndo, "]"));
}
return;
trunc:
ND_PRINT((ndo, "%s", tstr));
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_2661_0 |
crossvul-cpp_data_good_2612_0 | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% PPPP N N GGGG %
% P P NN N G %
% PPPP N N N G GG %
% P N NN G G %
% P N N GGG %
% %
% %
% Read/Write Portable Network Graphics Image Format %
% %
% Software Design %
% Cristy %
% Glenn Randers-Pehrson %
% November 1997 %
% %
% %
% Copyright 1999-2017 ImageMagick Studio LLC, a non-profit organization %
% dedicated to making software imaging solutions freely available. %
% %
% You may not use this file except in compliance with the License. You may %
% obtain a copy of the License at %
% %
% https://www.imagemagick.org/script/license.php %
% %
% Unless required by applicable law or agreed to in writing, software %
% distributed under the License is distributed on an "AS IS" BASIS, %
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %
% See the License for the specific language governing permissions and %
% limitations under the License. %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%
*/
/*
Include declarations.
*/
#include "magick/studio.h"
#include "magick/artifact.h"
#include "magick/attribute.h"
#include "magick/blob.h"
#include "magick/blob-private.h"
#include "magick/cache.h"
#include "magick/channel.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/enhance.h"
#include "magick/exception.h"
#include "magick/exception-private.h"
#include "magick/geometry.h"
#include "magick/histogram.h"
#include "magick/image.h"
#include "magick/image-private.h"
#include "magick/layer.h"
#include "magick/list.h"
#include "magick/log.h"
#include "magick/magick.h"
#include "magick/memory_.h"
#include "magick/module.h"
#include "magick/monitor.h"
#include "magick/monitor-private.h"
#include "magick/option.h"
#include "magick/pixel-accessor.h"
#include "magick/quantum-private.h"
#include "magick/profile.h"
#include "magick/property.h"
#include "magick/resource_.h"
#include "magick/semaphore.h"
#include "magick/static.h"
#include "magick/statistic.h"
#include "magick/string_.h"
#include "magick/string-private.h"
#include "magick/transform.h"
#include "magick/utility.h"
#if defined(MAGICKCORE_PNG_DELEGATE)
/* Suppress libpng pedantic warnings that were added in
* libpng-1.2.41 and libpng-1.4.0. If you are working on
* migration to libpng-1.5, remove these defines and then
* fix any code that generates warnings.
*/
/* #define PNG_DEPRECATED Use of this function is deprecated */
/* #define PNG_USE_RESULT The result of this function must be checked */
/* #define PNG_NORETURN This function does not return */
/* #define PNG_ALLOCATED The result of the function is new memory */
/* #define PNG_DEPSTRUCT Access to this struct member is deprecated */
/* PNG_PTR_NORETURN does not work on some platforms, in libpng-1.5.x */
#define PNG_PTR_NORETURN
#include "png.h"
#include "zlib.h"
/* ImageMagick differences */
#define first_scene scene
#if PNG_LIBPNG_VER > 10011
/*
Optional declarations. Define or undefine them as you like.
*/
/* #define PNG_DEBUG -- turning this on breaks VisualC compiling */
/*
Features under construction. Define these to work on them.
*/
#undef MNG_OBJECT_BUFFERS
#undef MNG_BASI_SUPPORTED
#define MNG_COALESCE_LAYERS /* In 5.4.4, this interfered with MMAP'ed files. */
#define MNG_INSERT_LAYERS /* Troublesome, but seem to work as of 5.4.4 */
#if defined(MAGICKCORE_JPEG_DELEGATE)
# define JNG_SUPPORTED /* Not finished as of 5.5.2. See "To do" comments. */
#endif
#if !defined(RGBColorMatchExact)
#define IsPNGColorEqual(color,target) \
(((color).red == (target).red) && \
((color).green == (target).green) && \
((color).blue == (target).blue))
#endif
/* Table of recognized sRGB ICC profiles */
struct sRGB_info_struct
{
png_uint_32 len;
png_uint_32 crc;
png_byte intent;
};
const struct sRGB_info_struct sRGB_info[] =
{
/* ICC v2 perceptual sRGB_IEC61966-2-1_black_scaled.icc */
{ 3048, 0x3b8772b9UL, 0},
/* ICC v2 relative sRGB_IEC61966-2-1_no_black_scaling.icc */
{ 3052, 0x427ebb21UL, 1},
/* ICC v4 perceptual sRGB_v4_ICC_preference_displayclass.icc */
{60988, 0x306fd8aeUL, 0},
/* ICC v4 perceptual sRGB_v4_ICC_preference.icc perceptual */
{60960, 0xbbef7812UL, 0},
/* HP? sRGB v2 media-relative sRGB_IEC61966-2-1_noBPC.icc */
{ 3024, 0x5d5129ceUL, 1},
/* HP-Microsoft sRGB v2 perceptual */
{ 3144, 0x182ea552UL, 0},
/* HP-Microsoft sRGB v2 media-relative */
{ 3144, 0xf29e526dUL, 1},
/* Facebook's "2012/01/25 03:41:57", 524, "TINYsRGB.icc" */
{ 524, 0xd4938c39UL, 0},
/* "2012/11/28 22:35:21", 3212, "Argyll_sRGB.icm") */
{ 3212, 0x034af5a1UL, 0},
/* Not recognized */
{ 0, 0x00000000UL, 0},
};
/* Macros for left-bit-replication to ensure that pixels
* and PixelPackets all have the same image->depth, and for use
* in PNG8 quantization.
*/
/* LBR01: Replicate top bit */
#define LBR01PacketRed(pixelpacket) \
(pixelpacket).red=(ScaleQuantumToChar((pixelpacket).red) < 0x10 ? \
0 : QuantumRange);
#define LBR01PacketGreen(pixelpacket) \
(pixelpacket).green=(ScaleQuantumToChar((pixelpacket).green) < 0x10 ? \
0 : QuantumRange);
#define LBR01PacketBlue(pixelpacket) \
(pixelpacket).blue=(ScaleQuantumToChar((pixelpacket).blue) < 0x10 ? \
0 : QuantumRange);
#define LBR01PacketOpacity(pixelpacket) \
(pixelpacket).opacity=(ScaleQuantumToChar((pixelpacket).opacity) < 0x10 ? \
0 : QuantumRange);
#define LBR01PacketRGB(pixelpacket) \
{ \
LBR01PacketRed((pixelpacket)); \
LBR01PacketGreen((pixelpacket)); \
LBR01PacketBlue((pixelpacket)); \
}
#define LBR01PacketRGBO(pixelpacket) \
{ \
LBR01PacketRGB((pixelpacket)); \
LBR01PacketOpacity((pixelpacket)); \
}
#define LBR01PixelRed(pixel) \
(SetPixelRed((pixel), \
ScaleQuantumToChar(GetPixelRed((pixel))) < 0x10 ? \
0 : QuantumRange));
#define LBR01PixelGreen(pixel) \
(SetPixelGreen((pixel), \
ScaleQuantumToChar(GetPixelGreen((pixel))) < 0x10 ? \
0 : QuantumRange));
#define LBR01PixelBlue(pixel) \
(SetPixelBlue((pixel), \
ScaleQuantumToChar(GetPixelBlue((pixel))) < 0x10 ? \
0 : QuantumRange));
#define LBR01PixelOpacity(pixel) \
(SetPixelOpacity((pixel), \
ScaleQuantumToChar(GetPixelOpacity((pixel))) < 0x10 ? \
0 : QuantumRange));
#define LBR01PixelRGB(pixel) \
{ \
LBR01PixelRed((pixel)); \
LBR01PixelGreen((pixel)); \
LBR01PixelBlue((pixel)); \
}
#define LBR01PixelRGBO(pixel) \
{ \
LBR01PixelRGB((pixel)); \
LBR01PixelOpacity((pixel)); \
}
/* LBR02: Replicate top 2 bits */
#define LBR02PacketRed(pixelpacket) \
{ \
unsigned char lbr_bits=ScaleQuantumToChar((pixelpacket).red) & 0xc0; \
(pixelpacket).red=ScaleCharToQuantum( \
(lbr_bits | (lbr_bits >> 2) | (lbr_bits >> 4) | (lbr_bits >> 6))); \
}
#define LBR02PacketGreen(pixelpacket) \
{ \
unsigned char lbr_bits=ScaleQuantumToChar((pixelpacket).green) & 0xc0; \
(pixelpacket).green=ScaleCharToQuantum( \
(lbr_bits | (lbr_bits >> 2) | (lbr_bits >> 4) | (lbr_bits >> 6))); \
}
#define LBR02PacketBlue(pixelpacket) \
{ \
unsigned char lbr_bits=ScaleQuantumToChar((pixelpacket).blue) & 0xc0; \
(pixelpacket).blue=ScaleCharToQuantum( \
(lbr_bits | (lbr_bits >> 2) | (lbr_bits >> 4) | (lbr_bits >> 6))); \
}
#define LBR02PacketOpacity(pixelpacket) \
{ \
unsigned char lbr_bits=ScaleQuantumToChar((pixelpacket).opacity) & 0xc0; \
(pixelpacket).opacity=ScaleCharToQuantum( \
(lbr_bits | (lbr_bits >> 2) | (lbr_bits >> 4) | (lbr_bits >> 6))); \
}
#define LBR02PacketRGB(pixelpacket) \
{ \
LBR02PacketRed((pixelpacket)); \
LBR02PacketGreen((pixelpacket)); \
LBR02PacketBlue((pixelpacket)); \
}
#define LBR02PacketRGBO(pixelpacket) \
{ \
LBR02PacketRGB((pixelpacket)); \
LBR02PacketOpacity((pixelpacket)); \
}
#define LBR02PixelRed(pixel) \
{ \
unsigned char lbr_bits=ScaleQuantumToChar(GetPixelRed((pixel))) \
& 0xc0; \
SetPixelRed((pixel), ScaleCharToQuantum( \
(lbr_bits | (lbr_bits >> 2) | (lbr_bits >> 4) | (lbr_bits >> 6)))); \
}
#define LBR02PixelGreen(pixel) \
{ \
unsigned char lbr_bits=ScaleQuantumToChar(GetPixelGreen((pixel)))\
& 0xc0; \
SetPixelGreen((pixel), ScaleCharToQuantum( \
(lbr_bits | (lbr_bits >> 2) | (lbr_bits >> 4) | (lbr_bits >> 6)))); \
}
#define LBR02PixelBlue(pixel) \
{ \
unsigned char lbr_bits= \
ScaleQuantumToChar(GetPixelBlue((pixel))) & 0xc0; \
SetPixelBlue((pixel), ScaleCharToQuantum( \
(lbr_bits | (lbr_bits >> 2) | (lbr_bits >> 4) | (lbr_bits >> 6)))); \
}
#define LBR02Opacity(pixel) \
{ \
unsigned char lbr_bits= \
ScaleQuantumToChar(GetPixelOpacity((pixel))) & 0xc0; \
SetPixelOpacity((pixel), ScaleCharToQuantum( \
(lbr_bits | (lbr_bits >> 2) | (lbr_bits >> 4) | (lbr_bits >> 6)))); \
}
#define LBR02PixelRGB(pixel) \
{ \
LBR02PixelRed((pixel)); \
LBR02PixelGreen((pixel)); \
LBR02PixelBlue((pixel)); \
}
#define LBR02PixelRGBO(pixel) \
{ \
LBR02PixelRGB((pixel)); \
LBR02Opacity((pixel)); \
}
/* LBR03: Replicate top 3 bits (only used with opaque pixels during
PNG8 quantization) */
#define LBR03PacketRed(pixelpacket) \
{ \
unsigned char lbr_bits=ScaleQuantumToChar((pixelpacket).red) & 0xe0; \
(pixelpacket).red=ScaleCharToQuantum( \
(lbr_bits | (lbr_bits >> 3) | (lbr_bits >> 6))); \
}
#define LBR03PacketGreen(pixelpacket) \
{ \
unsigned char lbr_bits=ScaleQuantumToChar((pixelpacket).green) & 0xe0; \
(pixelpacket).green=ScaleCharToQuantum( \
(lbr_bits | (lbr_bits >> 3) | (lbr_bits >> 6))); \
}
#define LBR03PacketBlue(pixelpacket) \
{ \
unsigned char lbr_bits=ScaleQuantumToChar((pixelpacket).blue) & 0xe0; \
(pixelpacket).blue=ScaleCharToQuantum( \
(lbr_bits | (lbr_bits >> 3) | (lbr_bits >> 6))); \
}
#define LBR03PacketRGB(pixelpacket) \
{ \
LBR03PacketRed((pixelpacket)); \
LBR03PacketGreen((pixelpacket)); \
LBR03PacketBlue((pixelpacket)); \
}
#define LBR03PixelRed(pixel) \
{ \
unsigned char lbr_bits=ScaleQuantumToChar(GetPixelRed((pixel))) \
& 0xe0; \
SetPixelRed((pixel), ScaleCharToQuantum( \
(lbr_bits | (lbr_bits >> 3) | (lbr_bits >> 6)))); \
}
#define LBR03PixelGreen(pixel) \
{ \
unsigned char lbr_bits=ScaleQuantumToChar(GetPixelGreen((pixel)))\
& 0xe0; \
SetPixelGreen((pixel), ScaleCharToQuantum( \
(lbr_bits | (lbr_bits >> 3) | (lbr_bits >> 6)))); \
}
#define LBR03PixelBlue(pixel) \
{ \
unsigned char lbr_bits=ScaleQuantumToChar(GetPixelBlue((pixel))) \
& 0xe0; \
SetPixelBlue((pixel), ScaleCharToQuantum( \
(lbr_bits | (lbr_bits >> 3) | (lbr_bits >> 6)))); \
}
#define LBR03PixelRGB(pixel) \
{ \
LBR03PixelRed((pixel)); \
LBR03PixelGreen((pixel)); \
LBR03PixelBlue((pixel)); \
}
/* LBR04: Replicate top 4 bits */
#define LBR04PacketRed(pixelpacket) \
{ \
unsigned char lbr_bits=ScaleQuantumToChar((pixelpacket).red) & 0xf0; \
(pixelpacket).red=ScaleCharToQuantum((lbr_bits | (lbr_bits >> 4))); \
}
#define LBR04PacketGreen(pixelpacket) \
{ \
unsigned char lbr_bits=ScaleQuantumToChar((pixelpacket).green) & 0xf0; \
(pixelpacket).green=ScaleCharToQuantum((lbr_bits | (lbr_bits >> 4))); \
}
#define LBR04PacketBlue(pixelpacket) \
{ \
unsigned char lbr_bits=ScaleQuantumToChar((pixelpacket).blue) & 0xf0; \
(pixelpacket).blue=ScaleCharToQuantum((lbr_bits | (lbr_bits >> 4))); \
}
#define LBR04PacketOpacity(pixelpacket) \
{ \
unsigned char lbr_bits=ScaleQuantumToChar((pixelpacket).opacity) & 0xf0; \
(pixelpacket).opacity=ScaleCharToQuantum((lbr_bits | (lbr_bits >> 4))); \
}
#define LBR04PacketRGB(pixelpacket) \
{ \
LBR04PacketRed((pixelpacket)); \
LBR04PacketGreen((pixelpacket)); \
LBR04PacketBlue((pixelpacket)); \
}
#define LBR04PacketRGBO(pixelpacket) \
{ \
LBR04PacketRGB((pixelpacket)); \
LBR04PacketOpacity((pixelpacket)); \
}
#define LBR04PixelRed(pixel) \
{ \
unsigned char lbr_bits=ScaleQuantumToChar(GetPixelRed((pixel))) \
& 0xf0; \
SetPixelRed((pixel),\
ScaleCharToQuantum((lbr_bits | (lbr_bits >> 4)))); \
}
#define LBR04PixelGreen(pixel) \
{ \
unsigned char lbr_bits=ScaleQuantumToChar(GetPixelGreen((pixel)))\
& 0xf0; \
SetPixelGreen((pixel),\
ScaleCharToQuantum((lbr_bits | (lbr_bits >> 4)))); \
}
#define LBR04PixelBlue(pixel) \
{ \
unsigned char lbr_bits= \
ScaleQuantumToChar(GetPixelBlue((pixel))) & 0xf0; \
SetPixelBlue((pixel),\
ScaleCharToQuantum((lbr_bits | (lbr_bits >> 4)))); \
}
#define LBR04PixelOpacity(pixel) \
{ \
unsigned char lbr_bits= \
ScaleQuantumToChar(GetPixelOpacity((pixel))) & 0xf0; \
SetPixelOpacity((pixel),\
ScaleCharToQuantum((lbr_bits | (lbr_bits >> 4)))); \
}
#define LBR04PixelRGB(pixel) \
{ \
LBR04PixelRed((pixel)); \
LBR04PixelGreen((pixel)); \
LBR04PixelBlue((pixel)); \
}
#define LBR04PixelRGBO(pixel) \
{ \
LBR04PixelRGB((pixel)); \
LBR04PixelOpacity((pixel)); \
}
/*
Establish thread safety.
setjmp/longjmp is claimed to be safe on these platforms:
setjmp/longjmp is alleged to be unsafe on these platforms:
*/
#ifdef PNG_SETJMP_SUPPORTED
# ifndef IMPNG_SETJMP_IS_THREAD_SAFE
# define IMPNG_SETJMP_NOT_THREAD_SAFE
# endif
# ifdef IMPNG_SETJMP_NOT_THREAD_SAFE
static SemaphoreInfo
*ping_semaphore = (SemaphoreInfo *) NULL;
# endif
#endif
/*
This temporary until I set up malloc'ed object attributes array.
Recompile with MNG_MAX_OBJECTS=65536L to avoid this limit but
waste more memory.
*/
#define MNG_MAX_OBJECTS 256
/*
If this not defined, spec is interpreted strictly. If it is
defined, an attempt will be made to recover from some errors,
including
o global PLTE too short
*/
#undef MNG_LOOSE
/*
Don't try to define PNG_MNG_FEATURES_SUPPORTED here. Make sure
it's defined in libpng/pngconf.h, version 1.0.9 or later. It won't work
with earlier versions of libpng. From libpng-1.0.3a to libpng-1.0.8,
PNG_READ|WRITE_EMPTY_PLTE were used but those have been deprecated in
libpng in favor of PNG_MNG_FEATURES_SUPPORTED, so we set them here.
PNG_MNG_FEATURES_SUPPORTED is disabled by default in libpng-1.0.9 and
will be enabled by default in libpng-1.2.0.
*/
#ifdef PNG_MNG_FEATURES_SUPPORTED
# ifndef PNG_READ_EMPTY_PLTE_SUPPORTED
# define PNG_READ_EMPTY_PLTE_SUPPORTED
# endif
# ifndef PNG_WRITE_EMPTY_PLTE_SUPPORTED
# define PNG_WRITE_EMPTY_PLTE_SUPPORTED
# endif
#endif
/*
Maximum valid size_t in PNG/MNG chunks is (2^31)-1
This macro is only defined in libpng-1.0.3 and later.
Previously it was PNG_MAX_UINT but that was deprecated in libpng-1.2.6
*/
#ifndef PNG_UINT_31_MAX
#define PNG_UINT_31_MAX (png_uint_32) 0x7fffffffL
#endif
/*
Constant strings for known chunk types. If you need to add a chunk,
add a string holding the name here. To make the code more
portable, we use ASCII numbers like this, not characters.
*/
/* until registration of eXIf */
static const png_byte mng_exIf[5]={101, 120, 73, 102, (png_byte) '\0'};
/* after registration of eXIf */
static const png_byte mng_eXIf[5]={101, 88, 73, 102, (png_byte) '\0'};
static const png_byte mng_MHDR[5]={ 77, 72, 68, 82, (png_byte) '\0'};
static const png_byte mng_BACK[5]={ 66, 65, 67, 75, (png_byte) '\0'};
static const png_byte mng_BASI[5]={ 66, 65, 83, 73, (png_byte) '\0'};
static const png_byte mng_CLIP[5]={ 67, 76, 73, 80, (png_byte) '\0'};
static const png_byte mng_CLON[5]={ 67, 76, 79, 78, (png_byte) '\0'};
static const png_byte mng_DEFI[5]={ 68, 69, 70, 73, (png_byte) '\0'};
static const png_byte mng_DHDR[5]={ 68, 72, 68, 82, (png_byte) '\0'};
static const png_byte mng_DISC[5]={ 68, 73, 83, 67, (png_byte) '\0'};
static const png_byte mng_ENDL[5]={ 69, 78, 68, 76, (png_byte) '\0'};
static const png_byte mng_FRAM[5]={ 70, 82, 65, 77, (png_byte) '\0'};
static const png_byte mng_IEND[5]={ 73, 69, 78, 68, (png_byte) '\0'};
static const png_byte mng_IHDR[5]={ 73, 72, 68, 82, (png_byte) '\0'};
static const png_byte mng_JHDR[5]={ 74, 72, 68, 82, (png_byte) '\0'};
static const png_byte mng_LOOP[5]={ 76, 79, 79, 80, (png_byte) '\0'};
static const png_byte mng_MAGN[5]={ 77, 65, 71, 78, (png_byte) '\0'};
static const png_byte mng_MEND[5]={ 77, 69, 78, 68, (png_byte) '\0'};
static const png_byte mng_MOVE[5]={ 77, 79, 86, 69, (png_byte) '\0'};
static const png_byte mng_PAST[5]={ 80, 65, 83, 84, (png_byte) '\0'};
static const png_byte mng_PLTE[5]={ 80, 76, 84, 69, (png_byte) '\0'};
static const png_byte mng_SAVE[5]={ 83, 65, 86, 69, (png_byte) '\0'};
static const png_byte mng_SEEK[5]={ 83, 69, 69, 75, (png_byte) '\0'};
static const png_byte mng_SHOW[5]={ 83, 72, 79, 87, (png_byte) '\0'};
static const png_byte mng_TERM[5]={ 84, 69, 82, 77, (png_byte) '\0'};
static const png_byte mng_bKGD[5]={ 98, 75, 71, 68, (png_byte) '\0'};
static const png_byte mng_caNv[5]={ 99, 97, 78, 118, (png_byte) '\0'};
static const png_byte mng_cHRM[5]={ 99, 72, 82, 77, (png_byte) '\0'};
static const png_byte mng_gAMA[5]={103, 65, 77, 65, (png_byte) '\0'};
static const png_byte mng_iCCP[5]={105, 67, 67, 80, (png_byte) '\0'};
static const png_byte mng_nEED[5]={110, 69, 69, 68, (png_byte) '\0'};
static const png_byte mng_pHYg[5]={112, 72, 89, 103, (png_byte) '\0'};
static const png_byte mng_vpAg[5]={118, 112, 65, 103, (png_byte) '\0'};
static const png_byte mng_pHYs[5]={112, 72, 89, 115, (png_byte) '\0'};
static const png_byte mng_sBIT[5]={115, 66, 73, 84, (png_byte) '\0'};
static const png_byte mng_sRGB[5]={115, 82, 71, 66, (png_byte) '\0'};
static const png_byte mng_tRNS[5]={116, 82, 78, 83, (png_byte) '\0'};
#if defined(JNG_SUPPORTED)
static const png_byte mng_IDAT[5]={ 73, 68, 65, 84, (png_byte) '\0'};
static const png_byte mng_JDAT[5]={ 74, 68, 65, 84, (png_byte) '\0'};
static const png_byte mng_JDAA[5]={ 74, 68, 65, 65, (png_byte) '\0'};
static const png_byte mng_JdAA[5]={ 74, 100, 65, 65, (png_byte) '\0'};
static const png_byte mng_JSEP[5]={ 74, 83, 69, 80, (png_byte) '\0'};
static const png_byte mng_oFFs[5]={111, 70, 70, 115, (png_byte) '\0'};
#endif
#if 0
/* Other known chunks that are not yet supported by ImageMagick: */
static const png_byte mng_hIST[5]={104, 73, 83, 84, (png_byte) '\0'};
static const png_byte mng_iTXt[5]={105, 84, 88, 116, (png_byte) '\0'};
static const png_byte mng_sPLT[5]={115, 80, 76, 84, (png_byte) '\0'};
static const png_byte mng_sTER[5]={115, 84, 69, 82, (png_byte) '\0'};
static const png_byte mng_tEXt[5]={116, 69, 88, 116, (png_byte) '\0'};
static const png_byte mng_tIME[5]={116, 73, 77, 69, (png_byte) '\0'};
static const png_byte mng_zTXt[5]={122, 84, 88, 116, (png_byte) '\0'};
#endif
typedef struct _MngBox
{
long
left,
right,
top,
bottom;
} MngBox;
typedef struct _MngPair
{
volatile long
a,
b;
} MngPair;
#ifdef MNG_OBJECT_BUFFERS
typedef struct _MngBuffer
{
size_t
height,
width;
Image
*image;
png_color
plte[256];
int
reference_count;
unsigned char
alpha_sample_depth,
compression_method,
color_type,
concrete,
filter_method,
frozen,
image_type,
interlace_method,
pixel_sample_depth,
plte_length,
sample_depth,
viewable;
} MngBuffer;
#endif
typedef struct _MngInfo
{
#ifdef MNG_OBJECT_BUFFERS
MngBuffer
*ob[MNG_MAX_OBJECTS];
#endif
Image *
image;
RectangleInfo
page;
int
adjoin,
#ifndef PNG_READ_EMPTY_PLTE_SUPPORTED
bytes_in_read_buffer,
found_empty_plte,
#endif
equal_backgrounds,
equal_chrms,
equal_gammas,
#if defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED) || \
defined(PNG_MNG_FEATURES_SUPPORTED)
equal_palettes,
#endif
equal_physs,
equal_srgbs,
framing_mode,
have_global_bkgd,
have_global_chrm,
have_global_gama,
have_global_phys,
have_global_sbit,
have_global_srgb,
have_saved_bkgd_index,
have_write_global_chrm,
have_write_global_gama,
have_write_global_plte,
have_write_global_srgb,
need_fram,
object_id,
old_framing_mode,
saved_bkgd_index;
int
new_number_colors;
ssize_t
image_found,
loop_count[256],
loop_iteration[256],
scenes_found,
x_off[MNG_MAX_OBJECTS],
y_off[MNG_MAX_OBJECTS];
MngBox
clip,
frame,
image_box,
object_clip[MNG_MAX_OBJECTS];
unsigned char
/* These flags could be combined into one byte */
exists[MNG_MAX_OBJECTS],
frozen[MNG_MAX_OBJECTS],
loop_active[256],
invisible[MNG_MAX_OBJECTS],
viewable[MNG_MAX_OBJECTS];
MagickOffsetType
loop_jump[256];
png_colorp
global_plte;
png_color_8
global_sbit;
png_byte
#ifndef PNG_READ_EMPTY_PLTE_SUPPORTED
read_buffer[8],
#endif
global_trns[256];
float
global_gamma;
ChromaticityInfo
global_chrm;
RenderingIntent
global_srgb_intent;
unsigned int
delay,
global_plte_length,
global_trns_length,
global_x_pixels_per_unit,
global_y_pixels_per_unit,
mng_width,
mng_height,
ticks_per_second;
MagickBooleanType
need_blob;
unsigned int
IsPalette,
global_phys_unit_type,
basi_warning,
clon_warning,
dhdr_warning,
jhdr_warning,
magn_warning,
past_warning,
phyg_warning,
phys_warning,
sbit_warning,
show_warning,
mng_type,
write_mng,
write_png_colortype,
write_png_depth,
write_png_compression_level,
write_png_compression_strategy,
write_png_compression_filter,
write_png8,
write_png24,
write_png32,
write_png48,
write_png64;
#ifdef MNG_BASI_SUPPORTED
size_t
basi_width,
basi_height;
unsigned int
basi_depth,
basi_color_type,
basi_compression_method,
basi_filter_type,
basi_interlace_method,
basi_red,
basi_green,
basi_blue,
basi_alpha,
basi_viewable;
#endif
png_uint_16
magn_first,
magn_last,
magn_mb,
magn_ml,
magn_mr,
magn_mt,
magn_mx,
magn_my,
magn_methx,
magn_methy;
PixelPacket
mng_global_bkgd;
/* Added at version 6.6.6-7 */
MagickBooleanType
ping_exclude_bKGD,
ping_exclude_cHRM,
ping_exclude_date,
ping_exclude_eXIf,
ping_exclude_EXIF,
ping_exclude_gAMA,
ping_exclude_iCCP,
/* ping_exclude_iTXt, */
ping_exclude_oFFs,
ping_exclude_pHYs,
ping_exclude_sRGB,
ping_exclude_tEXt,
ping_exclude_tRNS,
ping_exclude_vpAg,
ping_exclude_caNv,
ping_exclude_zCCP, /* hex-encoded iCCP */
ping_exclude_zTXt,
ping_preserve_colormap,
/* Added at version 6.8.5-7 */
ping_preserve_iCCP,
/* Added at version 6.8.9-9 */
ping_exclude_tIME;
} MngInfo;
#endif /* VER */
/*
Forward declarations.
*/
static MagickBooleanType
WritePNGImage(const ImageInfo *,Image *);
static MagickBooleanType
WriteMNGImage(const ImageInfo *,Image *);
#if defined(JNG_SUPPORTED)
static MagickBooleanType
WriteJNGImage(const ImageInfo *,Image *);
#endif
#if PNG_LIBPNG_VER > 10011
#if (MAGICKCORE_QUANTUM_DEPTH >= 16)
static MagickBooleanType
LosslessReduceDepthOK(Image *image)
{
/* Reduce bit depth if it can be reduced losslessly from 16+ to 8.
*
* This is true if the high byte and the next highest byte of
* each sample of the image, the colormap, and the background color
* are equal to each other. We check this by seeing if the samples
* are unchanged when we scale them down to 8 and back up to Quantum.
*
* We don't use the method GetImageDepth() because it doesn't check
* background and doesn't handle PseudoClass specially.
*/
#define QuantumToCharToQuantumEqQuantum(quantum) \
((ScaleCharToQuantum((unsigned char) ScaleQuantumToChar(quantum))) == quantum)
MagickBooleanType
ok_to_reduce=MagickFalse;
if (image->depth >= 16)
{
const PixelPacket
*p;
ok_to_reduce=
QuantumToCharToQuantumEqQuantum(image->background_color.red) &&
QuantumToCharToQuantumEqQuantum(image->background_color.green) &&
QuantumToCharToQuantumEqQuantum(image->background_color.blue) ?
MagickTrue : MagickFalse;
if (ok_to_reduce != MagickFalse && image->storage_class == PseudoClass)
{
int indx;
for (indx=0; indx < (ssize_t) image->colors; indx++)
{
ok_to_reduce=(
QuantumToCharToQuantumEqQuantum(
image->colormap[indx].red) &&
QuantumToCharToQuantumEqQuantum(
image->colormap[indx].green) &&
QuantumToCharToQuantumEqQuantum(
image->colormap[indx].blue)) ?
MagickTrue : MagickFalse;
if (ok_to_reduce == MagickFalse)
break;
}
}
if ((ok_to_reduce != MagickFalse) &&
(image->storage_class != PseudoClass))
{
ssize_t
y;
register ssize_t
x;
for (y=0; y < (ssize_t) image->rows; y++)
{
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
{
ok_to_reduce = MagickFalse;
break;
}
for (x=(ssize_t) image->columns-1; x >= 0; x--)
{
ok_to_reduce=
QuantumToCharToQuantumEqQuantum(GetPixelRed(p)) &&
QuantumToCharToQuantumEqQuantum(GetPixelGreen(p)) &&
QuantumToCharToQuantumEqQuantum(GetPixelBlue(p)) ?
MagickTrue : MagickFalse;
if (ok_to_reduce == MagickFalse)
break;
p++;
}
if (x >= 0)
break;
}
}
if (ok_to_reduce != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" OK to reduce PNG bit depth to 8 without loss of info");
}
else
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Not OK to reduce PNG bit depth to 8 without loss of info");
}
}
return ok_to_reduce;
}
#endif /* MAGICKCORE_QUANTUM_DEPTH >= 16 */
static const char* PngColorTypeToString(const unsigned int color_type)
{
const char
*result = "Unknown";
switch (color_type)
{
case PNG_COLOR_TYPE_GRAY:
result = "Gray";
break;
case PNG_COLOR_TYPE_GRAY_ALPHA:
result = "Gray+Alpha";
break;
case PNG_COLOR_TYPE_PALETTE:
result = "Palette";
break;
case PNG_COLOR_TYPE_RGB:
result = "RGB";
break;
case PNG_COLOR_TYPE_RGB_ALPHA:
result = "RGB+Alpha";
break;
}
return result;
}
static int
Magick_RenderingIntent_to_PNG_RenderingIntent(const RenderingIntent intent)
{
switch (intent)
{
case PerceptualIntent:
return 0;
case RelativeIntent:
return 1;
case SaturationIntent:
return 2;
case AbsoluteIntent:
return 3;
default:
return -1;
}
}
static RenderingIntent
Magick_RenderingIntent_from_PNG_RenderingIntent(const int ping_intent)
{
switch (ping_intent)
{
case 0:
return PerceptualIntent;
case 1:
return RelativeIntent;
case 2:
return SaturationIntent;
case 3:
return AbsoluteIntent;
default:
return UndefinedIntent;
}
}
static const char *
Magick_RenderingIntentString_from_PNG_RenderingIntent(const int ping_intent)
{
switch (ping_intent)
{
case 0:
return "Perceptual Intent";
case 1:
return "Relative Intent";
case 2:
return "Saturation Intent";
case 3:
return "Absolute Intent";
default:
return "Undefined Intent";
}
}
static const char *
Magick_ColorType_from_PNG_ColorType(const int ping_colortype)
{
switch (ping_colortype)
{
case 0:
return "Grayscale";
case 2:
return "Truecolor";
case 3:
return "Indexed";
case 4:
return "GrayAlpha";
case 6:
return "RGBA";
default:
return "UndefinedColorType";
}
}
#endif /* PNG_LIBPNG_VER > 10011 */
#endif /* MAGICKCORE_PNG_DELEGATE */
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% I s M N G %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% IsMNG() returns MagickTrue if the image format type, identified by the
% magick string, is MNG.
%
% The format of the IsMNG method is:
%
% MagickBooleanType IsMNG(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 IsMNG(const unsigned char *magick,const size_t length)
{
if (length < 8)
return(MagickFalse);
if (memcmp(magick,"\212MNG\r\n\032\n",8) == 0)
return(MagickTrue);
return(MagickFalse);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% I s J N G %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% IsJNG() returns MagickTrue if the image format type, identified by the
% magick string, is JNG.
%
% The format of the IsJNG method is:
%
% MagickBooleanType IsJNG(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 IsJNG(const unsigned char *magick,const size_t length)
{
if (length < 8)
return(MagickFalse);
if (memcmp(magick,"\213JNG\r\n\032\n",8) == 0)
return(MagickTrue);
return(MagickFalse);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% I s P N G %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% IsPNG() returns MagickTrue if the image format type, identified by the
% magick string, is PNG.
%
% The format of the IsPNG method is:
%
% MagickBooleanType IsPNG(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 IsPNG(const unsigned char *magick,const size_t length)
{
if (length < 8)
return(MagickFalse);
if (memcmp(magick,"\211PNG\r\n\032\n",8) == 0)
return(MagickTrue);
return(MagickFalse);
}
#if defined(MAGICKCORE_PNG_DELEGATE)
#if defined(__cplusplus) || defined(c_plusplus)
extern "C" {
#endif
#if (PNG_LIBPNG_VER > 10011)
static size_t WriteBlobMSBULong(Image *image,const size_t value)
{
unsigned char
buffer[4];
assert(image != (Image *) NULL);
assert(image->signature == MagickSignature);
buffer[0]=(unsigned char) (value >> 24);
buffer[1]=(unsigned char) (value >> 16);
buffer[2]=(unsigned char) (value >> 8);
buffer[3]=(unsigned char) value;
return((size_t) WriteBlob(image,4,buffer));
}
static void PNGLong(png_bytep p,png_uint_32 value)
{
*p++=(png_byte) ((value >> 24) & 0xff);
*p++=(png_byte) ((value >> 16) & 0xff);
*p++=(png_byte) ((value >> 8) & 0xff);
*p++=(png_byte) (value & 0xff);
}
static void PNGsLong(png_bytep p,png_int_32 value)
{
*p++=(png_byte) ((value >> 24) & 0xff);
*p++=(png_byte) ((value >> 16) & 0xff);
*p++=(png_byte) ((value >> 8) & 0xff);
*p++=(png_byte) (value & 0xff);
}
static void PNGShort(png_bytep p,png_uint_16 value)
{
*p++=(png_byte) ((value >> 8) & 0xff);
*p++=(png_byte) (value & 0xff);
}
static void PNGType(png_bytep p,const png_byte *type)
{
(void) CopyMagickMemory(p,type,4*sizeof(png_byte));
}
static void LogPNGChunk(MagickBooleanType logging, const png_byte *type,
size_t length)
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Writing %c%c%c%c chunk, length: %.20g",
type[0],type[1],type[2],type[3],(double) length);
}
#endif /* PNG_LIBPNG_VER > 10011 */
#if defined(__cplusplus) || defined(c_plusplus)
}
#endif
#if PNG_LIBPNG_VER > 10011
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e a d P N G I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ReadPNGImage() reads a Portable Network Graphics (PNG) or
% Multiple-image Network Graphics (MNG) image file and returns it. It
% allocates the memory necessary for the new Image structure and returns a
% pointer to the new image or set of images.
%
% MNG support written by Glenn Randers-Pehrson, glennrp@image...
%
% The format of the ReadPNGImage method is:
%
% Image *ReadPNGImage(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.
%
% To do, more or less in chronological order (as of version 5.5.2,
% November 26, 2002 -- glennrp -- see also "To do" under WriteMNGImage):
%
% Get 16-bit cheap transparency working.
%
% (At this point, PNG decoding is supposed to be in full MNG-LC compliance)
%
% Preserve all unknown and not-yet-handled known chunks found in input
% PNG file and copy them into output PNG files according to the PNG
% copying rules.
%
% (At this point, PNG encoding should be in full MNG compliance)
%
% Provide options for choice of background to use when the MNG BACK
% chunk is not present or is not mandatory (i.e., leave transparent,
% user specified, MNG BACK, PNG bKGD)
%
% Implement LOOP/ENDL [done, but could do discretionary loops more
% efficiently by linking in the duplicate frames.].
%
% Decode and act on the MHDR simplicity profile (offer option to reject
% files or attempt to process them anyway when the profile isn't LC or VLC).
%
% Upgrade to full MNG without Delta-PNG.
%
% o BACK [done a while ago except for background image ID]
% o MOVE [done 15 May 1999]
% o CLIP [done 15 May 1999]
% o DISC [done 19 May 1999]
% o SAVE [partially done 19 May 1999 (marks objects frozen)]
% o SEEK [partially done 19 May 1999 (discard function only)]
% o SHOW
% o PAST
% o BASI
% o MNG-level tEXt/iTXt/zTXt
% o pHYg
% o pHYs
% o sBIT
% o bKGD
% o iTXt (wait for libpng implementation).
%
% Use the scene signature to discover when an identical scene is
% being reused, and just point to the original image->exception instead
% of storing another set of pixels. This not specific to MNG
% but could be applied generally.
%
% Upgrade to full MNG with Delta-PNG.
%
% JNG tEXt/iTXt/zTXt
%
% We will not attempt to read files containing the CgBI chunk.
% They are really Xcode files meant for display on the iPhone.
% These are not valid PNG files and it is impossible to recover
% the original PNG from files that have been converted to Xcode-PNG,
% since irretrievable loss of color data has occurred due to the
% use of premultiplied alpha.
*/
#if defined(__cplusplus) || defined(c_plusplus)
extern "C" {
#endif
/*
This the function that does the actual reading of data. It is
the same as the one supplied in libpng, except that it receives the
datastream from the ReadBlob() function instead of standard input.
*/
static void png_get_data(png_structp png_ptr,png_bytep data,png_size_t length)
{
Image
*image;
image=(Image *) png_get_io_ptr(png_ptr);
if (length != 0)
{
png_size_t
check;
check=(png_size_t) ReadBlob(image,(size_t) length,data);
if (check != length)
{
char
msg[MaxTextExtent];
(void) FormatLocaleString(msg,MaxTextExtent,
"Expected %.20g bytes; found %.20g bytes",(double) length,
(double) check);
png_warning(png_ptr,msg);
png_error(png_ptr,"Read Exception");
}
}
}
#if !defined(PNG_READ_EMPTY_PLTE_SUPPORTED) && \
!defined(PNG_MNG_FEATURES_SUPPORTED)
/* We use mng_get_data() instead of png_get_data() if we have a libpng
* older than libpng-1.0.3a, which was the first to allow the empty
* PLTE, or a newer libpng in which PNG_MNG_FEATURES_SUPPORTED was
* ifdef'ed out. Earlier versions would crash if the bKGD chunk was
* encountered after an empty PLTE, so we have to look ahead for bKGD
* chunks and remove them from the datastream that is passed to libpng,
* and store their contents for later use.
*/
static void mng_get_data(png_structp png_ptr,png_bytep data,png_size_t length)
{
MngInfo
*mng_info;
Image
*image;
png_size_t
check;
register ssize_t
i;
i=0;
mng_info=(MngInfo *) png_get_io_ptr(png_ptr);
image=(Image *) mng_info->image;
while (mng_info->bytes_in_read_buffer && length)
{
data[i]=mng_info->read_buffer[i];
mng_info->bytes_in_read_buffer--;
length--;
i++;
}
if (length != 0)
{
check=(png_size_t) ReadBlob(image,(size_t) length,(char *) data);
if (check != length)
png_error(png_ptr,"Read Exception");
if (length == 4)
{
if ((data[0] == 0) && (data[1] == 0) && (data[2] == 0) &&
(data[3] == 0))
{
check=(png_size_t) ReadBlob(image,(size_t) length,
(char *) mng_info->read_buffer);
mng_info->read_buffer[4]=0;
mng_info->bytes_in_read_buffer=4;
if (memcmp(mng_info->read_buffer,mng_PLTE,4) == 0)
mng_info->found_empty_plte=MagickTrue;
if (memcmp(mng_info->read_buffer,mng_IEND,4) == 0)
{
mng_info->found_empty_plte=MagickFalse;
mng_info->have_saved_bkgd_index=MagickFalse;
}
}
if ((data[0] == 0) && (data[1] == 0) && (data[2] == 0) &&
(data[3] == 1))
{
check=(png_size_t) ReadBlob(image,(size_t) length,
(char *) mng_info->read_buffer);
mng_info->read_buffer[4]=0;
mng_info->bytes_in_read_buffer=4;
if (memcmp(mng_info->read_buffer,mng_bKGD,4) == 0)
if (mng_info->found_empty_plte)
{
/*
Skip the bKGD data byte and CRC.
*/
check=(png_size_t)
ReadBlob(image,5,(char *) mng_info->read_buffer);
check=(png_size_t) ReadBlob(image,(size_t) length,
(char *) mng_info->read_buffer);
mng_info->saved_bkgd_index=mng_info->read_buffer[0];
mng_info->have_saved_bkgd_index=MagickTrue;
mng_info->bytes_in_read_buffer=0;
}
}
}
}
}
#endif
static void png_put_data(png_structp png_ptr,png_bytep data,png_size_t length)
{
Image
*image;
image=(Image *) png_get_io_ptr(png_ptr);
if (length != 0)
{
png_size_t
check;
check=(png_size_t) WriteBlob(image,(size_t) length,data);
if (check != length)
png_error(png_ptr,"WriteBlob Failed");
}
}
static void png_flush_data(png_structp png_ptr)
{
(void) png_ptr;
}
#ifdef PNG_WRITE_EMPTY_PLTE_SUPPORTED
static int PalettesAreEqual(Image *a,Image *b)
{
ssize_t
i;
if ((a == (Image *) NULL) || (b == (Image *) NULL))
return((int) MagickFalse);
if (a->storage_class != PseudoClass || b->storage_class != PseudoClass)
return((int) MagickFalse);
if (a->colors != b->colors)
return((int) MagickFalse);
for (i=0; i < (ssize_t) a->colors; i++)
{
if ((a->colormap[i].red != b->colormap[i].red) ||
(a->colormap[i].green != b->colormap[i].green) ||
(a->colormap[i].blue != b->colormap[i].blue))
return((int) MagickFalse);
}
return((int) MagickTrue);
}
#endif
static void MngInfoDiscardObject(MngInfo *mng_info,int i)
{
if (i && (i < MNG_MAX_OBJECTS) && (mng_info != (MngInfo *) NULL) &&
mng_info->exists[i] && !mng_info->frozen[i])
{
#ifdef MNG_OBJECT_BUFFERS
if (mng_info->ob[i] != (MngBuffer *) NULL)
{
if (mng_info->ob[i]->reference_count > 0)
mng_info->ob[i]->reference_count--;
if (mng_info->ob[i]->reference_count == 0)
{
if (mng_info->ob[i]->image != (Image *) NULL)
mng_info->ob[i]->image=DestroyImage(mng_info->ob[i]->image);
mng_info->ob[i]=DestroyString(mng_info->ob[i]);
}
}
mng_info->ob[i]=(MngBuffer *) NULL;
#endif
mng_info->exists[i]=MagickFalse;
mng_info->invisible[i]=MagickFalse;
mng_info->viewable[i]=MagickFalse;
mng_info->frozen[i]=MagickFalse;
mng_info->x_off[i]=0;
mng_info->y_off[i]=0;
mng_info->object_clip[i].left=0;
mng_info->object_clip[i].right=(ssize_t) PNG_UINT_31_MAX;
mng_info->object_clip[i].top=0;
mng_info->object_clip[i].bottom=(ssize_t) PNG_UINT_31_MAX;
}
}
static MngInfo *MngInfoFreeStruct(MngInfo *mng_info)
{
register ssize_t
i;
if (mng_info == (MngInfo *) NULL)
return((MngInfo *) NULL);
for (i=1; i < MNG_MAX_OBJECTS; i++)
MngInfoDiscardObject(mng_info,i);
if (mng_info->global_plte != (png_colorp) NULL)
mng_info->global_plte=(png_colorp)
RelinquishMagickMemory(mng_info->global_plte);
return((MngInfo *) RelinquishMagickMemory(mng_info));
}
static MngBox mng_minimum_box(MngBox box1,MngBox box2)
{
MngBox
box;
box=box1;
if (box.left < box2.left)
box.left=box2.left;
if (box.top < box2.top)
box.top=box2.top;
if (box.right > box2.right)
box.right=box2.right;
if (box.bottom > box2.bottom)
box.bottom=box2.bottom;
return box;
}
static MngBox mng_read_box(MngBox previous_box,char delta_type,unsigned char *p)
{
MngBox
box;
/*
Read clipping boundaries from DEFI, CLIP, FRAM, or PAST chunk.
*/
box.left=(ssize_t) ((p[0] << 24) | (p[1] << 16) | (p[2] << 8) | p[3]);
box.right=(ssize_t) ((p[4] << 24) | (p[5] << 16) | (p[6] << 8) | p[7]);
box.top=(ssize_t) ((p[8] << 24) | (p[9] << 16) | (p[10] << 8) | p[11]);
box.bottom=(ssize_t) ((p[12] << 24) | (p[13] << 16) | (p[14] << 8) | p[15]);
if (delta_type != 0)
{
box.left+=previous_box.left;
box.right+=previous_box.right;
box.top+=previous_box.top;
box.bottom+=previous_box.bottom;
}
return(box);
}
static MngPair mng_read_pair(MngPair previous_pair,int delta_type,
unsigned char *p)
{
MngPair
pair;
/*
Read two ssize_ts from CLON, MOVE or PAST chunk
*/
pair.a=(long) ((p[0] << 24) | (p[1] << 16) | (p[2] << 8) | p[3]);
pair.b=(long) ((p[4] << 24) | (p[5] << 16) | (p[6] << 8) | p[7]);
if (delta_type != 0)
{
pair.a+=previous_pair.a;
pair.b+=previous_pair.b;
}
return(pair);
}
static long mng_get_long(unsigned char *p)
{
return((long) ((p[0] << 24) | (p[1] << 16) | (p[2] << 8) | p[3]));
}
typedef struct _PNGErrorInfo
{
Image
*image;
ExceptionInfo
*exception;
} PNGErrorInfo;
static void MagickPNGErrorHandler(png_struct *ping,png_const_charp message)
{
Image
*image;
image=(Image *) png_get_error_ptr(ping);
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" libpng-%s error: %s", PNG_LIBPNG_VER_STRING,message);
(void) ThrowMagickException(&image->exception,GetMagickModule(),CoderError,
message,"`%s'",image->filename);
#if (PNG_LIBPNG_VER < 10500)
/* A warning about deprecated use of jmpbuf here is unavoidable if you
* are building with libpng-1.4.x and can be ignored.
*/
longjmp(ping->jmpbuf,1);
#else
png_longjmp(ping,1);
#endif
}
static void MagickPNGWarningHandler(png_struct *ping,png_const_charp message)
{
Image
*image;
if (LocaleCompare(message, "Missing PLTE before tRNS") == 0)
png_error(ping, message);
image=(Image *) png_get_error_ptr(ping);
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" libpng-%s warning: %s", PNG_LIBPNG_VER_STRING,message);
(void) ThrowMagickException(&image->exception,GetMagickModule(),CoderWarning,
message,"`%s'",image->filename);
}
#ifdef PNG_USER_MEM_SUPPORTED
#if PNG_LIBPNG_VER >= 10400
static png_voidp Magick_png_malloc(png_structp png_ptr,png_alloc_size_t size)
#else
static png_voidp Magick_png_malloc(png_structp png_ptr,png_size_t size)
#endif
{
(void) png_ptr;
return((png_voidp) AcquireMagickMemory((size_t) size));
}
/*
Free a pointer. It is removed from the list at the same time.
*/
static png_free_ptr Magick_png_free(png_structp png_ptr,png_voidp ptr)
{
(void) png_ptr;
ptr=RelinquishMagickMemory(ptr);
return((png_free_ptr) NULL);
}
#endif
#if defined(__cplusplus) || defined(c_plusplus)
}
#endif
static int
Magick_png_read_raw_profile(png_struct *ping,Image *image,
const ImageInfo *image_info, png_textp text,int ii)
{
register ssize_t
i;
register unsigned char
*dp;
register png_charp
sp;
png_uint_32
length,
nibbles;
StringInfo
*profile;
const unsigned char
unhex[103]={0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,1, 2,3,4,5,6,7,8,9,0,0,
0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,10,11,12,
13,14,15};
sp=text[ii].text+1;
/* look for newline */
while (*sp != '\n')
sp++;
/* look for length */
while (*sp == '\0' || *sp == ' ' || *sp == '\n')
sp++;
length=(png_uint_32) StringToLong(sp);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" length: %lu",(unsigned long) length);
while (*sp != ' ' && *sp != '\n')
sp++;
/* allocate space */
if (length == 0)
{
png_warning(ping,"invalid profile length");
return(MagickFalse);
}
profile=BlobToStringInfo((const void *) NULL,length);
if (profile == (StringInfo *) NULL)
{
png_warning(ping, "unable to copy profile");
return(MagickFalse);
}
/* copy profile, skipping white space and column 1 "=" signs */
dp=GetStringInfoDatum(profile);
nibbles=length*2;
for (i=0; i < (ssize_t) nibbles; i++)
{
while (*sp < '0' || (*sp > '9' && *sp < 'a') || *sp > 'f')
{
if (*sp == '\0')
{
png_warning(ping, "ran out of profile data");
return(MagickFalse);
}
sp++;
}
if (i%2 == 0)
*dp=(unsigned char) (16*unhex[(int) *sp++]);
else
(*dp++)+=unhex[(int) *sp++];
}
/*
We have already read "Raw profile type.
*/
(void) SetImageProfile(image,&text[ii].key[17],profile);
profile=DestroyStringInfo(profile);
if (image_info->verbose)
(void) printf(" Found a generic profile, type %s\n",&text[ii].key[17]);
return MagickTrue;
}
#if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
static int read_user_chunk_callback(png_struct *ping, png_unknown_chunkp chunk)
{
Image
*image;
/* The unknown chunk structure contains the chunk data:
png_byte name[5];
png_byte *data;
png_size_t size;
Note that libpng has already taken care of the CRC handling.
*/
LogMagickEvent(CoderEvent,GetMagickModule(),
" read_user_chunk: found %c%c%c%c chunk",
chunk->name[0],chunk->name[1],chunk->name[2],chunk->name[3]);
if (chunk->name[0] == 101 &&
(chunk->name[1] == 88 || chunk->name[1] == 120 ) &&
chunk->name[2] == 73 &&
chunk-> name[3] == 102)
{
/* process eXIf or exIf chunk */
PNGErrorInfo
*error_info;
StringInfo
*profile;
unsigned char
*p;
png_byte
*s;
int
i;
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" recognized eXIf|exIf chunk");
image=(Image *) png_get_user_chunk_ptr(ping);
error_info=(PNGErrorInfo *) png_get_error_ptr(ping);
profile=BlobToStringInfo((const void *) NULL,chunk->size+6);
if (profile == (StringInfo *) NULL)
{
(void) ThrowMagickException(error_info->exception,GetMagickModule(),
ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename);
return(-1);
}
p=GetStringInfoDatum(profile);
/* Initialize profile with "Exif\0\0" */
*p++ ='E';
*p++ ='x';
*p++ ='i';
*p++ ='f';
*p++ ='\0';
*p++ ='\0';
/* copy chunk->data to profile */
s=chunk->data;
for (i=0; i < (ssize_t) chunk->size; i++)
*p++ = *s++;
(void) SetImageProfile(image,"exif",profile);
return(1);
}
/* vpAg (deprecated, replaced by caNv) */
if (chunk->name[0] == 118 &&
chunk->name[1] == 112 &&
chunk->name[2] == 65 &&
chunk->name[3] == 103)
{
/* recognized vpAg */
if (chunk->size != 9)
return(-1); /* Error return */
if (chunk->data[8] != 0)
return(0); /* ImageMagick requires pixel units */
image=(Image *) png_get_user_chunk_ptr(ping);
image->page.width=(size_t) ((chunk->data[0] << 24) |
(chunk->data[1] << 16) | (chunk->data[2] << 8) | chunk->data[3]);
image->page.height=(size_t) ((chunk->data[4] << 24) |
(chunk->data[5] << 16) | (chunk->data[6] << 8) | chunk->data[7]);
return(1);
}
/* caNv */
if (chunk->name[0] == 99 &&
chunk->name[1] == 97 &&
chunk->name[2] == 78 &&
chunk->name[3] == 118)
{
/* recognized caNv */
if (chunk->size != 16)
return(-1); /* Error return */
image=(Image *) png_get_user_chunk_ptr(ping);
image->page.width=(size_t) ((chunk->data[0] << 24) |
(chunk->data[1] << 16) | (chunk->data[2] << 8) | chunk->data[3]);
image->page.height=(size_t) ((chunk->data[4] << 24) |
(chunk->data[5] << 16) | (chunk->data[6] << 8) | chunk->data[7]);
image->page.x=(size_t) ((chunk->data[8] << 24) |
(chunk->data[9] << 16) | (chunk->data[10] << 8) | chunk->data[11]);
image->page.y=(size_t) ((chunk->data[12] << 24) |
(chunk->data[13] << 16) | (chunk->data[14] << 8) | chunk->data[15]);
/* Return one of the following: */
/* return(-n); chunk had an error */
/* return(0); did not recognize */
/* return(n); success */
return(1);
}
return(0); /* Did not recognize */
}
#endif
#if defined(PNG_tIME_SUPPORTED)
static void read_tIME_chunk(Image *image,png_struct *ping,png_info *info)
{
png_timep
time;
if (png_get_tIME(ping,info,&time))
{
char
timestamp[21];
FormatLocaleString(timestamp,21,"%04d-%02d-%02dT%02d:%02d:%02dZ",
time->year,time->month,time->day,time->hour,time->minute,time->second);
SetImageProperty(image,"png:tIME",timestamp);
}
}
#endif
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e a d O n e P N G I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ReadOnePNGImage() reads a Portable Network Graphics (PNG) image file
% (minus the 8-byte signature) 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 ReadOnePNGImage method is:
%
% Image *ReadOnePNGImage(MngInfo *mng_info, const ImageInfo *image_info,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o mng_info: Specifies a pointer to a MngInfo structure.
%
% o image_info: the image info.
%
% o exception: return any errors or warnings in this structure.
%
*/
static Image *ReadOnePNGImage(MngInfo *mng_info,
const ImageInfo *image_info, ExceptionInfo *exception)
{
/* Read one PNG image */
/* To do: Read the tEXt/Creation Time chunk into the date:create property */
Image
*image;
char
im_vers[32],
libpng_runv[32],
libpng_vers[32],
zlib_runv[32],
zlib_vers[32];
int
intent, /* "PNG Rendering intent", which is ICC intent + 1 */
num_raw_profiles,
num_text,
num_text_total,
num_passes,
number_colors,
pass,
ping_bit_depth,
ping_color_type,
ping_file_depth,
ping_interlace_method,
ping_compression_method,
ping_filter_method,
ping_num_trans,
unit_type;
double
file_gamma;
LongPixelPacket
transparent_color;
MagickBooleanType
logging,
ping_found_cHRM,
ping_found_gAMA,
ping_found_iCCP,
ping_found_sRGB,
ping_found_sRGB_cHRM,
ping_preserve_iCCP,
status;
MemoryInfo
*volatile pixel_info;
png_bytep
ping_trans_alpha;
png_color_16p
ping_background,
ping_trans_color;
png_info
*end_info,
*ping_info;
png_struct
*ping;
png_textp
text;
png_uint_32
ping_height,
ping_width,
x_resolution,
y_resolution;
ssize_t
ping_rowbytes,
y;
register unsigned char
*p;
register IndexPacket
*indexes;
register ssize_t
i,
x;
register PixelPacket
*q;
size_t
length,
row_offset;
ssize_t
j;
unsigned char
*ping_pixels;
#ifdef PNG_UNKNOWN_CHUNKS_SUPPORTED
png_byte unused_chunks[]=
{
104, 73, 83, 84, (png_byte) '\0', /* hIST */
105, 84, 88, 116, (png_byte) '\0', /* iTXt */
112, 67, 65, 76, (png_byte) '\0', /* pCAL */
115, 67, 65, 76, (png_byte) '\0', /* sCAL */
115, 80, 76, 84, (png_byte) '\0', /* sPLT */
#if !defined(PNG_tIME_SUPPORTED)
116, 73, 77, 69, (png_byte) '\0', /* tIME */
#endif
#ifdef PNG_APNG_SUPPORTED /* libpng was built with APNG patch; */
/* ignore the APNG chunks */
97, 99, 84, 76, (png_byte) '\0', /* acTL */
102, 99, 84, 76, (png_byte) '\0', /* fcTL */
102, 100, 65, 84, (png_byte) '\0', /* fdAT */
#endif
};
#endif
/* Define these outside of the following "if logging()" block so they will
* show in debuggers.
*/
*im_vers='\0';
(void) ConcatenateMagickString(im_vers,
MagickLibVersionText,32);
(void) ConcatenateMagickString(im_vers,
MagickLibAddendum,32);
*libpng_vers='\0';
(void) ConcatenateMagickString(libpng_vers,
PNG_LIBPNG_VER_STRING,32);
*libpng_runv='\0';
(void) ConcatenateMagickString(libpng_runv,
png_get_libpng_ver(NULL),32);
*zlib_vers='\0';
(void) ConcatenateMagickString(zlib_vers,
ZLIB_VERSION,32);
*zlib_runv='\0';
(void) ConcatenateMagickString(zlib_runv,
zlib_version,32);
logging=LogMagickEvent(CoderEvent,GetMagickModule(),
" Enter ReadOnePNGImage()\n"
" IM version = %s\n"
" Libpng version = %s",
im_vers, libpng_vers);
if (logging != MagickFalse)
{
if (LocaleCompare(libpng_vers,libpng_runv) != 0)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule()," running with %s",
libpng_runv);
}
(void) LogMagickEvent(CoderEvent,GetMagickModule()," Zlib version = %s",
zlib_vers);
if (LocaleCompare(zlib_vers,zlib_runv) != 0)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule()," running with %s",
zlib_runv);
}
}
#if (PNG_LIBPNG_VER < 10200)
if (image_info->verbose)
printf("Your PNG library (libpng-%s) is rather old.\n",
PNG_LIBPNG_VER_STRING);
#endif
#if (PNG_LIBPNG_VER >= 10400)
# ifndef PNG_TRANSFORM_GRAY_TO_RGB /* Added at libpng-1.4.0beta67 */
if (image_info->verbose)
{
printf("Your PNG library (libpng-%s) is an old beta version.\n",
PNG_LIBPNG_VER_STRING);
printf("Please update it.\n");
}
# endif
#endif
image=mng_info->image;
if (logging != MagickFalse)
{
(void)LogMagickEvent(CoderEvent,GetMagickModule(),
" Before reading:\n"
" image->matte=%d\n"
" image->rendering_intent=%d\n"
" image->colorspace=%d\n"
" image->gamma=%f",
(int) image->matte, (int) image->rendering_intent,
(int) image->colorspace, image->gamma);
}
intent=Magick_RenderingIntent_to_PNG_RenderingIntent(image->rendering_intent);
/* Set to an out-of-range color unless tRNS chunk is present */
transparent_color.red=65537;
transparent_color.green=65537;
transparent_color.blue=65537;
transparent_color.opacity=65537;
number_colors=0;
num_text = 0;
num_text_total = 0;
num_raw_profiles = 0;
ping_found_cHRM = MagickFalse;
ping_found_gAMA = MagickFalse;
ping_found_iCCP = MagickFalse;
ping_found_sRGB = MagickFalse;
ping_found_sRGB_cHRM = MagickFalse;
ping_preserve_iCCP = MagickFalse;
/*
Allocate the PNG structures
*/
#ifdef PNG_USER_MEM_SUPPORTED
ping=png_create_read_struct_2(PNG_LIBPNG_VER_STRING, image,
MagickPNGErrorHandler,MagickPNGWarningHandler, NULL,
(png_malloc_ptr) Magick_png_malloc,(png_free_ptr) Magick_png_free);
#else
ping=png_create_read_struct(PNG_LIBPNG_VER_STRING,image,
MagickPNGErrorHandler,MagickPNGWarningHandler);
#endif
if (ping == (png_struct *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
ping_info=png_create_info_struct(ping);
if (ping_info == (png_info *) NULL)
{
png_destroy_read_struct(&ping,(png_info **) NULL,(png_info **) NULL);
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
end_info=png_create_info_struct(ping);
if (end_info == (png_info *) NULL)
{
png_destroy_read_struct(&ping,&ping_info,(png_info **) NULL);
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
pixel_info=(MemoryInfo *) NULL;
if (setjmp(png_jmpbuf(ping)))
{
/*
PNG image is corrupt.
*/
png_destroy_read_struct(&ping,&ping_info,&end_info);
#ifdef IMPNG_SETJMP_NOT_THREAD_SAFE
UnlockSemaphoreInfo(ping_semaphore);
#endif
if (pixel_info != (MemoryInfo *) NULL)
pixel_info=RelinquishVirtualMemory(pixel_info);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" exit ReadOnePNGImage() with error.");
if (image != (Image *) NULL)
InheritException(exception,&image->exception);
return(GetFirstImageInList(image));
}
/* { For navigation to end of SETJMP-protected block. Within this
* block, use png_error() instead of Throwing an Exception, to ensure
* that libpng is able to clean up, and that the semaphore is unlocked.
*/
#ifdef IMPNG_SETJMP_NOT_THREAD_SAFE
LockSemaphoreInfo(ping_semaphore);
#endif
#ifdef PNG_BENIGN_ERRORS_SUPPORTED
/* Allow benign errors */
png_set_benign_errors(ping, 1);
#endif
#ifdef PNG_SET_USER_LIMITS_SUPPORTED
/* Reject images with too many rows or columns */
png_set_user_limits(ping,
(png_uint_32) MagickMin(0x7fffffffL,
GetMagickResourceLimit(WidthResource)),
(png_uint_32) MagickMin(0x7fffffffL,
GetMagickResourceLimit(HeightResource)));
#endif /* PNG_SET_USER_LIMITS_SUPPORTED */
/*
Prepare PNG for reading.
*/
mng_info->image_found++;
png_set_sig_bytes(ping,8);
if (LocaleCompare(image_info->magick,"MNG") == 0)
{
#if defined(PNG_MNG_FEATURES_SUPPORTED)
(void) png_permit_mng_features(ping,PNG_ALL_MNG_FEATURES);
png_set_read_fn(ping,image,png_get_data);
#else
#if defined(PNG_READ_EMPTY_PLTE_SUPPORTED)
png_permit_empty_plte(ping,MagickTrue);
png_set_read_fn(ping,image,png_get_data);
#else
mng_info->image=image;
mng_info->bytes_in_read_buffer=0;
mng_info->found_empty_plte=MagickFalse;
mng_info->have_saved_bkgd_index=MagickFalse;
png_set_read_fn(ping,mng_info,mng_get_data);
#endif
#endif
}
else
png_set_read_fn(ping,image,png_get_data);
{
const char
*value;
value=GetImageOption(image_info,"profile:skip");
if (IsOptionMember("ICC",value) == MagickFalse)
{
value=GetImageOption(image_info,"png:preserve-iCCP");
if (value == NULL)
value=GetImageArtifact(image,"png:preserve-iCCP");
if (value != NULL)
ping_preserve_iCCP=MagickTrue;
#if defined(PNG_SKIP_sRGB_CHECK_PROFILE) && defined(PNG_SET_OPTION_SUPPORTED)
/* Don't let libpng check for ICC/sRGB profile because we're going
* to do that anyway. This feature was added at libpng-1.6.12.
* If logging, go ahead and check and issue a warning as appropriate.
*/
if (logging == MagickFalse)
png_set_option(ping, PNG_SKIP_sRGB_CHECK_PROFILE, PNG_OPTION_ON);
#endif
}
#if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
else
{
/* Ignore the iCCP chunk */
png_set_keep_unknown_chunks(ping, 1, mng_iCCP, 1);
}
#endif
}
#if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
/* Ignore unused chunks and all unknown chunks except for exIf, caNv,
and vpAg */
# if PNG_LIBPNG_VER < 10700 /* Avoid libpng16 warning */
png_set_keep_unknown_chunks(ping, 2, NULL, 0);
# else
png_set_keep_unknown_chunks(ping, 1, NULL, 0);
# endif
png_set_keep_unknown_chunks(ping, 2, mng_exIf, 1);
png_set_keep_unknown_chunks(ping, 2, mng_caNv, 1);
png_set_keep_unknown_chunks(ping, 2, mng_vpAg, 1);
png_set_keep_unknown_chunks(ping, 1, unused_chunks,
(int)sizeof(unused_chunks)/5);
/* Callback for other unknown chunks */
png_set_read_user_chunk_fn(ping, image, read_user_chunk_callback);
#endif
#ifdef PNG_SET_USER_LIMITS_SUPPORTED
#if (PNG_LIBPNG_VER >= 10400)
/* Limit the size of the chunk storage cache used for sPLT, text,
* and unknown chunks.
*/
png_set_chunk_cache_max(ping, 32767);
#endif
#endif
#ifdef PNG_READ_CHECK_FOR_INVALID_INDEX_SUPPORTED
/* Disable new libpng-1.5.10 feature */
png_set_check_for_invalid_index (ping, 0);
#endif
#if (PNG_LIBPNG_VER < 10400)
# if defined(PNG_USE_PNGGCCRD) && defined(PNG_ASSEMBLER_CODE_SUPPORTED) && \
(PNG_LIBPNG_VER >= 10200) && (PNG_LIBPNG_VER < 10220) && defined(__i386__)
/* Disable thread-unsafe features of pnggccrd */
if (png_access_version_number() >= 10200)
{
png_uint_32 mmx_disable_mask=0;
png_uint_32 asm_flags;
mmx_disable_mask |= ( PNG_ASM_FLAG_MMX_READ_COMBINE_ROW \
| PNG_ASM_FLAG_MMX_READ_FILTER_SUB \
| PNG_ASM_FLAG_MMX_READ_FILTER_AVG \
| PNG_ASM_FLAG_MMX_READ_FILTER_PAETH );
asm_flags=png_get_asm_flags(ping);
png_set_asm_flags(ping, asm_flags & ~mmx_disable_mask);
}
# endif
#endif
png_read_info(ping,ping_info);
/* Read and check IHDR chunk data */
png_get_IHDR(ping,ping_info,&ping_width,&ping_height,
&ping_bit_depth,&ping_color_type,
&ping_interlace_method,&ping_compression_method,
&ping_filter_method);
ping_file_depth = ping_bit_depth;
/* Swap bytes if requested */
if (ping_file_depth == 16)
{
const char
*value;
value=GetImageOption(image_info,"png:swap-bytes");
if (value == NULL)
value=GetImageArtifact(image,"png:swap-bytes");
if (value != NULL)
png_set_swap(ping);
}
/* Save bit-depth and color-type in case we later want to write a PNG00 */
{
char
msg[MaxTextExtent];
(void) FormatLocaleString(msg,MaxTextExtent,"%d",(int) ping_color_type);
(void) SetImageProperty(image,"png:IHDR.color-type-orig",msg);
(void) FormatLocaleString(msg,MaxTextExtent,"%d",(int) ping_bit_depth);
(void) SetImageProperty(image,"png:IHDR.bit-depth-orig",msg);
}
(void) png_get_tRNS(ping, ping_info, &ping_trans_alpha, &ping_num_trans,
&ping_trans_color);
(void) png_get_bKGD(ping, ping_info, &ping_background);
if (ping_bit_depth < 8)
{
png_set_packing(ping);
ping_bit_depth = 8;
}
image->depth=ping_bit_depth;
image->depth=GetImageQuantumDepth(image,MagickFalse);
image->interlace=ping_interlace_method != 0 ? PNGInterlace : NoInterlace;
if (((int) ping_color_type == PNG_COLOR_TYPE_GRAY) ||
((int) ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA))
{
image->rendering_intent=UndefinedIntent;
intent=Magick_RenderingIntent_to_PNG_RenderingIntent(UndefinedIntent);
(void) ResetMagickMemory(&image->chromaticity,0,
sizeof(image->chromaticity));
}
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" PNG width: %.20g, height: %.20g\n"
" PNG color_type: %d, bit_depth: %d\n"
" PNG compression_method: %d\n"
" PNG interlace_method: %d, filter_method: %d",
(double) ping_width, (double) ping_height,
ping_color_type, ping_bit_depth,
ping_compression_method,
ping_interlace_method,ping_filter_method);
}
if (png_get_valid(ping,ping_info, PNG_INFO_iCCP))
{
ping_found_iCCP=MagickTrue;
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Found PNG iCCP chunk.");
}
if (png_get_valid(ping,ping_info,PNG_INFO_gAMA))
{
ping_found_gAMA=MagickTrue;
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Found PNG gAMA chunk.");
}
if (png_get_valid(ping,ping_info,PNG_INFO_cHRM))
{
ping_found_cHRM=MagickTrue;
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Found PNG cHRM chunk.");
}
if (ping_found_iCCP != MagickTrue && png_get_valid(ping,ping_info,
PNG_INFO_sRGB))
{
ping_found_sRGB=MagickTrue;
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Found PNG sRGB chunk.");
}
#ifdef PNG_READ_iCCP_SUPPORTED
if (ping_found_iCCP !=MagickTrue &&
ping_found_sRGB != MagickTrue &&
png_get_valid(ping,ping_info, PNG_INFO_iCCP))
{
ping_found_iCCP=MagickTrue;
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Found PNG iCCP chunk.");
}
if (png_get_valid(ping,ping_info,PNG_INFO_iCCP))
{
int
compression;
#if (PNG_LIBPNG_VER < 10500)
png_charp
info;
#else
png_bytep
info;
#endif
png_charp
name;
png_uint_32
profile_length;
(void) png_get_iCCP(ping,ping_info,&name,(int *) &compression,&info,
&profile_length);
if (profile_length != 0)
{
StringInfo
*profile;
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Reading PNG iCCP chunk.");
profile=BlobToStringInfo(info,profile_length);
if (profile == (StringInfo *) NULL)
{
png_warning(ping, "ICC profile is NULL");
profile=DestroyStringInfo(profile);
}
else
{
if (ping_preserve_iCCP == MagickFalse)
{
int
icheck,
got_crc=0;
png_uint_32
length,
profile_crc=0;
unsigned char
*data;
length=(png_uint_32) GetStringInfoLength(profile);
for (icheck=0; sRGB_info[icheck].len > 0; icheck++)
{
if (length == sRGB_info[icheck].len)
{
if (got_crc == 0)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Got a %lu-byte ICC profile (potentially sRGB)",
(unsigned long) length);
data=GetStringInfoDatum(profile);
profile_crc=crc32(0,data,length);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" with crc=%8x",(unsigned int) profile_crc);
got_crc++;
}
if (profile_crc == sRGB_info[icheck].crc)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" It is sRGB with rendering intent = %s",
Magick_RenderingIntentString_from_PNG_RenderingIntent(
sRGB_info[icheck].intent));
if (image->rendering_intent==UndefinedIntent)
{
image->rendering_intent=
Magick_RenderingIntent_from_PNG_RenderingIntent(
sRGB_info[icheck].intent);
}
break;
}
}
}
if (sRGB_info[icheck].len == 0)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Got a %lu-byte ICC profile not recognized as sRGB",
(unsigned long) length);
(void) SetImageProfile(image,"icc",profile);
}
}
else /* Preserve-iCCP */
{
(void) SetImageProfile(image,"icc",profile);
}
profile=DestroyStringInfo(profile);
}
}
}
#endif
#if defined(PNG_READ_sRGB_SUPPORTED)
{
if (ping_found_iCCP==MagickFalse && png_get_valid(ping,ping_info,
PNG_INFO_sRGB))
{
if (png_get_sRGB(ping,ping_info,&intent))
{
if (image->rendering_intent == UndefinedIntent)
image->rendering_intent=
Magick_RenderingIntent_from_PNG_RenderingIntent (intent);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Reading PNG sRGB chunk: rendering_intent: %d",intent);
}
}
else if (mng_info->have_global_srgb)
{
if (image->rendering_intent == UndefinedIntent)
image->rendering_intent=
Magick_RenderingIntent_from_PNG_RenderingIntent
(mng_info->global_srgb_intent);
}
}
#endif
{
if (!png_get_gAMA(ping,ping_info,&file_gamma))
if (mng_info->have_global_gama)
png_set_gAMA(ping,ping_info,mng_info->global_gamma);
if (png_get_gAMA(ping,ping_info,&file_gamma))
{
image->gamma=(float) file_gamma;
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Reading PNG gAMA chunk: gamma: %f",file_gamma);
}
}
if (!png_get_valid(ping,ping_info,PNG_INFO_cHRM))
{
if (mng_info->have_global_chrm != MagickFalse)
{
(void) png_set_cHRM(ping,ping_info,
mng_info->global_chrm.white_point.x,
mng_info->global_chrm.white_point.y,
mng_info->global_chrm.red_primary.x,
mng_info->global_chrm.red_primary.y,
mng_info->global_chrm.green_primary.x,
mng_info->global_chrm.green_primary.y,
mng_info->global_chrm.blue_primary.x,
mng_info->global_chrm.blue_primary.y);
}
}
if (png_get_valid(ping,ping_info,PNG_INFO_cHRM))
{
(void) png_get_cHRM(ping,ping_info,
&image->chromaticity.white_point.x,
&image->chromaticity.white_point.y,
&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);
ping_found_cHRM=MagickTrue;
if (image->chromaticity.red_primary.x>0.6399f &&
image->chromaticity.red_primary.x<0.6401f &&
image->chromaticity.red_primary.y>0.3299f &&
image->chromaticity.red_primary.y<0.3301f &&
image->chromaticity.green_primary.x>0.2999f &&
image->chromaticity.green_primary.x<0.3001f &&
image->chromaticity.green_primary.y>0.5999f &&
image->chromaticity.green_primary.y<0.6001f &&
image->chromaticity.blue_primary.x>0.1499f &&
image->chromaticity.blue_primary.x<0.1501f &&
image->chromaticity.blue_primary.y>0.0599f &&
image->chromaticity.blue_primary.y<0.0601f &&
image->chromaticity.white_point.x>0.3126f &&
image->chromaticity.white_point.x<0.3128f &&
image->chromaticity.white_point.y>0.3289f &&
image->chromaticity.white_point.y<0.3291f)
ping_found_sRGB_cHRM=MagickTrue;
}
if (image->rendering_intent != UndefinedIntent)
{
if (ping_found_sRGB != MagickTrue &&
(ping_found_gAMA != MagickTrue ||
(image->gamma > .45 && image->gamma < .46)) &&
(ping_found_cHRM != MagickTrue ||
ping_found_sRGB_cHRM != MagickFalse) &&
ping_found_iCCP != MagickTrue)
{
png_set_sRGB(ping,ping_info,
Magick_RenderingIntent_to_PNG_RenderingIntent
(image->rendering_intent));
file_gamma=1.000f/2.200f;
ping_found_sRGB=MagickTrue;
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Setting sRGB as if in input");
}
}
#if defined(PNG_oFFs_SUPPORTED)
if (png_get_valid(ping,ping_info,PNG_INFO_oFFs))
{
image->page.x=(ssize_t) png_get_x_offset_pixels(ping, ping_info);
image->page.y=(ssize_t) png_get_y_offset_pixels(ping, ping_info);
if (logging != MagickFalse)
if (image->page.x || image->page.y)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Reading PNG oFFs chunk: x: %.20g, y: %.20g.",(double)
image->page.x,(double) image->page.y);
}
#endif
#if defined(PNG_pHYs_SUPPORTED)
if (!png_get_valid(ping,ping_info,PNG_INFO_pHYs))
{
if (mng_info->have_global_phys)
{
png_set_pHYs(ping,ping_info,
mng_info->global_x_pixels_per_unit,
mng_info->global_y_pixels_per_unit,
mng_info->global_phys_unit_type);
}
}
x_resolution=0;
y_resolution=0;
unit_type=0;
if (png_get_valid(ping,ping_info,PNG_INFO_pHYs))
{
/*
Set image resolution.
*/
(void) png_get_pHYs(ping,ping_info,&x_resolution,&y_resolution,
&unit_type);
image->x_resolution=(double) x_resolution;
image->y_resolution=(double) y_resolution;
if (unit_type == PNG_RESOLUTION_METER)
{
image->units=PixelsPerCentimeterResolution;
image->x_resolution=(double) x_resolution/100.0;
image->y_resolution=(double) y_resolution/100.0;
}
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Reading PNG pHYs chunk: xres: %.20g, yres: %.20g, units: %d.",
(double) x_resolution,(double) y_resolution,unit_type);
}
#endif
if (png_get_valid(ping,ping_info,PNG_INFO_PLTE))
{
png_colorp
palette;
(void) png_get_PLTE(ping,ping_info,&palette,&number_colors);
if ((number_colors == 0) &&
((int) ping_color_type == PNG_COLOR_TYPE_PALETTE))
{
if (mng_info->global_plte_length)
{
png_set_PLTE(ping,ping_info,mng_info->global_plte,
(int) mng_info->global_plte_length);
if (!png_get_valid(ping,ping_info,PNG_INFO_tRNS))
if (mng_info->global_trns_length)
{
if (mng_info->global_trns_length >
mng_info->global_plte_length)
{
png_warning(ping,
"global tRNS has more entries than global PLTE");
}
else
{
png_set_tRNS(ping,ping_info,mng_info->global_trns,
(int) mng_info->global_trns_length,NULL);
}
}
#ifdef PNG_READ_bKGD_SUPPORTED
if (
#ifndef PNG_READ_EMPTY_PLTE_SUPPORTED
mng_info->have_saved_bkgd_index ||
#endif
png_get_valid(ping,ping_info,PNG_INFO_bKGD))
{
png_color_16
background;
#ifndef PNG_READ_EMPTY_PLTE_SUPPORTED
if (mng_info->have_saved_bkgd_index)
background.index=mng_info->saved_bkgd_index;
#endif
if (png_get_valid(ping, ping_info, PNG_INFO_bKGD))
background.index=ping_background->index;
background.red=(png_uint_16)
mng_info->global_plte[background.index].red;
background.green=(png_uint_16)
mng_info->global_plte[background.index].green;
background.blue=(png_uint_16)
mng_info->global_plte[background.index].blue;
background.gray=(png_uint_16)
mng_info->global_plte[background.index].green;
png_set_bKGD(ping,ping_info,&background);
}
#endif
}
else
png_error(ping,"No global PLTE in file");
}
}
#ifdef PNG_READ_bKGD_SUPPORTED
if (mng_info->have_global_bkgd &&
(!png_get_valid(ping,ping_info,PNG_INFO_bKGD)))
image->background_color=mng_info->mng_global_bkgd;
if (png_get_valid(ping,ping_info,PNG_INFO_bKGD))
{
unsigned int
bkgd_scale;
/* Set image background color.
* Scale background components to 16-bit, then scale
* to quantum depth
*/
bkgd_scale = 1;
if (ping_file_depth == 1)
bkgd_scale = 255;
else if (ping_file_depth == 2)
bkgd_scale = 85;
else if (ping_file_depth == 4)
bkgd_scale = 17;
if (ping_file_depth <= 8)
bkgd_scale *= 257;
ping_background->red *= bkgd_scale;
ping_background->green *= bkgd_scale;
ping_background->blue *= bkgd_scale;
if (logging != MagickFalse)
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Reading PNG bKGD chunk, raw ping_background=(%d,%d,%d).\n"
" bkgd_scale=%d. ping_background=(%d,%d,%d).",
ping_background->red,ping_background->green,
ping_background->blue,
bkgd_scale,ping_background->red,
ping_background->green,ping_background->blue);
}
image->background_color.red=
ScaleShortToQuantum(ping_background->red);
image->background_color.green=
ScaleShortToQuantum(ping_background->green);
image->background_color.blue=
ScaleShortToQuantum(ping_background->blue);
image->background_color.opacity=OpaqueOpacity;
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image->background_color=(%.20g,%.20g,%.20g).",
(double) image->background_color.red,
(double) image->background_color.green,
(double) image->background_color.blue);
}
#endif /* PNG_READ_bKGD_SUPPORTED */
if (png_get_valid(ping,ping_info,PNG_INFO_tRNS))
{
/*
Image has a tRNS chunk.
*/
int
max_sample;
size_t
one=1;
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Reading PNG tRNS chunk.");
max_sample = (int) ((one << ping_file_depth) - 1);
if ((ping_color_type == PNG_COLOR_TYPE_GRAY &&
(int)ping_trans_color->gray > max_sample) ||
(ping_color_type == PNG_COLOR_TYPE_RGB &&
((int)ping_trans_color->red > max_sample ||
(int)ping_trans_color->green > max_sample ||
(int)ping_trans_color->blue > max_sample)))
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Ignoring PNG tRNS chunk with out-of-range sample.");
png_free_data(ping, ping_info, PNG_FREE_TRNS, 0);
png_set_invalid(ping,ping_info,PNG_INFO_tRNS);
image->matte=MagickFalse;
}
else
{
int
scale_to_short;
scale_to_short = 65535L/((1UL << ping_file_depth)-1);
/* Scale transparent_color to short */
transparent_color.red= scale_to_short*ping_trans_color->red;
transparent_color.green= scale_to_short*ping_trans_color->green;
transparent_color.blue= scale_to_short*ping_trans_color->blue;
transparent_color.opacity= scale_to_short*ping_trans_color->gray;
if (ping_color_type == PNG_COLOR_TYPE_GRAY)
{
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Raw tRNS graylevel = %d, scaled graylevel = %d.",
ping_trans_color->gray,transparent_color.opacity);
}
transparent_color.red=transparent_color.opacity;
transparent_color.green=transparent_color.opacity;
transparent_color.blue=transparent_color.opacity;
}
}
}
#if defined(PNG_READ_sBIT_SUPPORTED)
if (mng_info->have_global_sbit)
{
if (!png_get_valid(ping,ping_info,PNG_INFO_sBIT))
png_set_sBIT(ping,ping_info,&mng_info->global_sbit);
}
#endif
num_passes=png_set_interlace_handling(ping);
png_read_update_info(ping,ping_info);
ping_rowbytes=png_get_rowbytes(ping,ping_info);
/*
Initialize image structure.
*/
mng_info->image_box.left=0;
mng_info->image_box.right=(ssize_t) ping_width;
mng_info->image_box.top=0;
mng_info->image_box.bottom=(ssize_t) ping_height;
if (mng_info->mng_type == 0)
{
mng_info->mng_width=ping_width;
mng_info->mng_height=ping_height;
mng_info->frame=mng_info->image_box;
mng_info->clip=mng_info->image_box;
}
else
{
image->page.y=mng_info->y_off[mng_info->object_id];
}
image->compression=ZipCompression;
image->columns=ping_width;
image->rows=ping_height;
if (((int) ping_color_type == PNG_COLOR_TYPE_PALETTE) ||
((int) ping_bit_depth < 16 &&
(int) ping_color_type == PNG_COLOR_TYPE_GRAY))
{
size_t
one;
image->storage_class=PseudoClass;
one=1;
image->colors=one << ping_file_depth;
#if (MAGICKCORE_QUANTUM_DEPTH == 8)
if (image->colors > 256)
image->colors=256;
#else
if (image->colors > 65536L)
image->colors=65536L;
#endif
if ((int) ping_color_type == PNG_COLOR_TYPE_PALETTE)
{
png_colorp
palette;
(void) png_get_PLTE(ping,ping_info,&palette,&number_colors);
image->colors=(size_t) number_colors;
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Reading PNG PLTE chunk: number_colors: %d.",number_colors);
}
}
if (image->storage_class == PseudoClass)
{
/*
Initialize image colormap.
*/
if (AcquireImageColormap(image,image->colors) == MagickFalse)
png_error(ping,"Memory allocation failed");
if ((int) ping_color_type == PNG_COLOR_TYPE_PALETTE)
{
png_colorp
palette;
(void) png_get_PLTE(ping,ping_info,&palette,&number_colors);
for (i=0; i < (ssize_t) number_colors; i++)
{
image->colormap[i].red=ScaleCharToQuantum(palette[i].red);
image->colormap[i].green=ScaleCharToQuantum(palette[i].green);
image->colormap[i].blue=ScaleCharToQuantum(palette[i].blue);
}
for ( ; i < (ssize_t) image->colors; i++)
{
image->colormap[i].red=0;
image->colormap[i].green=0;
image->colormap[i].blue=0;
}
}
else
{
Quantum
scale;
scale = 65535/((1UL << ping_file_depth)-1);
#if (MAGICKCORE_QUANTUM_DEPTH > 16)
scale = ScaleShortToQuantum(scale);
#endif
for (i=0; i < (ssize_t) image->colors; i++)
{
image->colormap[i].red=(Quantum) (i*scale);
image->colormap[i].green=(Quantum) (i*scale);
image->colormap[i].blue=(Quantum) (i*scale);
}
}
}
/* Set some properties for reporting by "identify" */
{
char
msg[MaxTextExtent];
/* encode ping_width, ping_height, ping_file_depth, ping_color_type,
ping_interlace_method in value */
(void) FormatLocaleString(msg,MaxTextExtent,
"%d, %d",(int) ping_width, (int) ping_height);
(void) SetImageProperty(image,"png:IHDR.width,height",msg);
(void) FormatLocaleString(msg,MaxTextExtent,"%d",(int) ping_file_depth);
(void) SetImageProperty(image,"png:IHDR.bit_depth",msg);
(void) FormatLocaleString(msg,MaxTextExtent,"%d (%s)",
(int) ping_color_type,
Magick_ColorType_from_PNG_ColorType((int)ping_color_type));
(void) SetImageProperty(image,"png:IHDR.color_type",msg);
if (ping_interlace_method == 0)
{
(void) FormatLocaleString(msg,MaxTextExtent,"%d (Not interlaced)",
(int) ping_interlace_method);
}
else if (ping_interlace_method == 1)
{
(void) FormatLocaleString(msg,MaxTextExtent,"%d (Adam7 method)",
(int) ping_interlace_method);
}
else
{
(void) FormatLocaleString(msg,MaxTextExtent,"%d (Unknown method)",
(int) ping_interlace_method);
}
(void) SetImageProperty(image,"png:IHDR.interlace_method",msg);
if (number_colors != 0)
{
(void) FormatLocaleString(msg,MaxTextExtent,"%d",
(int) number_colors);
(void) SetImageProperty(image,"png:PLTE.number_colors",msg);
}
}
#if defined(PNG_tIME_SUPPORTED)
read_tIME_chunk(image,ping,ping_info);
#endif
/*
Read image scanlines.
*/
if (image->delay != 0)
mng_info->scenes_found++;
if ((mng_info->mng_type == 0 && (image->ping != MagickFalse)) || (
(image_info->number_scenes != 0) && (mng_info->scenes_found > (ssize_t)
(image_info->first_scene+image_info->number_scenes))))
{
/* This happens later in non-ping decodes */
if (png_get_valid(ping,ping_info,PNG_INFO_tRNS))
image->storage_class=DirectClass;
image->matte=(((int) ping_color_type == PNG_COLOR_TYPE_RGB_ALPHA) ||
((int) ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA) ||
(png_get_valid(ping,ping_info,PNG_INFO_tRNS))) ?
MagickTrue : MagickFalse;
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Skipping PNG image data for scene %.20g",(double)
mng_info->scenes_found-1);
png_destroy_read_struct(&ping,&ping_info,&end_info);
#ifdef IMPNG_SETJMP_NOT_THREAD_SAFE
UnlockSemaphoreInfo(ping_semaphore);
#endif
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" exit ReadOnePNGImage().");
return(image);
}
status=SetImageExtent(image,image->columns,image->rows);
if (status == MagickFalse)
{
InheritException(exception,&image->exception);
return(DestroyImageList(image));
}
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Reading PNG IDAT chunk(s)");
if (num_passes > 1)
pixel_info=AcquireVirtualMemory(image->rows,ping_rowbytes*
sizeof(*ping_pixels));
else
pixel_info=AcquireVirtualMemory(ping_rowbytes,sizeof(*ping_pixels));
if (pixel_info == (MemoryInfo *) NULL)
png_error(ping,"Memory allocation failed");
ping_pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Converting PNG pixels to pixel packets");
/*
Convert PNG pixels to pixel packets.
*/
{
MagickBooleanType
found_transparent_pixel;
found_transparent_pixel=MagickFalse;
if (image->storage_class == DirectClass)
{
QuantumInfo
*quantum_info;
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
png_error(ping,"Failed to allocate quantum_info");
(void) SetQuantumEndian(image,quantum_info,MSBEndian);
for (pass=0; pass < num_passes; pass++)
{
/*
Convert image to DirectClass pixel packets.
*/
image->matte=(((int) ping_color_type == PNG_COLOR_TYPE_RGB_ALPHA) ||
((int) ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA) ||
(png_get_valid(ping,ping_info,PNG_INFO_tRNS))) ?
MagickTrue : MagickFalse;
for (y=0; y < (ssize_t) image->rows; y++)
{
if (num_passes > 1)
row_offset=ping_rowbytes*y;
else
row_offset=0;
png_read_row(ping,ping_pixels+row_offset,NULL);
if (pass < num_passes-1)
continue;
q=GetAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
else
{
if ((int) ping_color_type == PNG_COLOR_TYPE_GRAY)
(void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,
GrayQuantum,ping_pixels+row_offset,exception);
else if ((int) ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
(void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,
GrayAlphaQuantum,ping_pixels+row_offset,exception);
else if ((int) ping_color_type == PNG_COLOR_TYPE_RGB_ALPHA)
(void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,
RGBAQuantum,ping_pixels+row_offset,exception);
else if ((int) ping_color_type == PNG_COLOR_TYPE_PALETTE)
(void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,
IndexQuantum,ping_pixels+row_offset,exception);
else /* ping_color_type == PNG_COLOR_TYPE_RGB */
(void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,
RGBQuantum,ping_pixels+row_offset,exception);
}
if (found_transparent_pixel == MagickFalse)
{
/* Is there a transparent pixel in the row? */
if (y== 0 && logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Looking for cheap transparent pixel");
for (x=(ssize_t) image->columns-1; x >= 0; x--)
{
if ((ping_color_type == PNG_COLOR_TYPE_RGBA ||
ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA) &&
(GetPixelOpacity(q) != OpaqueOpacity))
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" ...got one.");
found_transparent_pixel = MagickTrue;
break;
}
if ((ping_color_type == PNG_COLOR_TYPE_RGB ||
ping_color_type == PNG_COLOR_TYPE_GRAY) &&
(ScaleQuantumToShort(GetPixelRed(q))
== transparent_color.red &&
ScaleQuantumToShort(GetPixelGreen(q))
== transparent_color.green &&
ScaleQuantumToShort(GetPixelBlue(q))
== transparent_color.blue))
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" ...got one.");
found_transparent_pixel = MagickTrue;
break;
}
q++;
}
}
if (num_passes == 1)
{
status=SetImageProgress(image,LoadImageTag,
(MagickOffsetType) y, image->rows);
if (status == MagickFalse)
break;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
if (num_passes != 1)
{
status=SetImageProgress(image,LoadImageTag,pass,num_passes);
if (status == MagickFalse)
break;
}
}
quantum_info=DestroyQuantumInfo(quantum_info);
}
else /* image->storage_class != DirectClass */
for (pass=0; pass < num_passes; pass++)
{
Quantum
*quantum_scanline;
register Quantum
*r;
/*
Convert grayscale image to PseudoClass pixel packets.
*/
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Converting grayscale pixels to pixel packets");
image->matte=ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA ?
MagickTrue : MagickFalse;
quantum_scanline=(Quantum *) AcquireQuantumMemory(image->columns,
(image->matte ? 2 : 1)*sizeof(*quantum_scanline));
if (quantum_scanline == (Quantum *) NULL)
png_error(ping,"Memory allocation failed");
for (y=0; y < (ssize_t) image->rows; y++)
{
Quantum
alpha;
if (num_passes > 1)
row_offset=ping_rowbytes*y;
else
row_offset=0;
png_read_row(ping,ping_pixels+row_offset,NULL);
if (pass < num_passes-1)
continue;
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
indexes=GetAuthenticIndexQueue(image);
p=ping_pixels+row_offset;
r=quantum_scanline;
switch (ping_bit_depth)
{
case 8:
{
if (ping_color_type == 4)
for (x=(ssize_t) image->columns-1; x >= 0; x--)
{
*r++=*p++;
/* In image.h, OpaqueOpacity is 0
* TransparentOpacity is QuantumRange
* In a PNG datastream, Opaque is QuantumRange
* and Transparent is 0.
*/
alpha=ScaleCharToQuantum((unsigned char)*p++);
SetPixelAlpha(q,alpha);
if (alpha != QuantumRange-OpaqueOpacity)
found_transparent_pixel = MagickTrue;
q++;
}
else
for (x=(ssize_t) image->columns-1; x >= 0; x--)
*r++=*p++;
break;
}
case 16:
{
for (x=(ssize_t) image->columns-1; x >= 0; x--)
{
#if (MAGICKCORE_QUANTUM_DEPTH >= 16)
size_t
quantum;
if (image->colors > 256)
quantum=((*p++) << 8);
else
quantum=0;
quantum|=(*p++);
*r=ScaleShortToQuantum(quantum);
r++;
if (ping_color_type == 4)
{
if (image->colors > 256)
quantum=((*p++) << 8);
else
quantum=0;
quantum|=(*p++);
alpha=ScaleShortToQuantum(quantum);
SetPixelAlpha(q,alpha);
if (alpha != QuantumRange-OpaqueOpacity)
found_transparent_pixel = MagickTrue;
q++;
}
#else /* MAGICKCORE_QUANTUM_DEPTH == 8 */
*r++=(*p++);
p++; /* strip low byte */
if (ping_color_type == 4)
{
alpha=*p++;
SetPixelAlpha(q,alpha);
if (alpha != QuantumRange-OpaqueOpacity)
found_transparent_pixel = MagickTrue;
p++;
q++;
}
#endif
}
break;
}
default:
break;
}
/*
Transfer image scanline.
*/
r=quantum_scanline;
for (x=0; x < (ssize_t) image->columns; x++)
SetPixelIndex(indexes+x,*r++);
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (num_passes == 1)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
if (num_passes != 1)
{
status=SetImageProgress(image,LoadImageTag,pass,num_passes);
if (status == MagickFalse)
break;
}
quantum_scanline=(Quantum *) RelinquishMagickMemory(quantum_scanline);
}
image->matte=found_transparent_pixel;
if (logging != MagickFalse)
{
if (found_transparent_pixel != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Found transparent pixel");
else
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" No transparent pixel was found");
ping_color_type&=0x03;
}
}
}
if (image->storage_class == PseudoClass)
{
MagickBooleanType
matte;
matte=image->matte;
image->matte=MagickFalse;
(void) SyncImage(image);
image->matte=matte;
}
png_read_end(ping,end_info);
if (image_info->number_scenes != 0 && mng_info->scenes_found-1 <
(ssize_t) image_info->first_scene && image->delay != 0)
{
png_destroy_read_struct(&ping,&ping_info,&end_info);
pixel_info=RelinquishVirtualMemory(pixel_info);
image->colors=2;
(void) SetImageBackgroundColor(image);
#ifdef IMPNG_SETJMP_NOT_THREAD_SAFE
UnlockSemaphoreInfo(ping_semaphore);
#endif
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" exit ReadOnePNGImage() early.");
return(image);
}
if (png_get_valid(ping,ping_info,PNG_INFO_tRNS))
{
ClassType
storage_class;
/*
Image has a transparent background.
*/
storage_class=image->storage_class;
image->matte=MagickTrue;
/* Balfour fix from imagemagick discourse server, 5 Feb 2010 */
if (storage_class == PseudoClass)
{
if ((int) ping_color_type == PNG_COLOR_TYPE_PALETTE)
{
for (x=0; x < ping_num_trans; x++)
{
image->colormap[x].opacity =
ScaleCharToQuantum((unsigned char)(255-ping_trans_alpha[x]));
}
}
else if (ping_color_type == PNG_COLOR_TYPE_GRAY)
{
for (x=0; x < (int) image->colors; x++)
{
if (ScaleQuantumToShort(image->colormap[x].red) ==
transparent_color.opacity)
{
image->colormap[x].opacity = (Quantum) TransparentOpacity;
}
}
}
(void) SyncImage(image);
}
#if 1 /* Should have already been done above, but glennrp problem P10
* needs this.
*/
else
{
for (y=0; y < (ssize_t) image->rows; y++)
{
image->storage_class=storage_class;
q=GetAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
indexes=GetAuthenticIndexQueue(image);
/* Caution: on a Q8 build, this does not distinguish between
* 16-bit colors that differ only in the low byte
*/
for (x=(ssize_t) image->columns-1; x >= 0; x--)
{
if (ScaleQuantumToShort(GetPixelRed(q))
== transparent_color.red &&
ScaleQuantumToShort(GetPixelGreen(q))
== transparent_color.green &&
ScaleQuantumToShort(GetPixelBlue(q))
== transparent_color.blue)
{
SetPixelOpacity(q,TransparentOpacity);
}
#if 0 /* I have not found a case where this is needed. */
else
{
SetPixelOpacity(q)=(Quantum) OpaqueOpacity;
}
#endif
q++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
}
#endif
image->storage_class=DirectClass;
}
if ((ping_color_type == PNG_COLOR_TYPE_GRAY) ||
(ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA))
{
double
image_gamma = image->gamma;
(void)LogMagickEvent(CoderEvent,GetMagickModule(),
" image->gamma=%f",(float) image_gamma);
if (image_gamma > 0.75)
{
/* Set image->rendering_intent to Undefined,
* image->colorspace to GRAY, and reset image->chromaticity.
*/
image->intensity = Rec709LuminancePixelIntensityMethod;
SetImageColorspace(image,GRAYColorspace);
}
else
{
RenderingIntent
save_rendering_intent = image->rendering_intent;
ChromaticityInfo
save_chromaticity = image->chromaticity;
SetImageColorspace(image,GRAYColorspace);
image->rendering_intent = save_rendering_intent;
image->chromaticity = save_chromaticity;
}
image->gamma = image_gamma;
}
(void)LogMagickEvent(CoderEvent,GetMagickModule(),
" image->colorspace=%d",(int) image->colorspace);
for (j = 0; j < 2; j++)
{
if (j == 0)
status = png_get_text(ping,ping_info,&text,&num_text) != 0 ?
MagickTrue : MagickFalse;
else
status = png_get_text(ping,end_info,&text,&num_text) != 0 ?
MagickTrue : MagickFalse;
if (status != MagickFalse)
for (i=0; i < (ssize_t) num_text; i++)
{
/* Check for a profile */
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Reading PNG text chunk");
if (strlen(text[i].key) > 16 &&
memcmp(text[i].key, "Raw profile type ",17) == 0)
{
const char
*value;
value=GetImageOption(image_info,"profile:skip");
if (IsOptionMember(text[i].key+17,value) == MagickFalse)
{
(void) Magick_png_read_raw_profile(ping,image,image_info,text,
(int) i);
num_raw_profiles++;
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Read raw profile %s",text[i].key+17);
}
else
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Skipping raw profile %s",text[i].key+17);
}
}
else
{
char
*value;
length=text[i].text_length;
value=(char *) AcquireQuantumMemory(length+MaxTextExtent,
sizeof(*value));
if (value == (char *) NULL)
png_error(ping,"Memory allocation failed");
*value='\0';
(void) ConcatenateMagickString(value,text[i].text,length+2);
/* Don't save "density" or "units" property if we have a pHYs
* chunk
*/
if (!png_get_valid(ping,ping_info,PNG_INFO_pHYs) ||
(LocaleCompare(text[i].key,"density") != 0 &&
LocaleCompare(text[i].key,"units") != 0))
(void) SetImageProperty(image,text[i].key,value);
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" length: %lu\n"
" Keyword: %s",
(unsigned long) length,
text[i].key);
}
value=DestroyString(value);
}
}
num_text_total += num_text;
}
#ifdef MNG_OBJECT_BUFFERS
/*
Store the object if necessary.
*/
if (object_id && !mng_info->frozen[object_id])
{
if (mng_info->ob[object_id] == (MngBuffer *) NULL)
{
/*
create a new object buffer.
*/
mng_info->ob[object_id]=(MngBuffer *)
AcquireMagickMemory(sizeof(MngBuffer));
if (mng_info->ob[object_id] != (MngBuffer *) NULL)
{
mng_info->ob[object_id]->image=(Image *) NULL;
mng_info->ob[object_id]->reference_count=1;
}
}
if ((mng_info->ob[object_id] == (MngBuffer *) NULL) ||
mng_info->ob[object_id]->frozen)
{
if (mng_info->ob[object_id] == (MngBuffer *) NULL)
png_error(ping,"Memory allocation failed");
if (mng_info->ob[object_id]->frozen)
png_error(ping,"Cannot overwrite frozen MNG object buffer");
}
else
{
if (mng_info->ob[object_id]->image != (Image *) NULL)
mng_info->ob[object_id]->image=DestroyImage
(mng_info->ob[object_id]->image);
mng_info->ob[object_id]->image=CloneImage(image,0,0,MagickTrue,
&image->exception);
if (mng_info->ob[object_id]->image != (Image *) NULL)
mng_info->ob[object_id]->image->file=(FILE *) NULL;
else
png_error(ping, "Cloning image for object buffer failed");
if (ping_width > 250000L || ping_height > 250000L)
png_error(ping,"PNG Image dimensions are too large.");
mng_info->ob[object_id]->width=ping_width;
mng_info->ob[object_id]->height=ping_height;
mng_info->ob[object_id]->color_type=ping_color_type;
mng_info->ob[object_id]->sample_depth=ping_bit_depth;
mng_info->ob[object_id]->interlace_method=ping_interlace_method;
mng_info->ob[object_id]->compression_method=
ping_compression_method;
mng_info->ob[object_id]->filter_method=ping_filter_method;
if (png_get_valid(ping,ping_info,PNG_INFO_PLTE))
{
png_colorp
plte;
/*
Copy the PLTE to the object buffer.
*/
png_get_PLTE(ping,ping_info,&plte,&number_colors);
mng_info->ob[object_id]->plte_length=number_colors;
for (i=0; i < number_colors; i++)
{
mng_info->ob[object_id]->plte[i]=plte[i];
}
}
else
mng_info->ob[object_id]->plte_length=0;
}
}
#endif
/* Set image->matte to MagickTrue if the input colortype supports
* alpha or if a valid tRNS chunk is present, no matter whether there
* is actual transparency present.
*/
image->matte=(((int) ping_color_type == PNG_COLOR_TYPE_RGB_ALPHA) ||
((int) ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA) ||
(png_get_valid(ping,ping_info,PNG_INFO_tRNS))) ?
MagickTrue : MagickFalse;
#if 0 /* I'm not sure what's wrong here but it does not work. */
if (image->matte != MagickFalse)
{
if (ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
(void) SetImageType(image,GrayscaleMatteType);
else if (ping_color_type == PNG_COLOR_TYPE_PALETTE)
(void) SetImageType(image,PaletteMatteType);
else
(void) SetImageType(image,TrueColorMatteType);
}
else
{
if (ping_color_type == PNG_COLOR_TYPE_GRAY)
(void) SetImageType(image,GrayscaleType);
else if (ping_color_type == PNG_COLOR_TYPE_PALETTE)
(void) SetImageType(image,PaletteType);
else
(void) SetImageType(image,TrueColorType);
}
#endif
/* Set more properties for identify to retrieve */
{
char
msg[MaxTextExtent];
if (num_text_total != 0)
{
/* libpng doesn't tell us whether they were tEXt, zTXt, or iTXt */
(void) FormatLocaleString(msg,MaxTextExtent,
"%d tEXt/zTXt/iTXt chunks were found", num_text_total);
(void) SetImageProperty(image,"png:text",msg);
}
if (num_raw_profiles != 0)
{
(void) FormatLocaleString(msg,MaxTextExtent,
"%d were found", num_raw_profiles);
(void) SetImageProperty(image,"png:text-encoded profiles",msg);
}
/* cHRM chunk: */
if (ping_found_cHRM != MagickFalse)
{
(void) FormatLocaleString(msg,MaxTextExtent,"%s",
"chunk was found (see Chromaticity, above)");
(void) SetImageProperty(image,"png:cHRM",msg);
}
/* bKGD chunk: */
if (png_get_valid(ping,ping_info,PNG_INFO_bKGD))
{
(void) FormatLocaleString(msg,MaxTextExtent,"%s",
"chunk was found (see Background color, above)");
(void) SetImageProperty(image,"png:bKGD",msg);
}
(void) FormatLocaleString(msg,MaxTextExtent,"%s",
"chunk was found");
/* iCCP chunk: */
if (ping_found_iCCP != MagickFalse)
(void) SetImageProperty(image,"png:iCCP",msg);
if (png_get_valid(ping,ping_info,PNG_INFO_tRNS))
(void) SetImageProperty(image,"png:tRNS",msg);
#if defined(PNG_sRGB_SUPPORTED)
/* sRGB chunk: */
if (ping_found_sRGB != MagickFalse)
{
(void) FormatLocaleString(msg,MaxTextExtent,
"intent=%d (%s)",
(int) intent,
Magick_RenderingIntentString_from_PNG_RenderingIntent(intent));
(void) SetImageProperty(image,"png:sRGB",msg);
}
#endif
/* gAMA chunk: */
if (ping_found_gAMA != MagickFalse)
{
(void) FormatLocaleString(msg,MaxTextExtent,
"gamma=%.8g (See Gamma, above)", file_gamma);
(void) SetImageProperty(image,"png:gAMA",msg);
}
#if defined(PNG_pHYs_SUPPORTED)
/* pHYs chunk: */
if (png_get_valid(ping,ping_info,PNG_INFO_pHYs))
{
(void) FormatLocaleString(msg,MaxTextExtent,
"x_res=%.10g, y_res=%.10g, units=%d",
(double) x_resolution,(double) y_resolution, unit_type);
(void) SetImageProperty(image,"png:pHYs",msg);
}
#endif
#if defined(PNG_oFFs_SUPPORTED)
/* oFFs chunk: */
if (png_get_valid(ping,ping_info,PNG_INFO_oFFs))
{
(void) FormatLocaleString(msg,MaxTextExtent,"x_off=%.20g, y_off=%.20g",
(double) image->page.x,(double) image->page.y);
(void) SetImageProperty(image,"png:oFFs",msg);
}
#endif
#if defined(PNG_tIME_SUPPORTED)
read_tIME_chunk(image,ping,end_info);
#endif
/* caNv chunk: */
if ((image->page.width != 0 && image->page.width != image->columns) ||
(image->page.height != 0 && image->page.height != image->rows) ||
(image->page.x != 0 || image->page.y != 0))
{
(void) FormatLocaleString(msg,MaxTextExtent,
"width=%.20g, height=%.20g, x_offset=%.20g, y_offset=%.20g",
(double) image->page.width,(double) image->page.height,
(double) image->page.x,(double) image->page.y);
(void) SetImageProperty(image,"png:caNv",msg);
}
/* vpAg chunk: */
if ((image->page.width != 0 && image->page.width != image->columns) ||
(image->page.height != 0 && image->page.height != image->rows))
{
(void) FormatLocaleString(msg,MaxTextExtent,
"width=%.20g, height=%.20g",
(double) image->page.width,(double) image->page.height);
(void) SetImageProperty(image,"png:vpAg",msg);
}
}
/*
Relinquish resources.
*/
png_destroy_read_struct(&ping,&ping_info,&end_info);
pixel_info=RelinquishVirtualMemory(pixel_info);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" exit ReadOnePNGImage()");
#ifdef IMPNG_SETJMP_NOT_THREAD_SAFE
UnlockSemaphoreInfo(ping_semaphore);
#endif
/* } for navigation to beginning of SETJMP-protected block, revert to
* Throwing an Exception when an error occurs.
*/
return(image);
/* end of reading one PNG image */
}
static Image *ReadPNGImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
Image
*image;
MagickBooleanType
logging,
status;
MngInfo
*mng_info;
char
magic_number[MaxTextExtent];
ssize_t
count;
/*
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);
logging=LogMagickEvent(CoderEvent,GetMagickModule(),"Enter ReadPNGImage()");
image=AcquireImage(image_info);
mng_info=(MngInfo *) NULL;
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
ThrowReaderException(FileOpenError,"UnableToOpenFile");
/*
Verify PNG signature.
*/
count=ReadBlob(image,8,(unsigned char *) magic_number);
if (count < 8 || memcmp(magic_number,"\211PNG\r\n\032\n",8) != 0)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
/*
Verify that file size large enough to contain a PNG datastream.
*/
if (GetBlobSize(image) < 61)
ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile");
/*
Allocate a MngInfo structure.
*/
mng_info=(MngInfo *) AcquireMagickMemory(sizeof(MngInfo));
if (mng_info == (MngInfo *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
/*
Initialize members of the MngInfo structure.
*/
(void) ResetMagickMemory(mng_info,0,sizeof(MngInfo));
mng_info->image=image;
image=ReadOnePNGImage(mng_info,image_info,exception);
mng_info=MngInfoFreeStruct(mng_info);
if (image == (Image *) NULL)
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"exit ReadPNGImage() with error");
return((Image *) NULL);
}
(void) CloseBlob(image);
if ((image->columns == 0) || (image->rows == 0))
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"exit ReadPNGImage() with error.");
ThrowReaderException(CorruptImageError,"CorruptImage");
}
if ((IssRGBColorspace(image->colorspace) != MagickFalse) &&
((image->gamma < .45) || (image->gamma > .46)) &&
!(image->chromaticity.red_primary.x>0.6399f &&
image->chromaticity.red_primary.x<0.6401f &&
image->chromaticity.red_primary.y>0.3299f &&
image->chromaticity.red_primary.y<0.3301f &&
image->chromaticity.green_primary.x>0.2999f &&
image->chromaticity.green_primary.x<0.3001f &&
image->chromaticity.green_primary.y>0.5999f &&
image->chromaticity.green_primary.y<0.6001f &&
image->chromaticity.blue_primary.x>0.1499f &&
image->chromaticity.blue_primary.x<0.1501f &&
image->chromaticity.blue_primary.y>0.0599f &&
image->chromaticity.blue_primary.y<0.0601f &&
image->chromaticity.white_point.x>0.3126f &&
image->chromaticity.white_point.x<0.3128f &&
image->chromaticity.white_point.y>0.3289f &&
image->chromaticity.white_point.y<0.3291f))
SetImageColorspace(image,RGBColorspace);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" page.w: %.20g, page.h: %.20g,page.x: %.20g, page.y: %.20g.",
(double) image->page.width,(double) image->page.height,
(double) image->page.x,(double) image->page.y);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),"exit ReadPNGImage()");
return(image);
}
#if defined(JNG_SUPPORTED)
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e a d O n e J N G I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ReadOneJNGImage() reads a JPEG Network Graphics (JNG) image file
% (minus the 8-byte signature) and returns it. It allocates the memory
% necessary for the new Image structure and returns a pointer to the new
% image.
%
% JNG support written by Glenn Randers-Pehrson, glennrp@image...
%
% The format of the ReadOneJNGImage method is:
%
% Image *ReadOneJNGImage(MngInfo *mng_info, const ImageInfo *image_info,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o mng_info: Specifies a pointer to a MngInfo structure.
%
% o image_info: the image info.
%
% o exception: return any errors or warnings in this structure.
%
*/
static Image *ReadOneJNGImage(MngInfo *mng_info,
const ImageInfo *image_info, ExceptionInfo *exception)
{
Image
*alpha_image,
*color_image,
*image,
*jng_image;
ImageInfo
*alpha_image_info,
*color_image_info;
MagickBooleanType
logging;
int
unique_filenames;
ssize_t
y;
MagickBooleanType
status;
png_uint_32
jng_height,
jng_width;
png_byte
jng_color_type,
jng_image_sample_depth,
jng_image_compression_method,
jng_image_interlace_method,
jng_alpha_sample_depth,
jng_alpha_compression_method,
jng_alpha_filter_method,
jng_alpha_interlace_method;
register const PixelPacket
*s;
register ssize_t
i,
x;
register PixelPacket
*q;
register unsigned char
*p;
unsigned int
read_JSEP,
reading_idat;
size_t
length;
jng_alpha_compression_method=0;
jng_alpha_sample_depth=8;
jng_color_type=0;
jng_height=0;
jng_width=0;
alpha_image=(Image *) NULL;
color_image=(Image *) NULL;
alpha_image_info=(ImageInfo *) NULL;
color_image_info=(ImageInfo *) NULL;
unique_filenames=0;
logging=LogMagickEvent(CoderEvent,GetMagickModule(),
" Enter ReadOneJNGImage()");
image=mng_info->image;
if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL)
{
/*
Allocate next image structure.
*/
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" AcquireNextImage()");
AcquireNextImage(image_info,image);
if (GetNextImageInList(image) == (Image *) NULL)
return(DestroyImageList(image));
image=SyncNextImageInList(image);
}
mng_info->image=image;
/*
Signature bytes have already been read.
*/
read_JSEP=MagickFalse;
reading_idat=MagickFalse;
for (;;)
{
char
type[MaxTextExtent];
unsigned char
*chunk;
unsigned int
count;
/*
Read a new JNG chunk.
*/
status=SetImageProgress(image,LoadImagesTag,TellBlob(image),
2*GetBlobSize(image));
if (status == MagickFalse)
break;
type[0]='\0';
(void) ConcatenateMagickString(type,"errr",MaxTextExtent);
length=ReadBlobMSBLong(image);
count=(unsigned int) ReadBlob(image,4,(unsigned char *) type);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Reading JNG chunk type %c%c%c%c, length: %.20g",
type[0],type[1],type[2],type[3],(double) length);
if (length > PNG_UINT_31_MAX || count == 0)
ThrowReaderException(CorruptImageError,"CorruptImage");
p=NULL;
chunk=(unsigned char *) NULL;
if (length != 0)
{
chunk=(unsigned char *) AcquireQuantumMemory(length+MagickPathExtent,
sizeof(*chunk));
if (chunk == (unsigned char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
for (i=0; i < (ssize_t) length; i++)
{
int
c;
c=ReadBlobByte(image);
if (c == EOF)
break;
chunk[i]=(unsigned char) c;
}
p=chunk;
}
(void) ReadBlobMSBLong(image); /* read crc word */
if (memcmp(type,mng_JHDR,4) == 0)
{
if (length == 16)
{
jng_width=(size_t) ((p[0] << 24) | (p[1] << 16) |
(p[2] << 8) | p[3]);
jng_height=(size_t) ((p[4] << 24) | (p[5] << 16) |
(p[6] << 8) | p[7]);
if ((jng_width == 0) || (jng_height == 0))
ThrowReaderException(CorruptImageError,"NegativeOrZeroImageSize");
jng_color_type=p[8];
jng_image_sample_depth=p[9];
jng_image_compression_method=p[10];
jng_image_interlace_method=p[11];
image->interlace=jng_image_interlace_method != 0 ? PNGInterlace :
NoInterlace;
jng_alpha_sample_depth=p[12];
jng_alpha_compression_method=p[13];
jng_alpha_filter_method=p[14];
jng_alpha_interlace_method=p[15];
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" jng_width: %16lu, jng_height: %16lu\n"
" jng_color_type: %16d, jng_image_sample_depth: %3d\n"
" jng_image_compression_method:%3d",
(unsigned long) jng_width, (unsigned long) jng_height,
jng_color_type, jng_image_sample_depth,
jng_image_compression_method);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" jng_image_interlace_method: %3d"
" jng_alpha_sample_depth: %3d",
jng_image_interlace_method,
jng_alpha_sample_depth);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" jng_alpha_compression_method:%3d\n"
" jng_alpha_filter_method: %3d\n"
" jng_alpha_interlace_method: %3d",
jng_alpha_compression_method,
jng_alpha_filter_method,
jng_alpha_interlace_method);
}
}
if (length != 0)
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if ((reading_idat == MagickFalse) && (read_JSEP == MagickFalse) &&
((memcmp(type,mng_JDAT,4) == 0) || (memcmp(type,mng_JdAA,4) == 0) ||
(memcmp(type,mng_IDAT,4) == 0) || (memcmp(type,mng_JDAA,4) == 0)))
{
/*
o create color_image
o open color_blob, attached to color_image
o if (color type has alpha)
open alpha_blob, attached to alpha_image
*/
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Creating color_blob.");
color_image_info=(ImageInfo *)AcquireMagickMemory(sizeof(ImageInfo));
if (color_image_info == (ImageInfo *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
GetImageInfo(color_image_info);
color_image=AcquireImage(color_image_info);
if (color_image == (Image *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
(void) AcquireUniqueFilename(color_image->filename);
unique_filenames++;
status=OpenBlob(color_image_info,color_image,WriteBinaryBlobMode,
exception);
if (status == MagickFalse)
{
color_image=DestroyImage(color_image);
return(DestroyImageList(image));
}
if ((image_info->ping == MagickFalse) && (jng_color_type >= 12))
{
alpha_image_info=(ImageInfo *)
AcquireMagickMemory(sizeof(ImageInfo));
if (alpha_image_info == (ImageInfo *) NULL)
{
color_image=DestroyImage(color_image);
ThrowReaderException(ResourceLimitError,
"MemoryAllocationFailed");
}
GetImageInfo(alpha_image_info);
alpha_image=AcquireImage(alpha_image_info);
if (alpha_image == (Image *) NULL)
{
alpha_image_info=DestroyImageInfo(alpha_image_info);
color_image=DestroyImage(color_image);
ThrowReaderException(ResourceLimitError,
"MemoryAllocationFailed");
}
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Creating alpha_blob.");
(void) AcquireUniqueFilename(alpha_image->filename);
unique_filenames++;
status=OpenBlob(alpha_image_info,alpha_image,WriteBinaryBlobMode,
exception);
if (status == MagickFalse)
{
alpha_image=DestroyImage(alpha_image);
alpha_image_info=DestroyImageInfo(alpha_image_info);
color_image=DestroyImage(color_image);
return(DestroyImageList(image));
}
if (jng_alpha_compression_method == 0)
{
unsigned char
data[18];
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Writing IHDR chunk to alpha_blob.");
(void) WriteBlob(alpha_image,8,(const unsigned char *)
"\211PNG\r\n\032\n");
(void) WriteBlobMSBULong(alpha_image,13L);
PNGType(data,mng_IHDR);
LogPNGChunk(logging,mng_IHDR,13L);
PNGLong(data+4,jng_width);
PNGLong(data+8,jng_height);
data[12]=jng_alpha_sample_depth;
data[13]=0; /* color_type gray */
data[14]=0; /* compression method 0 */
data[15]=0; /* filter_method 0 */
data[16]=0; /* interlace_method 0 */
(void) WriteBlob(alpha_image,17,data);
(void) WriteBlobMSBULong(alpha_image,crc32(0,data,17));
}
}
reading_idat=MagickTrue;
}
if (memcmp(type,mng_JDAT,4) == 0)
{
/* Copy chunk to color_image->blob */
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Copying JDAT chunk data to color_blob.");
if (length != 0)
{
(void) WriteBlob(color_image,length,chunk);
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
}
continue;
}
if (memcmp(type,mng_IDAT,4) == 0)
{
png_byte
data[5];
/* Copy IDAT header and chunk data to alpha_image->blob */
if (alpha_image != NULL && image_info->ping == MagickFalse)
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Copying IDAT chunk data to alpha_blob.");
(void) WriteBlobMSBULong(alpha_image,(size_t) length);
PNGType(data,mng_IDAT);
LogPNGChunk(logging,mng_IDAT,length);
(void) WriteBlob(alpha_image,4,data);
(void) WriteBlob(alpha_image,length,chunk);
(void) WriteBlobMSBULong(alpha_image,
crc32(crc32(0,data,4),chunk,(uInt) length));
}
if (length != 0)
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if ((memcmp(type,mng_JDAA,4) == 0) || (memcmp(type,mng_JdAA,4) == 0))
{
/* Copy chunk data to alpha_image->blob */
if (alpha_image != NULL && image_info->ping == MagickFalse)
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Copying JDAA chunk data to alpha_blob.");
(void) WriteBlob(alpha_image,length,chunk);
}
if (length != 0)
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_JSEP,4) == 0)
{
read_JSEP=MagickTrue;
if (length != 0)
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_bKGD,4) == 0)
{
if (length == 2)
{
image->background_color.red=ScaleCharToQuantum(p[1]);
image->background_color.green=image->background_color.red;
image->background_color.blue=image->background_color.red;
}
if (length == 6)
{
image->background_color.red=ScaleCharToQuantum(p[1]);
image->background_color.green=ScaleCharToQuantum(p[3]);
image->background_color.blue=ScaleCharToQuantum(p[5]);
}
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_gAMA,4) == 0)
{
if (length == 4)
image->gamma=((float) mng_get_long(p))*0.00001;
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_cHRM,4) == 0)
{
if (length == 32)
{
image->chromaticity.white_point.x=0.00001*mng_get_long(p);
image->chromaticity.white_point.y=0.00001*mng_get_long(&p[4]);
image->chromaticity.red_primary.x=0.00001*mng_get_long(&p[8]);
image->chromaticity.red_primary.y=0.00001*mng_get_long(&p[12]);
image->chromaticity.green_primary.x=0.00001*mng_get_long(&p[16]);
image->chromaticity.green_primary.y=0.00001*mng_get_long(&p[20]);
image->chromaticity.blue_primary.x=0.00001*mng_get_long(&p[24]);
image->chromaticity.blue_primary.y=0.00001*mng_get_long(&p[28]);
}
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_sRGB,4) == 0)
{
if (length == 1)
{
image->rendering_intent=
Magick_RenderingIntent_from_PNG_RenderingIntent(p[0]);
image->gamma=1.000f/2.200f;
image->chromaticity.red_primary.x=0.6400f;
image->chromaticity.red_primary.y=0.3300f;
image->chromaticity.green_primary.x=0.3000f;
image->chromaticity.green_primary.y=0.6000f;
image->chromaticity.blue_primary.x=0.1500f;
image->chromaticity.blue_primary.y=0.0600f;
image->chromaticity.white_point.x=0.3127f;
image->chromaticity.white_point.y=0.3290f;
}
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_oFFs,4) == 0)
{
if (length > 8)
{
image->page.x=(ssize_t) mng_get_long(p);
image->page.y=(ssize_t) mng_get_long(&p[4]);
if ((int) p[8] != 0)
{
image->page.x/=10000;
image->page.y/=10000;
}
}
if (length != 0)
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_pHYs,4) == 0)
{
if (length > 8)
{
image->x_resolution=(double) mng_get_long(p);
image->y_resolution=(double) mng_get_long(&p[4]);
if ((int) p[8] == PNG_RESOLUTION_METER)
{
image->units=PixelsPerCentimeterResolution;
image->x_resolution=image->x_resolution/100.0f;
image->y_resolution=image->y_resolution/100.0f;
}
}
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
#if 0
if (memcmp(type,mng_iCCP,4) == 0)
{
/* To do: */
if (length != 0)
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
#endif
if (length != 0)
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
if (memcmp(type,mng_IEND,4))
continue;
break;
}
/* IEND found */
/*
Finish up reading image data:
o read main image from color_blob.
o close color_blob.
o if (color_type has alpha)
if alpha_encoding is PNG
read secondary image from alpha_blob via ReadPNG
if alpha_encoding is JPEG
read secondary image from alpha_blob via ReadJPEG
o close alpha_blob.
o copy intensity of secondary image into
opacity samples of main image.
o destroy the secondary image.
*/
if (color_image_info == (ImageInfo *) NULL)
{
assert(color_image == (Image *) NULL);
assert(alpha_image == (Image *) NULL);
return(DestroyImageList(image));
}
if (color_image == (Image *) NULL)
{
assert(alpha_image == (Image *) NULL);
return(DestroyImageList(image));
}
(void) SeekBlob(color_image,0,SEEK_SET);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Reading jng_image from color_blob.");
assert(color_image_info != (ImageInfo *) NULL);
(void) FormatLocaleString(color_image_info->filename,MaxTextExtent,"%s",
color_image->filename);
color_image_info->ping=MagickFalse; /* To do: avoid this */
jng_image=ReadImage(color_image_info,exception);
(void) RelinquishUniqueFileResource(color_image->filename);
unique_filenames--;
color_image=DestroyImage(color_image);
color_image_info=DestroyImageInfo(color_image_info);
if (jng_image == (Image *) NULL)
return(DestroyImageList(image));
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Copying jng_image pixels to main image.");
image->columns=jng_width;
image->rows=jng_height;
length=image->columns*sizeof(PixelPacket);
status=SetImageExtent(image,image->columns,image->rows);
if (status == MagickFalse)
{
InheritException(exception,&image->exception);
return(DestroyImageList(image));
}
for (y=0; y < (ssize_t) image->rows; y++)
{
s=GetVirtualPixels(jng_image,0,y,image->columns,1,&image->exception);
q=GetAuthenticPixels(image,0,y,image->columns,1,exception);
(void) CopyMagickMemory(q,s,length);
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
jng_image=DestroyImage(jng_image);
if (image_info->ping == MagickFalse)
{
if (jng_color_type >= 12)
{
if (jng_alpha_compression_method == 0)
{
png_byte
data[5];
(void) WriteBlobMSBULong(alpha_image,0x00000000L);
PNGType(data,mng_IEND);
LogPNGChunk(logging,mng_IEND,0L);
(void) WriteBlob(alpha_image,4,data);
(void) WriteBlobMSBULong(alpha_image,crc32(0,data,4));
}
(void) SeekBlob(alpha_image,0,SEEK_SET);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Reading opacity from alpha_blob.");
(void) FormatLocaleString(alpha_image_info->filename,MaxTextExtent,
"%s",alpha_image->filename);
jng_image=ReadImage(alpha_image_info,exception);
if (jng_image != (Image *) NULL)
for (y=0; y < (ssize_t) image->rows; y++)
{
s=GetVirtualPixels(jng_image,0,y,image->columns,1,
&image->exception);
q=GetAuthenticPixels(image,0,y,image->columns,1,exception);
if (image->matte != MagickFalse)
for (x=(ssize_t) image->columns; x != 0; x--,q++,s++)
SetPixelOpacity(q,QuantumRange-
GetPixelRed(s));
else
for (x=(ssize_t) image->columns; x != 0; x--,q++,s++)
{
SetPixelAlpha(q,GetPixelRed(s));
if (GetPixelOpacity(q) != OpaqueOpacity)
image->matte=MagickTrue;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
(void) RelinquishUniqueFileResource(alpha_image->filename);
unique_filenames--;
alpha_image=DestroyImage(alpha_image);
alpha_image_info=DestroyImageInfo(alpha_image_info);
if (jng_image != (Image *) NULL)
jng_image=DestroyImage(jng_image);
}
}
/* Read the JNG image. */
if (mng_info->mng_type == 0)
{
mng_info->mng_width=jng_width;
mng_info->mng_height=jng_height;
}
if (image->page.width == 0 && image->page.height == 0)
{
image->page.width=jng_width;
image->page.height=jng_height;
}
if (image->page.x == 0 && image->page.y == 0)
{
image->page.x=mng_info->x_off[mng_info->object_id];
image->page.y=mng_info->y_off[mng_info->object_id];
}
else
{
image->page.y=mng_info->y_off[mng_info->object_id];
}
mng_info->image_found++;
status=SetImageProgress(image,LoadImagesTag,2*TellBlob(image),
2*GetBlobSize(image));
if (status == MagickFalse)
return(DestroyImageList(image));
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" exit ReadOneJNGImage(); unique_filenames=%d",unique_filenames);
return(image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e a d J N G I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ReadJNGImage() reads a JPEG Network Graphics (JNG) image file
% (including the 8-byte signature) and returns it. It allocates the memory
% necessary for the new Image structure and returns a pointer to the new
% image.
%
% JNG support written by Glenn Randers-Pehrson, glennrp@image...
%
% The format of the ReadJNGImage method is:
%
% Image *ReadJNGImage(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 *ReadJNGImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
Image
*image;
MagickBooleanType
logging,
status;
MngInfo
*mng_info;
char
magic_number[MaxTextExtent];
size_t
count;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
logging=LogMagickEvent(CoderEvent,GetMagickModule(),"Enter ReadJNGImage()");
image=AcquireImage(image_info);
mng_info=(MngInfo *) NULL;
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
return((Image *) NULL);
if (LocaleCompare(image_info->magick,"JNG") != 0)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
/* Verify JNG signature. */
count=(size_t) ReadBlob(image,8,(unsigned char *) magic_number);
if (count < 8 || memcmp(magic_number,"\213JNG\r\n\032\n",8) != 0)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
/*
Verify that file size large enough to contain a JNG datastream.
*/
if (GetBlobSize(image) < 147)
ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile");
/* Allocate a MngInfo structure. */
mng_info=(MngInfo *) AcquireMagickMemory(sizeof(*mng_info));
if (mng_info == (MngInfo *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
/* Initialize members of the MngInfo structure. */
(void) ResetMagickMemory(mng_info,0,sizeof(MngInfo));
mng_info->image=image;
image=ReadOneJNGImage(mng_info,image_info,exception);
mng_info=MngInfoFreeStruct(mng_info);
if (image == (Image *) NULL)
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"exit ReadJNGImage() with error");
return((Image *) NULL);
}
(void) CloseBlob(image);
if (image->columns == 0 || image->rows == 0)
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"exit ReadJNGImage() with error");
ThrowReaderException(CorruptImageError,"CorruptImage");
}
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),"exit ReadJNGImage()");
return(image);
}
#endif
static Image *ReadOneMNGImage(MngInfo* mng_info, const ImageInfo *image_info,
ExceptionInfo *exception)
{
char
page_geometry[MaxTextExtent];
Image
*image;
MagickBooleanType
logging;
volatile int
first_mng_object,
object_id,
term_chunk_found,
skip_to_iend;
volatile ssize_t
image_count=0;
MagickBooleanType
status;
MagickOffsetType
offset;
MngBox
default_fb,
fb,
previous_fb;
#if defined(MNG_INSERT_LAYERS)
PixelPacket
mng_background_color;
#endif
register unsigned char
*p;
register ssize_t
i;
size_t
count;
ssize_t
loop_level;
volatile short
skipping_loop;
#if defined(MNG_INSERT_LAYERS)
unsigned int
mandatory_back=0;
#endif
volatile unsigned int
#ifdef MNG_OBJECT_BUFFERS
mng_background_object=0,
#endif
mng_type=0; /* 0: PNG or JNG; 1: MNG; 2: MNG-LC; 3: MNG-VLC */
size_t
default_frame_timeout,
frame_timeout,
#if defined(MNG_INSERT_LAYERS)
image_height,
image_width,
#endif
length;
/* These delays are all measured in image ticks_per_second,
* not in MNG ticks_per_second
*/
volatile size_t
default_frame_delay,
final_delay,
final_image_delay,
frame_delay,
#if defined(MNG_INSERT_LAYERS)
insert_layers,
#endif
mng_iterations=1,
simplicity=0,
subframe_height=0,
subframe_width=0;
previous_fb.top=0;
previous_fb.bottom=0;
previous_fb.left=0;
previous_fb.right=0;
default_fb.top=0;
default_fb.bottom=0;
default_fb.left=0;
default_fb.right=0;
logging=LogMagickEvent(CoderEvent,GetMagickModule(),
" Enter ReadOneMNGImage()");
image=mng_info->image;
if (LocaleCompare(image_info->magick,"MNG") == 0)
{
char
magic_number[MaxTextExtent];
/* Verify MNG signature. */
count=(size_t) ReadBlob(image,8,(unsigned char *) magic_number);
if (memcmp(magic_number,"\212MNG\r\n\032\n",8) != 0)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
/* Initialize some nonzero members of the MngInfo structure. */
for (i=0; i < MNG_MAX_OBJECTS; i++)
{
mng_info->object_clip[i].right=(ssize_t) PNG_UINT_31_MAX;
mng_info->object_clip[i].bottom=(ssize_t) PNG_UINT_31_MAX;
}
mng_info->exists[0]=MagickTrue;
}
skipping_loop=(-1);
first_mng_object=MagickTrue;
mng_type=0;
#if defined(MNG_INSERT_LAYERS)
insert_layers=MagickFalse; /* should be False when converting or mogrifying */
#endif
default_frame_delay=0;
default_frame_timeout=0;
frame_delay=0;
final_delay=1;
mng_info->ticks_per_second=1UL*image->ticks_per_second;
object_id=0;
skip_to_iend=MagickFalse;
term_chunk_found=MagickFalse;
mng_info->framing_mode=1;
#if defined(MNG_INSERT_LAYERS)
mandatory_back=MagickFalse;
#endif
#if defined(MNG_INSERT_LAYERS)
mng_background_color=image->background_color;
#endif
default_fb=mng_info->frame;
previous_fb=mng_info->frame;
do
{
char
type[MaxTextExtent];
if (LocaleCompare(image_info->magick,"MNG") == 0)
{
unsigned char
*chunk;
/*
Read a new chunk.
*/
type[0]='\0';
(void) ConcatenateMagickString(type,"errr",MaxTextExtent);
length=ReadBlobMSBLong(image);
count=(size_t) ReadBlob(image,4,(unsigned char *) type);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Reading MNG chunk type %c%c%c%c, length: %.20g",
type[0],type[1],type[2],type[3],(double) length);
if (length > PNG_UINT_31_MAX)
{
status=MagickFalse;
break;
}
if (count == 0)
ThrowReaderException(CorruptImageError,"CorruptImage");
p=NULL;
chunk=(unsigned char *) NULL;
if (length != 0)
{
chunk=(unsigned char *) AcquireQuantumMemory(length+
MagickPathExtent,sizeof(*chunk));
if (chunk == (unsigned char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
for (i=0; i < (ssize_t) length; i++)
{
int
c;
c=ReadBlobByte(image);
if (c == EOF)
break;
chunk[i]=(unsigned char) c;
}
p=chunk;
}
(void) ReadBlobMSBLong(image); /* read crc word */
#if !defined(JNG_SUPPORTED)
if (memcmp(type,mng_JHDR,4) == 0)
{
skip_to_iend=MagickTrue;
if (mng_info->jhdr_warning == 0)
(void) ThrowMagickException(&image->exception,GetMagickModule(),
CoderError,"JNGCompressNotSupported","`%s'",image->filename);
mng_info->jhdr_warning++;
}
#endif
if (memcmp(type,mng_DHDR,4) == 0)
{
skip_to_iend=MagickTrue;
if (mng_info->dhdr_warning == 0)
(void) ThrowMagickException(&image->exception,GetMagickModule(),
CoderError,"DeltaPNGNotSupported","`%s'",image->filename);
mng_info->dhdr_warning++;
}
if (memcmp(type,mng_MEND,4) == 0)
break;
if (skip_to_iend)
{
if (memcmp(type,mng_IEND,4) == 0)
skip_to_iend=MagickFalse;
if (length != 0)
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Skip to IEND.");
continue;
}
if (memcmp(type,mng_MHDR,4) == 0)
{
if (length != 28)
{
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
ThrowReaderException(CorruptImageError,"CorruptImage");
}
mng_info->mng_width=(size_t) ((p[0] << 24) | (p[1] << 16) |
(p[2] << 8) | p[3]);
mng_info->mng_height=(size_t) ((p[4] << 24) | (p[5] << 16) |
(p[6] << 8) | p[7]);
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" MNG width: %.20g",(double) mng_info->mng_width);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" MNG height: %.20g",(double) mng_info->mng_height);
}
p+=8;
mng_info->ticks_per_second=(size_t) mng_get_long(p);
if (mng_info->ticks_per_second == 0)
default_frame_delay=0;
else
default_frame_delay=1UL*image->ticks_per_second/
mng_info->ticks_per_second;
frame_delay=default_frame_delay;
simplicity=0;
/* Skip nominal layer count, frame count, and play time */
p+=16;
simplicity=(size_t) mng_get_long(p);
mng_type=1; /* Full MNG */
if ((simplicity != 0) && ((simplicity | 11) == 11))
mng_type=2; /* LC */
if ((simplicity != 0) && ((simplicity | 9) == 9))
mng_type=3; /* VLC */
#if defined(MNG_INSERT_LAYERS)
if (mng_type != 3)
insert_layers=MagickTrue;
#endif
if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL)
{
/* Allocate next image structure. */
AcquireNextImage(image_info,image);
if (GetNextImageInList(image) == (Image *) NULL)
return(DestroyImageList(image));
image=SyncNextImageInList(image);
mng_info->image=image;
}
if ((mng_info->mng_width > 65535L) ||
(mng_info->mng_height > 65535L))
{
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
ThrowReaderException(ImageError,"WidthOrHeightExceedsLimit");
}
(void) FormatLocaleString(page_geometry,MaxTextExtent,
"%.20gx%.20g+0+0",(double) mng_info->mng_width,(double)
mng_info->mng_height);
mng_info->frame.left=0;
mng_info->frame.right=(ssize_t) mng_info->mng_width;
mng_info->frame.top=0;
mng_info->frame.bottom=(ssize_t) mng_info->mng_height;
mng_info->clip=default_fb=previous_fb=mng_info->frame;
for (i=0; i < MNG_MAX_OBJECTS; i++)
mng_info->object_clip[i]=mng_info->frame;
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_TERM,4) == 0)
{
int
repeat=0;
if (length != 0)
repeat=p[0];
if (repeat == 3 && length > 8)
{
final_delay=(png_uint_32) mng_get_long(&p[2]);
mng_iterations=(png_uint_32) mng_get_long(&p[6]);
if (mng_iterations == PNG_UINT_31_MAX)
mng_iterations=0;
image->iterations=mng_iterations;
term_chunk_found=MagickTrue;
}
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" repeat=%d, final_delay=%.20g, iterations=%.20g",
repeat,(double) final_delay, (double) image->iterations);
}
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_DEFI,4) == 0)
{
if (mng_type == 3)
(void) ThrowMagickException(&image->exception,GetMagickModule(),
CoderError,"DEFI chunk found in MNG-VLC datastream","`%s'",
image->filename);
if (length > 1)
{
object_id=(p[0] << 8) | p[1];
if (mng_type == 2 && object_id != 0)
(void) ThrowMagickException(&image->exception,
GetMagickModule(),
CoderError,"Nonzero object_id in MNG-LC datastream",
"`%s'", image->filename);
if (object_id > MNG_MAX_OBJECTS)
{
/*
Instead of using a warning we should allocate a larger
MngInfo structure and continue.
*/
(void) ThrowMagickException(&image->exception,
GetMagickModule(), CoderError,
"object id too large","`%s'",image->filename);
object_id=MNG_MAX_OBJECTS;
}
if (mng_info->exists[object_id])
if (mng_info->frozen[object_id])
{
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
(void) ThrowMagickException(&image->exception,
GetMagickModule(),CoderError,
"DEFI cannot redefine a frozen MNG object","`%s'",
image->filename);
continue;
}
mng_info->exists[object_id]=MagickTrue;
if (length > 2)
mng_info->invisible[object_id]=p[2];
/*
Extract object offset info.
*/
if (length > 11)
{
mng_info->x_off[object_id]=(ssize_t) ((p[4] << 24) |
(p[5] << 16) | (p[6] << 8) | p[7]);
mng_info->y_off[object_id]=(ssize_t) ((p[8] << 24) |
(p[9] << 16) | (p[10] << 8) | p[11]);
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" x_off[%d]: %.20g, y_off[%d]: %.20g",
object_id,(double) mng_info->x_off[object_id],
object_id,(double) mng_info->y_off[object_id]);
}
}
/*
Extract object clipping info.
*/
if (length > 27)
mng_info->object_clip[object_id]=
mng_read_box(mng_info->frame,0, &p[12]);
}
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_bKGD,4) == 0)
{
mng_info->have_global_bkgd=MagickFalse;
if (length > 5)
{
mng_info->mng_global_bkgd.red=
ScaleShortToQuantum((unsigned short) ((p[0] << 8) | p[1]));
mng_info->mng_global_bkgd.green=
ScaleShortToQuantum((unsigned short) ((p[2] << 8) | p[3]));
mng_info->mng_global_bkgd.blue=
ScaleShortToQuantum((unsigned short) ((p[4] << 8) | p[5]));
mng_info->have_global_bkgd=MagickTrue;
}
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_BACK,4) == 0)
{
#if defined(MNG_INSERT_LAYERS)
if (length > 6)
mandatory_back=p[6];
else
mandatory_back=0;
if (mandatory_back && length > 5)
{
mng_background_color.red=
ScaleShortToQuantum((unsigned short) ((p[0] << 8) | p[1]));
mng_background_color.green=
ScaleShortToQuantum((unsigned short) ((p[2] << 8) | p[3]));
mng_background_color.blue=
ScaleShortToQuantum((unsigned short) ((p[4] << 8) | p[5]));
mng_background_color.opacity=OpaqueOpacity;
}
#ifdef MNG_OBJECT_BUFFERS
if (length > 8)
mng_background_object=(p[7] << 8) | p[8];
#endif
#endif
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_PLTE,4) == 0)
{
/* Read global PLTE. */
if (length && (length < 769))
{
if (mng_info->global_plte == (png_colorp) NULL)
mng_info->global_plte=(png_colorp) AcquireQuantumMemory(256,
sizeof(*mng_info->global_plte));
for (i=0; i < (ssize_t) (length/3); i++)
{
mng_info->global_plte[i].red=p[3*i];
mng_info->global_plte[i].green=p[3*i+1];
mng_info->global_plte[i].blue=p[3*i+2];
}
mng_info->global_plte_length=(unsigned int) (length/3);
}
#ifdef MNG_LOOSE
for ( ; i < 256; i++)
{
mng_info->global_plte[i].red=i;
mng_info->global_plte[i].green=i;
mng_info->global_plte[i].blue=i;
}
if (length != 0)
mng_info->global_plte_length=256;
#endif
else
mng_info->global_plte_length=0;
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_tRNS,4) == 0)
{
/* read global tRNS */
if (length > 0 && length < 257)
for (i=0; i < (ssize_t) length; i++)
mng_info->global_trns[i]=p[i];
#ifdef MNG_LOOSE
for ( ; i < 256; i++)
mng_info->global_trns[i]=255;
#endif
mng_info->global_trns_length=(unsigned int) length;
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_gAMA,4) == 0)
{
if (length == 4)
{
ssize_t
igamma;
igamma=mng_get_long(p);
mng_info->global_gamma=((float) igamma)*0.00001;
mng_info->have_global_gama=MagickTrue;
}
else
mng_info->have_global_gama=MagickFalse;
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_cHRM,4) == 0)
{
/* Read global cHRM */
if (length == 32)
{
mng_info->global_chrm.white_point.x=0.00001*mng_get_long(p);
mng_info->global_chrm.white_point.y=0.00001*mng_get_long(&p[4]);
mng_info->global_chrm.red_primary.x=0.00001*mng_get_long(&p[8]);
mng_info->global_chrm.red_primary.y=0.00001*
mng_get_long(&p[12]);
mng_info->global_chrm.green_primary.x=0.00001*
mng_get_long(&p[16]);
mng_info->global_chrm.green_primary.y=0.00001*
mng_get_long(&p[20]);
mng_info->global_chrm.blue_primary.x=0.00001*
mng_get_long(&p[24]);
mng_info->global_chrm.blue_primary.y=0.00001*
mng_get_long(&p[28]);
mng_info->have_global_chrm=MagickTrue;
}
else
mng_info->have_global_chrm=MagickFalse;
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_sRGB,4) == 0)
{
/*
Read global sRGB.
*/
if (length != 0)
{
mng_info->global_srgb_intent=
Magick_RenderingIntent_from_PNG_RenderingIntent(p[0]);
mng_info->have_global_srgb=MagickTrue;
}
else
mng_info->have_global_srgb=MagickFalse;
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_iCCP,4) == 0)
{
/* To do: */
/*
Read global iCCP.
*/
if (length != 0)
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_FRAM,4) == 0)
{
if (mng_type == 3)
(void) ThrowMagickException(&image->exception,GetMagickModule(),
CoderError,"FRAM chunk found in MNG-VLC datastream","`%s'",
image->filename);
if ((mng_info->framing_mode == 2) || (mng_info->framing_mode == 4))
image->delay=frame_delay;
frame_delay=default_frame_delay;
frame_timeout=default_frame_timeout;
fb=default_fb;
if (length > 0)
if (p[0])
mng_info->framing_mode=p[0];
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Framing_mode=%d",mng_info->framing_mode);
if (length > 6)
{
/* Note the delay and frame clipping boundaries. */
p++; /* framing mode */
while (*p && ((p-chunk) < (ssize_t) length))
p++; /* frame name */
p++; /* frame name terminator */
if ((p-chunk) < (ssize_t) (length-4))
{
int
change_delay,
change_timeout,
change_clipping;
change_delay=(*p++);
change_timeout=(*p++);
change_clipping=(*p++);
p++; /* change_sync */
if (change_delay && (p-chunk) < (ssize_t) (length-4))
{
frame_delay=1UL*image->ticks_per_second*
mng_get_long(p);
if (mng_info->ticks_per_second != 0)
frame_delay/=mng_info->ticks_per_second;
else
frame_delay=PNG_UINT_31_MAX;
if (change_delay == 2)
default_frame_delay=frame_delay;
p+=4;
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Framing_delay=%.20g",(double) frame_delay);
}
if (change_timeout && (p-chunk) < (ssize_t) (length-4))
{
frame_timeout=1UL*image->ticks_per_second*
mng_get_long(p);
if (mng_info->ticks_per_second != 0)
frame_timeout/=mng_info->ticks_per_second;
else
frame_timeout=PNG_UINT_31_MAX;
if (change_timeout == 2)
default_frame_timeout=frame_timeout;
p+=4;
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Framing_timeout=%.20g",(double) frame_timeout);
}
if (change_clipping && (p-chunk) < (ssize_t) (length-17))
{
fb=mng_read_box(previous_fb,(char) p[0],&p[1]);
p+=17;
previous_fb=fb;
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Frame_clip: L=%.20g R=%.20g T=%.20g B=%.20g",
(double) fb.left,(double) fb.right,(double) fb.top,
(double) fb.bottom);
if (change_clipping == 2)
default_fb=fb;
}
}
}
mng_info->clip=fb;
mng_info->clip=mng_minimum_box(fb,mng_info->frame);
subframe_width=(size_t) (mng_info->clip.right
-mng_info->clip.left);
subframe_height=(size_t) (mng_info->clip.bottom
-mng_info->clip.top);
/*
Insert a background layer behind the frame if framing_mode is 4.
*/
#if defined(MNG_INSERT_LAYERS)
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" subframe_width=%.20g, subframe_height=%.20g",(double)
subframe_width,(double) subframe_height);
if (insert_layers && (mng_info->framing_mode == 4) &&
(subframe_width) && (subframe_height))
{
/* Allocate next image structure. */
if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL)
{
AcquireNextImage(image_info,image);
if (GetNextImageInList(image) == (Image *) NULL)
return(DestroyImageList(image));
image=SyncNextImageInList(image);
}
mng_info->image=image;
if (term_chunk_found)
{
image->start_loop=MagickTrue;
image->iterations=mng_iterations;
term_chunk_found=MagickFalse;
}
else
image->start_loop=MagickFalse;
image->columns=subframe_width;
image->rows=subframe_height;
image->page.width=subframe_width;
image->page.height=subframe_height;
image->page.x=mng_info->clip.left;
image->page.y=mng_info->clip.top;
image->background_color=mng_background_color;
image->matte=MagickFalse;
image->delay=0;
(void) SetImageBackgroundColor(image);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Insert backgd layer, L=%.20g, R=%.20g T=%.20g, B=%.20g",
(double) mng_info->clip.left,(double) mng_info->clip.right,
(double) mng_info->clip.top,(double) mng_info->clip.bottom);
}
#endif
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_CLIP,4) == 0)
{
unsigned int
first_object,
last_object;
/*
Read CLIP.
*/
if (length > 3)
{
first_object=(p[0] << 8) | p[1];
last_object=(p[2] << 8) | p[3];
p+=4;
for (i=(int) first_object; i <= (int) last_object; i++)
{
if (mng_info->exists[i] && !mng_info->frozen[i])
{
MngBox
box;
box=mng_info->object_clip[i];
if ((p-chunk) < (ssize_t) (length-17))
mng_info->object_clip[i]=
mng_read_box(box,(char) p[0],&p[1]);
}
}
}
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_SAVE,4) == 0)
{
for (i=1; i < MNG_MAX_OBJECTS; i++)
if (mng_info->exists[i])
{
mng_info->frozen[i]=MagickTrue;
#ifdef MNG_OBJECT_BUFFERS
if (mng_info->ob[i] != (MngBuffer *) NULL)
mng_info->ob[i]->frozen=MagickTrue;
#endif
}
if (length != 0)
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if ((memcmp(type,mng_DISC,4) == 0) || (memcmp(type,mng_SEEK,4) == 0))
{
/* Read DISC or SEEK. */
if ((length == 0) || !memcmp(type,mng_SEEK,4))
{
for (i=1; i < MNG_MAX_OBJECTS; i++)
MngInfoDiscardObject(mng_info,i);
}
else
{
register ssize_t
j;
for (j=1; j < (ssize_t) length; j+=2)
{
i=p[j-1] << 8 | p[j];
MngInfoDiscardObject(mng_info,i);
}
}
if (length != 0)
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_MOVE,4) == 0)
{
size_t
first_object,
last_object;
/* read MOVE */
if (length > 3)
{
first_object=(p[0] << 8) | p[1];
last_object=(p[2] << 8) | p[3];
p+=4;
for (i=(ssize_t) first_object; i <= (ssize_t) last_object; i++)
{
if ((i < 0) || (i >= MNG_MAX_OBJECTS))
continue;
if (mng_info->exists[i] && !mng_info->frozen[i] &&
(p-chunk) < (ssize_t) (length-8))
{
MngPair
new_pair;
MngPair
old_pair;
old_pair.a=mng_info->x_off[i];
old_pair.b=mng_info->y_off[i];
new_pair=mng_read_pair(old_pair,(int) p[0],&p[1]);
mng_info->x_off[i]=new_pair.a;
mng_info->y_off[i]=new_pair.b;
}
}
}
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_LOOP,4) == 0)
{
ssize_t loop_iters=1;
if (length > 4)
{
loop_level=chunk[0];
mng_info->loop_active[loop_level]=1; /* mark loop active */
/* Record starting point. */
loop_iters=mng_get_long(&chunk[1]);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" LOOP level %.20g has %.20g iterations ",
(double) loop_level, (double) loop_iters);
if (loop_iters == 0)
skipping_loop=loop_level;
else
{
mng_info->loop_jump[loop_level]=TellBlob(image);
mng_info->loop_count[loop_level]=loop_iters;
}
mng_info->loop_iteration[loop_level]=0;
}
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_ENDL,4) == 0)
{
if (length > 0)
{
loop_level=chunk[0];
if (skipping_loop > 0)
{
if (skipping_loop == loop_level)
{
/*
Found end of zero-iteration loop.
*/
skipping_loop=(-1);
mng_info->loop_active[loop_level]=0;
}
}
else
{
if (mng_info->loop_active[loop_level] == 1)
{
mng_info->loop_count[loop_level]--;
mng_info->loop_iteration[loop_level]++;
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" ENDL: LOOP level %.20g has %.20g remaining iters ",
(double) loop_level,(double)
mng_info->loop_count[loop_level]);
if (mng_info->loop_count[loop_level] != 0)
{
offset=SeekBlob(image,
mng_info->loop_jump[loop_level], SEEK_SET);
if (offset < 0)
{
chunk=(unsigned char *) RelinquishMagickMemory(
chunk);
ThrowReaderException(CorruptImageError,
"ImproperImageHeader");
}
}
else
{
short
last_level;
/*
Finished loop.
*/
mng_info->loop_active[loop_level]=0;
last_level=(-1);
for (i=0; i < loop_level; i++)
if (mng_info->loop_active[i] == 1)
last_level=(short) i;
loop_level=last_level;
}
}
}
}
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_CLON,4) == 0)
{
if (mng_info->clon_warning == 0)
(void) ThrowMagickException(&image->exception,GetMagickModule(),
CoderError,"CLON is not implemented yet","`%s'",
image->filename);
mng_info->clon_warning++;
}
if (memcmp(type,mng_MAGN,4) == 0)
{
png_uint_16
magn_first,
magn_last,
magn_mb,
magn_ml,
magn_mr,
magn_mt,
magn_mx,
magn_my,
magn_methx,
magn_methy;
if (length > 1)
magn_first=(p[0] << 8) | p[1];
else
magn_first=0;
if (length > 3)
magn_last=(p[2] << 8) | p[3];
else
magn_last=magn_first;
#ifndef MNG_OBJECT_BUFFERS
if (magn_first || magn_last)
if (mng_info->magn_warning == 0)
{
(void) ThrowMagickException(&image->exception,
GetMagickModule(),CoderError,
"MAGN is not implemented yet for nonzero objects",
"`%s'",image->filename);
mng_info->magn_warning++;
}
#endif
if (length > 4)
magn_methx=p[4];
else
magn_methx=0;
if (length > 6)
magn_mx=(p[5] << 8) | p[6];
else
magn_mx=1;
if (magn_mx == 0)
magn_mx=1;
if (length > 8)
magn_my=(p[7] << 8) | p[8];
else
magn_my=magn_mx;
if (magn_my == 0)
magn_my=1;
if (length > 10)
magn_ml=(p[9] << 8) | p[10];
else
magn_ml=magn_mx;
if (magn_ml == 0)
magn_ml=1;
if (length > 12)
magn_mr=(p[11] << 8) | p[12];
else
magn_mr=magn_mx;
if (magn_mr == 0)
magn_mr=1;
if (length > 14)
magn_mt=(p[13] << 8) | p[14];
else
magn_mt=magn_my;
if (magn_mt == 0)
magn_mt=1;
if (length > 16)
magn_mb=(p[15] << 8) | p[16];
else
magn_mb=magn_my;
if (magn_mb == 0)
magn_mb=1;
if (length > 17)
magn_methy=p[17];
else
magn_methy=magn_methx;
if (magn_methx > 5 || magn_methy > 5)
if (mng_info->magn_warning == 0)
{
(void) ThrowMagickException(&image->exception,
GetMagickModule(),CoderError,
"Unknown MAGN method in MNG datastream","`%s'",
image->filename);
mng_info->magn_warning++;
}
#ifdef MNG_OBJECT_BUFFERS
/* Magnify existing objects in the range magn_first to magn_last */
#endif
if (magn_first == 0 || magn_last == 0)
{
/* Save the magnification factors for object 0 */
mng_info->magn_mb=magn_mb;
mng_info->magn_ml=magn_ml;
mng_info->magn_mr=magn_mr;
mng_info->magn_mt=magn_mt;
mng_info->magn_mx=magn_mx;
mng_info->magn_my=magn_my;
mng_info->magn_methx=magn_methx;
mng_info->magn_methy=magn_methy;
}
}
if (memcmp(type,mng_PAST,4) == 0)
{
if (mng_info->past_warning == 0)
(void) ThrowMagickException(&image->exception,GetMagickModule(),
CoderError,"PAST is not implemented yet","`%s'",
image->filename);
mng_info->past_warning++;
}
if (memcmp(type,mng_SHOW,4) == 0)
{
if (mng_info->show_warning == 0)
(void) ThrowMagickException(&image->exception,GetMagickModule(),
CoderError,"SHOW is not implemented yet","`%s'",
image->filename);
mng_info->show_warning++;
}
if (memcmp(type,mng_sBIT,4) == 0)
{
if (length < 4)
mng_info->have_global_sbit=MagickFalse;
else
{
mng_info->global_sbit.gray=p[0];
mng_info->global_sbit.red=p[0];
mng_info->global_sbit.green=p[1];
mng_info->global_sbit.blue=p[2];
mng_info->global_sbit.alpha=p[3];
mng_info->have_global_sbit=MagickTrue;
}
}
if (memcmp(type,mng_pHYs,4) == 0)
{
if (length > 8)
{
mng_info->global_x_pixels_per_unit=
(size_t) mng_get_long(p);
mng_info->global_y_pixels_per_unit=
(size_t) mng_get_long(&p[4]);
mng_info->global_phys_unit_type=p[8];
mng_info->have_global_phys=MagickTrue;
}
else
mng_info->have_global_phys=MagickFalse;
}
if (memcmp(type,mng_pHYg,4) == 0)
{
if (mng_info->phyg_warning == 0)
(void) ThrowMagickException(&image->exception,GetMagickModule(),
CoderError,"pHYg is not implemented.","`%s'",image->filename);
mng_info->phyg_warning++;
}
if (memcmp(type,mng_BASI,4) == 0)
{
skip_to_iend=MagickTrue;
if (mng_info->basi_warning == 0)
(void) ThrowMagickException(&image->exception,GetMagickModule(),
CoderError,"BASI is not implemented yet","`%s'",
image->filename);
mng_info->basi_warning++;
#ifdef MNG_BASI_SUPPORTED
if (length > 11)
{
basi_width=(size_t) ((p[0] << 24) | (p[1] << 16) |
(p[2] << 8) | p[3]);
basi_height=(size_t) ((p[4] << 24) | (p[5] << 16) |
(p[6] << 8) | p[7]);
basi_color_type=p[8];
basi_compression_method=p[9];
basi_filter_type=p[10];
basi_interlace_method=p[11];
}
if (length > 13)
basi_red=(p[12] << 8) & p[13];
else
basi_red=0;
if (length > 15)
basi_green=(p[14] << 8) & p[15];
else
basi_green=0;
if (length > 17)
basi_blue=(p[16] << 8) & p[17];
else
basi_blue=0;
if (length > 19)
basi_alpha=(p[18] << 8) & p[19];
else
{
if (basi_sample_depth == 16)
basi_alpha=65535L;
else
basi_alpha=255;
}
if (length > 20)
basi_viewable=p[20];
else
basi_viewable=0;
#endif
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_IHDR,4)
#if defined(JNG_SUPPORTED)
&& memcmp(type,mng_JHDR,4)
#endif
)
{
/* Not an IHDR or JHDR chunk */
if (length != 0)
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
/* Process IHDR */
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Processing %c%c%c%c chunk",type[0],type[1],type[2],type[3]);
mng_info->exists[object_id]=MagickTrue;
mng_info->viewable[object_id]=MagickTrue;
if (mng_info->invisible[object_id])
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Skipping invisible object");
skip_to_iend=MagickTrue;
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
#if defined(MNG_INSERT_LAYERS)
if (length < 8)
{
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
image_width=(size_t) mng_get_long(p);
image_height=(size_t) mng_get_long(&p[4]);
#endif
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
/*
Insert a transparent background layer behind the entire animation
if it is not full screen.
*/
#if defined(MNG_INSERT_LAYERS)
if (insert_layers && mng_type && first_mng_object)
{
if ((mng_info->clip.left > 0) || (mng_info->clip.top > 0) ||
(image_width < mng_info->mng_width) ||
(mng_info->clip.right < (ssize_t) mng_info->mng_width) ||
(image_height < mng_info->mng_height) ||
(mng_info->clip.bottom < (ssize_t) mng_info->mng_height))
{
if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL)
{
/*
Allocate next image structure.
*/
AcquireNextImage(image_info,image);
if (GetNextImageInList(image) == (Image *) NULL)
return(DestroyImageList(image));
image=SyncNextImageInList(image);
}
mng_info->image=image;
if (term_chunk_found)
{
image->start_loop=MagickTrue;
image->iterations=mng_iterations;
term_chunk_found=MagickFalse;
}
else
image->start_loop=MagickFalse;
/* Make a background rectangle. */
image->delay=0;
image->columns=mng_info->mng_width;
image->rows=mng_info->mng_height;
image->page.width=mng_info->mng_width;
image->page.height=mng_info->mng_height;
image->page.x=0;
image->page.y=0;
image->background_color=mng_background_color;
(void) SetImageBackgroundColor(image);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Inserted transparent background layer, W=%.20g, H=%.20g",
(double) mng_info->mng_width,(double) mng_info->mng_height);
}
}
/*
Insert a background layer behind the upcoming image if
framing_mode is 3, and we haven't already inserted one.
*/
if (insert_layers && (mng_info->framing_mode == 3) &&
(subframe_width) && (subframe_height) && (simplicity == 0 ||
(simplicity & 0x08)))
{
if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL)
{
/*
Allocate next image structure.
*/
AcquireNextImage(image_info,image);
if (GetNextImageInList(image) == (Image *) NULL)
return(DestroyImageList(image));
image=SyncNextImageInList(image);
}
mng_info->image=image;
if (term_chunk_found)
{
image->start_loop=MagickTrue;
image->iterations=mng_iterations;
term_chunk_found=MagickFalse;
}
else
image->start_loop=MagickFalse;
image->delay=0;
image->columns=subframe_width;
image->rows=subframe_height;
image->page.width=subframe_width;
image->page.height=subframe_height;
image->page.x=mng_info->clip.left;
image->page.y=mng_info->clip.top;
image->background_color=mng_background_color;
image->matte=MagickFalse;
(void) SetImageBackgroundColor(image);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Insert background layer, L=%.20g, R=%.20g T=%.20g, B=%.20g",
(double) mng_info->clip.left,(double) mng_info->clip.right,
(double) mng_info->clip.top,(double) mng_info->clip.bottom);
}
#endif /* MNG_INSERT_LAYERS */
first_mng_object=MagickFalse;
if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL)
{
/*
Allocate next image structure.
*/
AcquireNextImage(image_info,image);
if (GetNextImageInList(image) == (Image *) NULL)
return(DestroyImageList(image));
image=SyncNextImageInList(image);
}
mng_info->image=image;
status=SetImageProgress(image,LoadImagesTag,TellBlob(image),
GetBlobSize(image));
if (status == MagickFalse)
break;
if (term_chunk_found)
{
image->start_loop=MagickTrue;
term_chunk_found=MagickFalse;
}
else
image->start_loop=MagickFalse;
if (mng_info->framing_mode == 1 || mng_info->framing_mode == 3)
{
image->delay=frame_delay;
frame_delay=default_frame_delay;
}
else
image->delay=0;
image->page.width=mng_info->mng_width;
image->page.height=mng_info->mng_height;
image->page.x=mng_info->x_off[object_id];
image->page.y=mng_info->y_off[object_id];
image->iterations=mng_iterations;
/*
Seek back to the beginning of the IHDR or JHDR chunk's length field.
*/
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Seeking back to beginning of %c%c%c%c chunk",type[0],type[1],
type[2],type[3]);
offset=SeekBlob(image,-((ssize_t) length+12),SEEK_CUR);
if (offset < 0)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
mng_info->image=image;
mng_info->mng_type=mng_type;
mng_info->object_id=object_id;
if (memcmp(type,mng_IHDR,4) == 0)
image=ReadOnePNGImage(mng_info,image_info,exception);
#if defined(JNG_SUPPORTED)
else
image=ReadOneJNGImage(mng_info,image_info,exception);
#endif
if (image == (Image *) NULL)
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"exit ReadJNGImage() with error");
return((Image *) NULL);
}
if (image->columns == 0 || image->rows == 0)
{
(void) CloseBlob(image);
return(DestroyImageList(image));
}
mng_info->image=image;
if (mng_type)
{
MngBox
crop_box;
if (mng_info->magn_methx || mng_info->magn_methy)
{
png_uint_32
magnified_height,
magnified_width;
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Processing MNG MAGN chunk");
if (mng_info->magn_methx == 1)
{
magnified_width=mng_info->magn_ml;
if (image->columns > 1)
magnified_width += mng_info->magn_mr;
if (image->columns > 2)
magnified_width += (png_uint_32)
((image->columns-2)*(mng_info->magn_mx));
}
else
{
magnified_width=(png_uint_32) image->columns;
if (image->columns > 1)
magnified_width += mng_info->magn_ml-1;
if (image->columns > 2)
magnified_width += mng_info->magn_mr-1;
if (image->columns > 3)
magnified_width += (png_uint_32)
((image->columns-3)*(mng_info->magn_mx-1));
}
if (mng_info->magn_methy == 1)
{
magnified_height=mng_info->magn_mt;
if (image->rows > 1)
magnified_height += mng_info->magn_mb;
if (image->rows > 2)
magnified_height += (png_uint_32)
((image->rows-2)*(mng_info->magn_my));
}
else
{
magnified_height=(png_uint_32) image->rows;
if (image->rows > 1)
magnified_height += mng_info->magn_mt-1;
if (image->rows > 2)
magnified_height += mng_info->magn_mb-1;
if (image->rows > 3)
magnified_height += (png_uint_32)
((image->rows-3)*(mng_info->magn_my-1));
}
if (magnified_height > image->rows ||
magnified_width > image->columns)
{
Image
*large_image;
int
yy;
ssize_t
m,
y;
register ssize_t
x;
register PixelPacket
*n,
*q;
PixelPacket
*next,
*prev;
png_uint_16
magn_methx,
magn_methy;
/* Allocate next image structure. */
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Allocate magnified image");
AcquireNextImage(image_info,image);
if (GetNextImageInList(image) == (Image *) NULL)
return(DestroyImageList(image));
large_image=SyncNextImageInList(image);
large_image->columns=magnified_width;
large_image->rows=magnified_height;
magn_methx=mng_info->magn_methx;
magn_methy=mng_info->magn_methy;
#if (MAGICKCORE_QUANTUM_DEPTH > 16)
#define QM unsigned short
if (magn_methx != 1 || magn_methy != 1)
{
/*
Scale pixels to unsigned shorts to prevent
overflow of intermediate values of interpolations
*/
for (y=0; y < (ssize_t) image->rows; y++)
{
q=GetAuthenticPixels(image,0,y,image->columns,1,
exception);
for (x=(ssize_t) image->columns-1; x >= 0; x--)
{
SetPixelRed(q,ScaleQuantumToShort(
GetPixelRed(q)));
SetPixelGreen(q,ScaleQuantumToShort(
GetPixelGreen(q)));
SetPixelBlue(q,ScaleQuantumToShort(
GetPixelBlue(q)));
SetPixelOpacity(q,ScaleQuantumToShort(
GetPixelOpacity(q)));
q++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
}
#else
#define QM Quantum
#endif
if (image->matte != MagickFalse)
(void) SetImageBackgroundColor(large_image);
else
{
large_image->background_color.opacity=OpaqueOpacity;
(void) SetImageBackgroundColor(large_image);
if (magn_methx == 4)
magn_methx=2;
if (magn_methx == 5)
magn_methx=3;
if (magn_methy == 4)
magn_methy=2;
if (magn_methy == 5)
magn_methy=3;
}
/* magnify the rows into the right side of the large image */
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Magnify the rows to %.20g",(double) large_image->rows);
m=(ssize_t) mng_info->magn_mt;
yy=0;
length=(size_t) image->columns;
next=(PixelPacket *) AcquireQuantumMemory(length,sizeof(*next));
prev=(PixelPacket *) AcquireQuantumMemory(length,sizeof(*prev));
if ((prev == (PixelPacket *) NULL) ||
(next == (PixelPacket *) NULL))
{
image=DestroyImageList(image);
ThrowReaderException(ResourceLimitError,
"MemoryAllocationFailed");
}
n=GetAuthenticPixels(image,0,0,image->columns,1,exception);
(void) CopyMagickMemory(next,n,length);
for (y=0; y < (ssize_t) image->rows; y++)
{
if (y == 0)
m=(ssize_t) mng_info->magn_mt;
else if (magn_methy > 1 && y == (ssize_t) image->rows-2)
m=(ssize_t) mng_info->magn_mb;
else if (magn_methy <= 1 && y == (ssize_t) image->rows-1)
m=(ssize_t) mng_info->magn_mb;
else if (magn_methy > 1 && y == (ssize_t) image->rows-1)
m=1;
else
m=(ssize_t) mng_info->magn_my;
n=prev;
prev=next;
next=n;
if (y < (ssize_t) image->rows-1)
{
n=GetAuthenticPixels(image,0,y+1,image->columns,1,
exception);
(void) CopyMagickMemory(next,n,length);
}
for (i=0; i < m; i++, yy++)
{
register PixelPacket
*pixels;
assert(yy < (ssize_t) large_image->rows);
pixels=prev;
n=next;
q=GetAuthenticPixels(large_image,0,yy,large_image->columns,
1,exception);
q+=(large_image->columns-image->columns);
for (x=(ssize_t) image->columns-1; x >= 0; x--)
{
/* To do: get color as function of indexes[x] */
/*
if (image->storage_class == PseudoClass)
{
}
*/
if (magn_methy <= 1)
{
/* replicate previous */
SetPixelRGBO(q,(pixels));
}
else if (magn_methy == 2 || magn_methy == 4)
{
if (i == 0)
{
SetPixelRGBO(q,(pixels));
}
else
{
/* Interpolate */
SetPixelRed(q,
((QM) (((ssize_t)
(2*i*(GetPixelRed(n)
-GetPixelRed(pixels)+m))/
((ssize_t) (m*2))
+GetPixelRed(pixels)))));
SetPixelGreen(q,
((QM) (((ssize_t)
(2*i*(GetPixelGreen(n)
-GetPixelGreen(pixels)+m))/
((ssize_t) (m*2))
+GetPixelGreen(pixels)))));
SetPixelBlue(q,
((QM) (((ssize_t)
(2*i*(GetPixelBlue(n)
-GetPixelBlue(pixels)+m))/
((ssize_t) (m*2))
+GetPixelBlue(pixels)))));
if (image->matte != MagickFalse)
SetPixelOpacity(q,
((QM) (((ssize_t)
(2*i*(GetPixelOpacity(n)
-GetPixelOpacity(pixels)+m))
/((ssize_t) (m*2))+
GetPixelOpacity(pixels)))));
}
if (magn_methy == 4)
{
/* Replicate nearest */
if (i <= ((m+1) << 1))
SetPixelOpacity(q,
(*pixels).opacity+0);
else
SetPixelOpacity(q,
(*n).opacity+0);
}
}
else /* if (magn_methy == 3 || magn_methy == 5) */
{
/* Replicate nearest */
if (i <= ((m+1) << 1))
{
SetPixelRGBO(q,(pixels));
}
else
{
SetPixelRGBO(q,(n));
}
if (magn_methy == 5)
{
SetPixelOpacity(q,
(QM) (((ssize_t) (2*i*
(GetPixelOpacity(n)
-GetPixelOpacity(pixels))
+m))/((ssize_t) (m*2))
+GetPixelOpacity(pixels)));
}
}
n++;
q++;
pixels++;
} /* x */
if (SyncAuthenticPixels(large_image,exception) == 0)
break;
} /* i */
} /* y */
prev=(PixelPacket *) RelinquishMagickMemory(prev);
next=(PixelPacket *) RelinquishMagickMemory(next);
length=image->columns;
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Delete original image");
DeleteImageFromList(&image);
image=large_image;
mng_info->image=image;
/* magnify the columns */
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Magnify the columns to %.20g",(double) image->columns);
for (y=0; y < (ssize_t) image->rows; y++)
{
register PixelPacket
*pixels;
q=GetAuthenticPixels(image,0,y,image->columns,1,exception);
pixels=q+(image->columns-length);
n=pixels+1;
for (x=(ssize_t) (image->columns-length);
x < (ssize_t) image->columns; x++)
{
/* To do: Rewrite using Get/Set***PixelComponent() */
if (x == (ssize_t) (image->columns-length))
m=(ssize_t) mng_info->magn_ml;
else if (magn_methx > 1 && x == (ssize_t) image->columns-2)
m=(ssize_t) mng_info->magn_mr;
else if (magn_methx <= 1 && x == (ssize_t) image->columns-1)
m=(ssize_t) mng_info->magn_mr;
else if (magn_methx > 1 && x == (ssize_t) image->columns-1)
m=1;
else
m=(ssize_t) mng_info->magn_mx;
for (i=0; i < m; i++)
{
if (magn_methx <= 1)
{
/* replicate previous */
SetPixelRGBO(q,(pixels));
}
else if (magn_methx == 2 || magn_methx == 4)
{
if (i == 0)
{
SetPixelRGBO(q,(pixels));
}
/* To do: Rewrite using Get/Set***PixelComponent() */
else
{
/* Interpolate */
SetPixelRed(q,
(QM) ((2*i*(
GetPixelRed(n)
-GetPixelRed(pixels))+m)
/((ssize_t) (m*2))+
GetPixelRed(pixels)));
SetPixelGreen(q,
(QM) ((2*i*(
GetPixelGreen(n)
-GetPixelGreen(pixels))+m)
/((ssize_t) (m*2))+
GetPixelGreen(pixels)));
SetPixelBlue(q,
(QM) ((2*i*(
GetPixelBlue(n)
-GetPixelBlue(pixels))+m)
/((ssize_t) (m*2))+
GetPixelBlue(pixels)));
if (image->matte != MagickFalse)
SetPixelOpacity(q,
(QM) ((2*i*(
GetPixelOpacity(n)
-GetPixelOpacity(pixels))+m)
/((ssize_t) (m*2))+
GetPixelOpacity(pixels)));
}
if (magn_methx == 4)
{
/* Replicate nearest */
if (i <= ((m+1) << 1))
{
SetPixelOpacity(q,
GetPixelOpacity(pixels)+0);
}
else
{
SetPixelOpacity(q,
GetPixelOpacity(n)+0);
}
}
}
else /* if (magn_methx == 3 || magn_methx == 5) */
{
/* Replicate nearest */
if (i <= ((m+1) << 1))
{
SetPixelRGBO(q,(pixels));
}
else
{
SetPixelRGBO(q,(n));
}
if (magn_methx == 5)
{
/* Interpolate */
SetPixelOpacity(q,
(QM) ((2*i*( GetPixelOpacity(n)
-GetPixelOpacity(pixels))+m)/
((ssize_t) (m*2))
+GetPixelOpacity(pixels)));
}
}
q++;
}
n++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
#if (MAGICKCORE_QUANTUM_DEPTH > 16)
if (magn_methx != 1 || magn_methy != 1)
{
/*
Rescale pixels to Quantum
*/
for (y=0; y < (ssize_t) image->rows; y++)
{
q=GetAuthenticPixels(image,0,y,image->columns,1,exception);
for (x=(ssize_t) image->columns-1; x >= 0; x--)
{
SetPixelRed(q,ScaleShortToQuantum(
GetPixelRed(q)));
SetPixelGreen(q,ScaleShortToQuantum(
GetPixelGreen(q)));
SetPixelBlue(q,ScaleShortToQuantum(
GetPixelBlue(q)));
SetPixelOpacity(q,ScaleShortToQuantum(
GetPixelOpacity(q)));
q++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
}
#endif
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Finished MAGN processing");
}
}
/*
Crop_box is with respect to the upper left corner of the MNG.
*/
crop_box.left=mng_info->image_box.left+mng_info->x_off[object_id];
crop_box.right=mng_info->image_box.right+mng_info->x_off[object_id];
crop_box.top=mng_info->image_box.top+mng_info->y_off[object_id];
crop_box.bottom=mng_info->image_box.bottom+mng_info->y_off[object_id];
crop_box=mng_minimum_box(crop_box,mng_info->clip);
crop_box=mng_minimum_box(crop_box,mng_info->frame);
crop_box=mng_minimum_box(crop_box,mng_info->object_clip[object_id]);
if ((crop_box.left != (mng_info->image_box.left
+mng_info->x_off[object_id])) ||
(crop_box.right != (mng_info->image_box.right
+mng_info->x_off[object_id])) ||
(crop_box.top != (mng_info->image_box.top
+mng_info->y_off[object_id])) ||
(crop_box.bottom != (mng_info->image_box.bottom
+mng_info->y_off[object_id])))
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Crop the PNG image");
if ((crop_box.left < crop_box.right) &&
(crop_box.top < crop_box.bottom))
{
Image
*im;
RectangleInfo
crop_info;
/*
Crop_info is with respect to the upper left corner of
the image.
*/
crop_info.x=(crop_box.left-mng_info->x_off[object_id]);
crop_info.y=(crop_box.top-mng_info->y_off[object_id]);
crop_info.width=(size_t) (crop_box.right-crop_box.left);
crop_info.height=(size_t) (crop_box.bottom-crop_box.top);
image->page.width=image->columns;
image->page.height=image->rows;
image->page.x=0;
image->page.y=0;
im=CropImage(image,&crop_info,exception);
if (im != (Image *) NULL)
{
image->columns=im->columns;
image->rows=im->rows;
im=DestroyImage(im);
image->page.width=image->columns;
image->page.height=image->rows;
image->page.x=crop_box.left;
image->page.y=crop_box.top;
}
}
else
{
/*
No pixels in crop area. The MNG spec still requires
a layer, though, so make a single transparent pixel in
the top left corner.
*/
image->columns=1;
image->rows=1;
image->colors=2;
(void) SetImageBackgroundColor(image);
image->page.width=1;
image->page.height=1;
image->page.x=0;
image->page.y=0;
}
}
#ifndef PNG_READ_EMPTY_PLTE_SUPPORTED
image=mng_info->image;
#endif
}
#if (MAGICKCORE_QUANTUM_DEPTH > 16)
/* PNG does not handle depths greater than 16 so reduce it even
* if lossy, and promote any depths > 8 to 16.
*/
if (image->depth > 16)
image->depth=16;
#endif
#if (MAGICKCORE_QUANTUM_DEPTH > 8)
if (image->depth > 8)
{
/* To do: fill low byte properly */
image->depth=16;
}
if (LosslessReduceDepthOK(image) != MagickFalse)
image->depth = 8;
#endif
GetImageException(image,exception);
if (image_info->number_scenes != 0)
{
if (mng_info->scenes_found >
(ssize_t) (image_info->first_scene+image_info->number_scenes))
break;
}
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Finished reading image datastream.");
} while (LocaleCompare(image_info->magick,"MNG") == 0);
(void) CloseBlob(image);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Finished reading all image datastreams.");
#if defined(MNG_INSERT_LAYERS)
if (insert_layers && !mng_info->image_found && (mng_info->mng_width) &&
(mng_info->mng_height))
{
/*
Insert a background layer if nothing else was found.
*/
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" No images found. Inserting a background layer.");
if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL)
{
/*
Allocate next image structure.
*/
AcquireNextImage(image_info,image);
if (GetNextImageInList(image) == (Image *) NULL)
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Allocation failed, returning NULL.");
return(DestroyImageList(image));
}
image=SyncNextImageInList(image);
}
image->columns=mng_info->mng_width;
image->rows=mng_info->mng_height;
image->page.width=mng_info->mng_width;
image->page.height=mng_info->mng_height;
image->page.x=0;
image->page.y=0;
image->background_color=mng_background_color;
image->matte=MagickFalse;
if (image_info->ping == MagickFalse)
(void) SetImageBackgroundColor(image);
mng_info->image_found++;
}
#endif
image->iterations=mng_iterations;
if (mng_iterations == 1)
image->start_loop=MagickTrue;
while (GetPreviousImageInList(image) != (Image *) NULL)
{
image_count++;
if (image_count > 10*mng_info->image_found)
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule()," No beginning");
(void) ThrowMagickException(&image->exception,GetMagickModule(),
CoderError,"Linked list is corrupted, beginning of list not found",
"`%s'",image_info->filename);
return(DestroyImageList(image));
}
image=GetPreviousImageInList(image);
if (GetNextImageInList(image) == (Image *) NULL)
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule()," Corrupt list");
(void) ThrowMagickException(&image->exception,GetMagickModule(),
CoderError,"Linked list is corrupted; next_image is NULL","`%s'",
image_info->filename);
}
}
if (mng_info->ticks_per_second && mng_info->image_found > 1 &&
GetNextImageInList(image) ==
(Image *) NULL)
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" First image null");
(void) ThrowMagickException(&image->exception,GetMagickModule(),
CoderError,"image->next for first image is NULL but shouldn't be.",
"`%s'",image_info->filename);
}
if (mng_info->image_found == 0)
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" No visible images found.");
(void) ThrowMagickException(&image->exception,GetMagickModule(),
CoderError,"No visible images in file","`%s'",image_info->filename);
return(DestroyImageList(image));
}
if (mng_info->ticks_per_second)
final_delay=1UL*MagickMax(image->ticks_per_second,1L)*
final_delay/mng_info->ticks_per_second;
else
image->start_loop=MagickTrue;
/* Find final nonzero image delay */
final_image_delay=0;
while (GetNextImageInList(image) != (Image *) NULL)
{
if (image->delay)
final_image_delay=image->delay;
image=GetNextImageInList(image);
}
if (final_delay < final_image_delay)
final_delay=final_image_delay;
image->delay=final_delay;
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image->delay=%.20g, final_delay=%.20g",(double) image->delay,
(double) final_delay);
if (logging != MagickFalse)
{
int
scene;
scene=0;
image=GetFirstImageInList(image);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Before coalesce:");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" scene 0 delay=%.20g",(double) image->delay);
while (GetNextImageInList(image) != (Image *) NULL)
{
image=GetNextImageInList(image);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" scene %.20g delay=%.20g",(double) scene++,(double) image->delay);
}
}
image=GetFirstImageInList(image);
#ifdef MNG_COALESCE_LAYERS
if (insert_layers)
{
Image
*next_image,
*next;
size_t
scene;
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule()," Coalesce Images");
scene=image->scene;
next_image=CoalesceImages(image,&image->exception);
if (next_image == (Image *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
image=DestroyImageList(image);
image=next_image;
for (next=image; next != (Image *) NULL; next=next_image)
{
next->page.width=mng_info->mng_width;
next->page.height=mng_info->mng_height;
next->page.x=0;
next->page.y=0;
next->scene=scene++;
next_image=GetNextImageInList(next);
if (next_image == (Image *) NULL)
break;
if (next->delay == 0)
{
scene--;
next_image->previous=GetPreviousImageInList(next);
if (GetPreviousImageInList(next) == (Image *) NULL)
image=next_image;
else
next->previous->next=next_image;
next=DestroyImage(next);
}
}
}
#endif
while (GetNextImageInList(image) != (Image *) NULL)
image=GetNextImageInList(image);
image->dispose=BackgroundDispose;
if (logging != MagickFalse)
{
int
scene;
scene=0;
image=GetFirstImageInList(image);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" After coalesce:");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" scene 0 delay=%.20g dispose=%.20g",(double) image->delay,
(double) image->dispose);
while (GetNextImageInList(image) != (Image *) NULL)
{
image=GetNextImageInList(image);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" scene %.20g delay=%.20g dispose=%.20g",(double) scene++,
(double) image->delay,(double) image->dispose);
}
}
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" exit ReadOneJNGImage();");
return(image);
}
static Image *ReadMNGImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
Image
*image;
MagickBooleanType
logging,
status;
MngInfo
*mng_info;
/* Open image file. */
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
logging=LogMagickEvent(CoderEvent,GetMagickModule(),"Enter ReadMNGImage()");
image=AcquireImage(image_info);
mng_info=(MngInfo *) NULL;
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
return((Image *) NULL);
/* Allocate a MngInfo structure. */
mng_info=(MngInfo *) AcquireMagickMemory(sizeof(MngInfo));
if (mng_info == (MngInfo *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
/* Initialize members of the MngInfo structure. */
(void) ResetMagickMemory(mng_info,0,sizeof(MngInfo));
mng_info->image=image;
image=ReadOneMNGImage(mng_info,image_info,exception);
mng_info=MngInfoFreeStruct(mng_info);
if (image == (Image *) NULL)
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"exit ReadMNGImage() with error");
return((Image *) NULL);
}
(void) CloseBlob(image);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),"exit ReadMNGImage()");
return(GetFirstImageInList(image));
}
#else /* PNG_LIBPNG_VER > 10011 */
static Image *ReadPNGImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
printf("Your PNG library is too old: You have libpng-%s\n",
PNG_LIBPNG_VER_STRING);
(void) ThrowMagickException(exception,GetMagickModule(),CoderError,
"PNG library is too old","`%s'",image_info->filename);
return(Image *) NULL;
}
static Image *ReadMNGImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
return(ReadPNGImage(image_info,exception));
}
#endif /* PNG_LIBPNG_VER > 10011 */
#endif
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e g i s t e r P N G I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% RegisterPNGImage() adds properties for the PNG 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 RegisterPNGImage method is:
%
% size_t RegisterPNGImage(void)
%
*/
ModuleExport size_t RegisterPNGImage(void)
{
char
version[MaxTextExtent];
MagickInfo
*entry;
static const char
*PNGNote=
{
"See http://www.libpng.org/ for details about the PNG format."
},
*JNGNote=
{
"See http://www.libpng.org/pub/mng/ for details about the JNG\n"
"format."
},
*MNGNote=
{
"See http://www.libpng.org/pub/mng/ for details about the MNG\n"
"format."
};
*version='\0';
#if defined(PNG_LIBPNG_VER_STRING)
(void) ConcatenateMagickString(version,"libpng ",MaxTextExtent);
(void) ConcatenateMagickString(version,PNG_LIBPNG_VER_STRING,MaxTextExtent);
if (LocaleCompare(PNG_LIBPNG_VER_STRING,png_get_header_ver(NULL)) != 0)
{
(void) ConcatenateMagickString(version,",",MaxTextExtent);
(void) ConcatenateMagickString(version,png_get_libpng_ver(NULL),
MaxTextExtent);
}
#endif
entry=SetMagickInfo("MNG");
entry->seekable_stream=MagickTrue;
#if defined(MAGICKCORE_PNG_DELEGATE)
entry->decoder=(DecodeImageHandler *) ReadMNGImage;
entry->encoder=(EncodeImageHandler *) WriteMNGImage;
#endif
entry->magick=(IsImageFormatHandler *) IsMNG;
entry->description=ConstantString("Multiple-image Network Graphics");
if (*version != '\0')
entry->version=ConstantString(version);
entry->mime_type=ConstantString("video/x-mng");
entry->module=ConstantString("PNG");
entry->note=ConstantString(MNGNote);
(void) RegisterMagickInfo(entry);
entry=SetMagickInfo("PNG");
#if defined(MAGICKCORE_PNG_DELEGATE)
entry->decoder=(DecodeImageHandler *) ReadPNGImage;
entry->encoder=(EncodeImageHandler *) WritePNGImage;
#endif
entry->magick=(IsImageFormatHandler *) IsPNG;
entry->seekable_stream=MagickTrue;
entry->adjoin=MagickFalse;
entry->description=ConstantString("Portable Network Graphics");
entry->mime_type=ConstantString("image/png");
entry->module=ConstantString("PNG");
if (*version != '\0')
entry->version=ConstantString(version);
entry->note=ConstantString(PNGNote);
(void) RegisterMagickInfo(entry);
entry=SetMagickInfo("PNG8");
#if defined(MAGICKCORE_PNG_DELEGATE)
entry->decoder=(DecodeImageHandler *) ReadPNGImage;
entry->encoder=(EncodeImageHandler *) WritePNGImage;
#endif
entry->magick=(IsImageFormatHandler *) IsPNG;
entry->seekable_stream=MagickTrue;
entry->adjoin=MagickFalse;
entry->description=ConstantString(
"8-bit indexed with optional binary transparency");
entry->mime_type=ConstantString("image/png");
entry->module=ConstantString("PNG");
(void) RegisterMagickInfo(entry);
entry=SetMagickInfo("PNG24");
*version='\0';
#if defined(ZLIB_VERSION)
(void) ConcatenateMagickString(version,"zlib ",MaxTextExtent);
(void) ConcatenateMagickString(version,ZLIB_VERSION,MaxTextExtent);
if (LocaleCompare(ZLIB_VERSION,zlib_version) != 0)
{
(void) ConcatenateMagickString(version,",",MaxTextExtent);
(void) ConcatenateMagickString(version,zlib_version,MaxTextExtent);
}
#endif
if (*version != '\0')
entry->version=ConstantString(version);
#if defined(MAGICKCORE_PNG_DELEGATE)
entry->decoder=(DecodeImageHandler *) ReadPNGImage;
entry->encoder=(EncodeImageHandler *) WritePNGImage;
#endif
entry->magick=(IsImageFormatHandler *) IsPNG;
entry->seekable_stream=MagickTrue;
entry->adjoin=MagickFalse;
entry->description=ConstantString("opaque or binary transparent 24-bit RGB");
entry->mime_type=ConstantString("image/png");
entry->module=ConstantString("PNG");
(void) RegisterMagickInfo(entry);
entry=SetMagickInfo("PNG32");
#if defined(MAGICKCORE_PNG_DELEGATE)
entry->decoder=(DecodeImageHandler *) ReadPNGImage;
entry->encoder=(EncodeImageHandler *) WritePNGImage;
#endif
entry->magick=(IsImageFormatHandler *) IsPNG;
entry->seekable_stream=MagickTrue;
entry->adjoin=MagickFalse;
entry->description=ConstantString("opaque or transparent 32-bit RGBA");
entry->mime_type=ConstantString("image/png");
entry->module=ConstantString("PNG");
(void) RegisterMagickInfo(entry);
entry=SetMagickInfo("PNG48");
#if defined(MAGICKCORE_PNG_DELEGATE)
entry->decoder=(DecodeImageHandler *) ReadPNGImage;
entry->encoder=(EncodeImageHandler *) WritePNGImage;
#endif
entry->magick=(IsImageFormatHandler *) IsPNG;
entry->seekable_stream=MagickTrue;
entry->adjoin=MagickFalse;
entry->description=ConstantString("opaque or binary transparent 48-bit RGB");
entry->mime_type=ConstantString("image/png");
entry->module=ConstantString("PNG");
(void) RegisterMagickInfo(entry);
entry=SetMagickInfo("PNG64");
#if defined(MAGICKCORE_PNG_DELEGATE)
entry->decoder=(DecodeImageHandler *) ReadPNGImage;
entry->encoder=(EncodeImageHandler *) WritePNGImage;
#endif
entry->magick=(IsImageFormatHandler *) IsPNG;
entry->seekable_stream=MagickTrue;
entry->adjoin=MagickFalse;
entry->description=ConstantString("opaque or transparent 64-bit RGBA");
entry->mime_type=ConstantString("image/png");
entry->module=ConstantString("PNG");
(void) RegisterMagickInfo(entry);
entry=SetMagickInfo("PNG00");
#if defined(MAGICKCORE_PNG_DELEGATE)
entry->decoder=(DecodeImageHandler *) ReadPNGImage;
entry->encoder=(EncodeImageHandler *) WritePNGImage;
#endif
entry->magick=(IsImageFormatHandler *) IsPNG;
entry->seekable_stream=MagickTrue;
entry->adjoin=MagickFalse;
entry->description=ConstantString(
"PNG inheriting bit-depth, color-type from original if possible");
entry->mime_type=ConstantString("image/png");
entry->module=ConstantString("PNG");
(void) RegisterMagickInfo(entry);
entry=SetMagickInfo("JNG");
#if defined(JNG_SUPPORTED)
#if defined(MAGICKCORE_PNG_DELEGATE)
entry->decoder=(DecodeImageHandler *) ReadJNGImage;
entry->encoder=(EncodeImageHandler *) WriteJNGImage;
#endif
#endif
entry->magick=(IsImageFormatHandler *) IsJNG;
entry->seekable_stream=MagickTrue;
entry->adjoin=MagickFalse;
entry->description=ConstantString("JPEG Network Graphics");
entry->mime_type=ConstantString("image/x-jng");
entry->module=ConstantString("PNG");
entry->note=ConstantString(JNGNote);
(void) RegisterMagickInfo(entry);
#ifdef IMPNG_SETJMP_NOT_THREAD_SAFE
ping_semaphore=AllocateSemaphoreInfo();
#endif
return(MagickImageCoderSignature);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% U n r e g i s t e r P N G I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% UnregisterPNGImage() removes format registrations made by the
% PNG module from the list of supported formats.
%
% The format of the UnregisterPNGImage method is:
%
% UnregisterPNGImage(void)
%
*/
ModuleExport void UnregisterPNGImage(void)
{
(void) UnregisterMagickInfo("MNG");
(void) UnregisterMagickInfo("PNG");
(void) UnregisterMagickInfo("PNG8");
(void) UnregisterMagickInfo("PNG24");
(void) UnregisterMagickInfo("PNG32");
(void) UnregisterMagickInfo("PNG48");
(void) UnregisterMagickInfo("PNG64");
(void) UnregisterMagickInfo("PNG00");
(void) UnregisterMagickInfo("JNG");
#ifdef IMPNG_SETJMP_NOT_THREAD_SAFE
if (ping_semaphore != (SemaphoreInfo *) NULL)
DestroySemaphoreInfo(&ping_semaphore);
#endif
}
#if defined(MAGICKCORE_PNG_DELEGATE)
#if PNG_LIBPNG_VER > 10011
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% W r i t e M N G I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% WriteMNGImage() writes an image in the Portable Network Graphics
% Group's "Multiple-image Network Graphics" encoded image format.
%
% MNG support written by Glenn Randers-Pehrson, glennrp@image...
%
% The format of the WriteMNGImage method is:
%
% MagickBooleanType WriteMNGImage(const ImageInfo *image_info,Image *image)
%
% A description of each parameter follows.
%
% o image_info: the image info.
%
% o image: The image.
%
%
% To do (as of version 5.5.2, November 26, 2002 -- glennrp -- see also
% "To do" under ReadPNGImage):
%
% Preserve all unknown and not-yet-handled known chunks found in input
% PNG file and copy them into output PNG files according to the PNG
% copying rules.
%
% Write the iCCP chunk at MNG level when (icc profile length > 0)
%
% Improve selection of color type (use indexed-colour or indexed-colour
% with tRNS when 256 or fewer unique RGBA values are present).
%
% Figure out what to do with "dispose=<restore-to-previous>" (dispose == 3)
% This will be complicated if we limit ourselves to generating MNG-LC
% files. For now we ignore disposal method 3 and simply overlay the next
% image on it.
%
% Check for identical PLTE's or PLTE/tRNS combinations and use a
% global MNG PLTE or PLTE/tRNS combination when appropriate.
% [mostly done 15 June 1999 but still need to take care of tRNS]
%
% Check for identical sRGB and replace with a global sRGB (and remove
% gAMA/cHRM if sRGB is found; check for identical gAMA/cHRM and
% replace with global gAMA/cHRM (or with sRGB if appropriate; replace
% local gAMA/cHRM with local sRGB if appropriate).
%
% Check for identical sBIT chunks and write global ones.
%
% Provide option to skip writing the signature tEXt chunks.
%
% Use signatures to detect identical objects and reuse the first
% instance of such objects instead of writing duplicate objects.
%
% Use a smaller-than-32k value of compression window size when
% appropriate.
%
% Encode JNG datastreams. Mostly done as of 5.5.2; need to write
% ancillary text chunks and save profiles.
%
% Provide an option to force LC files (to ensure exact framing rate)
% instead of VLC.
%
% Provide an option to force VLC files instead of LC, even when offsets
% are present. This will involve expanding the embedded images with a
% transparent region at the top and/or left.
*/
static void
Magick_png_write_raw_profile(const ImageInfo *image_info,png_struct *ping,
png_info *ping_info, unsigned char *profile_type, unsigned char
*profile_description, unsigned char *profile_data, png_uint_32 length)
{
png_textp
text;
register ssize_t
i;
unsigned char
*sp;
png_charp
dp;
png_uint_32
allocated_length,
description_length;
unsigned char
hex[16]={'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};
if (LocaleNCompare((char *) profile_type+1, "ng-chunk-",9) == 0)
return;
if (image_info->verbose)
{
(void) printf("writing raw profile: type=%s, length=%.20g\n",
(char *) profile_type, (double) length);
}
#if PNG_LIBPNG_VER >= 10400
text=(png_textp) png_malloc(ping,(png_alloc_size_t) sizeof(png_text));
#else
text=(png_textp) png_malloc(ping,(png_size_t) sizeof(png_text));
#endif
description_length=(png_uint_32) strlen((const char *) profile_description);
allocated_length=(png_uint_32) (length*2 + (length >> 5) + 20
+ description_length);
#if PNG_LIBPNG_VER >= 10400
text[0].text=(png_charp) png_malloc(ping,
(png_alloc_size_t) allocated_length);
text[0].key=(png_charp) png_malloc(ping, (png_alloc_size_t) 80);
#else
text[0].text=(png_charp) png_malloc(ping, (png_size_t) allocated_length);
text[0].key=(png_charp) png_malloc(ping, (png_size_t) 80);
#endif
text[0].key[0]='\0';
(void) ConcatenateMagickString(text[0].key,
"Raw profile type ",MaxTextExtent);
(void) ConcatenateMagickString(text[0].key,(const char *) profile_type,62);
sp=profile_data;
dp=text[0].text;
*dp++='\n';
(void) CopyMagickString(dp,(const char *) profile_description,
allocated_length);
dp+=description_length;
*dp++='\n';
(void) FormatLocaleString(dp,allocated_length-
(png_size_t) (dp-text[0].text),"%8lu ",(unsigned long) length);
dp+=8;
for (i=0; i < (ssize_t) length; i++)
{
if (i%36 == 0)
*dp++='\n';
*(dp++)=(char) hex[((*sp >> 4) & 0x0f)];
*(dp++)=(char) hex[((*sp++ ) & 0x0f)];
}
*dp++='\n';
*dp='\0';
text[0].text_length=(png_size_t) (dp-text[0].text);
text[0].compression=image_info->compression == NoCompression ||
(image_info->compression == UndefinedCompression &&
text[0].text_length < 128) ? -1 : 0;
if (text[0].text_length <= allocated_length)
png_set_text(ping,ping_info,text,1);
png_free(ping,text[0].text);
png_free(ping,text[0].key);
png_free(ping,text);
}
static MagickBooleanType Magick_png_write_chunk_from_profile(Image *image,
const char *string, MagickBooleanType logging)
{
char
*name;
const StringInfo
*profile;
unsigned char
*data;
png_uint_32 length;
ResetImageProfileIterator(image);
for (name=GetNextImageProfile(image); name != (const char *) NULL; )
{
profile=GetImageProfile(image,name);
if (profile != (const StringInfo *) NULL)
{
StringInfo
*ping_profile;
if (LocaleNCompare(name,string,11) == 0)
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Found %s profile",name);
ping_profile=CloneStringInfo(profile);
data=GetStringInfoDatum(ping_profile),
length=(png_uint_32) GetStringInfoLength(ping_profile);
data[4]=data[3];
data[3]=data[2];
data[2]=data[1];
data[1]=data[0];
(void) WriteBlobMSBULong(image,length-5); /* data length */
(void) WriteBlob(image,length-1,data+1);
(void) WriteBlobMSBULong(image,crc32(0,data+1,(uInt) length-1));
ping_profile=DestroyStringInfo(ping_profile);
}
}
name=GetNextImageProfile(image);
}
return(MagickTrue);
}
#if defined(PNG_tIME_SUPPORTED)
static void write_tIME_chunk(Image *image,png_struct *ping,png_info *info,
const char *date)
{
unsigned int
day,
hour,
minute,
month,
second,
year;
png_time
ptime;
time_t
ttime;
if (date != (const char *) NULL)
{
if (sscanf(date,"%d-%d-%dT%d:%d:%dZ",&year,&month,&day,&hour,&minute,
&second) != 6)
{
(void) ThrowMagickException(&image->exception,GetMagickModule(),
CoderError,
"Invalid date format specified for png:tIME","`%s'",
image->filename);
return;
}
ptime.year=(png_uint_16) year;
ptime.month=(png_byte) month;
ptime.day=(png_byte) day;
ptime.hour=(png_byte) hour;
ptime.minute=(png_byte) minute;
ptime.second=(png_byte) second;
}
else
{
time(&ttime);
png_convert_from_time_t(&ptime,ttime);
}
png_set_tIME(ping,info,&ptime);
}
#endif
/* Write one PNG image */
static MagickBooleanType WriteOnePNGImage(MngInfo *mng_info,
const ImageInfo *image_info,Image *image)
{
char
s[2];
char
im_vers[32],
libpng_runv[32],
libpng_vers[32],
zlib_runv[32],
zlib_vers[32];
const char
*name,
*property,
*value;
const StringInfo
*profile;
int
num_passes,
pass,
ping_wrote_caNv;
png_byte
ping_trans_alpha[256];
png_color
palette[257];
png_color_16
ping_background,
ping_trans_color;
png_info
*ping_info;
png_struct
*ping;
png_uint_32
ping_height,
ping_width;
ssize_t
y;
MagickBooleanType
image_matte,
logging,
matte,
ping_have_blob,
ping_have_cheap_transparency,
ping_have_color,
ping_have_non_bw,
ping_have_PLTE,
ping_have_bKGD,
ping_have_eXIf,
ping_have_iCCP,
ping_have_pHYs,
ping_have_sRGB,
ping_have_tRNS,
ping_exclude_bKGD,
ping_exclude_cHRM,
ping_exclude_date,
/* ping_exclude_EXIF, */
ping_exclude_eXIf,
ping_exclude_gAMA,
ping_exclude_iCCP,
/* ping_exclude_iTXt, */
ping_exclude_oFFs,
ping_exclude_pHYs,
ping_exclude_sRGB,
ping_exclude_tEXt,
ping_exclude_tIME,
/* ping_exclude_tRNS, */
ping_exclude_vpAg,
ping_exclude_caNv,
ping_exclude_zCCP, /* hex-encoded iCCP */
ping_exclude_zTXt,
ping_preserve_colormap,
ping_preserve_iCCP,
ping_need_colortype_warning,
status,
tried_332,
tried_333,
tried_444;
MemoryInfo
*volatile pixel_info;
QuantumInfo
*quantum_info;
register ssize_t
i,
x;
unsigned char
*ping_pixels;
volatile int
image_colors,
ping_bit_depth,
ping_color_type,
ping_interlace_method,
ping_compression_method,
ping_filter_method,
ping_num_trans;
volatile size_t
image_depth,
old_bit_depth;
size_t
quality,
rowbytes,
save_image_depth;
int
j,
number_colors,
number_opaque,
number_semitransparent,
number_transparent,
ping_pHYs_unit_type;
png_uint_32
ping_pHYs_x_resolution,
ping_pHYs_y_resolution;
logging=LogMagickEvent(CoderEvent,GetMagickModule(),
" Enter WriteOnePNGImage()");
/* Define these outside of the following "if logging()" block so they will
* show in debuggers.
*/
*im_vers='\0';
(void) ConcatenateMagickString(im_vers,
MagickLibVersionText,MaxTextExtent);
(void) ConcatenateMagickString(im_vers,
MagickLibAddendum,MaxTextExtent);
*libpng_vers='\0';
(void) ConcatenateMagickString(libpng_vers,
PNG_LIBPNG_VER_STRING,32);
*libpng_runv='\0';
(void) ConcatenateMagickString(libpng_runv,
png_get_libpng_ver(NULL),32);
*zlib_vers='\0';
(void) ConcatenateMagickString(zlib_vers,
ZLIB_VERSION,32);
*zlib_runv='\0';
(void) ConcatenateMagickString(zlib_runv,
zlib_version,32);
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule()," IM version = %s",
im_vers);
(void) LogMagickEvent(CoderEvent,GetMagickModule()," Libpng version = %s",
libpng_vers);
if (LocaleCompare(libpng_vers,libpng_runv) != 0)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule()," running with %s",
libpng_runv);
}
(void) LogMagickEvent(CoderEvent,GetMagickModule()," Zlib version = %s",
zlib_vers);
if (LocaleCompare(zlib_vers,zlib_runv) != 0)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule()," running with %s",
zlib_runv);
}
}
/* Initialize some stuff */
ping_bit_depth=0,
ping_color_type=0,
ping_interlace_method=0,
ping_compression_method=0,
ping_filter_method=0,
ping_num_trans = 0;
ping_background.red = 0;
ping_background.green = 0;
ping_background.blue = 0;
ping_background.gray = 0;
ping_background.index = 0;
ping_trans_color.red=0;
ping_trans_color.green=0;
ping_trans_color.blue=0;
ping_trans_color.gray=0;
ping_pHYs_unit_type = 0;
ping_pHYs_x_resolution = 0;
ping_pHYs_y_resolution = 0;
ping_have_blob=MagickFalse;
ping_have_cheap_transparency=MagickFalse;
ping_have_color=MagickTrue;
ping_have_non_bw=MagickTrue;
ping_have_PLTE=MagickFalse;
ping_have_bKGD=MagickFalse;
ping_have_eXIf=MagickTrue;
ping_have_iCCP=MagickFalse;
ping_have_pHYs=MagickFalse;
ping_have_sRGB=MagickFalse;
ping_have_tRNS=MagickFalse;
ping_exclude_bKGD=mng_info->ping_exclude_bKGD;
ping_exclude_caNv=mng_info->ping_exclude_caNv;
ping_exclude_cHRM=mng_info->ping_exclude_cHRM;
ping_exclude_date=mng_info->ping_exclude_date;
/* ping_exclude_EXIF=mng_info->ping_exclude_EXIF; */
ping_exclude_eXIf=mng_info->ping_exclude_eXIf;
ping_exclude_gAMA=mng_info->ping_exclude_gAMA;
ping_exclude_iCCP=mng_info->ping_exclude_iCCP;
/* ping_exclude_iTXt=mng_info->ping_exclude_iTXt; */
ping_exclude_oFFs=mng_info->ping_exclude_oFFs;
ping_exclude_pHYs=mng_info->ping_exclude_pHYs;
ping_exclude_sRGB=mng_info->ping_exclude_sRGB;
ping_exclude_tEXt=mng_info->ping_exclude_tEXt;
ping_exclude_tIME=mng_info->ping_exclude_tIME;
/* ping_exclude_tRNS=mng_info->ping_exclude_tRNS; */
ping_exclude_vpAg=mng_info->ping_exclude_vpAg;
ping_exclude_zCCP=mng_info->ping_exclude_zCCP; /* hex-encoded iCCP in zTXt */
ping_exclude_zTXt=mng_info->ping_exclude_zTXt;
ping_preserve_colormap = mng_info->ping_preserve_colormap;
ping_preserve_iCCP = mng_info->ping_preserve_iCCP;
ping_need_colortype_warning = MagickFalse;
property=(const char *) NULL;
/* Recognize the ICC sRGB profile and convert it to the sRGB chunk,
* i.e., eliminate the ICC profile and set image->rendering_intent.
* Note that this will not involve any changes to the actual pixels
* but merely passes information to applications that read the resulting
* PNG image.
*
* To do: recognize other variants of the sRGB profile, using the CRC to
* verify all recognized variants including the 7 already known.
*
* Work around libpng16+ rejecting some "known invalid sRGB profiles".
*
* Use something other than image->rendering_intent to record the fact
* that the sRGB profile was found.
*
* Record the ICC version (currently v2 or v4) of the incoming sRGB ICC
* profile. Record the Blackpoint Compensation, if any.
*/
if (ping_exclude_sRGB == MagickFalse && ping_preserve_iCCP == MagickFalse)
{
char
*name;
const StringInfo
*profile;
ResetImageProfileIterator(image);
for (name=GetNextImageProfile(image); name != (const char *) NULL; )
{
profile=GetImageProfile(image,name);
if (profile != (StringInfo *) NULL)
{
if ((LocaleCompare(name,"ICC") == 0) ||
(LocaleCompare(name,"ICM") == 0))
{
int
icheck,
got_crc=0;
png_uint_32
length,
profile_crc=0;
unsigned char
*data;
length=(png_uint_32) GetStringInfoLength(profile);
for (icheck=0; sRGB_info[icheck].len > 0; icheck++)
{
if (length == sRGB_info[icheck].len)
{
if (got_crc == 0)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Got a %lu-byte ICC profile (potentially sRGB)",
(unsigned long) length);
data=GetStringInfoDatum(profile);
profile_crc=crc32(0,data,length);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" with crc=%8x",(unsigned int) profile_crc);
got_crc++;
}
if (profile_crc == sRGB_info[icheck].crc)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" It is sRGB with rendering intent = %s",
Magick_RenderingIntentString_from_PNG_RenderingIntent(
sRGB_info[icheck].intent));
if (image->rendering_intent==UndefinedIntent)
{
image->rendering_intent=
Magick_RenderingIntent_from_PNG_RenderingIntent(
sRGB_info[icheck].intent);
}
ping_exclude_iCCP = MagickTrue;
ping_exclude_zCCP = MagickTrue;
ping_have_sRGB = MagickTrue;
break;
}
}
}
if (sRGB_info[icheck].len == 0)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Got a %lu-byte ICC profile not recognized as sRGB",
(unsigned long) length);
}
}
name=GetNextImageProfile(image);
}
}
number_opaque = 0;
number_semitransparent = 0;
number_transparent = 0;
if (logging != MagickFalse)
{
if (image->storage_class == UndefinedClass)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image->storage_class=UndefinedClass");
if (image->storage_class == DirectClass)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image->storage_class=DirectClass");
if (image->storage_class == PseudoClass)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image->storage_class=PseudoClass");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image_info->magick= %s",image_info->magick);
(void) LogMagickEvent(CoderEvent,GetMagickModule(), image->taint ?
" image->taint=MagickTrue":
" image->taint=MagickFalse");
}
if (image->storage_class == PseudoClass &&
(mng_info->write_png8 || mng_info->write_png24 || mng_info->write_png32 ||
mng_info->write_png48 || mng_info->write_png64 ||
(mng_info->write_png_colortype != 1 &&
mng_info->write_png_colortype != 5)))
{
(void) SyncImage(image);
image->storage_class = DirectClass;
}
if (ping_preserve_colormap == MagickFalse)
{
if (image->storage_class != PseudoClass && image->colormap != NULL)
{
/* Free the bogus colormap; it can cause trouble later */
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Freeing bogus colormap");
(void) RelinquishMagickMemory(image->colormap);
image->colormap=NULL;
}
}
if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse)
(void) TransformImageColorspace(image,sRGBColorspace);
/*
Sometimes we get PseudoClass images whose RGB values don't match
the colors in the colormap. This code syncs the RGB values.
*/
if (image->depth <= 8 && image->taint && image->storage_class == PseudoClass)
(void) SyncImage(image);
#if (MAGICKCORE_QUANTUM_DEPTH == 8)
if (image->depth > 8)
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Reducing PNG bit depth to 8 since this is a Q8 build.");
image->depth=8;
}
#endif
/* Respect the -depth option */
if (image->depth < 4)
{
register PixelPacket
*r;
ExceptionInfo
*exception;
exception=(&image->exception);
if (image->depth > 2)
{
/* Scale to 4-bit */
LBR04PacketRGBO(image->background_color);
for (y=0; y < (ssize_t) image->rows; y++)
{
r=GetAuthenticPixels(image,0,y,image->columns,1,
exception);
if (r == (PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
LBR04PixelRGBO(r);
r++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
if (image->storage_class == PseudoClass && image->colormap != NULL)
{
for (i=0; i < (ssize_t) image->colors; i++)
{
LBR04PacketRGBO(image->colormap[i]);
}
}
}
else if (image->depth > 1)
{
/* Scale to 2-bit */
LBR02PacketRGBO(image->background_color);
for (y=0; y < (ssize_t) image->rows; y++)
{
r=GetAuthenticPixels(image,0,y,image->columns,1,
exception);
if (r == (PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
LBR02PixelRGBO(r);
r++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
if (image->storage_class == PseudoClass && image->colormap != NULL)
{
for (i=0; i < (ssize_t) image->colors; i++)
{
LBR02PacketRGBO(image->colormap[i]);
}
}
}
else
{
/* Scale to 1-bit */
LBR01PacketRGBO(image->background_color);
for (y=0; y < (ssize_t) image->rows; y++)
{
r=GetAuthenticPixels(image,0,y,image->columns,1,
exception);
if (r == (PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
LBR01PixelRGBO(r);
r++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
if (image->storage_class == PseudoClass && image->colormap != NULL)
{
for (i=0; i < (ssize_t) image->colors; i++)
{
LBR01PacketRGBO(image->colormap[i]);
}
}
}
}
/* To do: set to next higher multiple of 8 */
if (image->depth < 8)
image->depth=8;
#if (MAGICKCORE_QUANTUM_DEPTH > 16)
/* PNG does not handle depths greater than 16 so reduce it even
* if lossy
*/
if (image->depth > 8)
image->depth=16;
#endif
#if (MAGICKCORE_QUANTUM_DEPTH > 8)
if (image->depth > 8)
{
/* To do: fill low byte properly */
image->depth=16;
}
if (image->depth == 16 && mng_info->write_png_depth != 16)
if (mng_info->write_png8 || LosslessReduceDepthOK(image) != MagickFalse)
image->depth = 8;
#endif
image_colors = (int) image->colors;
if (mng_info->write_png_colortype &&
(mng_info->write_png_colortype > 4 || (mng_info->write_png_depth >= 8 &&
mng_info->write_png_colortype < 4 && image->matte == MagickFalse)))
{
/* Avoid the expensive BUILD_PALETTE operation if we're sure that we
* are not going to need the result.
*/
number_opaque = (int) image->colors;
if (mng_info->write_png_colortype == 1 ||
mng_info->write_png_colortype == 5)
ping_have_color=MagickFalse;
else
ping_have_color=MagickTrue;
ping_have_non_bw=MagickFalse;
if (image->matte != MagickFalse)
{
number_transparent = 2;
number_semitransparent = 1;
}
else
{
number_transparent = 0;
number_semitransparent = 0;
}
}
if (mng_info->write_png_colortype < 7)
{
/* BUILD_PALETTE
*
* Normally we run this just once, but in the case of writing PNG8
* we reduce the transparency to binary and run again, then if there
* are still too many colors we reduce to a simple 4-4-4-1, then 3-3-3-1
* RGBA palette and run again, and then to a simple 3-3-2-1 RGBA
* palette. Then (To do) we take care of a final reduction that is only
* needed if there are still 256 colors present and one of them has both
* transparent and opaque instances.
*/
tried_332 = MagickFalse;
tried_333 = MagickFalse;
tried_444 = MagickFalse;
for (j=0; j<6; j++)
{
/*
* Sometimes we get DirectClass images that have 256 colors or fewer.
* This code will build a colormap.
*
* Also, sometimes we get PseudoClass images with an out-of-date
* colormap. This code will replace the colormap with a new one.
* Sometimes we get PseudoClass images that have more than 256 colors.
* This code will delete the colormap and change the image to
* DirectClass.
*
* If image->matte is MagickFalse, we ignore the opacity channel
* even though it sometimes contains left-over non-opaque values.
*
* Also we gather some information (number of opaque, transparent,
* and semitransparent pixels, and whether the image has any non-gray
* pixels or only black-and-white pixels) that we might need later.
*
* Even if the user wants to force GrayAlpha or RGBA (colortype 4 or 6)
* we need to check for bogus non-opaque values, at least.
*/
ExceptionInfo
*exception;
int
n;
PixelPacket
opaque[260],
semitransparent[260],
transparent[260];
register IndexPacket
*indexes;
register const PixelPacket
*s,
*q;
register PixelPacket
*r;
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Enter BUILD_PALETTE:");
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image->columns=%.20g",(double) image->columns);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image->rows=%.20g",(double) image->rows);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image->matte=%.20g",(double) image->matte);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image->depth=%.20g",(double) image->depth);
if (image->storage_class == PseudoClass && image->colormap != NULL)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Original colormap:");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" i (red,green,blue,opacity)");
for (i=0; i < 256; i++)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" %d (%d,%d,%d,%d)",
(int) i,
(int) image->colormap[i].red,
(int) image->colormap[i].green,
(int) image->colormap[i].blue,
(int) image->colormap[i].opacity);
}
for (i=image->colors - 10; i < (ssize_t) image->colors; i++)
{
if (i > 255)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" %d (%d,%d,%d,%d)",
(int) i,
(int) image->colormap[i].red,
(int) image->colormap[i].green,
(int) image->colormap[i].blue,
(int) image->colormap[i].opacity);
}
}
}
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image->colors=%d",(int) image->colors);
if (image->colors == 0)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" (zero means unknown)");
if (ping_preserve_colormap == MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Regenerate the colormap");
}
exception=(&image->exception);
image_colors=0;
number_opaque = 0;
number_semitransparent = 0;
number_transparent = 0;
for (y=0; y < (ssize_t) image->rows; y++)
{
q=GetAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (image->matte == MagickFalse ||
GetPixelOpacity(q) == OpaqueOpacity)
{
if (number_opaque < 259)
{
if (number_opaque == 0)
{
GetPixelRGB(q, opaque);
opaque[0].opacity=OpaqueOpacity;
number_opaque=1;
}
for (i=0; i< (ssize_t) number_opaque; i++)
{
if (IsColorEqual(q, opaque+i))
break;
}
if (i == (ssize_t) number_opaque &&
number_opaque < 259)
{
number_opaque++;
GetPixelRGB(q, opaque+i);
opaque[i].opacity=OpaqueOpacity;
}
}
}
else if (q->opacity == TransparentOpacity)
{
if (number_transparent < 259)
{
if (number_transparent == 0)
{
GetPixelRGBO(q, transparent);
ping_trans_color.red=
(unsigned short) GetPixelRed(q);
ping_trans_color.green=
(unsigned short) GetPixelGreen(q);
ping_trans_color.blue=
(unsigned short) GetPixelBlue(q);
ping_trans_color.gray=
(unsigned short) GetPixelRed(q);
number_transparent = 1;
}
for (i=0; i< (ssize_t) number_transparent; i++)
{
if (IsColorEqual(q, transparent+i))
break;
}
if (i == (ssize_t) number_transparent &&
number_transparent < 259)
{
number_transparent++;
GetPixelRGBO(q, transparent+i);
}
}
}
else
{
if (number_semitransparent < 259)
{
if (number_semitransparent == 0)
{
GetPixelRGBO(q, semitransparent);
number_semitransparent = 1;
}
for (i=0; i< (ssize_t) number_semitransparent; i++)
{
if (IsColorEqual(q, semitransparent+i)
&& GetPixelOpacity(q) ==
semitransparent[i].opacity)
break;
}
if (i == (ssize_t) number_semitransparent &&
number_semitransparent < 259)
{
number_semitransparent++;
GetPixelRGBO(q, semitransparent+i);
}
}
}
q++;
}
}
if (mng_info->write_png8 == MagickFalse &&
ping_exclude_bKGD == MagickFalse)
{
/* Add the background color to the palette, if it
* isn't already there.
*/
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Check colormap for background (%d,%d,%d)",
(int) image->background_color.red,
(int) image->background_color.green,
(int) image->background_color.blue);
}
for (i=0; i<number_opaque; i++)
{
if (opaque[i].red == image->background_color.red &&
opaque[i].green == image->background_color.green &&
opaque[i].blue == image->background_color.blue)
break;
}
if (number_opaque < 259 && i == number_opaque)
{
opaque[i] = image->background_color;
ping_background.index = i;
number_opaque++;
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" background_color index is %d",(int) i);
}
}
else if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" No room in the colormap to add background color");
}
image_colors=number_opaque+number_transparent+number_semitransparent;
if (logging != MagickFalse)
{
if (image_colors > 256)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image has more than 256 colors");
else
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image has %d colors",image_colors);
}
if (ping_preserve_colormap != MagickFalse)
break;
if (mng_info->write_png_colortype != 7) /* We won't need this info */
{
ping_have_color=MagickFalse;
ping_have_non_bw=MagickFalse;
if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"incompatible colorspace");
ping_have_color=MagickTrue;
ping_have_non_bw=MagickTrue;
}
if(image_colors > 256)
{
for (y=0; y < (ssize_t) image->rows; y++)
{
q=GetAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
s=q;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (GetPixelRed(s) != GetPixelGreen(s) ||
GetPixelRed(s) != GetPixelBlue(s))
{
ping_have_color=MagickTrue;
ping_have_non_bw=MagickTrue;
break;
}
s++;
}
if (ping_have_color != MagickFalse)
break;
/* Worst case is black-and-white; we are looking at every
* pixel twice.
*/
if (ping_have_non_bw == MagickFalse)
{
s=q;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (GetPixelRed(s) != 0 &&
GetPixelRed(s) != QuantumRange)
{
ping_have_non_bw=MagickTrue;
break;
}
s++;
}
}
}
}
}
if (image_colors < 257)
{
PixelPacket
colormap[260];
/*
* Initialize image colormap.
*/
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Sort the new colormap");
/* Sort palette, transparent first */;
n = 0;
for (i=0; i<number_transparent; i++)
colormap[n++] = transparent[i];
for (i=0; i<number_semitransparent; i++)
colormap[n++] = semitransparent[i];
for (i=0; i<number_opaque; i++)
colormap[n++] = opaque[i];
ping_background.index +=
(number_transparent + number_semitransparent);
/* image_colors < 257; search the colormap instead of the pixels
* to get ping_have_color and ping_have_non_bw
*/
for (i=0; i<n; i++)
{
if (ping_have_color == MagickFalse)
{
if (colormap[i].red != colormap[i].green ||
colormap[i].red != colormap[i].blue)
{
ping_have_color=MagickTrue;
ping_have_non_bw=MagickTrue;
break;
}
}
if (ping_have_non_bw == MagickFalse)
{
if (colormap[i].red != 0 && colormap[i].red != QuantumRange)
ping_have_non_bw=MagickTrue;
}
}
if ((mng_info->ping_exclude_tRNS == MagickFalse ||
(number_transparent == 0 && number_semitransparent == 0)) &&
(((mng_info->write_png_colortype-1) ==
PNG_COLOR_TYPE_PALETTE) ||
(mng_info->write_png_colortype == 0)))
{
if (logging != MagickFalse)
{
if (n != (ssize_t) image_colors)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image_colors (%d) and n (%d) don't match",
image_colors, n);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" AcquireImageColormap");
}
image->colors = image_colors;
if (AcquireImageColormap(image,image_colors) ==
MagickFalse)
ThrowWriterException(ResourceLimitError,
"MemoryAllocationFailed");
for (i=0; i< (ssize_t) image_colors; i++)
image->colormap[i] = colormap[i];
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image->colors=%d (%d)",
(int) image->colors, image_colors);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Update the pixel indexes");
}
/* Sync the pixel indices with the new colormap */
for (y=0; y < (ssize_t) image->rows; y++)
{
q=GetAuthenticPixels(image,0,y,image->columns,1,
exception);
if (q == (PixelPacket *) NULL)
break;
indexes=GetAuthenticIndexQueue(image);
for (x=0; x < (ssize_t) image->columns; x++)
{
for (i=0; i< (ssize_t) image_colors; i++)
{
if ((image->matte == MagickFalse ||
image->colormap[i].opacity ==
GetPixelOpacity(q)) &&
image->colormap[i].red ==
GetPixelRed(q) &&
image->colormap[i].green ==
GetPixelGreen(q) &&
image->colormap[i].blue ==
GetPixelBlue(q))
{
SetPixelIndex(indexes+x,i);
break;
}
}
q++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
}
}
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image->colors=%d", (int) image->colors);
if (image->colormap != NULL)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" i (red,green,blue,opacity)");
for (i=0; i < (ssize_t) image->colors; i++)
{
if (i < 300 || i >= (ssize_t) image->colors - 10)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" %d (%d,%d,%d,%d)",
(int) i,
(int) image->colormap[i].red,
(int) image->colormap[i].green,
(int) image->colormap[i].blue,
(int) image->colormap[i].opacity);
}
}
}
if (number_transparent < 257)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" number_transparent = %d",
number_transparent);
else
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" number_transparent > 256");
if (number_opaque < 257)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" number_opaque = %d",
number_opaque);
else
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" number_opaque > 256");
if (number_semitransparent < 257)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" number_semitransparent = %d",
number_semitransparent);
else
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" number_semitransparent > 256");
if (ping_have_non_bw == MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" All pixels and the background are black or white");
else if (ping_have_color == MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" All pixels and the background are gray");
else
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" At least one pixel or the background is non-gray");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Exit BUILD_PALETTE:");
}
if (mng_info->write_png8 == MagickFalse)
break;
/* Make any reductions necessary for the PNG8 format */
if (image_colors <= 256 &&
image_colors != 0 && image->colormap != NULL &&
number_semitransparent == 0 &&
number_transparent <= 1)
break;
/* PNG8 can't have semitransparent colors so we threshold the
* opacity to 0 or OpaqueOpacity, and PNG8 can only have one
* transparent color so if more than one is transparent we merge
* them into image->background_color.
*/
if (number_semitransparent != 0 || number_transparent > 1)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Thresholding the alpha channel to binary");
for (y=0; y < (ssize_t) image->rows; y++)
{
r=GetAuthenticPixels(image,0,y,image->columns,1,
exception);
if (r == (PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (GetPixelOpacity(r) > TransparentOpacity/2)
{
SetPixelOpacity(r,TransparentOpacity);
SetPixelRgb(r,&image->background_color);
}
else
SetPixelOpacity(r,OpaqueOpacity);
r++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image_colors != 0 && image_colors <= 256 &&
image->colormap != NULL)
for (i=0; i<image_colors; i++)
image->colormap[i].opacity =
(image->colormap[i].opacity > TransparentOpacity/2 ?
TransparentOpacity : OpaqueOpacity);
}
continue;
}
/* PNG8 can't have more than 256 colors so we quantize the pixels and
* background color to the 4-4-4-1, 3-3-3-1 or 3-3-2-1 palette. If the
* image is mostly gray, the 4-4-4-1 palette is likely to end up with 256
* colors or less.
*/
if (tried_444 == MagickFalse && (image_colors == 0 || image_colors > 256))
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Quantizing the background color to 4-4-4");
tried_444 = MagickTrue;
LBR04PacketRGB(image->background_color);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Quantizing the pixel colors to 4-4-4");
if (image->colormap == NULL)
{
for (y=0; y < (ssize_t) image->rows; y++)
{
r=GetAuthenticPixels(image,0,y,image->columns,1,
exception);
if (r == (PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (GetPixelOpacity(r) == OpaqueOpacity)
LBR04PixelRGB(r);
r++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
}
else /* Should not reach this; colormap already exists and
must be <= 256 */
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Quantizing the colormap to 4-4-4");
for (i=0; i<image_colors; i++)
{
LBR04PacketRGB(image->colormap[i]);
}
}
continue;
}
if (tried_333 == MagickFalse && (image_colors == 0 || image_colors > 256))
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Quantizing the background color to 3-3-3");
tried_333 = MagickTrue;
LBR03PacketRGB(image->background_color);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Quantizing the pixel colors to 3-3-3-1");
if (image->colormap == NULL)
{
for (y=0; y < (ssize_t) image->rows; y++)
{
r=GetAuthenticPixels(image,0,y,image->columns,1,
exception);
if (r == (PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (GetPixelOpacity(r) == OpaqueOpacity)
LBR03PixelRGB(r);
r++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
}
else /* Should not reach this; colormap already exists and
must be <= 256 */
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Quantizing the colormap to 3-3-3-1");
for (i=0; i<image_colors; i++)
{
LBR03PacketRGB(image->colormap[i]);
}
}
continue;
}
if (tried_332 == MagickFalse && (image_colors == 0 || image_colors > 256))
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Quantizing the background color to 3-3-2");
tried_332 = MagickTrue;
/* Red and green were already done so we only quantize the blue
* channel
*/
LBR02PacketBlue(image->background_color);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Quantizing the pixel colors to 3-3-2-1");
if (image->colormap == NULL)
{
for (y=0; y < (ssize_t) image->rows; y++)
{
r=GetAuthenticPixels(image,0,y,image->columns,1,
exception);
if (r == (PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (GetPixelOpacity(r) == OpaqueOpacity)
LBR02PixelBlue(r);
r++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
}
else /* Should not reach this; colormap already exists and
must be <= 256 */
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Quantizing the colormap to 3-3-2-1");
for (i=0; i<image_colors; i++)
{
LBR02PacketBlue(image->colormap[i]);
}
}
continue;
}
if (image_colors == 0 || image_colors > 256)
{
/* Take care of special case with 256 opaque colors + 1 transparent
* color. We don't need to quantize to 2-3-2-1; we only need to
* eliminate one color, so we'll merge the two darkest red
* colors (0x49, 0, 0) -> (0x24, 0, 0).
*/
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Merging two dark red background colors to 3-3-2-1");
if (ScaleQuantumToChar(image->background_color.red) == 0x49 &&
ScaleQuantumToChar(image->background_color.green) == 0x00 &&
ScaleQuantumToChar(image->background_color.blue) == 0x00)
{
image->background_color.red=ScaleCharToQuantum(0x24);
}
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Merging two dark red pixel colors to 3-3-2-1");
if (image->colormap == NULL)
{
for (y=0; y < (ssize_t) image->rows; y++)
{
r=GetAuthenticPixels(image,0,y,image->columns,1,
exception);
if (r == (PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (ScaleQuantumToChar(GetPixelRed(r)) == 0x49 &&
ScaleQuantumToChar(GetPixelGreen(r)) == 0x00 &&
ScaleQuantumToChar(GetPixelBlue(r)) == 0x00 &&
GetPixelOpacity(r) == OpaqueOpacity)
{
SetPixelRed(r,ScaleCharToQuantum(0x24));
}
r++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
}
else
{
for (i=0; i<image_colors; i++)
{
if (ScaleQuantumToChar(image->colormap[i].red) == 0x49 &&
ScaleQuantumToChar(image->colormap[i].green) == 0x00 &&
ScaleQuantumToChar(image->colormap[i].blue) == 0x00)
{
image->colormap[i].red=ScaleCharToQuantum(0x24);
}
}
}
}
}
}
/* END OF BUILD_PALETTE */
/* If we are excluding the tRNS chunk and there is transparency,
* then we must write a Gray-Alpha (color-type 4) or RGBA (color-type 6)
* PNG.
*/
if (mng_info->ping_exclude_tRNS != MagickFalse &&
(number_transparent != 0 || number_semitransparent != 0))
{
unsigned int colortype=mng_info->write_png_colortype;
if (ping_have_color == MagickFalse)
mng_info->write_png_colortype = 5;
else
mng_info->write_png_colortype = 7;
if (colortype != 0 &&
mng_info->write_png_colortype != colortype)
ping_need_colortype_warning=MagickTrue;
}
/* See if cheap transparency is possible. It is only possible
* when there is a single transparent color, no semitransparent
* color, and no opaque color that has the same RGB components
* as the transparent color. We only need this information if
* we are writing a PNG with colortype 0 or 2, and we have not
* excluded the tRNS chunk.
*/
if (number_transparent == 1 &&
mng_info->write_png_colortype < 4)
{
ping_have_cheap_transparency = MagickTrue;
if (number_semitransparent != 0)
ping_have_cheap_transparency = MagickFalse;
else if (image_colors == 0 || image_colors > 256 ||
image->colormap == NULL)
{
ExceptionInfo
*exception;
register const PixelPacket
*q;
exception=(&image->exception);
for (y=0; y < (ssize_t) image->rows; y++)
{
q=GetVirtualPixels(image,0,y,image->columns,1, exception);
if (q == (PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (q->opacity != TransparentOpacity &&
(unsigned short) GetPixelRed(q) ==
ping_trans_color.red &&
(unsigned short) GetPixelGreen(q) ==
ping_trans_color.green &&
(unsigned short) GetPixelBlue(q) ==
ping_trans_color.blue)
{
ping_have_cheap_transparency = MagickFalse;
break;
}
q++;
}
if (ping_have_cheap_transparency == MagickFalse)
break;
}
}
else
{
/* Assuming that image->colormap[0] is the one transparent color
* and that all others are opaque.
*/
if (image_colors > 1)
for (i=1; i<image_colors; i++)
if (image->colormap[i].red == image->colormap[0].red &&
image->colormap[i].green == image->colormap[0].green &&
image->colormap[i].blue == image->colormap[0].blue)
{
ping_have_cheap_transparency = MagickFalse;
break;
}
}
if (logging != MagickFalse)
{
if (ping_have_cheap_transparency == MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Cheap transparency is not possible.");
else
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Cheap transparency is possible.");
}
}
else
ping_have_cheap_transparency = MagickFalse;
image_depth=image->depth;
quantum_info = (QuantumInfo *) NULL;
number_colors=0;
image_colors=(int) image->colors;
image_matte=image->matte;
if (mng_info->write_png_colortype < 5)
mng_info->IsPalette=image->storage_class == PseudoClass &&
image_colors <= 256 && image->colormap != NULL;
else
mng_info->IsPalette = MagickFalse;
if ((mng_info->write_png_colortype == 4 || mng_info->write_png8) &&
(image->colors == 0 || image->colormap == NULL))
{
(void) ThrowMagickException(&image->exception,
GetMagickModule(),CoderError,
"Cannot write PNG8 or color-type 3; colormap is NULL",
"`%s'",image->filename);
return(MagickFalse);
}
/*
Allocate the PNG structures
*/
#ifdef PNG_USER_MEM_SUPPORTED
ping=png_create_write_struct_2(PNG_LIBPNG_VER_STRING,image,
MagickPNGErrorHandler,MagickPNGWarningHandler,(void *) NULL,
(png_malloc_ptr) Magick_png_malloc,(png_free_ptr) Magick_png_free);
#else
ping=png_create_write_struct(PNG_LIBPNG_VER_STRING,image,
MagickPNGErrorHandler,MagickPNGWarningHandler);
#endif
if (ping == (png_struct *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
ping_info=png_create_info_struct(ping);
if (ping_info == (png_info *) NULL)
{
png_destroy_write_struct(&ping,(png_info **) NULL);
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
}
png_set_write_fn(ping,image,png_put_data,png_flush_data);
pixel_info=(MemoryInfo *) NULL;
if (setjmp(png_jmpbuf(ping)))
{
/*
PNG write failed.
*/
#ifdef PNG_DEBUG
if (image_info->verbose)
(void) printf("PNG write has failed.\n");
#endif
png_destroy_write_struct(&ping,&ping_info);
#ifdef IMPNG_SETJMP_NOT_THREAD_SAFE
UnlockSemaphoreInfo(ping_semaphore);
#endif
if (pixel_info != (MemoryInfo *) NULL)
pixel_info=RelinquishVirtualMemory(pixel_info);
if (quantum_info != (QuantumInfo *) NULL)
quantum_info=DestroyQuantumInfo(quantum_info);
return(MagickFalse);
}
/* { For navigation to end of SETJMP-protected block. Within this
* block, use png_error() instead of Throwing an Exception, to ensure
* that libpng is able to clean up, and that the semaphore is unlocked.
*/
#ifdef IMPNG_SETJMP_NOT_THREAD_SAFE
LockSemaphoreInfo(ping_semaphore);
#endif
#ifdef PNG_BENIGN_ERRORS_SUPPORTED
/* Allow benign errors */
png_set_benign_errors(ping, 1);
#endif
#ifdef PNG_SET_USER_LIMITS_SUPPORTED
/* Reject images with too many rows or columns */
png_set_user_limits(ping,
(png_uint_32) MagickMin(0x7fffffffL,
GetMagickResourceLimit(WidthResource)),
(png_uint_32) MagickMin(0x7fffffffL,
GetMagickResourceLimit(HeightResource)));
#endif /* PNG_SET_USER_LIMITS_SUPPORTED */
/*
Prepare PNG for writing.
*/
#if defined(PNG_MNG_FEATURES_SUPPORTED)
if (mng_info->write_mng)
{
(void) png_permit_mng_features(ping,PNG_ALL_MNG_FEATURES);
# ifdef PNG_WRITE_CHECK_FOR_INVALID_INDEX_SUPPORTED
/* Disable new libpng-1.5.10 feature when writing a MNG because
* zero-length PLTE is OK
*/
png_set_check_for_invalid_index (ping, 0);
# endif
}
#else
# ifdef PNG_WRITE_EMPTY_PLTE_SUPPORTED
if (mng_info->write_mng)
png_permit_empty_plte(ping,MagickTrue);
# endif
#endif
x=0;
ping_width=(png_uint_32) image->columns;
ping_height=(png_uint_32) image->rows;
if (mng_info->write_png8 || mng_info->write_png24 || mng_info->write_png32)
image_depth=8;
if (mng_info->write_png48 || mng_info->write_png64)
image_depth=16;
if (mng_info->write_png_depth != 0)
image_depth=mng_info->write_png_depth;
/* Adjust requested depth to next higher valid depth if necessary */
if (image_depth > 8)
image_depth=16;
if ((image_depth > 4) && (image_depth < 8))
image_depth=8;
if (image_depth == 3)
image_depth=4;
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" width=%.20g",(double) ping_width);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" height=%.20g",(double) ping_height);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image_matte=%.20g",(double) image->matte);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image->depth=%.20g",(double) image->depth);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Tentative ping_bit_depth=%.20g",(double) image_depth);
}
save_image_depth=image_depth;
ping_bit_depth=(png_byte) save_image_depth;
#if defined(PNG_pHYs_SUPPORTED)
if (ping_exclude_pHYs == MagickFalse)
{
if ((image->x_resolution != 0) && (image->y_resolution != 0) &&
(!mng_info->write_mng || !mng_info->equal_physs))
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Setting up pHYs chunk");
if (image->units == PixelsPerInchResolution)
{
ping_pHYs_unit_type=PNG_RESOLUTION_METER;
ping_pHYs_x_resolution=
(png_uint_32) ((100.0*image->x_resolution+0.5)/2.54);
ping_pHYs_y_resolution=
(png_uint_32) ((100.0*image->y_resolution+0.5)/2.54);
}
else if (image->units == PixelsPerCentimeterResolution)
{
ping_pHYs_unit_type=PNG_RESOLUTION_METER;
ping_pHYs_x_resolution=(png_uint_32) (100.0*image->x_resolution+0.5);
ping_pHYs_y_resolution=(png_uint_32) (100.0*image->y_resolution+0.5);
}
else
{
ping_pHYs_unit_type=PNG_RESOLUTION_UNKNOWN;
ping_pHYs_x_resolution=(png_uint_32) image->x_resolution;
ping_pHYs_y_resolution=(png_uint_32) image->y_resolution;
}
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Set up PNG pHYs chunk: xres: %.20g, yres: %.20g, units: %d.",
(double) ping_pHYs_x_resolution,(double) ping_pHYs_y_resolution,
(int) ping_pHYs_unit_type);
ping_have_pHYs = MagickTrue;
}
}
#endif
if (ping_exclude_bKGD == MagickFalse)
{
if ((!mng_info->adjoin || !mng_info->equal_backgrounds))
{
unsigned int
mask;
mask=0xffff;
if (ping_bit_depth == 8)
mask=0x00ff;
if (ping_bit_depth == 4)
mask=0x000f;
if (ping_bit_depth == 2)
mask=0x0003;
if (ping_bit_depth == 1)
mask=0x0001;
ping_background.red=(png_uint_16)
(ScaleQuantumToShort(image->background_color.red) & mask);
ping_background.green=(png_uint_16)
(ScaleQuantumToShort(image->background_color.green) & mask);
ping_background.blue=(png_uint_16)
(ScaleQuantumToShort(image->background_color.blue) & mask);
ping_background.gray=(png_uint_16) ping_background.green;
}
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Setting up bKGD chunk (1)");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" background_color index is %d",
(int) ping_background.index);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" ping_bit_depth=%d",ping_bit_depth);
}
ping_have_bKGD = MagickTrue;
}
/*
Select the color type.
*/
matte=image_matte;
old_bit_depth=0;
if (mng_info->IsPalette && mng_info->write_png8)
{
/* To do: make this a function cause it's used twice, except
for reducing the sample depth from 8. */
number_colors=image_colors;
ping_have_tRNS=MagickFalse;
/*
Set image palette.
*/
ping_color_type=(png_byte) PNG_COLOR_TYPE_PALETTE;
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Setting up PLTE chunk with %d colors (%d)",
number_colors, image_colors);
for (i=0; i < (ssize_t) number_colors; i++)
{
palette[i].red=ScaleQuantumToChar(image->colormap[i].red);
palette[i].green=ScaleQuantumToChar(image->colormap[i].green);
palette[i].blue=ScaleQuantumToChar(image->colormap[i].blue);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
#if MAGICKCORE_QUANTUM_DEPTH == 8
" %3ld (%3d,%3d,%3d)",
#else
" %5ld (%5d,%5d,%5d)",
#endif
(long) i,palette[i].red,palette[i].green,palette[i].blue);
}
ping_have_PLTE=MagickTrue;
image_depth=ping_bit_depth;
ping_num_trans=0;
if (matte != MagickFalse)
{
/*
Identify which colormap entry is transparent.
*/
assert(number_colors <= 256);
assert(image->colormap != NULL);
for (i=0; i < (ssize_t) number_transparent; i++)
ping_trans_alpha[i]=0;
ping_num_trans=(unsigned short) (number_transparent +
number_semitransparent);
if (ping_num_trans == 0)
ping_have_tRNS=MagickFalse;
else
ping_have_tRNS=MagickTrue;
}
if (ping_exclude_bKGD == MagickFalse)
{
/*
* Identify which colormap entry is the background color.
*/
for (i=0; i < (ssize_t) MagickMax(1L*number_colors-1L,1L); i++)
if (IsPNGColorEqual(ping_background,image->colormap[i]))
break;
ping_background.index=(png_byte) i;
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" background_color index is %d",
(int) ping_background.index);
}
}
} /* end of write_png8 */
else if (mng_info->write_png_colortype == 1)
{
image_matte=MagickFalse;
ping_color_type=(png_byte) PNG_COLOR_TYPE_GRAY;
}
else if (mng_info->write_png24 || mng_info->write_png48 ||
mng_info->write_png_colortype == 3)
{
image_matte=MagickFalse;
ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB;
}
else if (mng_info->write_png32 || mng_info->write_png64 ||
mng_info->write_png_colortype == 7)
{
image_matte=MagickTrue;
ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB_ALPHA;
}
else /* mng_info->write_pngNN not specified */
{
image_depth=ping_bit_depth;
if (mng_info->write_png_colortype != 0)
{
ping_color_type=(png_byte) mng_info->write_png_colortype-1;
if (ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA ||
ping_color_type == PNG_COLOR_TYPE_RGB_ALPHA)
image_matte=MagickTrue;
else
image_matte=MagickFalse;
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" PNG colortype %d was specified:",(int) ping_color_type);
}
else /* write_png_colortype not specified */
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Selecting PNG colortype:");
ping_color_type=(png_byte) ((matte != MagickFalse)?
PNG_COLOR_TYPE_RGB_ALPHA:PNG_COLOR_TYPE_RGB);
if (image_info->type == TrueColorType)
{
ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB;
image_matte=MagickFalse;
}
if (image_info->type == TrueColorMatteType)
{
ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB_ALPHA;
image_matte=MagickTrue;
}
if (image_info->type == PaletteType ||
image_info->type == PaletteMatteType)
ping_color_type=(png_byte) PNG_COLOR_TYPE_PALETTE;
if (mng_info->write_png_colortype == 0 &&
image_info->type == UndefinedType)
{
if (ping_have_color == MagickFalse)
{
if (image_matte == MagickFalse)
{
ping_color_type=(png_byte) PNG_COLOR_TYPE_GRAY;
image_matte=MagickFalse;
}
else
{
ping_color_type=(png_byte) PNG_COLOR_TYPE_GRAY_ALPHA;
image_matte=MagickTrue;
}
}
else
{
if (image_matte == MagickFalse)
{
ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB;
image_matte=MagickFalse;
}
else
{
ping_color_type=(png_byte) PNG_COLOR_TYPE_RGBA;
image_matte=MagickTrue;
}
}
}
}
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Selected PNG colortype=%d",ping_color_type);
if (ping_bit_depth < 8)
{
if (ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA ||
ping_color_type == PNG_COLOR_TYPE_RGB ||
ping_color_type == PNG_COLOR_TYPE_RGB_ALPHA)
ping_bit_depth=8;
}
old_bit_depth=ping_bit_depth;
if (ping_color_type == PNG_COLOR_TYPE_GRAY)
{
if (image->matte == MagickFalse && ping_have_non_bw == MagickFalse)
ping_bit_depth=1;
}
if (ping_color_type == PNG_COLOR_TYPE_PALETTE)
{
size_t one = 1;
ping_bit_depth=1;
if (image->colors == 0)
{
/* DO SOMETHING */
png_error(ping,"image has 0 colors");
}
while ((int) (one << ping_bit_depth) < (ssize_t) image_colors)
ping_bit_depth <<= 1;
}
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Number of colors: %.20g",(double) image_colors);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Tentative PNG bit depth: %d",ping_bit_depth);
}
if (ping_bit_depth < (int) mng_info->write_png_depth)
ping_bit_depth = mng_info->write_png_depth;
}
image_depth=ping_bit_depth;
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Tentative PNG color type: %s (%.20g)",
PngColorTypeToString(ping_color_type),
(double) ping_color_type);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image_info->type: %.20g",(double) image_info->type);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image_depth: %.20g",(double) image_depth);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image->depth: %.20g",(double) image->depth);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" ping_bit_depth: %.20g",(double) ping_bit_depth);
}
if (matte != MagickFalse)
{
if (mng_info->IsPalette)
{
if (mng_info->write_png_colortype == 0)
{
ping_color_type=PNG_COLOR_TYPE_GRAY_ALPHA;
if (ping_have_color != MagickFalse)
ping_color_type=PNG_COLOR_TYPE_RGBA;
}
/*
* Determine if there is any transparent color.
*/
if (number_transparent + number_semitransparent == 0)
{
/*
No transparent pixels are present. Change 4 or 6 to 0 or 2.
*/
image_matte=MagickFalse;
if (mng_info->write_png_colortype == 0)
ping_color_type&=0x03;
}
else
{
unsigned int
mask;
mask=0xffff;
if (ping_bit_depth == 8)
mask=0x00ff;
if (ping_bit_depth == 4)
mask=0x000f;
if (ping_bit_depth == 2)
mask=0x0003;
if (ping_bit_depth == 1)
mask=0x0001;
ping_trans_color.red=(png_uint_16)
(ScaleQuantumToShort(image->colormap[0].red) & mask);
ping_trans_color.green=(png_uint_16)
(ScaleQuantumToShort(image->colormap[0].green) & mask);
ping_trans_color.blue=(png_uint_16)
(ScaleQuantumToShort(image->colormap[0].blue) & mask);
ping_trans_color.gray=(png_uint_16)
(ScaleQuantumToShort(ClampToQuantum(GetPixelLuma(image,
image->colormap))) & mask);
ping_trans_color.index=(png_byte) 0;
ping_have_tRNS=MagickTrue;
}
if (ping_have_tRNS != MagickFalse)
{
/*
* Determine if there is one and only one transparent color
* and if so if it is fully transparent.
*/
if (ping_have_cheap_transparency == MagickFalse)
ping_have_tRNS=MagickFalse;
}
if (ping_have_tRNS != MagickFalse)
{
if (mng_info->write_png_colortype == 0)
ping_color_type &= 0x03; /* changes 4 or 6 to 0 or 2 */
if (image_depth == 8)
{
ping_trans_color.red&=0xff;
ping_trans_color.green&=0xff;
ping_trans_color.blue&=0xff;
ping_trans_color.gray&=0xff;
}
}
}
else
{
if (image_depth == 8)
{
ping_trans_color.red&=0xff;
ping_trans_color.green&=0xff;
ping_trans_color.blue&=0xff;
ping_trans_color.gray&=0xff;
}
}
}
matte=image_matte;
if (ping_have_tRNS != MagickFalse)
image_matte=MagickFalse;
if ((mng_info->IsPalette) &&
mng_info->write_png_colortype-1 != PNG_COLOR_TYPE_PALETTE &&
ping_have_color == MagickFalse &&
(image_matte == MagickFalse || image_depth >= 8))
{
size_t one=1;
if (image_matte != MagickFalse)
ping_color_type=PNG_COLOR_TYPE_GRAY_ALPHA;
else if (mng_info->write_png_colortype-1 != PNG_COLOR_TYPE_GRAY_ALPHA)
{
ping_color_type=PNG_COLOR_TYPE_GRAY;
if (save_image_depth == 16 && image_depth == 8)
{
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Scaling ping_trans_color (0)");
}
ping_trans_color.gray*=0x0101;
}
}
if (image_depth > MAGICKCORE_QUANTUM_DEPTH)
image_depth=MAGICKCORE_QUANTUM_DEPTH;
if ((image_colors == 0) ||
((ssize_t) (image_colors-1) > (ssize_t) MaxColormapSize))
image_colors=(int) (one << image_depth);
if (image_depth > 8)
ping_bit_depth=16;
else
{
ping_bit_depth=8;
if ((int) ping_color_type == PNG_COLOR_TYPE_PALETTE)
{
if(!mng_info->write_png_depth)
{
ping_bit_depth=1;
while ((int) (one << ping_bit_depth)
< (ssize_t) image_colors)
ping_bit_depth <<= 1;
}
}
else if (ping_color_type ==
PNG_COLOR_TYPE_GRAY && image_colors < 17 &&
mng_info->IsPalette)
{
/* Check if grayscale is reducible */
int
depth_4_ok=MagickTrue,
depth_2_ok=MagickTrue,
depth_1_ok=MagickTrue;
for (i=0; i < (ssize_t) image_colors; i++)
{
unsigned char
intensity;
intensity=ScaleQuantumToChar(image->colormap[i].red);
if ((intensity & 0x0f) != ((intensity & 0xf0) >> 4))
depth_4_ok=depth_2_ok=depth_1_ok=MagickFalse;
else if ((intensity & 0x03) != ((intensity & 0x0c) >> 2))
depth_2_ok=depth_1_ok=MagickFalse;
else if ((intensity & 0x01) != ((intensity & 0x02) >> 1))
depth_1_ok=MagickFalse;
}
if (depth_1_ok && mng_info->write_png_depth <= 1)
ping_bit_depth=1;
else if (depth_2_ok && mng_info->write_png_depth <= 2)
ping_bit_depth=2;
else if (depth_4_ok && mng_info->write_png_depth <= 4)
ping_bit_depth=4;
}
}
image_depth=ping_bit_depth;
}
else
if (mng_info->IsPalette)
{
number_colors=image_colors;
if (image_depth <= 8)
{
/*
Set image palette.
*/
ping_color_type=(png_byte) PNG_COLOR_TYPE_PALETTE;
if (!(mng_info->have_write_global_plte && matte == MagickFalse))
{
for (i=0; i < (ssize_t) number_colors; i++)
{
palette[i].red=ScaleQuantumToChar(image->colormap[i].red);
palette[i].green=ScaleQuantumToChar(image->colormap[i].green);
palette[i].blue=ScaleQuantumToChar(image->colormap[i].blue);
}
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Setting up PLTE chunk with %d colors",
number_colors);
ping_have_PLTE=MagickTrue;
}
/* color_type is PNG_COLOR_TYPE_PALETTE */
if (mng_info->write_png_depth == 0)
{
size_t
one;
ping_bit_depth=1;
one=1;
while ((one << ping_bit_depth) < (size_t) number_colors)
ping_bit_depth <<= 1;
}
ping_num_trans=0;
if (matte != MagickFalse)
{
/*
* Set up trans_colors array.
*/
assert(number_colors <= 256);
ping_num_trans=(unsigned short) (number_transparent +
number_semitransparent);
if (ping_num_trans == 0)
ping_have_tRNS=MagickFalse;
else
{
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Scaling ping_trans_color (1)");
}
ping_have_tRNS=MagickTrue;
for (i=0; i < ping_num_trans; i++)
{
ping_trans_alpha[i]= (png_byte) (255-
ScaleQuantumToChar(image->colormap[i].opacity));
}
}
}
}
}
else
{
if (image_depth < 8)
image_depth=8;
if ((save_image_depth == 16) && (image_depth == 8))
{
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Scaling ping_trans_color from (%d,%d,%d)",
(int) ping_trans_color.red,
(int) ping_trans_color.green,
(int) ping_trans_color.blue);
}
ping_trans_color.red*=0x0101;
ping_trans_color.green*=0x0101;
ping_trans_color.blue*=0x0101;
ping_trans_color.gray*=0x0101;
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" to (%d,%d,%d)",
(int) ping_trans_color.red,
(int) ping_trans_color.green,
(int) ping_trans_color.blue);
}
}
}
if (ping_bit_depth < (ssize_t) mng_info->write_png_depth)
ping_bit_depth = (ssize_t) mng_info->write_png_depth;
/*
Adjust background and transparency samples in sub-8-bit grayscale files.
*/
if (ping_bit_depth < 8 && ping_color_type ==
PNG_COLOR_TYPE_GRAY)
{
png_uint_16
maxval;
size_t
one=1;
maxval=(png_uint_16) ((one << ping_bit_depth)-1);
if (ping_exclude_bKGD == MagickFalse)
{
ping_background.gray=(png_uint_16)
((maxval/65535.)*(ScaleQuantumToShort((Quantum)
GetPixelLuma(image,&image->background_color)))+.5);
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Setting up bKGD chunk (2)");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" ping_background.index is %d",
(int) ping_background.index);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" ping_background.gray is %d",
(int) ping_background.gray);
}
ping_have_bKGD = MagickTrue;
}
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Scaling ping_trans_color.gray from %d",
(int)ping_trans_color.gray);
ping_trans_color.gray=(png_uint_16) ((maxval/255.)*(
ping_trans_color.gray)+.5);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" to %d", (int)ping_trans_color.gray);
}
if (ping_exclude_bKGD == MagickFalse)
{
if (mng_info->IsPalette && (int) ping_color_type == PNG_COLOR_TYPE_PALETTE)
{
/*
Identify which colormap entry is the background color.
*/
number_colors=image_colors;
for (i=0; i < (ssize_t) MagickMax(1L*number_colors,1L); i++)
if (IsPNGColorEqual(image->background_color,image->colormap[i]))
break;
ping_background.index=(png_byte) i;
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Setting up bKGD chunk with index=%d",(int) i);
}
if (i < (ssize_t) number_colors)
{
ping_have_bKGD = MagickTrue;
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" background =(%d,%d,%d)",
(int) ping_background.red,
(int) ping_background.green,
(int) ping_background.blue);
}
}
else /* Can't happen */
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" No room in PLTE to add bKGD color");
ping_have_bKGD = MagickFalse;
}
}
}
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" PNG color type: %s (%d)", PngColorTypeToString(ping_color_type),
ping_color_type);
/*
Initialize compression level and filtering.
*/
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Setting up deflate compression");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Compression buffer size: 32768");
}
png_set_compression_buffer_size(ping,32768L);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Compression mem level: 9");
png_set_compression_mem_level(ping, 9);
/* Untangle the "-quality" setting:
Undefined is 0; the default is used.
Default is 75
10's digit:
0 or omitted: Use Z_HUFFMAN_ONLY strategy with the
zlib default compression level
1-9: the zlib compression level
1's digit:
0-4: the PNG filter method
5: libpng adaptive filtering if compression level > 5
libpng filter type "none" if compression level <= 5
or if image is grayscale or palette
6: libpng adaptive filtering
7: "LOCO" filtering (intrapixel differing) if writing
a MNG, otherwise "none". Did not work in IM-6.7.0-9
and earlier because of a missing "else".
8: Z_RLE strategy (or Z_HUFFMAN_ONLY if quality < 10), adaptive
filtering. Unused prior to IM-6.7.0-10, was same as 6
9: Z_RLE strategy (or Z_HUFFMAN_ONLY if quality < 10), no PNG filters
Unused prior to IM-6.7.0-10, was same as 6
Note that using the -quality option, not all combinations of
PNG filter type, zlib compression level, and zlib compression
strategy are possible. This is addressed by using
"-define png:compression-strategy", etc., which takes precedence
over -quality.
*/
quality=image_info->quality == UndefinedCompressionQuality ? 75UL :
image_info->quality;
if (quality <= 9)
{
if (mng_info->write_png_compression_strategy == 0)
mng_info->write_png_compression_strategy = Z_HUFFMAN_ONLY+1;
}
else if (mng_info->write_png_compression_level == 0)
{
int
level;
level=(int) MagickMin((ssize_t) quality/10,9);
mng_info->write_png_compression_level = level+1;
}
if (mng_info->write_png_compression_strategy == 0)
{
if ((quality %10) == 8 || (quality %10) == 9)
#ifdef Z_RLE /* Z_RLE was added to zlib-1.2.0 */
mng_info->write_png_compression_strategy=Z_RLE+1;
#else
mng_info->write_png_compression_strategy = Z_DEFAULT_STRATEGY+1;
#endif
}
if (mng_info->write_png_compression_filter == 0)
mng_info->write_png_compression_filter=((int) quality % 10) + 1;
if (logging != MagickFalse)
{
if (mng_info->write_png_compression_level)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Compression level: %d",
(int) mng_info->write_png_compression_level-1);
if (mng_info->write_png_compression_strategy)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Compression strategy: %d",
(int) mng_info->write_png_compression_strategy-1);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Setting up filtering");
if (mng_info->write_png_compression_filter == 6)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Base filter method: ADAPTIVE");
else if (mng_info->write_png_compression_filter == 0 ||
mng_info->write_png_compression_filter == 1)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Base filter method: NONE");
else
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Base filter method: %d",
(int) mng_info->write_png_compression_filter-1);
}
if (mng_info->write_png_compression_level != 0)
png_set_compression_level(ping,mng_info->write_png_compression_level-1);
if (mng_info->write_png_compression_filter == 6)
{
if (((int) ping_color_type == PNG_COLOR_TYPE_GRAY) ||
((int) ping_color_type == PNG_COLOR_TYPE_PALETTE) ||
(quality < 50))
png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_NO_FILTERS);
else
png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_ALL_FILTERS);
}
else if (mng_info->write_png_compression_filter == 7 ||
mng_info->write_png_compression_filter == 10)
png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_ALL_FILTERS);
else if (mng_info->write_png_compression_filter == 8)
{
#if defined(PNG_MNG_FEATURES_SUPPORTED) && defined(PNG_INTRAPIXEL_DIFFERENCING)
if (mng_info->write_mng)
{
if (((int) ping_color_type == PNG_COLOR_TYPE_RGB) ||
((int) ping_color_type == PNG_COLOR_TYPE_RGBA))
ping_filter_method=PNG_INTRAPIXEL_DIFFERENCING;
}
#endif
png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_NO_FILTERS);
}
else if (mng_info->write_png_compression_filter == 9)
png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_NO_FILTERS);
else if (mng_info->write_png_compression_filter != 0)
png_set_filter(ping,PNG_FILTER_TYPE_BASE,
mng_info->write_png_compression_filter-1);
if (mng_info->write_png_compression_strategy != 0)
png_set_compression_strategy(ping,
mng_info->write_png_compression_strategy-1);
ping_interlace_method=image_info->interlace != NoInterlace;
if (mng_info->write_mng)
png_set_sig_bytes(ping,8);
/* Bail out if cannot meet defined png:bit-depth or png:color-type */
if (mng_info->write_png_colortype != 0)
{
if (mng_info->write_png_colortype-1 == PNG_COLOR_TYPE_GRAY)
if (ping_have_color != MagickFalse)
{
ping_color_type = PNG_COLOR_TYPE_RGB;
if (ping_bit_depth < 8)
ping_bit_depth=8;
}
if (mng_info->write_png_colortype-1 == PNG_COLOR_TYPE_GRAY_ALPHA)
if (ping_have_color != MagickFalse)
ping_color_type = PNG_COLOR_TYPE_RGB_ALPHA;
}
if (ping_need_colortype_warning != MagickFalse ||
((mng_info->write_png_depth &&
(int) mng_info->write_png_depth != ping_bit_depth) ||
(mng_info->write_png_colortype &&
((int) mng_info->write_png_colortype-1 != ping_color_type &&
mng_info->write_png_colortype != 7 &&
!(mng_info->write_png_colortype == 5 && ping_color_type == 0)))))
{
if (logging != MagickFalse)
{
if (ping_need_colortype_warning != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Image has transparency but tRNS chunk was excluded");
}
if (mng_info->write_png_depth)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Defined png:bit-depth=%u, Computed depth=%u",
mng_info->write_png_depth,
ping_bit_depth);
}
if (mng_info->write_png_colortype)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Defined png:color-type=%u, Computed color type=%u",
mng_info->write_png_colortype-1,
ping_color_type);
}
}
png_warning(ping,
"Cannot write image with defined png:bit-depth or png:color-type.");
}
if (image_matte != MagickFalse && image->matte == MagickFalse)
{
/* Add an opaque matte channel */
image->matte = MagickTrue;
(void) SetImageOpacity(image,0);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Added an opaque matte channel");
}
if (number_transparent != 0 || number_semitransparent != 0)
{
if (ping_color_type < 4)
{
ping_have_tRNS=MagickTrue;
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Setting ping_have_tRNS=MagickTrue.");
}
}
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Writing PNG header chunks");
png_set_IHDR(ping,ping_info,ping_width,ping_height,
ping_bit_depth,ping_color_type,
ping_interlace_method,ping_compression_method,
ping_filter_method);
if (ping_color_type == 3 && ping_have_PLTE != MagickFalse)
{
if (mng_info->have_write_global_plte && matte == MagickFalse)
{
png_set_PLTE(ping,ping_info,NULL,0);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Setting up empty PLTE chunk");
}
else
png_set_PLTE(ping,ping_info,palette,number_colors);
if (logging != MagickFalse)
{
for (i=0; i< (ssize_t) number_colors; i++)
{
if (i < ping_num_trans)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" PLTE[%d] = (%d,%d,%d), tRNS[%d] = (%d)",
(int) i,
(int) palette[i].red,
(int) palette[i].green,
(int) palette[i].blue,
(int) i,
(int) ping_trans_alpha[i]);
else
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" PLTE[%d] = (%d,%d,%d)",
(int) i,
(int) palette[i].red,
(int) palette[i].green,
(int) palette[i].blue);
}
}
}
/* Only write the iCCP chunk if we are not writing the sRGB chunk. */
if (ping_exclude_sRGB != MagickFalse ||
(!png_get_valid(ping,ping_info,PNG_INFO_sRGB)))
{
if ((ping_exclude_tEXt == MagickFalse ||
ping_exclude_zTXt == MagickFalse) &&
(ping_exclude_iCCP == MagickFalse || ping_exclude_zCCP == MagickFalse))
{
ResetImageProfileIterator(image);
for (name=GetNextImageProfile(image); name != (const char *) NULL; )
{
profile=GetImageProfile(image,name);
if (profile != (StringInfo *) NULL)
{
#ifdef PNG_WRITE_iCCP_SUPPORTED
if ((LocaleCompare(name,"ICC") == 0) ||
(LocaleCompare(name,"ICM") == 0))
{
if (ping_exclude_iCCP == MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Setting up iCCP chunk");
png_set_iCCP(ping,ping_info,(const png_charp) name,0,
#if (PNG_LIBPNG_VER < 10500)
(png_charp) GetStringInfoDatum(profile),
#else
(const png_byte *) GetStringInfoDatum(profile),
#endif
(png_uint_32) GetStringInfoLength(profile));
ping_have_iCCP = MagickTrue;
}
}
else
#endif
if (ping_exclude_zCCP == MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Setting up zTXT chunk with uuencoded ICC");
Magick_png_write_raw_profile(image_info,ping,ping_info,
(unsigned char *) name,(unsigned char *) name,
GetStringInfoDatum(profile),
(png_uint_32) GetStringInfoLength(profile));
ping_have_iCCP = MagickTrue;
}
}
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Setting up text chunk with %s profile",name);
name=GetNextImageProfile(image);
}
}
}
#if defined(PNG_WRITE_sRGB_SUPPORTED)
if ((mng_info->have_write_global_srgb == 0) &&
ping_have_iCCP != MagickTrue &&
(ping_have_sRGB != MagickFalse ||
png_get_valid(ping,ping_info,PNG_INFO_sRGB)))
{
if (ping_exclude_sRGB == MagickFalse)
{
/*
Note image rendering intent.
*/
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Setting up sRGB chunk");
(void) png_set_sRGB(ping,ping_info,(
Magick_RenderingIntent_to_PNG_RenderingIntent(
image->rendering_intent)));
ping_have_sRGB = MagickTrue;
}
}
if ((!mng_info->write_mng) || (!png_get_valid(ping,ping_info,PNG_INFO_sRGB)))
#endif
{
if (ping_exclude_gAMA == MagickFalse &&
ping_have_iCCP == MagickFalse &&
ping_have_sRGB == MagickFalse &&
(ping_exclude_sRGB == MagickFalse ||
(image->gamma < .45 || image->gamma > .46)))
{
if ((mng_info->have_write_global_gama == 0) && (image->gamma != 0.0))
{
/*
Note image gamma.
To do: check for cHRM+gAMA == sRGB, and write sRGB instead.
*/
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Setting up gAMA chunk");
png_set_gAMA(ping,ping_info,image->gamma);
}
}
if (ping_exclude_cHRM == MagickFalse && ping_have_sRGB == MagickFalse)
{
if ((mng_info->have_write_global_chrm == 0) &&
(image->chromaticity.red_primary.x != 0.0))
{
/*
Note image chromaticity.
Note: if cHRM+gAMA == sRGB write sRGB instead.
*/
PrimaryInfo
bp,
gp,
rp,
wp;
wp=image->chromaticity.white_point;
rp=image->chromaticity.red_primary;
gp=image->chromaticity.green_primary;
bp=image->chromaticity.blue_primary;
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Setting up cHRM chunk");
png_set_cHRM(ping,ping_info,wp.x,wp.y,rp.x,rp.y,gp.x,gp.y,
bp.x,bp.y);
}
}
}
if (ping_exclude_bKGD == MagickFalse)
{
if (ping_have_bKGD != MagickFalse)
{
png_set_bKGD(ping,ping_info,&ping_background);
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Setting up bKGD chunk");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" background color = (%d,%d,%d)",
(int) ping_background.red,
(int) ping_background.green,
(int) ping_background.blue);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" index = %d, gray=%d",
(int) ping_background.index,
(int) ping_background.gray);
}
}
}
if (ping_exclude_pHYs == MagickFalse)
{
if (ping_have_pHYs != MagickFalse)
{
png_set_pHYs(ping,ping_info,
ping_pHYs_x_resolution,
ping_pHYs_y_resolution,
ping_pHYs_unit_type);
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Setting up pHYs chunk");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" x_resolution=%lu",
(unsigned long) ping_pHYs_x_resolution);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" y_resolution=%lu",
(unsigned long) ping_pHYs_y_resolution);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" unit_type=%lu",
(unsigned long) ping_pHYs_unit_type);
}
}
}
#if defined(PNG_tIME_SUPPORTED)
if (ping_exclude_tIME == MagickFalse)
{
const char
*timestamp;
if (image->taint == MagickFalse)
{
timestamp=GetImageOption(image_info,"png:tIME");
if (timestamp == (const char *) NULL)
timestamp=GetImageProperty(image,"png:tIME");
}
else
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Reset tIME in tainted image");
timestamp=GetImageProperty(image,"date:modify");
}
if (timestamp != (const char *) NULL)
write_tIME_chunk(image,ping,ping_info,timestamp);
}
#endif
if (mng_info->need_blob != MagickFalse)
{
if (OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception) ==
MagickFalse)
png_error(ping,"WriteBlob Failed");
ping_have_blob=MagickTrue;
(void) ping_have_blob;
}
png_write_info_before_PLTE(ping, ping_info);
if (ping_have_tRNS != MagickFalse && ping_color_type < 4)
{
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Calling png_set_tRNS with num_trans=%d",ping_num_trans);
}
if (ping_color_type == 3)
(void) png_set_tRNS(ping, ping_info,
ping_trans_alpha,
ping_num_trans,
NULL);
else
{
(void) png_set_tRNS(ping, ping_info,
NULL,
0,
&ping_trans_color);
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" tRNS color =(%d,%d,%d)",
(int) ping_trans_color.red,
(int) ping_trans_color.green,
(int) ping_trans_color.blue);
}
}
}
/* write any png-chunk-b profiles */
(void) Magick_png_write_chunk_from_profile(image,"PNG-chunk-b",logging);
png_write_info(ping,ping_info);
/* write any PNG-chunk-m profiles */
(void) Magick_png_write_chunk_from_profile(image,"PNG-chunk-m",logging);
ping_wrote_caNv = MagickFalse;
/* write caNv chunk */
if (ping_exclude_caNv == MagickFalse)
{
if ((image->page.width != 0 && image->page.width != image->columns) ||
(image->page.height != 0 && image->page.height != image->rows) ||
image->page.x != 0 || image->page.y != 0)
{
unsigned char
chunk[20];
(void) WriteBlobMSBULong(image,16L); /* data length=8 */
PNGType(chunk,mng_caNv);
LogPNGChunk(logging,mng_caNv,16L);
PNGLong(chunk+4,(png_uint_32) image->page.width);
PNGLong(chunk+8,(png_uint_32) image->page.height);
PNGsLong(chunk+12,(png_int_32) image->page.x);
PNGsLong(chunk+16,(png_int_32) image->page.y);
(void) WriteBlob(image,20,chunk);
(void) WriteBlobMSBULong(image,crc32(0,chunk,20));
ping_wrote_caNv = MagickTrue;
}
}
#if defined(PNG_oFFs_SUPPORTED)
if (ping_exclude_oFFs == MagickFalse && ping_wrote_caNv == MagickFalse)
{
if (image->page.x || image->page.y)
{
png_set_oFFs(ping,ping_info,(png_int_32) image->page.x,
(png_int_32) image->page.y, 0);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Setting up oFFs chunk with x=%d, y=%d, units=0",
(int) image->page.x, (int) image->page.y);
}
}
#endif
/* write vpAg chunk (deprecated, replaced by caNv) */
if (ping_exclude_vpAg == MagickFalse && ping_wrote_caNv == MagickFalse)
{
if ((image->page.width != 0 && image->page.width != image->columns) ||
(image->page.height != 0 && image->page.height != image->rows))
{
unsigned char
chunk[14];
(void) WriteBlobMSBULong(image,9L); /* data length=8 */
PNGType(chunk,mng_vpAg);
LogPNGChunk(logging,mng_vpAg,9L);
PNGLong(chunk+4,(png_uint_32) image->page.width);
PNGLong(chunk+8,(png_uint_32) image->page.height);
chunk[12]=0; /* unit = pixels */
(void) WriteBlob(image,13,chunk);
(void) WriteBlobMSBULong(image,crc32(0,chunk,13));
}
}
#if (PNG_LIBPNG_VER == 10206)
/* avoid libpng-1.2.6 bug by setting PNG_HAVE_IDAT flag */
#define PNG_HAVE_IDAT 0x04
ping->mode |= PNG_HAVE_IDAT;
#undef PNG_HAVE_IDAT
#endif
png_set_packing(ping);
/*
Allocate memory.
*/
rowbytes=image->columns;
if (image_depth > 8)
rowbytes*=2;
switch (ping_color_type)
{
case PNG_COLOR_TYPE_RGB:
rowbytes*=3;
break;
case PNG_COLOR_TYPE_GRAY_ALPHA:
rowbytes*=2;
break;
case PNG_COLOR_TYPE_RGBA:
rowbytes*=4;
break;
default:
break;
}
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Writing PNG image data");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Allocating %.20g bytes of memory for pixels",(double) rowbytes);
}
pixel_info=AcquireVirtualMemory(rowbytes,sizeof(*ping_pixels));
if (pixel_info == (MemoryInfo *) NULL)
png_error(ping,"Allocation of memory for pixels failed");
ping_pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);
/*
Initialize image scanlines.
*/
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
png_error(ping,"Memory allocation for quantum_info failed");
quantum_info->format=UndefinedQuantumFormat;
SetQuantumDepth(image,quantum_info,image_depth);
(void) SetQuantumEndian(image,quantum_info,MSBEndian);
num_passes=png_set_interlace_handling(ping);
if ((!mng_info->write_png8 && !mng_info->write_png24 &&
!mng_info->write_png48 && !mng_info->write_png64 &&
!mng_info->write_png32) &&
(mng_info->IsPalette ||
(image_info->type == BilevelType)) &&
image_matte == MagickFalse &&
ping_have_non_bw == MagickFalse)
{
/* Palette, Bilevel, or Opaque Monochrome */
register const PixelPacket
*p;
SetQuantumDepth(image,quantum_info,8);
for (pass=0; pass < num_passes; pass++)
{
/*
Convert PseudoClass image to a PNG monochrome image.
*/
for (y=0; y < (ssize_t) image->rows; y++)
{
if (logging != MagickFalse && y == 0)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Writing row of pixels (0)");
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
if (mng_info->IsPalette)
{
(void) ExportQuantumPixels(image,(const CacheView *) NULL,
quantum_info,GrayQuantum,ping_pixels,&image->exception);
if (mng_info->write_png_colortype-1 == PNG_COLOR_TYPE_PALETTE &&
mng_info->write_png_depth &&
mng_info->write_png_depth != old_bit_depth)
{
/* Undo pixel scaling */
for (i=0; i < (ssize_t) image->columns; i++)
*(ping_pixels+i)=(unsigned char) (*(ping_pixels+i)
>> (8-old_bit_depth));
}
}
else
{
(void) ExportQuantumPixels(image,(const CacheView *) NULL,
quantum_info,RedQuantum,ping_pixels,&image->exception);
}
if (mng_info->write_png_colortype-1 != PNG_COLOR_TYPE_PALETTE)
for (i=0; i < (ssize_t) image->columns; i++)
*(ping_pixels+i)=(unsigned char) ((*(ping_pixels+i) > 127) ?
255 : 0);
if (logging != MagickFalse && y == 0)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Writing row of pixels (1)");
png_write_row(ping,ping_pixels);
status=SetImageProgress(image,SaveImageTag,
(MagickOffsetType) (pass * image->rows + y),
num_passes * image->rows);
if (status == MagickFalse)
break;
}
}
}
else /* Not Palette, Bilevel, or Opaque Monochrome */
{
if ((!mng_info->write_png8 && !mng_info->write_png24 &&
!mng_info->write_png48 && !mng_info->write_png64 &&
!mng_info->write_png32) && (image_matte != MagickFalse ||
(ping_bit_depth >= MAGICKCORE_QUANTUM_DEPTH)) &&
(mng_info->IsPalette) && ping_have_color == MagickFalse)
{
register const PixelPacket
*p;
for (pass=0; pass < num_passes; pass++)
{
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 (ping_color_type == PNG_COLOR_TYPE_GRAY)
{
if (mng_info->IsPalette)
(void) ExportQuantumPixels(image,(const CacheView *) NULL,
quantum_info,GrayQuantum,ping_pixels,&image->exception);
else
(void) ExportQuantumPixels(image,(const CacheView *) NULL,
quantum_info,RedQuantum,ping_pixels,&image->exception);
if (logging != MagickFalse && y == 0)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Writing GRAY PNG pixels (2)");
}
else /* PNG_COLOR_TYPE_GRAY_ALPHA */
{
if (logging != MagickFalse && y == 0)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Writing GRAY_ALPHA PNG pixels (2)");
(void) ExportQuantumPixels(image,(const CacheView *) NULL,
quantum_info,GrayAlphaQuantum,ping_pixels,&image->exception);
}
if (logging != MagickFalse && y == 0)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Writing row of pixels (2)");
png_write_row(ping,ping_pixels);
status=SetImageProgress(image,SaveImageTag,
(MagickOffsetType) (pass * image->rows + y),
num_passes * image->rows);
if (status == MagickFalse)
break;
}
}
}
else
{
register const PixelPacket
*p;
for (pass=0; pass < num_passes; pass++)
{
if ((image_depth > 8) ||
mng_info->write_png24 ||
mng_info->write_png32 ||
mng_info->write_png48 ||
mng_info->write_png64 ||
(!mng_info->write_png8 && !mng_info->IsPalette))
{
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 (ping_color_type == PNG_COLOR_TYPE_GRAY)
{
if (image->storage_class == DirectClass)
(void) ExportQuantumPixels(image,(const CacheView *) NULL,
quantum_info,RedQuantum,ping_pixels,&image->exception);
else
(void) ExportQuantumPixels(image,(const CacheView *) NULL,
quantum_info,GrayQuantum,ping_pixels,&image->exception);
}
else if (ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
{
(void) ExportQuantumPixels(image,(const CacheView *) NULL,
quantum_info,GrayAlphaQuantum,ping_pixels,
&image->exception);
if (logging != MagickFalse && y == 0)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Writing GRAY_ALPHA PNG pixels (3)");
}
else if (image_matte != MagickFalse)
(void) ExportQuantumPixels(image,(const CacheView *) NULL,
quantum_info,RGBAQuantum,ping_pixels,&image->exception);
else
(void) ExportQuantumPixels(image,(const CacheView *) NULL,
quantum_info,RGBQuantum,ping_pixels,&image->exception);
if (logging != MagickFalse && y == 0)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Writing row of pixels (3)");
png_write_row(ping,ping_pixels);
status=SetImageProgress(image,SaveImageTag,
(MagickOffsetType) (pass * image->rows + y),
num_passes * image->rows);
if (status == MagickFalse)
break;
}
}
else
/* not ((image_depth > 8) ||
mng_info->write_png24 || mng_info->write_png32 ||
mng_info->write_png48 || mng_info->write_png64 ||
(!mng_info->write_png8 && !mng_info->IsPalette))
*/
{
if ((ping_color_type != PNG_COLOR_TYPE_GRAY) &&
(ping_color_type != PNG_COLOR_TYPE_GRAY_ALPHA))
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" pass %d, Image Is not GRAY or GRAY_ALPHA",pass);
SetQuantumDepth(image,quantum_info,8);
image_depth=8;
}
for (y=0; y < (ssize_t) image->rows; y++)
{
if (logging != MagickFalse && y == 0)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" pass %d, Image Is RGB, 16-bit GRAY, or GRAY_ALPHA",pass);
p=GetVirtualPixels(image,0,y,image->columns,1,
&image->exception);
if (p == (const PixelPacket *) NULL)
break;
if (ping_color_type == PNG_COLOR_TYPE_GRAY)
{
SetQuantumDepth(image,quantum_info,image->depth);
(void) ExportQuantumPixels(image,(const CacheView *) NULL,
quantum_info,GrayQuantum,ping_pixels,&image->exception);
}
else if (ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
{
if (logging != MagickFalse && y == 0)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Writing GRAY_ALPHA PNG pixels (4)");
(void) ExportQuantumPixels(image,(const CacheView *) NULL,
quantum_info,GrayAlphaQuantum,ping_pixels,
&image->exception);
}
else
{
(void) ExportQuantumPixels(image,(const CacheView *) NULL,
quantum_info,IndexQuantum,ping_pixels,&image->exception);
if (logging != MagickFalse && y <= 2)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Writing row of non-gray pixels (4)");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" ping_pixels[0]=%d,ping_pixels[1]=%d",
(int)ping_pixels[0],(int)ping_pixels[1]);
}
}
png_write_row(ping,ping_pixels);
status=SetImageProgress(image,SaveImageTag,
(MagickOffsetType) (pass * image->rows + y),
num_passes * image->rows);
if (status == MagickFalse)
break;
}
}
}
}
}
if (quantum_info != (QuantumInfo *) NULL)
quantum_info=DestroyQuantumInfo(quantum_info);
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Wrote PNG image data");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Width: %.20g",(double) ping_width);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Height: %.20g",(double) ping_height);
if (mng_info->write_png_depth)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Defined png:bit-depth: %d",mng_info->write_png_depth);
}
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" PNG bit-depth written: %d",ping_bit_depth);
if (mng_info->write_png_colortype)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Defined png:color-type: %d",mng_info->write_png_colortype-1);
}
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" PNG color-type written: %d",ping_color_type);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" PNG Interlace method: %d",ping_interlace_method);
}
/*
Generate text chunks after IDAT.
*/
if (ping_exclude_tEXt == MagickFalse || ping_exclude_zTXt == MagickFalse)
{
ResetImagePropertyIterator(image);
property=GetNextImageProperty(image);
while (property != (const char *) NULL)
{
png_textp
text;
value=GetImageProperty(image,property);
/* Don't write any "png:" or "jpeg:" properties; those are just for
* "identify" or for passing through to another JPEG
*/
if ((LocaleNCompare(property,"png:",4) != 0 &&
LocaleNCompare(property,"jpeg:",5) != 0) &&
/* Suppress density and units if we wrote a pHYs chunk */
(ping_exclude_pHYs != MagickFalse ||
LocaleCompare(property,"density") != 0 ||
LocaleCompare(property,"units") != 0) &&
/* Suppress the IM-generated Date:create and Date:modify */
(ping_exclude_date == MagickFalse ||
LocaleNCompare(property, "Date:",5) != 0))
{
if (value != (const char *) NULL)
{
#if PNG_LIBPNG_VER >= 10400
text=(png_textp) png_malloc(ping,
(png_alloc_size_t) sizeof(png_text));
#else
text=(png_textp) png_malloc(ping,(png_size_t) sizeof(png_text));
#endif
text[0].key=(char *) property;
text[0].text=(char *) value;
text[0].text_length=strlen(value);
if (ping_exclude_tEXt != MagickFalse)
text[0].compression=PNG_TEXT_COMPRESSION_zTXt;
else if (ping_exclude_zTXt != MagickFalse)
text[0].compression=PNG_TEXT_COMPRESSION_NONE;
else
{
text[0].compression=image_info->compression == NoCompression ||
(image_info->compression == UndefinedCompression &&
text[0].text_length < 128) ? PNG_TEXT_COMPRESSION_NONE :
PNG_TEXT_COMPRESSION_zTXt ;
}
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Setting up text chunk");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" keyword: '%s'",text[0].key);
}
png_set_text(ping,ping_info,text,1);
png_free(ping,text);
}
}
property=GetNextImageProperty(image);
}
}
/* write any PNG-chunk-e profiles */
(void) Magick_png_write_chunk_from_profile(image,"PNG-chunk-e",logging);
/* write exIf profile */
if (ping_have_eXIf != MagickFalse && ping_exclude_eXIf == MagickFalse)
{
char
*name;
ResetImageProfileIterator(image);
for (name=GetNextImageProfile(image); name != (const char *) NULL; )
{
if (LocaleCompare(name,"exif") == 0)
{
const StringInfo
*profile;
profile=GetImageProfile(image,name);
if (profile != (StringInfo *) NULL)
{
png_uint_32
length;
unsigned char
chunk[4],
*data;
StringInfo
*ping_profile;
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Have eXIf profile");
ping_profile=CloneStringInfo(profile);
data=GetStringInfoDatum(ping_profile),
length=(png_uint_32) GetStringInfoLength(ping_profile);
#if 0 /* eXIf chunk is registered */
PNGType(chunk,mng_eXIf);
#else /* eXIf chunk not yet registered; write exIf instead */
PNGType(chunk,mng_exIf);
#endif
if (length < 7)
break; /* othewise crashes */
/* skip the "Exif\0\0" JFIF Exif Header ID */
length -= 6;
LogPNGChunk(logging,chunk,length);
(void) WriteBlobMSBULong(image,length);
(void) WriteBlob(image,4,chunk);
(void) WriteBlob(image,length,data+6);
(void) WriteBlobMSBULong(image,crc32(crc32(0,chunk,4),
data+6, (uInt) length));
break;
}
}
name=GetNextImageProfile(image);
}
}
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Writing PNG end info");
png_write_end(ping,ping_info);
if (mng_info->need_fram && (int) image->dispose == BackgroundDispose)
{
if (mng_info->page.x || mng_info->page.y ||
(ping_width != mng_info->page.width) ||
(ping_height != mng_info->page.height))
{
unsigned char
chunk[32];
/*
Write FRAM 4 with clipping boundaries followed by FRAM 1.
*/
(void) WriteBlobMSBULong(image,27L); /* data length=27 */
PNGType(chunk,mng_FRAM);
LogPNGChunk(logging,mng_FRAM,27L);
chunk[4]=4;
chunk[5]=0; /* frame name separator (no name) */
chunk[6]=1; /* flag for changing delay, for next frame only */
chunk[7]=0; /* flag for changing frame timeout */
chunk[8]=1; /* flag for changing frame clipping for next frame */
chunk[9]=0; /* flag for changing frame sync_id */
PNGLong(chunk+10,(png_uint_32) (0L)); /* temporary 0 delay */
chunk[14]=0; /* clipping boundaries delta type */
PNGLong(chunk+15,(png_uint_32) (mng_info->page.x)); /* left cb */
PNGLong(chunk+19,
(png_uint_32) (mng_info->page.x + ping_width));
PNGLong(chunk+23,(png_uint_32) (mng_info->page.y)); /* top cb */
PNGLong(chunk+27,
(png_uint_32) (mng_info->page.y + ping_height));
(void) WriteBlob(image,31,chunk);
(void) WriteBlobMSBULong(image,crc32(0,chunk,31));
mng_info->old_framing_mode=4;
mng_info->framing_mode=1;
}
else
mng_info->framing_mode=3;
}
if (mng_info->write_mng && !mng_info->need_fram &&
((int) image->dispose == 3))
png_error(ping, "Cannot convert GIF with disposal method 3 to MNG-LC");
/*
Free PNG resources.
*/
png_destroy_write_struct(&ping,&ping_info);
pixel_info=RelinquishVirtualMemory(pixel_info);
/* Store bit depth actually written */
s[0]=(char) ping_bit_depth;
s[1]='\0';
(void) SetImageProperty(image,"png:bit-depth-written",s);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" exit WriteOnePNGImage()");
#ifdef IMPNG_SETJMP_NOT_THREAD_SAFE
UnlockSemaphoreInfo(ping_semaphore);
#endif
/* } for navigation to beginning of SETJMP-protected block. Revert to
* Throwing an Exception when an error occurs.
*/
return(MagickTrue);
/* End write one PNG image */
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% W r i t e P N G I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% WritePNGImage() writes a Portable Network Graphics (PNG) or
% Multiple-image Network Graphics (MNG) image file.
%
% MNG support written by Glenn Randers-Pehrson, glennrp@image...
%
% The format of the WritePNGImage method is:
%
% MagickBooleanType WritePNGImage(const ImageInfo *image_info,Image *image)
%
% A description of each parameter follows:
%
% o image_info: the image info.
%
% o image: The image.
%
% Returns MagickTrue on success, MagickFalse on failure.
%
% Communicating with the PNG encoder:
%
% While the datastream written is always in PNG format and normally would
% be given the "png" file extension, this method also writes the following
% pseudo-formats which are subsets of png:
%
% o PNG8: An 8-bit indexed PNG datastream is written. If the image has
% a depth greater than 8, the depth is reduced. If transparency
% is present, the tRNS chunk must only have values 0 and 255
% (i.e., transparency is binary: fully opaque or fully
% transparent). If other values are present they will be
% 50%-thresholded to binary transparency. If more than 256
% colors are present, they will be quantized to the 4-4-4-1,
% 3-3-3-1, or 3-3-2-1 palette. The underlying RGB color
% of any resulting fully-transparent pixels is changed to
% the image's background color.
%
% If you want better quantization or dithering of the colors
% or alpha than that, you need to do it before calling the
% PNG encoder. The pixels contain 8-bit indices even if
% they could be represented with 1, 2, or 4 bits. Grayscale
% images will be written as indexed PNG files even though the
% PNG grayscale type might be slightly more efficient. Please
% note that writing to the PNG8 format may result in loss
% of color and alpha data.
%
% o PNG24: An 8-bit per sample RGB PNG datastream is written. The tRNS
% chunk can be present to convey binary transparency by naming
% one of the colors as transparent. The only loss incurred
% is reduction of sample depth to 8. If the image has more
% than one transparent color, has semitransparent pixels, or
% has an opaque pixel with the same RGB components as the
% transparent color, an image is not written.
%
% o PNG32: An 8-bit per sample RGBA PNG is written. Partial
% transparency is permitted, i.e., the alpha sample for
% each pixel can have any value from 0 to 255. The alpha
% channel is present even if the image is fully opaque.
% The only loss in data is the reduction of the sample depth
% to 8.
%
% o PNG48: A 16-bit per sample RGB PNG datastream is written. The tRNS
% chunk can be present to convey binary transparency by naming
% one of the colors as transparent. If the image has more
% than one transparent color, has semitransparent pixels, or
% has an opaque pixel with the same RGB components as the
% transparent color, an image is not written.
%
% o PNG64: A 16-bit per sample RGBA PNG is written. Partial
% transparency is permitted, i.e., the alpha sample for
% each pixel can have any value from 0 to 65535. The alpha
% channel is present even if the image is fully opaque.
%
% o PNG00: A PNG that inherits its colortype and bit-depth from the input
% image, if the input was a PNG, is written. If these values
% cannot be found, or if the pixels have been changed in a way
% that makes this impossible, then "PNG00" falls back to the
% regular "PNG" format.
%
% o -define: For more precise control of the PNG output, you can use the
% Image options "png:bit-depth" and "png:color-type". These
% can be set from the commandline with "-define" and also
% from the application programming interfaces. The options
% are case-independent and are converted to lowercase before
% being passed to this encoder.
%
% png:color-type can be 0, 2, 3, 4, or 6.
%
% When png:color-type is 0 (Grayscale), png:bit-depth can
% be 1, 2, 4, 8, or 16.
%
% When png:color-type is 2 (RGB), png:bit-depth can
% be 8 or 16.
%
% When png:color-type is 3 (Indexed), png:bit-depth can
% be 1, 2, 4, or 8. This refers to the number of bits
% used to store the index. The color samples always have
% bit-depth 8 in indexed PNG files.
%
% When png:color-type is 4 (Gray-Matte) or 6 (RGB-Matte),
% png:bit-depth can be 8 or 16.
%
% If the image cannot be written without loss with the
% requested bit-depth and color-type, a PNG file will not
% be written, a warning will be issued, and the encoder will
% return MagickFalse.
%
% Since image encoders should not be responsible for the "heavy lifting",
% the user should make sure that ImageMagick has already reduced the
% image depth and number of colors and limit transparency to binary
% transparency prior to attempting to write the image with depth, color,
% or transparency limitations.
%
% To do: Enforce the previous paragraph.
%
% Note that another definition, "png:bit-depth-written" exists, but it
% is not intended for external use. It is only used internally by the
% PNG encoder to inform the JNG encoder of the depth of the alpha channel.
%
% It is possible to request that the PNG encoder write previously-formatted
% ancillary chunks in the output PNG file, using the "-profile" commandline
% option as shown below or by setting the profile via a programming
% interface:
%
% -profile PNG-chunk-x:<file>
%
% where x is a location flag and <file> is a file containing the chunk
% name in the first 4 bytes, then a colon (":"), followed by the chunk data.
% This encoder will compute the chunk length and CRC, so those must not
% be included in the file.
%
% "x" can be "b" (before PLTE), "m" (middle, i.e., between PLTE and IDAT),
% or "e" (end, i.e., after IDAT). If you want to write multiple chunks
% of the same type, then add a short unique string after the "x" to prevent
% subsequent profiles from overwriting the preceding ones, e.g.,
%
% -profile PNG-chunk-b01:file01 -profile PNG-chunk-b02:file02
%
% As of version 6.6.6 the following optimizations are always done:
%
% o 32-bit depth is reduced to 16.
% o 16-bit depth is reduced to 8 if all pixels contain samples whose
% high byte and low byte are identical.
% o Palette is sorted to remove unused entries and to put a
% transparent color first, if BUILD_PNG_PALETTE is defined.
% o Opaque matte channel is removed when writing an indexed PNG.
% o Grayscale images are reduced to 1, 2, or 4 bit depth if
% this can be done without loss and a larger bit depth N was not
% requested via the "-define png:bit-depth=N" option.
% o If matte channel is present but only one transparent color is
% present, RGB+tRNS is written instead of RGBA
% o Opaque matte channel is removed (or added, if color-type 4 or 6
% was requested when converting an opaque image).
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
*/
static MagickBooleanType WritePNGImage(const ImageInfo *image_info,Image *image)
{
MagickBooleanType
excluding,
logging,
status;
MngInfo
*mng_info;
const char
*value;
int
source;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
assert(image != (Image *) NULL);
assert(image->signature == MagickSignature);
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
logging=LogMagickEvent(CoderEvent,GetMagickModule(),"Enter WritePNGImage()");
/*
Allocate a MngInfo structure.
*/
mng_info=(MngInfo *) AcquireMagickMemory(sizeof(MngInfo));
if (mng_info == (MngInfo *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
/*
Initialize members of the MngInfo structure.
*/
(void) ResetMagickMemory(mng_info,0,sizeof(MngInfo));
mng_info->image=image;
mng_info->equal_backgrounds=MagickTrue;
/* See if user has requested a specific PNG subformat */
mng_info->write_png8=LocaleCompare(image_info->magick,"PNG8") == 0;
mng_info->write_png24=LocaleCompare(image_info->magick,"PNG24") == 0;
mng_info->write_png32=LocaleCompare(image_info->magick,"PNG32") == 0;
mng_info->write_png48=LocaleCompare(image_info->magick,"PNG48") == 0;
mng_info->write_png64=LocaleCompare(image_info->magick,"PNG64") == 0;
value=GetImageOption(image_info,"png:format");
if (value != (char *) NULL || LocaleCompare(image_info->magick,"PNG00") == 0)
{
mng_info->write_png8 = MagickFalse;
mng_info->write_png24 = MagickFalse;
mng_info->write_png32 = MagickFalse;
mng_info->write_png48 = MagickFalse;
mng_info->write_png64 = MagickFalse;
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Format=%s",value);
if (LocaleCompare(value,"png8") == 0)
mng_info->write_png8 = MagickTrue;
else if (LocaleCompare(value,"png24") == 0)
mng_info->write_png24 = MagickTrue;
else if (LocaleCompare(value,"png32") == 0)
mng_info->write_png32 = MagickTrue;
else if (LocaleCompare(value,"png48") == 0)
mng_info->write_png48 = MagickTrue;
else if (LocaleCompare(value,"png64") == 0)
mng_info->write_png64 = MagickTrue;
else if ((LocaleCompare(value,"png00") == 0) ||
LocaleCompare(image_info->magick,"PNG00") == 0)
{
/* Retrieve png:IHDR.bit-depth-orig and png:IHDR.color-type-orig */
value=GetImageProperty(image,"png:IHDR.bit-depth-orig");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" png00 inherited bit depth=%s",value);
if (value != (char *) NULL)
{
if (LocaleCompare(value,"1") == 0)
mng_info->write_png_depth = 1;
else if (LocaleCompare(value,"2") == 0)
mng_info->write_png_depth = 2;
else if (LocaleCompare(value,"4") == 0)
mng_info->write_png_depth = 4;
else if (LocaleCompare(value,"8") == 0)
mng_info->write_png_depth = 8;
else if (LocaleCompare(value,"16") == 0)
mng_info->write_png_depth = 16;
}
value=GetImageProperty(image,"png:IHDR.color-type-orig");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" png00 inherited color type=%s",value);
if (value != (char *) NULL)
{
if (LocaleCompare(value,"0") == 0)
mng_info->write_png_colortype = 1;
else if (LocaleCompare(value,"2") == 0)
mng_info->write_png_colortype = 3;
else if (LocaleCompare(value,"3") == 0)
mng_info->write_png_colortype = 4;
else if (LocaleCompare(value,"4") == 0)
mng_info->write_png_colortype = 5;
else if (LocaleCompare(value,"6") == 0)
mng_info->write_png_colortype = 7;
}
}
}
if (mng_info->write_png8)
{
mng_info->write_png_colortype = /* 3 */ 4;
mng_info->write_png_depth = 8;
image->depth = 8;
}
if (mng_info->write_png24)
{
mng_info->write_png_colortype = /* 2 */ 3;
mng_info->write_png_depth = 8;
image->depth = 8;
if (image->matte != MagickFalse)
(void) SetImageType(image,TrueColorMatteType);
else
(void) SetImageType(image,TrueColorType);
(void) SyncImage(image);
}
if (mng_info->write_png32)
{
mng_info->write_png_colortype = /* 6 */ 7;
mng_info->write_png_depth = 8;
image->depth = 8;
image->matte = MagickTrue;
(void) SetImageType(image,TrueColorMatteType);
(void) SyncImage(image);
}
if (mng_info->write_png48)
{
mng_info->write_png_colortype = /* 2 */ 3;
mng_info->write_png_depth = 16;
image->depth = 16;
if (image->matte != MagickFalse)
(void) SetImageType(image,TrueColorMatteType);
else
(void) SetImageType(image,TrueColorType);
(void) SyncImage(image);
}
if (mng_info->write_png64)
{
mng_info->write_png_colortype = /* 6 */ 7;
mng_info->write_png_depth = 16;
image->depth = 16;
image->matte = MagickTrue;
(void) SetImageType(image,TrueColorMatteType);
(void) SyncImage(image);
}
value=GetImageOption(image_info,"png:bit-depth");
if (value != (char *) NULL)
{
if (LocaleCompare(value,"1") == 0)
mng_info->write_png_depth = 1;
else if (LocaleCompare(value,"2") == 0)
mng_info->write_png_depth = 2;
else if (LocaleCompare(value,"4") == 0)
mng_info->write_png_depth = 4;
else if (LocaleCompare(value,"8") == 0)
mng_info->write_png_depth = 8;
else if (LocaleCompare(value,"16") == 0)
mng_info->write_png_depth = 16;
else
(void) ThrowMagickException(&image->exception,
GetMagickModule(),CoderWarning,
"ignoring invalid defined png:bit-depth",
"=%s",value);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" png:bit-depth=%d was defined.\n",mng_info->write_png_depth);
}
value=GetImageOption(image_info,"png:color-type");
if (value != (char *) NULL)
{
/* We must store colortype+1 because 0 is a valid colortype */
if (LocaleCompare(value,"0") == 0)
mng_info->write_png_colortype = 1;
else if (LocaleCompare(value,"2") == 0)
mng_info->write_png_colortype = 3;
else if (LocaleCompare(value,"3") == 0)
mng_info->write_png_colortype = 4;
else if (LocaleCompare(value,"4") == 0)
mng_info->write_png_colortype = 5;
else if (LocaleCompare(value,"6") == 0)
mng_info->write_png_colortype = 7;
else
(void) ThrowMagickException(&image->exception,
GetMagickModule(),CoderWarning,
"ignoring invalid defined png:color-type",
"=%s",value);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" png:color-type=%d was defined.\n",mng_info->write_png_colortype-1);
}
/* Check for chunks to be excluded:
*
* The default is to not exclude any known chunks except for any
* listed in the "unused_chunks" array, above.
*
* Chunks can be listed for exclusion via a "png:exclude-chunk"
* define (in the image properties or in the image artifacts)
* or via a mng_info member. For convenience, in addition
* to or instead of a comma-separated list of chunks, the
* "exclude-chunk" string can be simply "all" or "none".
*
* The exclude-chunk define takes priority over the mng_info.
*
* A "png:include-chunk" define takes priority over both the
* mng_info and the "png:exclude-chunk" define. Like the
* "exclude-chunk" string, it can define "all" or "none" as
* well as a comma-separated list. Chunks that are unknown to
* ImageMagick are always excluded, regardless of their "copy-safe"
* status according to the PNG specification, and even if they
* appear in the "include-chunk" list. Such defines appearing among
* the image options take priority over those found among the image
* artifacts.
*
* Finally, all chunks listed in the "unused_chunks" array are
* automatically excluded, regardless of the other instructions
* or lack thereof.
*
* if you exclude sRGB but not gAMA (recommended), then sRGB chunk
* will not be written and the gAMA chunk will only be written if it
* is not between .45 and .46, or approximately (1.0/2.2).
*
* If you exclude tRNS and the image has transparency, the colortype
* is forced to be 4 or 6 (GRAY_ALPHA or RGB_ALPHA).
*
* The -strip option causes StripImage() to set the png:include-chunk
* artifact to "none,trns,gama".
*/
mng_info->ping_exclude_bKGD=MagickFalse;
mng_info->ping_exclude_caNv=MagickFalse;
mng_info->ping_exclude_cHRM=MagickFalse;
mng_info->ping_exclude_date=MagickFalse;
mng_info->ping_exclude_eXIf=MagickFalse;
mng_info->ping_exclude_EXIF=MagickFalse; /* hex-encoded EXIF in zTXt */
mng_info->ping_exclude_gAMA=MagickFalse;
mng_info->ping_exclude_iCCP=MagickFalse;
/* mng_info->ping_exclude_iTXt=MagickFalse; */
mng_info->ping_exclude_oFFs=MagickFalse;
mng_info->ping_exclude_pHYs=MagickFalse;
mng_info->ping_exclude_sRGB=MagickFalse;
mng_info->ping_exclude_tEXt=MagickFalse;
mng_info->ping_exclude_tIME=MagickFalse;
mng_info->ping_exclude_tRNS=MagickFalse;
mng_info->ping_exclude_vpAg=MagickFalse;
mng_info->ping_exclude_zCCP=MagickFalse; /* hex-encoded iCCP in zTXt */
mng_info->ping_exclude_zTXt=MagickFalse;
mng_info->ping_preserve_colormap=MagickFalse;
value=GetImageOption(image_info,"png:preserve-colormap");
if (value == NULL)
value=GetImageArtifact(image,"png:preserve-colormap");
if (value != NULL)
mng_info->ping_preserve_colormap=MagickTrue;
mng_info->ping_preserve_iCCP=MagickFalse;
value=GetImageOption(image_info,"png:preserve-iCCP");
if (value == NULL)
value=GetImageArtifact(image,"png:preserve-iCCP");
if (value != NULL)
mng_info->ping_preserve_iCCP=MagickTrue;
/* These compression-level, compression-strategy, and compression-filter
* defines take precedence over values from the -quality option.
*/
value=GetImageOption(image_info,"png:compression-level");
if (value == NULL)
value=GetImageArtifact(image,"png:compression-level");
if (value != NULL)
{
/* To do: use a "LocaleInteger:()" function here. */
/* We have to add 1 to everything because 0 is a valid input,
* and we want to use 0 (the default) to mean undefined.
*/
if (LocaleCompare(value,"0") == 0)
mng_info->write_png_compression_level = 1;
else if (LocaleCompare(value,"1") == 0)
mng_info->write_png_compression_level = 2;
else if (LocaleCompare(value,"2") == 0)
mng_info->write_png_compression_level = 3;
else if (LocaleCompare(value,"3") == 0)
mng_info->write_png_compression_level = 4;
else if (LocaleCompare(value,"4") == 0)
mng_info->write_png_compression_level = 5;
else if (LocaleCompare(value,"5") == 0)
mng_info->write_png_compression_level = 6;
else if (LocaleCompare(value,"6") == 0)
mng_info->write_png_compression_level = 7;
else if (LocaleCompare(value,"7") == 0)
mng_info->write_png_compression_level = 8;
else if (LocaleCompare(value,"8") == 0)
mng_info->write_png_compression_level = 9;
else if (LocaleCompare(value,"9") == 0)
mng_info->write_png_compression_level = 10;
else
(void) ThrowMagickException(&image->exception,
GetMagickModule(),CoderWarning,
"ignoring invalid defined png:compression-level",
"=%s",value);
}
value=GetImageOption(image_info,"png:compression-strategy");
if (value == NULL)
value=GetImageArtifact(image,"png:compression-strategy");
if (value != NULL)
{
if (LocaleCompare(value,"0") == 0)
mng_info->write_png_compression_strategy = Z_DEFAULT_STRATEGY+1;
else if (LocaleCompare(value,"1") == 0)
mng_info->write_png_compression_strategy = Z_FILTERED+1;
else if (LocaleCompare(value,"2") == 0)
mng_info->write_png_compression_strategy = Z_HUFFMAN_ONLY+1;
else if (LocaleCompare(value,"3") == 0)
#ifdef Z_RLE /* Z_RLE was added to zlib-1.2.0 */
mng_info->write_png_compression_strategy = Z_RLE+1;
#else
mng_info->write_png_compression_strategy = Z_DEFAULT_STRATEGY+1;
#endif
else if (LocaleCompare(value,"4") == 0)
#ifdef Z_FIXED /* Z_FIXED was added to zlib-1.2.2.2 */
mng_info->write_png_compression_strategy = Z_FIXED+1;
#else
mng_info->write_png_compression_strategy = Z_DEFAULT_STRATEGY+1;
#endif
else
(void) ThrowMagickException(&image->exception,
GetMagickModule(),CoderWarning,
"ignoring invalid defined png:compression-strategy",
"=%s",value);
}
value=GetImageOption(image_info,"png:compression-filter");
if (value == NULL)
value=GetImageArtifact(image,"png:compression-filter");
if (value != NULL)
{
/* To do: combinations of filters allowed by libpng
* masks 0x08 through 0xf8
*
* Implement this as a comma-separated list of 0,1,2,3,4,5
* where 5 is a special case meaning PNG_ALL_FILTERS.
*/
if (LocaleCompare(value,"0") == 0)
mng_info->write_png_compression_filter = 1;
else if (LocaleCompare(value,"1") == 0)
mng_info->write_png_compression_filter = 2;
else if (LocaleCompare(value,"2") == 0)
mng_info->write_png_compression_filter = 3;
else if (LocaleCompare(value,"3") == 0)
mng_info->write_png_compression_filter = 4;
else if (LocaleCompare(value,"4") == 0)
mng_info->write_png_compression_filter = 5;
else if (LocaleCompare(value,"5") == 0)
mng_info->write_png_compression_filter = 6;
else
(void) ThrowMagickException(&image->exception,
GetMagickModule(),CoderWarning,
"ignoring invalid defined png:compression-filter",
"=%s",value);
}
for (source=0; source<8; source++)
{
value = NULL;
if (source == 0)
value=GetImageOption(image_info,"png:exclude-chunks");
if (source == 1)
value=GetImageArtifact(image,"png:exclude-chunks");
if (source == 2)
value=GetImageOption(image_info,"png:exclude-chunk");
if (source == 3)
value=GetImageArtifact(image,"png:exclude-chunk");
if (source == 4)
value=GetImageOption(image_info,"png:include-chunks");
if (source == 5)
value=GetImageArtifact(image,"png:include-chunks");
if (source == 6)
value=GetImageOption(image_info,"png:include-chunk");
if (source == 7)
value=GetImageArtifact(image,"png:include-chunk");
if (value == NULL)
continue;
if (source < 4)
excluding = MagickTrue;
else
excluding = MagickFalse;
if (logging != MagickFalse)
{
if (source == 0 || source == 2)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" png:exclude-chunk=%s found in image options.\n", value);
else if (source == 1 || source == 3)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" png:exclude-chunk=%s found in image artifacts.\n", value);
else if (source == 4 || source == 6)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" png:include-chunk=%s found in image options.\n", value);
else /* if (source == 5 || source == 7) */
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" png:include-chunk=%s found in image artifacts.\n", value);
}
if (IsOptionMember("all",value) != MagickFalse)
{
mng_info->ping_exclude_bKGD=excluding;
mng_info->ping_exclude_caNv=excluding;
mng_info->ping_exclude_cHRM=excluding;
mng_info->ping_exclude_date=excluding;
mng_info->ping_exclude_EXIF=excluding;
mng_info->ping_exclude_eXIf=excluding;
mng_info->ping_exclude_gAMA=excluding;
mng_info->ping_exclude_iCCP=excluding;
/* mng_info->ping_exclude_iTXt=excluding; */
mng_info->ping_exclude_oFFs=excluding;
mng_info->ping_exclude_pHYs=excluding;
mng_info->ping_exclude_sRGB=excluding;
mng_info->ping_exclude_tIME=excluding;
mng_info->ping_exclude_tEXt=excluding;
mng_info->ping_exclude_tRNS=excluding;
mng_info->ping_exclude_vpAg=excluding;
mng_info->ping_exclude_zCCP=excluding;
mng_info->ping_exclude_zTXt=excluding;
}
if (IsOptionMember("none",value) != MagickFalse)
{
mng_info->ping_exclude_bKGD=excluding != MagickFalse ? MagickFalse :
MagickTrue;
mng_info->ping_exclude_caNv=excluding != MagickFalse ? MagickFalse :
MagickTrue;
mng_info->ping_exclude_cHRM=excluding != MagickFalse ? MagickFalse :
MagickTrue;
mng_info->ping_exclude_date=excluding != MagickFalse ? MagickFalse :
MagickTrue;
mng_info->ping_exclude_eXIf=excluding != MagickFalse ? MagickFalse :
MagickTrue;
mng_info->ping_exclude_EXIF=excluding != MagickFalse ? MagickFalse :
MagickTrue;
mng_info->ping_exclude_gAMA=excluding != MagickFalse ? MagickFalse :
MagickTrue;
mng_info->ping_exclude_iCCP=excluding != MagickFalse ? MagickFalse :
MagickTrue;
/* mng_info->ping_exclude_iTXt=!excluding; */
mng_info->ping_exclude_oFFs=excluding != MagickFalse ? MagickFalse :
MagickTrue;
mng_info->ping_exclude_pHYs=excluding != MagickFalse ? MagickFalse :
MagickTrue;
mng_info->ping_exclude_sRGB=excluding != MagickFalse ? MagickFalse :
MagickTrue;
mng_info->ping_exclude_tEXt=excluding != MagickFalse ? MagickFalse :
MagickTrue;
mng_info->ping_exclude_tIME=excluding != MagickFalse ? MagickFalse :
MagickTrue;
mng_info->ping_exclude_tRNS=excluding != MagickFalse ? MagickFalse :
MagickTrue;
mng_info->ping_exclude_vpAg=excluding != MagickFalse ? MagickFalse :
MagickTrue;
mng_info->ping_exclude_zCCP=excluding != MagickFalse ? MagickFalse :
MagickTrue;
mng_info->ping_exclude_zTXt=excluding != MagickFalse ? MagickFalse :
MagickTrue;
}
if (IsOptionMember("bkgd",value) != MagickFalse)
mng_info->ping_exclude_bKGD=excluding;
if (IsOptionMember("caNv",value) != MagickFalse)
mng_info->ping_exclude_caNv=excluding;
if (IsOptionMember("chrm",value) != MagickFalse)
mng_info->ping_exclude_cHRM=excluding;
if (IsOptionMember("date",value) != MagickFalse)
mng_info->ping_exclude_date=excluding;
if (IsOptionMember("exif",value) != MagickFalse)
{
mng_info->ping_exclude_EXIF=excluding;
mng_info->ping_exclude_eXIf=excluding;
}
if (IsOptionMember("gama",value) != MagickFalse)
mng_info->ping_exclude_gAMA=excluding;
if (IsOptionMember("iccp",value) != MagickFalse)
mng_info->ping_exclude_iCCP=excluding;
#if 0
if (IsOptionMember("itxt",value) != MagickFalse)
mng_info->ping_exclude_iTXt=excluding;
#endif
if (IsOptionMember("offs",value) != MagickFalse)
mng_info->ping_exclude_oFFs=excluding;
if (IsOptionMember("phys",value) != MagickFalse)
mng_info->ping_exclude_pHYs=excluding;
if (IsOptionMember("srgb",value) != MagickFalse)
mng_info->ping_exclude_sRGB=excluding;
if (IsOptionMember("text",value) != MagickFalse)
mng_info->ping_exclude_tEXt=excluding;
if (IsOptionMember("time",value) != MagickFalse)
mng_info->ping_exclude_tIME=excluding;
if (IsOptionMember("trns",value) != MagickFalse)
mng_info->ping_exclude_tRNS=excluding;
if (IsOptionMember("vpag",value) != MagickFalse)
mng_info->ping_exclude_vpAg=excluding;
if (IsOptionMember("zccp",value) != MagickFalse)
mng_info->ping_exclude_zCCP=excluding;
if (IsOptionMember("ztxt",value) != MagickFalse)
mng_info->ping_exclude_zTXt=excluding;
}
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Chunks to be excluded from the output png:");
if (mng_info->ping_exclude_bKGD != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" bKGD");
if (mng_info->ping_exclude_caNv != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" caNv");
if (mng_info->ping_exclude_cHRM != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" cHRM");
if (mng_info->ping_exclude_date != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" date");
if (mng_info->ping_exclude_EXIF != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" EXIF");
if (mng_info->ping_exclude_eXIf != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" eXIf");
if (mng_info->ping_exclude_gAMA != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" gAMA");
if (mng_info->ping_exclude_iCCP != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" iCCP");
#if 0
if (mng_info->ping_exclude_iTXt != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" iTXt");
#endif
if (mng_info->ping_exclude_oFFs != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" oFFs");
if (mng_info->ping_exclude_pHYs != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" pHYs");
if (mng_info->ping_exclude_sRGB != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" sRGB");
if (mng_info->ping_exclude_tEXt != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" tEXt");
if (mng_info->ping_exclude_tIME != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" tIME");
if (mng_info->ping_exclude_tRNS != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" tRNS");
if (mng_info->ping_exclude_vpAg != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" vpAg");
if (mng_info->ping_exclude_zCCP != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" zCCP");
if (mng_info->ping_exclude_zTXt != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" zTXt");
}
mng_info->need_blob = MagickTrue;
status=WriteOnePNGImage(mng_info,image_info,image);
(void) CloseBlob(image);
mng_info=MngInfoFreeStruct(mng_info);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),"exit WritePNGImage()");
return(status);
}
#if defined(JNG_SUPPORTED)
/* Write one JNG image */
static MagickBooleanType WriteOneJNGImage(MngInfo *mng_info,
const ImageInfo *image_info,Image *image)
{
Image
*jpeg_image;
ImageInfo
*jpeg_image_info;
int
unique_filenames;
MagickBooleanType
logging,
status;
size_t
length;
unsigned char
*blob,
chunk[80],
*p;
unsigned int
jng_alpha_compression_method,
jng_alpha_sample_depth,
jng_color_type,
transparent;
size_t
jng_alpha_quality,
jng_quality;
logging=LogMagickEvent(CoderEvent,GetMagickModule(),
" Enter WriteOneJNGImage()");
blob=(unsigned char *) NULL;
jpeg_image=(Image *) NULL;
jpeg_image_info=(ImageInfo *) NULL;
length=0;
unique_filenames=0;
status=MagickTrue;
transparent=image_info->type==GrayscaleMatteType ||
image_info->type==TrueColorMatteType || image->matte != MagickFalse;
jng_alpha_sample_depth = 0;
jng_quality=image_info->quality == 0UL ? 75UL : image_info->quality%1000;
jng_alpha_compression_method=image->compression==JPEGCompression? 8 : 0;
jng_alpha_quality=image_info->quality == 0UL ? 75UL :
image_info->quality;
if (jng_alpha_quality >= 1000)
jng_alpha_quality /= 1000;
if (transparent != 0)
{
jng_color_type=14;
/* Create JPEG blob, image, and image_info */
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Creating jpeg_image_info for opacity.");
jpeg_image_info=(ImageInfo *) CloneImageInfo(image_info);
if (jpeg_image_info == (ImageInfo *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Creating jpeg_image.");
jpeg_image=CloneImage(image,0,0,MagickTrue,&image->exception);
if (jpeg_image == (Image *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
(void) CopyMagickString(jpeg_image->magick,"JPEG",MaxTextExtent);
status=SeparateImageChannel(jpeg_image,OpacityChannel);
if (status == MagickFalse)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
status=NegateImage(jpeg_image,MagickFalse);
if (status == MagickFalse)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
jpeg_image->matte=MagickFalse;
jpeg_image_info->type=GrayscaleType;
jpeg_image->quality=jng_alpha_quality;
(void) SetImageType(jpeg_image,GrayscaleType);
(void) AcquireUniqueFilename(jpeg_image->filename);
unique_filenames++;
(void) FormatLocaleString(jpeg_image_info->filename,MaxTextExtent,
"%s",jpeg_image->filename);
}
else
{
jng_alpha_compression_method=0;
jng_color_type=10;
jng_alpha_sample_depth=0;
}
/* To do: check bit depth of PNG alpha channel */
/* Check if image is grayscale. */
if (image_info->type != TrueColorMatteType && image_info->type !=
TrueColorType && SetImageGray(image,&image->exception))
jng_color_type-=2;
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" JNG Quality = %d",(int) jng_quality);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" JNG Color Type = %d",jng_color_type);
if (transparent != 0)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" JNG Alpha Compression = %d",jng_alpha_compression_method);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" JNG Alpha Depth = %d",jng_alpha_sample_depth);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" JNG Alpha Quality = %d",(int) jng_alpha_quality);
}
}
if (transparent != 0)
{
if (jng_alpha_compression_method==0)
{
const char
*value;
/* Encode opacity as a grayscale PNG blob */
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Creating PNG blob for alpha.");
status=OpenBlob(jpeg_image_info,jpeg_image,WriteBinaryBlobMode,
&image->exception);
if (status == MagickFalse)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
length=0;
(void) CopyMagickString(jpeg_image_info->magick,"PNG",MaxTextExtent);
(void) CopyMagickString(jpeg_image->magick,"PNG",MaxTextExtent);
jpeg_image_info->interlace=NoInterlace;
/* Exclude all ancillary chunks */
(void) SetImageArtifact(jpeg_image,"png:exclude-chunks","all");
blob=ImageToBlob(jpeg_image_info,jpeg_image,&length,
&image->exception);
/* Retrieve sample depth used */
value=GetImageProperty(jpeg_image,"png:bit-depth-written");
if (value != (char *) NULL)
jng_alpha_sample_depth= (unsigned int) value[0];
}
else
{
/* Encode opacity as a grayscale JPEG blob */
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Creating JPEG blob for alpha.");
status=OpenBlob(jpeg_image_info,jpeg_image,WriteBinaryBlobMode,
&image->exception);
if (status == MagickFalse)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
(void) CopyMagickString(jpeg_image_info->magick,"JPEG",MaxTextExtent);
(void) CopyMagickString(jpeg_image->magick,"JPEG",MaxTextExtent);
jpeg_image_info->interlace=NoInterlace;
blob=ImageToBlob(jpeg_image_info,jpeg_image,&length,
&image->exception);
jng_alpha_sample_depth=8;
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Successfully read jpeg_image into a blob, length=%.20g.",
(double) length);
}
/* Destroy JPEG image and image_info */
jpeg_image=DestroyImage(jpeg_image);
(void) RelinquishUniqueFileResource(jpeg_image_info->filename);
unique_filenames--;
jpeg_image_info=DestroyImageInfo(jpeg_image_info);
}
/* Write JHDR chunk */
(void) WriteBlobMSBULong(image,16L); /* chunk data length=16 */
PNGType(chunk,mng_JHDR);
LogPNGChunk(logging,mng_JHDR,16L);
PNGLong(chunk+4,(png_uint_32) image->columns);
PNGLong(chunk+8,(png_uint_32) image->rows);
chunk[12]=jng_color_type;
chunk[13]=8; /* sample depth */
chunk[14]=8; /*jng_image_compression_method */
chunk[15]=(unsigned char) (image_info->interlace == NoInterlace ? 0 : 8);
chunk[16]=jng_alpha_sample_depth;
chunk[17]=jng_alpha_compression_method;
chunk[18]=0; /*jng_alpha_filter_method */
chunk[19]=0; /*jng_alpha_interlace_method */
(void) WriteBlob(image,20,chunk);
(void) WriteBlobMSBULong(image,crc32(0,chunk,20));
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" JNG width:%15lu",(unsigned long) image->columns);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" JNG height:%14lu",(unsigned long) image->rows);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" JNG color type:%10d",jng_color_type);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" JNG sample depth:%8d",8);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" JNG compression:%9d",8);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" JNG interlace:%11d",0);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" JNG alpha depth:%9d",jng_alpha_sample_depth);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" JNG alpha compression:%3d",jng_alpha_compression_method);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" JNG alpha filter:%8d",0);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" JNG alpha interlace:%5d",0);
}
/* Write any JNG-chunk-b profiles */
(void) Magick_png_write_chunk_from_profile(image,"JNG-chunk-b",logging);
/*
Write leading ancillary chunks
*/
if (transparent != 0)
{
/*
Write JNG bKGD chunk
*/
unsigned char
blue,
green,
red;
ssize_t
num_bytes;
if (jng_color_type == 8 || jng_color_type == 12)
num_bytes=6L;
else
num_bytes=10L;
(void) WriteBlobMSBULong(image,(size_t) (num_bytes-4L));
PNGType(chunk,mng_bKGD);
LogPNGChunk(logging,mng_bKGD,(size_t) (num_bytes-4L));
red=ScaleQuantumToChar(image->background_color.red);
green=ScaleQuantumToChar(image->background_color.green);
blue=ScaleQuantumToChar(image->background_color.blue);
*(chunk+4)=0;
*(chunk+5)=red;
*(chunk+6)=0;
*(chunk+7)=green;
*(chunk+8)=0;
*(chunk+9)=blue;
(void) WriteBlob(image,(size_t) num_bytes,chunk);
(void) WriteBlobMSBULong(image,crc32(0,chunk,(uInt) num_bytes));
}
if ((image->colorspace == sRGBColorspace || image->rendering_intent))
{
/*
Write JNG sRGB chunk
*/
(void) WriteBlobMSBULong(image,1L);
PNGType(chunk,mng_sRGB);
LogPNGChunk(logging,mng_sRGB,1L);
if (image->rendering_intent != UndefinedIntent)
chunk[4]=(unsigned char)
Magick_RenderingIntent_to_PNG_RenderingIntent(
(image->rendering_intent));
else
chunk[4]=(unsigned char)
Magick_RenderingIntent_to_PNG_RenderingIntent(
(PerceptualIntent));
(void) WriteBlob(image,5,chunk);
(void) WriteBlobMSBULong(image,crc32(0,chunk,5));
}
else
{
if (image->gamma != 0.0)
{
/*
Write JNG gAMA chunk
*/
(void) WriteBlobMSBULong(image,4L);
PNGType(chunk,mng_gAMA);
LogPNGChunk(logging,mng_gAMA,4L);
PNGLong(chunk+4,(png_uint_32) (100000*image->gamma+0.5));
(void) WriteBlob(image,8,chunk);
(void) WriteBlobMSBULong(image,crc32(0,chunk,8));
}
if ((mng_info->equal_chrms == MagickFalse) &&
(image->chromaticity.red_primary.x != 0.0))
{
PrimaryInfo
primary;
/*
Write JNG cHRM chunk
*/
(void) WriteBlobMSBULong(image,32L);
PNGType(chunk,mng_cHRM);
LogPNGChunk(logging,mng_cHRM,32L);
primary=image->chromaticity.white_point;
PNGLong(chunk+4,(png_uint_32) (100000*primary.x+0.5));
PNGLong(chunk+8,(png_uint_32) (100000*primary.y+0.5));
primary=image->chromaticity.red_primary;
PNGLong(chunk+12,(png_uint_32) (100000*primary.x+0.5));
PNGLong(chunk+16,(png_uint_32) (100000*primary.y+0.5));
primary=image->chromaticity.green_primary;
PNGLong(chunk+20,(png_uint_32) (100000*primary.x+0.5));
PNGLong(chunk+24,(png_uint_32) (100000*primary.y+0.5));
primary=image->chromaticity.blue_primary;
PNGLong(chunk+28,(png_uint_32) (100000*primary.x+0.5));
PNGLong(chunk+32,(png_uint_32) (100000*primary.y+0.5));
(void) WriteBlob(image,36,chunk);
(void) WriteBlobMSBULong(image,crc32(0,chunk,36));
}
}
if (image->x_resolution && image->y_resolution && !mng_info->equal_physs)
{
/*
Write JNG pHYs chunk
*/
(void) WriteBlobMSBULong(image,9L);
PNGType(chunk,mng_pHYs);
LogPNGChunk(logging,mng_pHYs,9L);
if (image->units == PixelsPerInchResolution)
{
PNGLong(chunk+4,(png_uint_32)
(image->x_resolution*100.0/2.54+0.5));
PNGLong(chunk+8,(png_uint_32)
(image->y_resolution*100.0/2.54+0.5));
chunk[12]=1;
}
else
{
if (image->units == PixelsPerCentimeterResolution)
{
PNGLong(chunk+4,(png_uint_32)
(image->x_resolution*100.0+0.5));
PNGLong(chunk+8,(png_uint_32)
(image->y_resolution*100.0+0.5));
chunk[12]=1;
}
else
{
PNGLong(chunk+4,(png_uint_32) (image->x_resolution+0.5));
PNGLong(chunk+8,(png_uint_32) (image->y_resolution+0.5));
chunk[12]=0;
}
}
(void) WriteBlob(image,13,chunk);
(void) WriteBlobMSBULong(image,crc32(0,chunk,13));
}
if (mng_info->write_mng == 0 && (image->page.x || image->page.y))
{
/*
Write JNG oFFs chunk
*/
(void) WriteBlobMSBULong(image,9L);
PNGType(chunk,mng_oFFs);
LogPNGChunk(logging,mng_oFFs,9L);
PNGsLong(chunk+4,(ssize_t) (image->page.x));
PNGsLong(chunk+8,(ssize_t) (image->page.y));
chunk[12]=0;
(void) WriteBlob(image,13,chunk);
(void) WriteBlobMSBULong(image,crc32(0,chunk,13));
}
if (mng_info->write_mng == 0 && (image->page.width || image->page.height))
{
(void) WriteBlobMSBULong(image,9L); /* data length=8 */
PNGType(chunk,mng_vpAg);
LogPNGChunk(logging,mng_vpAg,9L);
PNGLong(chunk+4,(png_uint_32) image->page.width);
PNGLong(chunk+8,(png_uint_32) image->page.height);
chunk[12]=0; /* unit = pixels */
(void) WriteBlob(image,13,chunk);
(void) WriteBlobMSBULong(image,crc32(0,chunk,13));
}
if (transparent != 0)
{
if (jng_alpha_compression_method==0)
{
register ssize_t
i;
size_t
len;
/* Write IDAT chunk header */
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Write IDAT chunks from blob, length=%.20g.",(double)
length);
/* Copy IDAT chunks */
len=0;
p=blob+8;
for (i=8; i<(ssize_t) length; i+=len+12)
{
len=(size_t) (*p) << 24;
len|=(size_t) (*(p+1)) << 16;
len|=(size_t) (*(p+2)) << 8;
len|=(size_t) (*(p+3));
p+=4;
if (*(p)==73 && *(p+1)==68 && *(p+2)==65 && *(p+3)==84) /* IDAT */
{
/* Found an IDAT chunk. */
(void) WriteBlobMSBULong(image,len);
LogPNGChunk(logging,mng_IDAT,len);
(void) WriteBlob(image,len+4,p);
(void) WriteBlobMSBULong(image,crc32(0,p,(uInt) len+4));
}
else
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Skipping %c%c%c%c chunk, length=%.20g.",
*(p),*(p+1),*(p+2),*(p+3),(double) len);
}
p+=(8+len);
}
}
else if (length != 0)
{
/* Write JDAA chunk header */
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Write JDAA chunk, length=%.20g.",(double) length);
(void) WriteBlobMSBULong(image,(size_t) length);
PNGType(chunk,mng_JDAA);
LogPNGChunk(logging,mng_JDAA,length);
/* Write JDAT chunk(s) data */
(void) WriteBlob(image,4,chunk);
(void) WriteBlob(image,length,blob);
(void) WriteBlobMSBULong(image,crc32(crc32(0,chunk,4),blob,
(uInt) length));
}
blob=(unsigned char *) RelinquishMagickMemory(blob);
}
/* Encode image as a JPEG blob */
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Creating jpeg_image_info.");
jpeg_image_info=(ImageInfo *) CloneImageInfo(image_info);
if (jpeg_image_info == (ImageInfo *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Creating jpeg_image.");
jpeg_image=CloneImage(image,0,0,MagickTrue,&image->exception);
if (jpeg_image == (Image *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
(void) CopyMagickString(jpeg_image->magick,"JPEG",MaxTextExtent);
(void) AcquireUniqueFilename(jpeg_image->filename);
unique_filenames++;
(void) FormatLocaleString(jpeg_image_info->filename,MaxTextExtent,"%s",
jpeg_image->filename);
status=OpenBlob(jpeg_image_info,jpeg_image,WriteBinaryBlobMode,
&image->exception);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Created jpeg_image, %.20g x %.20g.",(double) jpeg_image->columns,
(double) jpeg_image->rows);
if (status == MagickFalse)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
if (jng_color_type == 8 || jng_color_type == 12)
jpeg_image_info->type=GrayscaleType;
jpeg_image_info->quality=jng_quality;
jpeg_image->quality=jng_quality;
(void) CopyMagickString(jpeg_image_info->magick,"JPEG",MaxTextExtent);
(void) CopyMagickString(jpeg_image->magick,"JPEG",MaxTextExtent);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Creating blob.");
blob=ImageToBlob(jpeg_image_info,jpeg_image,&length,&image->exception);
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Successfully read jpeg_image into a blob, length=%.20g.",
(double) length);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Write JDAT chunk, length=%.20g.",(double) length);
}
/* Write JDAT chunk(s) */
(void) WriteBlobMSBULong(image,(size_t) length);
PNGType(chunk,mng_JDAT);
LogPNGChunk(logging,mng_JDAT,length);
(void) WriteBlob(image,4,chunk);
(void) WriteBlob(image,length,blob);
(void) WriteBlobMSBULong(image,crc32(crc32(0,chunk,4),blob,(uInt) length));
jpeg_image=DestroyImage(jpeg_image);
(void) RelinquishUniqueFileResource(jpeg_image_info->filename);
unique_filenames--;
jpeg_image_info=DestroyImageInfo(jpeg_image_info);
blob=(unsigned char *) RelinquishMagickMemory(blob);
/* Write any JNG-chunk-e profiles */
(void) Magick_png_write_chunk_from_profile(image,"JNG-chunk-e",logging);
/* Write IEND chunk */
(void) WriteBlobMSBULong(image,0L);
PNGType(chunk,mng_IEND);
LogPNGChunk(logging,mng_IEND,0);
(void) WriteBlob(image,4,chunk);
(void) WriteBlobMSBULong(image,crc32(0,chunk,4));
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" exit WriteOneJNGImage(); unique_filenames=%d",unique_filenames);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% W r i t e J N G I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% WriteJNGImage() writes a JPEG Network Graphics (JNG) image file.
%
% JNG support written by Glenn Randers-Pehrson, glennrp@image...
%
% The format of the WriteJNGImage method is:
%
% MagickBooleanType WriteJNGImage(const ImageInfo *image_info,Image *image)
%
% A description of each parameter follows:
%
% o image_info: the image info.
%
% o image: The image.
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
*/
static MagickBooleanType WriteJNGImage(const ImageInfo *image_info,Image *image)
{
MagickBooleanType
logging,
status;
MngInfo
*mng_info;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
assert(image != (Image *) NULL);
assert(image->signature == MagickSignature);
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
logging=LogMagickEvent(CoderEvent,GetMagickModule(),"Enter WriteJNGImage()");
status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception);
if (status == MagickFalse)
return(status);
if ((image->columns > 65535UL) || (image->rows > 65535UL))
ThrowWriterException(ImageError,"WidthOrHeightExceedsLimit");
/*
Allocate a MngInfo structure.
*/
mng_info=(MngInfo *) AcquireMagickMemory(sizeof(MngInfo));
if (mng_info == (MngInfo *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
/*
Initialize members of the MngInfo structure.
*/
(void) ResetMagickMemory(mng_info,0,sizeof(MngInfo));
mng_info->image=image;
(void) WriteBlob(image,8,(const unsigned char *) "\213JNG\r\n\032\n");
status=WriteOneJNGImage(mng_info,image_info,image);
mng_info=MngInfoFreeStruct(mng_info);
(void) CloseBlob(image);
(void) CatchImageException(image);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" exit WriteJNGImage()");
return(status);
}
#endif
static MagickBooleanType WriteMNGImage(const ImageInfo *image_info,Image *image)
{
const char
*option;
Image
*next_image;
MagickBooleanType
status;
volatile MagickBooleanType
logging;
MngInfo
*mng_info;
int
image_count,
need_iterations,
need_matte;
volatile int
#if defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED) || \
defined(PNG_MNG_FEATURES_SUPPORTED)
need_local_plte,
#endif
all_images_are_gray,
need_defi,
use_global_plte;
register ssize_t
i;
unsigned char
chunk[800];
volatile unsigned int
write_jng,
write_mng;
volatile size_t
scene;
size_t
final_delay=0,
initial_delay;
#if (PNG_LIBPNG_VER < 10200)
if (image_info->verbose)
printf("Your PNG library (libpng-%s) is rather old.\n",
PNG_LIBPNG_VER_STRING);
#endif
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
assert(image != (Image *) NULL);
assert(image->signature == MagickSignature);
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
logging=LogMagickEvent(CoderEvent,GetMagickModule(),"Enter WriteMNGImage()");
status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception);
if (status == MagickFalse)
return(status);
/*
Allocate a MngInfo structure.
*/
mng_info=(MngInfo *) AcquireMagickMemory(sizeof(MngInfo));
if (mng_info == (MngInfo *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
/*
Initialize members of the MngInfo structure.
*/
(void) ResetMagickMemory(mng_info,0,sizeof(MngInfo));
mng_info->image=image;
write_mng=LocaleCompare(image_info->magick,"MNG") == 0;
/*
* See if user has requested a specific PNG subformat to be used
* for all of the PNGs in the MNG being written, e.g.,
*
* convert *.png png8:animation.mng
*
* To do: check -define png:bit_depth and png:color_type as well,
* or perhaps use mng:bit_depth and mng:color_type instead for
* global settings.
*/
mng_info->write_png8=LocaleCompare(image_info->magick,"PNG8") == 0;
mng_info->write_png24=LocaleCompare(image_info->magick,"PNG24") == 0;
mng_info->write_png32=LocaleCompare(image_info->magick,"PNG32") == 0;
write_jng=MagickFalse;
if (image_info->compression == JPEGCompression)
write_jng=MagickTrue;
mng_info->adjoin=image_info->adjoin &&
(GetNextImageInList(image) != (Image *) NULL) && write_mng;
if (logging != MagickFalse)
{
/* Log some info about the input */
Image
*p;
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Checking input image(s)\n"
" Image_info depth: %.20g, Type: %d",
(double) image_info->depth, image_info->type);
scene=0;
for (p=image; p != (Image *) NULL; p=GetNextImageInList(p))
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Scene: %.20g\n, Image depth: %.20g",
(double) scene++, (double) p->depth);
if (p->matte)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Matte: True");
else
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Matte: False");
if (p->storage_class == PseudoClass)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Storage class: PseudoClass");
else
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Storage class: DirectClass");
if (p->colors)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Number of colors: %.20g",(double) p->colors);
else
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Number of colors: unspecified");
if (mng_info->adjoin == MagickFalse)
break;
}
}
use_global_plte=MagickFalse;
all_images_are_gray=MagickFalse;
#ifdef PNG_WRITE_EMPTY_PLTE_SUPPORTED
need_local_plte=MagickTrue;
#endif
need_defi=MagickFalse;
need_matte=MagickFalse;
mng_info->framing_mode=1;
mng_info->old_framing_mode=1;
if (write_mng)
if (image_info->page != (char *) NULL)
{
/*
Determine image bounding box.
*/
SetGeometry(image,&mng_info->page);
(void) ParseMetaGeometry(image_info->page,&mng_info->page.x,
&mng_info->page.y,&mng_info->page.width,&mng_info->page.height);
}
if (write_mng)
{
unsigned int
need_geom;
unsigned short
red,
green,
blue;
mng_info->page=image->page;
need_geom=MagickTrue;
if (mng_info->page.width || mng_info->page.height)
need_geom=MagickFalse;
/*
Check all the scenes.
*/
initial_delay=image->delay;
need_iterations=MagickFalse;
mng_info->equal_chrms=image->chromaticity.red_primary.x != 0.0;
mng_info->equal_physs=MagickTrue,
mng_info->equal_gammas=MagickTrue;
mng_info->equal_srgbs=MagickTrue;
mng_info->equal_backgrounds=MagickTrue;
image_count=0;
#if defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED) || \
defined(PNG_MNG_FEATURES_SUPPORTED)
all_images_are_gray=MagickTrue;
mng_info->equal_palettes=MagickFalse;
need_local_plte=MagickFalse;
#endif
for (next_image=image; next_image != (Image *) NULL; )
{
if (need_geom)
{
if ((next_image->columns+next_image->page.x) > mng_info->page.width)
mng_info->page.width=next_image->columns+next_image->page.x;
if ((next_image->rows+next_image->page.y) > mng_info->page.height)
mng_info->page.height=next_image->rows+next_image->page.y;
}
if (next_image->page.x || next_image->page.y)
need_defi=MagickTrue;
if (next_image->matte)
need_matte=MagickTrue;
if ((int) next_image->dispose >= BackgroundDispose)
if (next_image->matte || next_image->page.x || next_image->page.y ||
((next_image->columns < mng_info->page.width) &&
(next_image->rows < mng_info->page.height)))
mng_info->need_fram=MagickTrue;
if (next_image->iterations)
need_iterations=MagickTrue;
final_delay=next_image->delay;
if (final_delay != initial_delay || final_delay > 1UL*
next_image->ticks_per_second)
mng_info->need_fram=1;
#if defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED) || \
defined(PNG_MNG_FEATURES_SUPPORTED)
/*
check for global palette possibility.
*/
if (image->matte != MagickFalse)
need_local_plte=MagickTrue;
if (need_local_plte == 0)
{
if (SetImageGray(image,&image->exception) == MagickFalse)
all_images_are_gray=MagickFalse;
mng_info->equal_palettes=PalettesAreEqual(image,next_image);
if (use_global_plte == 0)
use_global_plte=mng_info->equal_palettes;
need_local_plte=!mng_info->equal_palettes;
}
#endif
if (GetNextImageInList(next_image) != (Image *) NULL)
{
if (next_image->background_color.red !=
next_image->next->background_color.red ||
next_image->background_color.green !=
next_image->next->background_color.green ||
next_image->background_color.blue !=
next_image->next->background_color.blue)
mng_info->equal_backgrounds=MagickFalse;
if (next_image->gamma != next_image->next->gamma)
mng_info->equal_gammas=MagickFalse;
if (next_image->rendering_intent !=
next_image->next->rendering_intent)
mng_info->equal_srgbs=MagickFalse;
if ((next_image->units != next_image->next->units) ||
(next_image->x_resolution != next_image->next->x_resolution) ||
(next_image->y_resolution != next_image->next->y_resolution))
mng_info->equal_physs=MagickFalse;
if (mng_info->equal_chrms)
{
if (next_image->chromaticity.red_primary.x !=
next_image->next->chromaticity.red_primary.x ||
next_image->chromaticity.red_primary.y !=
next_image->next->chromaticity.red_primary.y ||
next_image->chromaticity.green_primary.x !=
next_image->next->chromaticity.green_primary.x ||
next_image->chromaticity.green_primary.y !=
next_image->next->chromaticity.green_primary.y ||
next_image->chromaticity.blue_primary.x !=
next_image->next->chromaticity.blue_primary.x ||
next_image->chromaticity.blue_primary.y !=
next_image->next->chromaticity.blue_primary.y ||
next_image->chromaticity.white_point.x !=
next_image->next->chromaticity.white_point.x ||
next_image->chromaticity.white_point.y !=
next_image->next->chromaticity.white_point.y)
mng_info->equal_chrms=MagickFalse;
}
}
image_count++;
next_image=GetNextImageInList(next_image);
}
if (image_count < 2)
{
mng_info->equal_backgrounds=MagickFalse;
mng_info->equal_chrms=MagickFalse;
mng_info->equal_gammas=MagickFalse;
mng_info->equal_srgbs=MagickFalse;
mng_info->equal_physs=MagickFalse;
use_global_plte=MagickFalse;
#ifdef PNG_WRITE_EMPTY_PLTE_SUPPORTED
need_local_plte=MagickTrue;
#endif
need_iterations=MagickFalse;
}
if (mng_info->need_fram == MagickFalse)
{
/*
Only certain framing rates 100/n are exactly representable without
the FRAM chunk but we'll allow some slop in VLC files
*/
if (final_delay == 0)
{
if (need_iterations != MagickFalse)
{
/*
It's probably a GIF with loop; don't run it *too* fast.
*/
if (mng_info->adjoin)
{
final_delay=10;
(void) ThrowMagickException(&image->exception,
GetMagickModule(),CoderWarning,
"input has zero delay between all frames; assuming",
" 10 cs `%s'","");
}
}
else
mng_info->ticks_per_second=0;
}
if (final_delay != 0)
mng_info->ticks_per_second=(png_uint_32)
(image->ticks_per_second/final_delay);
if (final_delay > 50)
mng_info->ticks_per_second=2;
if (final_delay > 75)
mng_info->ticks_per_second=1;
if (final_delay > 125)
mng_info->need_fram=MagickTrue;
if (need_defi && final_delay > 2 && (final_delay != 4) &&
(final_delay != 5) && (final_delay != 10) && (final_delay != 20) &&
(final_delay != 25) && (final_delay != 50) &&
(final_delay != (size_t) image->ticks_per_second))
mng_info->need_fram=MagickTrue; /* make it exact; cannot be VLC */
}
if (mng_info->need_fram != MagickFalse)
mng_info->ticks_per_second=1UL*image->ticks_per_second;
/*
If pseudocolor, we should also check to see if all the
palettes are identical and write a global PLTE if they are.
../glennrp Feb 99.
*/
/*
Write the MNG version 1.0 signature and MHDR chunk.
*/
(void) WriteBlob(image,8,(const unsigned char *) "\212MNG\r\n\032\n");
(void) WriteBlobMSBULong(image,28L); /* chunk data length=28 */
PNGType(chunk,mng_MHDR);
LogPNGChunk(logging,mng_MHDR,28L);
PNGLong(chunk+4,(png_uint_32) mng_info->page.width);
PNGLong(chunk+8,(png_uint_32) mng_info->page.height);
PNGLong(chunk+12,mng_info->ticks_per_second);
PNGLong(chunk+16,0L); /* layer count=unknown */
PNGLong(chunk+20,0L); /* frame count=unknown */
PNGLong(chunk+24,0L); /* play time=unknown */
if (write_jng)
{
if (need_matte)
{
if (need_defi || mng_info->need_fram || use_global_plte)
PNGLong(chunk+28,27L); /* simplicity=LC+JNG */
else
PNGLong(chunk+28,25L); /* simplicity=VLC+JNG */
}
else
{
if (need_defi || mng_info->need_fram || use_global_plte)
PNGLong(chunk+28,19L); /* simplicity=LC+JNG, no transparency */
else
PNGLong(chunk+28,17L); /* simplicity=VLC+JNG, no transparency */
}
}
else
{
if (need_matte)
{
if (need_defi || mng_info->need_fram || use_global_plte)
PNGLong(chunk+28,11L); /* simplicity=LC */
else
PNGLong(chunk+28,9L); /* simplicity=VLC */
}
else
{
if (need_defi || mng_info->need_fram || use_global_plte)
PNGLong(chunk+28,3L); /* simplicity=LC, no transparency */
else
PNGLong(chunk+28,1L); /* simplicity=VLC, no transparency */
}
}
(void) WriteBlob(image,32,chunk);
(void) WriteBlobMSBULong(image,crc32(0,chunk,32));
option=GetImageOption(image_info,"mng:need-cacheoff");
if (option != (const char *) NULL)
{
size_t
length;
/*
Write "nEED CACHEOFF" to turn playback caching off for streaming MNG.
*/
PNGType(chunk,mng_nEED);
length=CopyMagickString((char *) chunk+4,"CACHEOFF",20);
(void) WriteBlobMSBULong(image,(size_t) length);
LogPNGChunk(logging,mng_nEED,(size_t) length);
length+=4;
(void) WriteBlob(image,length,chunk);
(void) WriteBlobMSBULong(image,crc32(0,chunk,(uInt) length));
}
if ((GetPreviousImageInList(image) == (Image *) NULL) &&
(GetNextImageInList(image) != (Image *) NULL) &&
(image->iterations != 1))
{
/*
Write MNG TERM chunk
*/
(void) WriteBlobMSBULong(image,10L); /* data length=10 */
PNGType(chunk,mng_TERM);
LogPNGChunk(logging,mng_TERM,10L);
chunk[4]=3; /* repeat animation */
chunk[5]=0; /* show last frame when done */
PNGLong(chunk+6,(png_uint_32) (mng_info->ticks_per_second*
final_delay/MagickMax(image->ticks_per_second,1)));
if (image->iterations == 0)
PNGLong(chunk+10,PNG_UINT_31_MAX);
else
PNGLong(chunk+10,(png_uint_32) image->iterations);
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" TERM delay: %.20g",(double) (mng_info->ticks_per_second*
final_delay/MagickMax(image->ticks_per_second,1)));
if (image->iterations == 0)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" TERM iterations: %.20g",(double) PNG_UINT_31_MAX);
else
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Image iterations: %.20g",(double) image->iterations);
}
(void) WriteBlob(image,14,chunk);
(void) WriteBlobMSBULong(image,crc32(0,chunk,14));
}
/*
To do: check for cHRM+gAMA == sRGB, and write sRGB instead.
*/
if ((image->colorspace == sRGBColorspace || image->rendering_intent) &&
mng_info->equal_srgbs)
{
/*
Write MNG sRGB chunk
*/
(void) WriteBlobMSBULong(image,1L);
PNGType(chunk,mng_sRGB);
LogPNGChunk(logging,mng_sRGB,1L);
if (image->rendering_intent != UndefinedIntent)
chunk[4]=(unsigned char)
Magick_RenderingIntent_to_PNG_RenderingIntent(
(image->rendering_intent));
else
chunk[4]=(unsigned char)
Magick_RenderingIntent_to_PNG_RenderingIntent(
(PerceptualIntent));
(void) WriteBlob(image,5,chunk);
(void) WriteBlobMSBULong(image,crc32(0,chunk,5));
mng_info->have_write_global_srgb=MagickTrue;
}
else
{
if (image->gamma && mng_info->equal_gammas)
{
/*
Write MNG gAMA chunk
*/
(void) WriteBlobMSBULong(image,4L);
PNGType(chunk,mng_gAMA);
LogPNGChunk(logging,mng_gAMA,4L);
PNGLong(chunk+4,(png_uint_32) (100000*image->gamma+0.5));
(void) WriteBlob(image,8,chunk);
(void) WriteBlobMSBULong(image,crc32(0,chunk,8));
mng_info->have_write_global_gama=MagickTrue;
}
if (mng_info->equal_chrms)
{
PrimaryInfo
primary;
/*
Write MNG cHRM chunk
*/
(void) WriteBlobMSBULong(image,32L);
PNGType(chunk,mng_cHRM);
LogPNGChunk(logging,mng_cHRM,32L);
primary=image->chromaticity.white_point;
PNGLong(chunk+4,(png_uint_32) (100000*primary.x+0.5));
PNGLong(chunk+8,(png_uint_32) (100000*primary.y+0.5));
primary=image->chromaticity.red_primary;
PNGLong(chunk+12,(png_uint_32) (100000*primary.x+0.5));
PNGLong(chunk+16,(png_uint_32) (100000*primary.y+0.5));
primary=image->chromaticity.green_primary;
PNGLong(chunk+20,(png_uint_32) (100000*primary.x+0.5));
PNGLong(chunk+24,(png_uint_32) (100000*primary.y+0.5));
primary=image->chromaticity.blue_primary;
PNGLong(chunk+28,(png_uint_32) (100000*primary.x+0.5));
PNGLong(chunk+32,(png_uint_32) (100000*primary.y+0.5));
(void) WriteBlob(image,36,chunk);
(void) WriteBlobMSBULong(image,crc32(0,chunk,36));
mng_info->have_write_global_chrm=MagickTrue;
}
}
if (image->x_resolution && image->y_resolution && mng_info->equal_physs)
{
/*
Write MNG pHYs chunk
*/
(void) WriteBlobMSBULong(image,9L);
PNGType(chunk,mng_pHYs);
LogPNGChunk(logging,mng_pHYs,9L);
if (image->units == PixelsPerInchResolution)
{
PNGLong(chunk+4,(png_uint_32)
(image->x_resolution*100.0/2.54+0.5));
PNGLong(chunk+8,(png_uint_32)
(image->y_resolution*100.0/2.54+0.5));
chunk[12]=1;
}
else
{
if (image->units == PixelsPerCentimeterResolution)
{
PNGLong(chunk+4,(png_uint_32)
(image->x_resolution*100.0+0.5));
PNGLong(chunk+8,(png_uint_32)
(image->y_resolution*100.0+0.5));
chunk[12]=1;
}
else
{
PNGLong(chunk+4,(png_uint_32) (image->x_resolution+0.5));
PNGLong(chunk+8,(png_uint_32) (image->y_resolution+0.5));
chunk[12]=0;
}
}
(void) WriteBlob(image,13,chunk);
(void) WriteBlobMSBULong(image,crc32(0,chunk,13));
}
/*
Write MNG BACK chunk and global bKGD chunk, if the image is transparent
or does not cover the entire frame.
*/
if (write_mng && (image->matte || image->page.x > 0 ||
image->page.y > 0 || (image->page.width &&
(image->page.width+image->page.x < mng_info->page.width))
|| (image->page.height && (image->page.height+image->page.y
< mng_info->page.height))))
{
(void) WriteBlobMSBULong(image,6L);
PNGType(chunk,mng_BACK);
LogPNGChunk(logging,mng_BACK,6L);
red=ScaleQuantumToShort(image->background_color.red);
green=ScaleQuantumToShort(image->background_color.green);
blue=ScaleQuantumToShort(image->background_color.blue);
PNGShort(chunk+4,red);
PNGShort(chunk+6,green);
PNGShort(chunk+8,blue);
(void) WriteBlob(image,10,chunk);
(void) WriteBlobMSBULong(image,crc32(0,chunk,10));
if (mng_info->equal_backgrounds)
{
(void) WriteBlobMSBULong(image,6L);
PNGType(chunk,mng_bKGD);
LogPNGChunk(logging,mng_bKGD,6L);
(void) WriteBlob(image,10,chunk);
(void) WriteBlobMSBULong(image,crc32(0,chunk,10));
}
}
#ifdef PNG_WRITE_EMPTY_PLTE_SUPPORTED
if ((need_local_plte == MagickFalse) &&
(image->storage_class == PseudoClass) &&
(all_images_are_gray == MagickFalse))
{
size_t
data_length;
/*
Write MNG PLTE chunk
*/
data_length=3*image->colors;
(void) WriteBlobMSBULong(image,data_length);
PNGType(chunk,mng_PLTE);
LogPNGChunk(logging,mng_PLTE,data_length);
for (i=0; i < (ssize_t) image->colors; i++)
{
chunk[4+i*3]=ScaleQuantumToChar(image->colormap[i].red) & 0xff;
chunk[5+i*3]=ScaleQuantumToChar(image->colormap[i].green) & 0xff;
chunk[6+i*3]=ScaleQuantumToChar(image->colormap[i].blue) & 0xff;
}
(void) WriteBlob(image,data_length+4,chunk);
(void) WriteBlobMSBULong(image,crc32(0,chunk,(uInt) (data_length+4)));
mng_info->have_write_global_plte=MagickTrue;
}
#endif
}
scene=0;
mng_info->delay=0;
#if defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED) || \
defined(PNG_MNG_FEATURES_SUPPORTED)
mng_info->equal_palettes=MagickFalse;
#endif
do
{
if (mng_info->adjoin)
{
#if defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED) || \
defined(PNG_MNG_FEATURES_SUPPORTED)
/*
If we aren't using a global palette for the entire MNG, check to
see if we can use one for two or more consecutive images.
*/
if (need_local_plte && use_global_plte && !all_images_are_gray)
{
if (mng_info->IsPalette)
{
/*
When equal_palettes is true, this image has the same palette
as the previous PseudoClass image
*/
mng_info->have_write_global_plte=mng_info->equal_palettes;
mng_info->equal_palettes=PalettesAreEqual(image,image->next);
if (mng_info->equal_palettes && !mng_info->have_write_global_plte)
{
/*
Write MNG PLTE chunk
*/
size_t
data_length;
data_length=3*image->colors;
(void) WriteBlobMSBULong(image,data_length);
PNGType(chunk,mng_PLTE);
LogPNGChunk(logging,mng_PLTE,data_length);
for (i=0; i < (ssize_t) image->colors; i++)
{
chunk[4+i*3]=ScaleQuantumToChar(image->colormap[i].red);
chunk[5+i*3]=ScaleQuantumToChar(image->colormap[i].green);
chunk[6+i*3]=ScaleQuantumToChar(image->colormap[i].blue);
}
(void) WriteBlob(image,data_length+4,chunk);
(void) WriteBlobMSBULong(image,crc32(0,chunk,
(uInt) (data_length+4)));
mng_info->have_write_global_plte=MagickTrue;
}
}
else
mng_info->have_write_global_plte=MagickFalse;
}
#endif
if (need_defi)
{
ssize_t
previous_x,
previous_y;
if (scene != 0)
{
previous_x=mng_info->page.x;
previous_y=mng_info->page.y;
}
else
{
previous_x=0;
previous_y=0;
}
mng_info->page=image->page;
if ((mng_info->page.x != previous_x) ||
(mng_info->page.y != previous_y))
{
(void) WriteBlobMSBULong(image,12L); /* data length=12 */
PNGType(chunk,mng_DEFI);
LogPNGChunk(logging,mng_DEFI,12L);
chunk[4]=0; /* object 0 MSB */
chunk[5]=0; /* object 0 LSB */
chunk[6]=0; /* visible */
chunk[7]=0; /* abstract */
PNGLong(chunk+8,(png_uint_32) mng_info->page.x);
PNGLong(chunk+12,(png_uint_32) mng_info->page.y);
(void) WriteBlob(image,16,chunk);
(void) WriteBlobMSBULong(image,crc32(0,chunk,16));
}
}
}
mng_info->write_mng=write_mng;
if ((int) image->dispose >= 3)
mng_info->framing_mode=3;
if (mng_info->need_fram && mng_info->adjoin &&
((image->delay != mng_info->delay) ||
(mng_info->framing_mode != mng_info->old_framing_mode)))
{
if (image->delay == mng_info->delay)
{
/*
Write a MNG FRAM chunk with the new framing mode.
*/
(void) WriteBlobMSBULong(image,1L); /* data length=1 */
PNGType(chunk,mng_FRAM);
LogPNGChunk(logging,mng_FRAM,1L);
chunk[4]=(unsigned char) mng_info->framing_mode;
(void) WriteBlob(image,5,chunk);
(void) WriteBlobMSBULong(image,crc32(0,chunk,5));
}
else
{
/*
Write a MNG FRAM chunk with the delay.
*/
(void) WriteBlobMSBULong(image,10L); /* data length=10 */
PNGType(chunk,mng_FRAM);
LogPNGChunk(logging,mng_FRAM,10L);
chunk[4]=(unsigned char) mng_info->framing_mode;
chunk[5]=0; /* frame name separator (no name) */
chunk[6]=2; /* flag for changing default delay */
chunk[7]=0; /* flag for changing frame timeout */
chunk[8]=0; /* flag for changing frame clipping */
chunk[9]=0; /* flag for changing frame sync_id */
PNGLong(chunk+10,(png_uint_32)
((mng_info->ticks_per_second*
image->delay)/MagickMax(image->ticks_per_second,1)));
(void) WriteBlob(image,14,chunk);
(void) WriteBlobMSBULong(image,crc32(0,chunk,14));
mng_info->delay=(png_uint_32) image->delay;
}
mng_info->old_framing_mode=mng_info->framing_mode;
}
#if defined(JNG_SUPPORTED)
if (image_info->compression == JPEGCompression)
{
ImageInfo
*write_info;
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Writing JNG object.");
/* To do: specify the desired alpha compression method. */
write_info=CloneImageInfo(image_info);
write_info->compression=UndefinedCompression;
status=WriteOneJNGImage(mng_info,write_info,image);
write_info=DestroyImageInfo(write_info);
}
else
#endif
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Writing PNG object.");
mng_info->need_blob = MagickFalse;
mng_info->ping_preserve_colormap = MagickFalse;
/* We don't want any ancillary chunks written */
mng_info->ping_exclude_bKGD=MagickTrue;
mng_info->ping_exclude_caNv=MagickTrue;
mng_info->ping_exclude_cHRM=MagickTrue;
mng_info->ping_exclude_date=MagickTrue;
mng_info->ping_exclude_EXIF=MagickTrue;
mng_info->ping_exclude_eXIf=MagickTrue;
mng_info->ping_exclude_gAMA=MagickTrue;
mng_info->ping_exclude_iCCP=MagickTrue;
/* mng_info->ping_exclude_iTXt=MagickTrue; */
mng_info->ping_exclude_oFFs=MagickTrue;
mng_info->ping_exclude_pHYs=MagickTrue;
mng_info->ping_exclude_sRGB=MagickTrue;
mng_info->ping_exclude_tEXt=MagickTrue;
mng_info->ping_exclude_tRNS=MagickTrue;
mng_info->ping_exclude_vpAg=MagickTrue;
mng_info->ping_exclude_zCCP=MagickTrue;
mng_info->ping_exclude_zTXt=MagickTrue;
status=WriteOnePNGImage(mng_info,image_info,image);
}
if (status == MagickFalse)
{
mng_info=MngInfoFreeStruct(mng_info);
(void) CloseBlob(image);
return(MagickFalse);
}
(void) CatchImageException(image);
if (GetNextImageInList(image) == (Image *) NULL)
break;
image=SyncNextImageInList(image);
status=SetImageProgress(image,SaveImagesTag,scene++,
GetImageListLength(image));
if (status == MagickFalse)
break;
} while (mng_info->adjoin);
if (write_mng)
{
while (GetPreviousImageInList(image) != (Image *) NULL)
image=GetPreviousImageInList(image);
/*
Write the MEND chunk.
*/
(void) WriteBlobMSBULong(image,0x00000000L);
PNGType(chunk,mng_MEND);
LogPNGChunk(logging,mng_MEND,0L);
(void) WriteBlob(image,4,chunk);
(void) WriteBlobMSBULong(image,crc32(0,chunk,4));
}
/*
Relinquish resources.
*/
(void) CloseBlob(image);
mng_info=MngInfoFreeStruct(mng_info);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),"exit WriteMNGImage()");
return(MagickTrue);
}
#else /* PNG_LIBPNG_VER > 10011 */
static MagickBooleanType WritePNGImage(const ImageInfo *image_info,Image *image)
{
(void) image;
printf("Your PNG library is too old: You have libpng-%s\n",
PNG_LIBPNG_VER_STRING);
ThrowBinaryException(CoderError,"PNG library is too old",
image_info->filename);
}
static MagickBooleanType WriteMNGImage(const ImageInfo *image_info,Image *image)
{
return(WritePNGImage(image_info,image));
}
#endif /* PNG_LIBPNG_VER > 10011 */
#endif
| ./CrossVul/dataset_final_sorted/CWE-125/c/good_2612_0 |
crossvul-cpp_data_bad_501_1 | 404: Not Found | ./CrossVul/dataset_final_sorted/CWE-125/c/bad_501_1 |
crossvul-cpp_data_bad_394_0 | /* liblouis Braille Translation and Back-Translation Library
Based on the Linux screenreader BRLTTY, copyright (C) 1999-2006 by The
BRLTTY Team
Copyright (C) 2004, 2005, 2006 ViewPlus Technologies, Inc. www.viewplus.com
Copyright (C) 2004, 2005, 2006 JJB Software, Inc. www.jjb-software.com
Copyright (C) 2016 Mike Gray, American Printing House for the Blind
Copyright (C) 2016 Davy Kager, Dedicon
This file is part of liblouis.
liblouis 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.
liblouis 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 liblouis. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* @file
* @brief Translate to braille
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "internal.h"
/* additional bits in typebuf */
#define SYLLABLE_MARKER_1 0x2000
#define SYLLABLE_MARKER_2 0x4000
#define CAPSEMPH 0x8000
#define EMPHASIS 0x3fff // all typeform bits that can be used
/* bits for wordBuffer */
#define WORD_CHAR 0x00000001
#define WORD_RESET 0x00000002
#define WORD_STOP 0x00000004
#define WORD_WHOLE 0x00000008
typedef struct {
int size;
widechar **buffers;
int *inUse;
widechar *(*alloc)(int index, int length);
void (*free)(widechar *);
} StringBufferPool;
static widechar *
allocStringBuffer(int index, int length) {
return _lou_allocMem(alloc_passbuf, index, 0, length);
}
static const StringBufferPool *stringBufferPool = NULL;
static void
initStringBufferPool() {
static widechar *stringBuffers[MAXPASSBUF] = { NULL };
static int stringBuffersInUse[MAXPASSBUF] = { 0 };
StringBufferPool *pool = malloc(sizeof(StringBufferPool));
pool->size = MAXPASSBUF;
pool->buffers = stringBuffers;
pool->inUse = stringBuffersInUse;
pool->alloc = &allocStringBuffer;
pool->free = NULL;
stringBufferPool = pool;
}
static int
getStringBuffer(int length) {
int i;
for (i = 0; i < stringBufferPool->size; i++) {
if (!stringBufferPool->inUse[i]) {
stringBufferPool->buffers[i] = stringBufferPool->alloc(i, length);
stringBufferPool->inUse[i] = 1;
return i;
}
}
_lou_outOfMemory();
return -1;
}
static int
releaseStringBuffer(int idx) {
if (idx >= 0 && idx < stringBufferPool->size) {
int inUse = stringBufferPool->inUse[idx];
if (inUse && stringBufferPool->free)
stringBufferPool->free(stringBufferPool->buffers[idx]);
stringBufferPool->inUse[idx] = 0;
return inUse;
}
return 0;
}
typedef struct {
int bufferIndex;
const widechar *chars;
int length;
} InString;
typedef struct {
int bufferIndex;
widechar *chars;
int maxlength;
int length;
} OutString;
typedef struct {
int startMatch;
int startReplace;
int endReplace;
int endMatch;
} PassRuleMatch;
static int
putCharacter(widechar c, const TranslationTableHeader *table, int pos,
const InString *input, OutString *output, int *posMapping, int *cursorPosition,
int *cursorStatus);
static int
passDoTest(const TranslationTableHeader *table, int pos, const InString *input,
int transOpcode, const TranslationTableRule *transRule, int *passCharDots,
const widechar **passInstructions, int *passIC, PassRuleMatch *match,
TranslationTableRule **groupingRule, widechar *groupingOp);
static int
passDoAction(const TranslationTableHeader *table, const InString **input,
OutString *output, int *posMapping, int transOpcode,
const TranslationTableRule **transRule, int passCharDots,
const widechar *passInstructions, int passIC, int *pos, PassRuleMatch match,
int *cursorPosition, int *cursorStatus, TranslationTableRule *groupingRule,
widechar groupingOp);
static const TranslationTableRule **appliedRules;
static int maxAppliedRules;
static int appliedRulesCount;
static TranslationTableCharacter *
findCharOrDots(widechar c, int m, const TranslationTableHeader *table) {
/* Look up character or dot pattern in the appropriate
* table. */
static TranslationTableCharacter noChar = { 0, 0, 0, CTC_Space, 32, 32, 32 };
static TranslationTableCharacter noDots = { 0, 0, 0, CTC_Space, B16, B16, B16 };
TranslationTableCharacter *notFound;
TranslationTableCharacter *character;
TranslationTableOffset bucket;
unsigned long int makeHash = (unsigned long int)c % HASHNUM;
if (m == 0) {
bucket = table->characters[makeHash];
notFound = &noChar;
} else {
bucket = table->dots[makeHash];
notFound = &noDots;
}
while (bucket) {
character = (TranslationTableCharacter *)&table->ruleArea[bucket];
if (character->realchar == c) return character;
bucket = character->next;
}
notFound->realchar = notFound->uppercase = notFound->lowercase = c;
return notFound;
}
static int
checkAttr(const widechar c, const TranslationTableCharacterAttributes a, int m,
const TranslationTableHeader *table) {
static widechar prevc = 0;
static TranslationTableCharacterAttributes preva = 0;
if (c != prevc) {
preva = (findCharOrDots(c, m, table))->attributes;
prevc = c;
}
return ((preva & a) ? 1 : 0);
}
static int
checkAttr_safe(const InString *input, int pos,
const TranslationTableCharacterAttributes a, int m,
const TranslationTableHeader *table) {
return ((pos < input->length) ? checkAttr(input->chars[pos], a, m, table) : 0);
}
static int
findForPassRule(const TranslationTableHeader *table, int pos, int currentPass,
const InString *input, int *transOpcode, const TranslationTableRule **transRule,
int *transCharslen, int *passCharDots, widechar const **passInstructions,
int *passIC, PassRuleMatch *match, TranslationTableRule **groupingRule,
widechar *groupingOp) {
int save_transCharslen = *transCharslen;
const TranslationTableRule *save_transRule = *transRule;
TranslationTableOpcode save_transOpcode = *transOpcode;
TranslationTableOffset ruleOffset;
ruleOffset = table->forPassRules[currentPass];
*transCharslen = 0;
while (ruleOffset) {
*transRule = (TranslationTableRule *)&table->ruleArea[ruleOffset];
*transOpcode = (*transRule)->opcode;
if (passDoTest(table, pos, input, *transOpcode, *transRule, passCharDots,
passInstructions, passIC, match, groupingRule, groupingOp))
return 1;
ruleOffset = (*transRule)->charsnext;
}
*transCharslen = save_transCharslen;
*transRule = save_transRule;
*transOpcode = save_transOpcode;
return 0;
}
static int
compareChars(const widechar *address1, const widechar *address2, int count, int m,
const TranslationTableHeader *table) {
int k;
if (!count) return 0;
for (k = 0; k < count; k++)
if ((findCharOrDots(address1[k], m, table))->lowercase !=
(findCharOrDots(address2[k], m, table))->lowercase)
return 0;
return 1;
}
static int
makeCorrections(const TranslationTableHeader *table, const InString *input,
OutString *output, int *posMapping, formtype *typebuf, int *realInlen,
int *posIncremented, int *cursorPosition, int *cursorStatus) {
int pos;
int transOpcode;
const TranslationTableRule *transRule;
int transCharslen;
int passCharDots;
const widechar *passInstructions;
int passIC; /* Instruction counter */
PassRuleMatch patternMatch;
TranslationTableRule *groupingRule;
widechar groupingOp;
const InString *origInput = input;
if (!table->corrections) return 1;
pos = 0;
output->length = 0;
*posIncremented = 1;
_lou_resetPassVariables();
while (pos < input->length) {
int length = input->length - pos;
const TranslationTableCharacter *character =
findCharOrDots(input->chars[pos], 0, table);
const TranslationTableCharacter *character2;
int tryThis = 0;
if (!findForPassRule(table, pos, 0, input, &transOpcode, &transRule,
&transCharslen, &passCharDots, &passInstructions, &passIC,
&patternMatch, &groupingRule, &groupingOp))
while (tryThis < 3) {
TranslationTableOffset ruleOffset = 0;
unsigned long int makeHash = 0;
switch (tryThis) {
case 0:
if (!(length >= 2)) break;
makeHash = (unsigned long int)character->lowercase << 8;
character2 = findCharOrDots(input->chars[pos + 1], 0, table);
makeHash += (unsigned long int)character2->lowercase;
makeHash %= HASHNUM;
ruleOffset = table->forRules[makeHash];
break;
case 1:
if (!(length >= 1)) break;
length = 1;
ruleOffset = character->otherRules;
break;
case 2: /* No rule found */
transOpcode = CTO_Always;
ruleOffset = 0;
break;
}
while (ruleOffset) {
transRule = (TranslationTableRule *)&table->ruleArea[ruleOffset];
transOpcode = transRule->opcode;
transCharslen = transRule->charslen;
if (tryThis == 1 || (transCharslen <= length &&
compareChars(&transRule->charsdots[0],
&input->chars[pos], transCharslen,
0, table))) {
if (*posIncremented && transOpcode == CTO_Correct &&
passDoTest(table, pos, input, transOpcode, transRule,
&passCharDots, &passInstructions, &passIC,
&patternMatch, &groupingRule, &groupingOp)) {
tryThis = 4;
break;
}
}
ruleOffset = transRule->charsnext;
}
tryThis++;
}
*posIncremented = 1;
switch (transOpcode) {
case CTO_Always:
if (output->length >= output->maxlength) goto failure;
posMapping[output->length] = pos;
output->chars[output->length++] = input->chars[pos++];
break;
case CTO_Correct: {
const InString *inputBefore = input;
int posBefore = pos;
if (appliedRules != NULL && appliedRulesCount < maxAppliedRules)
appliedRules[appliedRulesCount++] = transRule;
if (!passDoAction(table, &input, output, posMapping, transOpcode, &transRule,
passCharDots, passInstructions, passIC, &pos, patternMatch,
cursorPosition, cursorStatus, groupingRule, groupingOp))
goto failure;
if (input->bufferIndex != inputBefore->bufferIndex &&
inputBefore->bufferIndex != origInput->bufferIndex)
releaseStringBuffer(inputBefore->bufferIndex);
if (pos == posBefore) *posIncremented = 0;
break;
}
default:
break;
}
}
{ // We have to transform typebuf accordingly
int k;
formtype *typebuf_temp;
if ((typebuf_temp = malloc(output->length * sizeof(formtype))) == NULL)
_lou_outOfMemory();
for (k = 0; k < output->length; k++)
// posMapping will never be < 0 but in theory it could
if (posMapping[k] < 0)
typebuf_temp[k] = typebuf[0]; // prepend to next
else if (posMapping[k] >= input->length)
typebuf_temp[k] = typebuf[input->length - 1]; // append to previous
else
typebuf_temp[k] = typebuf[posMapping[k]];
memcpy(typebuf, typebuf_temp, output->length * sizeof(formtype));
free(typebuf_temp);
}
failure:
*realInlen = pos;
if (input->bufferIndex != origInput->bufferIndex)
releaseStringBuffer(input->bufferIndex);
return 1;
}
static int
matchCurrentInput(
const InString *input, int pos, const widechar *passInstructions, int passIC) {
int k;
int kk = pos;
for (k = passIC + 2; k < passIC + 2 + passInstructions[passIC + 1]; k++)
if (input->chars[kk] == ENDSEGMENT || passInstructions[k] != input->chars[kk++])
return 0;
return 1;
}
static int
swapTest(int swapIC, int *pos, const TranslationTableHeader *table, const InString *input,
const widechar *passInstructions) {
int p = *pos;
TranslationTableOffset swapRuleOffset;
TranslationTableRule *swapRule;
swapRuleOffset = (passInstructions[swapIC + 1] << 16) | passInstructions[swapIC + 2];
swapRule = (TranslationTableRule *)&table->ruleArea[swapRuleOffset];
while (p - *pos < passInstructions[swapIC + 3]) {
int test;
if (swapRule->opcode == CTO_SwapDd) {
for (test = 1; test < swapRule->charslen; test += 2) {
if (input->chars[p] == swapRule->charsdots[test]) break;
}
} else {
for (test = 0; test < swapRule->charslen; test++) {
if (input->chars[p] == swapRule->charsdots[test]) break;
}
}
if (test >= swapRule->charslen) return 0;
p++;
}
if (passInstructions[swapIC + 3] == passInstructions[swapIC + 4]) {
*pos = p;
return 1;
}
while (p - *pos < passInstructions[swapIC + 4]) {
int test;
if (swapRule->opcode == CTO_SwapDd) {
for (test = 1; test < swapRule->charslen; test += 2) {
if (input->chars[p] == swapRule->charsdots[test]) break;
}
} else {
for (test = 0; test < swapRule->charslen; test++) {
if (input->chars[p] == swapRule->charsdots[test]) break;
}
}
if (test >= swapRule->charslen) {
*pos = p;
return 1;
}
p++;
}
*pos = p;
return 1;
}
static int
swapReplace(int start, int end, const TranslationTableHeader *table,
const InString *input, OutString *output, int *posMapping,
const widechar *passInstructions, int passIC) {
TranslationTableOffset swapRuleOffset;
TranslationTableRule *swapRule;
widechar *replacements;
int p;
swapRuleOffset = (passInstructions[passIC + 1] << 16) | passInstructions[passIC + 2];
swapRule = (TranslationTableRule *)&table->ruleArea[swapRuleOffset];
replacements = &swapRule->charsdots[swapRule->charslen];
for (p = start; p < end; p++) {
int rep;
int test;
int k;
if (swapRule->opcode == CTO_SwapDd) {
// A sequence of dot patterns is encoded as the length of the first dot
// pattern (single widechar) followed by the contents of the first dot pattern
// (one widechar per cell) followed by the length of the second dot pattern,
// etc. See the function `compileSwapDots'. Because the third operand of a
// swapdd rule can only contain single-cell dot patterns, the elements at
// index 0, 2, ... are "1" and the elements at index 1, 3, ... are the dot
// patterns.
for (test = 0; test * 2 + 1 < swapRule->charslen; test++)
if (input->chars[p] == swapRule->charsdots[test * 2 + 1]) break;
if (test * 2 == swapRule->charslen) continue;
} else {
for (test = 0; test < swapRule->charslen; test++)
if (input->chars[p] == swapRule->charsdots[test]) break;
if (test == swapRule->charslen) continue;
}
k = 0;
for (rep = 0; rep < test; rep++)
if (swapRule->opcode == CTO_SwapCc)
k++;
else
k += replacements[k];
if (swapRule->opcode == CTO_SwapCc) {
if ((output->length + 1) > output->maxlength) return 0;
posMapping[output->length] = p;
output->chars[output->length++] = replacements[k];
} else {
int l = replacements[k] - 1;
int d = output->length + l;
if (d > output->maxlength) return 0;
while (--d >= output->length) posMapping[d] = p;
memcpy(&output->chars[output->length], &replacements[k + 1],
l * sizeof(*output->chars));
output->length += l;
}
}
return 1;
}
static int
replaceGrouping(const TranslationTableHeader *table, const InString **input,
OutString *output, int transOpcode, int passCharDots,
const widechar *passInstructions, int passIC, int startReplace,
TranslationTableRule *groupingRule, widechar groupingOp) {
widechar startCharDots = groupingRule->charsdots[2 * passCharDots];
widechar endCharDots = groupingRule->charsdots[2 * passCharDots + 1];
int p;
int level = 0;
TranslationTableOffset replaceOffset =
passInstructions[passIC + 1] << 16 | (passInstructions[passIC + 2] & 0xff);
TranslationTableRule *replaceRule =
(TranslationTableRule *)&table->ruleArea[replaceOffset];
widechar replaceStart = replaceRule->charsdots[2 * passCharDots];
widechar replaceEnd = replaceRule->charsdots[2 * passCharDots + 1];
if (groupingOp == pass_groupstart) {
for (p = startReplace + 1; p < (*input)->length; p++) {
if ((*input)->chars[p] == startCharDots) level--;
if ((*input)->chars[p] == endCharDots) level++;
if (level == 1) break;
}
if (p == (*input)->length)
return 0;
else {
// Create a new string instead of modifying it. This is slightly less
// efficient, but makes the code more readable. Grouping is not a much used
// feature anyway.
int idx = getStringBuffer((*input)->length);
widechar *chars = stringBufferPool->buffers[idx];
memcpy(chars, (*input)->chars, (*input)->length * sizeof(widechar));
chars[startReplace] = replaceStart;
chars[p] = replaceEnd;
*input = &(InString){
.chars = chars, .length = (*input)->length, .bufferIndex = idx
};
}
} else {
if (transOpcode == CTO_Context) {
startCharDots = groupingRule->charsdots[2];
endCharDots = groupingRule->charsdots[3];
replaceStart = replaceRule->charsdots[2];
replaceEnd = replaceRule->charsdots[3];
}
output->chars[output->length] = replaceEnd;
for (p = output->length - 1; p >= 0; p--) {
if (output->chars[p] == endCharDots) level--;
if (output->chars[p] == startCharDots) level++;
if (level == 1) break;
}
if (p < 0) return 0;
output->chars[p] = replaceStart;
output->length++;
}
return 1;
}
static int
removeGrouping(const InString **input, OutString *output, int passCharDots,
int startReplace, TranslationTableRule *groupingRule, widechar groupingOp) {
widechar startCharDots = groupingRule->charsdots[2 * passCharDots];
widechar endCharDots = groupingRule->charsdots[2 * passCharDots + 1];
int p;
int level = 0;
if (groupingOp == pass_groupstart) {
for (p = startReplace + 1; p < (*input)->length; p++) {
if ((*input)->chars[p] == startCharDots) level--;
if ((*input)->chars[p] == endCharDots) level++;
if (level == 1) break;
}
if (p == (*input)->length)
return 0;
else {
// Create a new string instead of modifying it. This is slightly less
// efficient, but makes the code more readable. Grouping is not a much used
// feature anyway.
int idx = getStringBuffer((*input)->length);
widechar *chars = stringBufferPool->buffers[idx];
int len = 0;
int k;
for (k = 0; k < (*input)->length; k++) {
if (k == p) continue;
chars[len++] = (*input)->chars[k];
}
*input = &(InString){.chars = chars, .length = len, .bufferIndex = idx };
}
} else {
for (p = output->length - 1; p >= 0; p--) {
if (output->chars[p] == endCharDots) level--;
if (output->chars[p] == startCharDots) level++;
if (level == 1) break;
}
if (p < 0) return 0;
p++;
for (; p < output->length; p++) output->chars[p - 1] = output->chars[p];
output->length--;
}
return 1;
}
static int
doPassSearch(const TranslationTableHeader *table, const InString *input,
const TranslationTableRule *transRule, int passCharDots, int pos,
const widechar *passInstructions, int passIC, int *searchIC, int *searchPos,
TranslationTableRule *groupingRule, widechar groupingOp) {
int level = 0;
int k, kk;
int not = 0; // whether next operand should be reversed
TranslationTableOffset ruleOffset;
TranslationTableRule *rule;
TranslationTableCharacterAttributes attributes;
while (pos < input->length) {
*searchIC = passIC + 1;
*searchPos = pos;
while (*searchIC < transRule->dotslen) {
int itsTrue = 1; // whether we have a match or not
if (*searchPos > input->length) return 0;
switch (passInstructions[*searchIC]) {
case pass_lookback:
*searchPos -= passInstructions[*searchIC + 1];
if (*searchPos < 0) {
*searchPos = 0;
itsTrue = 0;
}
*searchIC += 2;
break;
case pass_not:
not = !not;
(*searchIC)++;
continue;
case pass_string:
case pass_dots:
kk = *searchPos;
for (k = *searchIC + 2;
k < *searchIC + 2 + passInstructions[*searchIC + 1]; k++)
if (input->chars[kk] == ENDSEGMENT ||
passInstructions[k] != input->chars[kk++]) {
itsTrue = 0;
break;
}
*searchPos += passInstructions[*searchIC + 1];
*searchIC += passInstructions[*searchIC + 1] + 2;
break;
case pass_startReplace:
(*searchIC)++;
break;
case pass_endReplace:
(*searchIC)++;
break;
case pass_attributes:
attributes = (passInstructions[*searchIC + 1] << 16) |
passInstructions[*searchIC + 2];
for (k = 0; k < passInstructions[*searchIC + 3]; k++) {
if (input->chars[*searchPos] == ENDSEGMENT)
itsTrue = 0;
else {
itsTrue = ((findCharOrDots(input->chars[(*searchPos)++],
passCharDots,
table)->attributes &
attributes)
? 1
: 0);
if (not) itsTrue = !itsTrue;
}
if (!itsTrue) break;
}
if (itsTrue) {
for (k = passInstructions[*searchIC + 3];
k < passInstructions[*searchIC + 4]; k++) {
if (input->chars[*searchPos] == ENDSEGMENT) {
itsTrue = 0;
break;
}
if (!(findCharOrDots(input->chars[*searchPos], passCharDots,
table)->attributes &
attributes)) {
if (!not) break;
} else if (not)
break;
(*searchPos)++;
}
}
not = 0;
*searchIC += 5;
break;
case pass_groupstart:
case pass_groupend:
ruleOffset = (passInstructions[*searchIC + 1] << 16) |
passInstructions[*searchIC + 2];
rule = (TranslationTableRule *)&table->ruleArea[ruleOffset];
if (passInstructions[*searchIC] == pass_groupstart)
itsTrue = (input->chars[*searchPos] ==
rule->charsdots[2 * passCharDots])
? 1
: 0;
else
itsTrue = (input->chars[*searchPos] ==
rule->charsdots[2 * passCharDots + 1])
? 1
: 0;
if (groupingRule != NULL && groupingOp == pass_groupstart &&
rule == groupingRule) {
if (input->chars[*searchPos] == rule->charsdots[2 * passCharDots])
level--;
else if (input->chars[*searchPos] ==
rule->charsdots[2 * passCharDots + 1])
level++;
}
(*searchPos)++;
*searchIC += 3;
break;
case pass_swap:
itsTrue = swapTest(*searchIC, searchPos, table, input, passInstructions);
*searchIC += 5;
break;
case pass_endTest:
if (itsTrue) {
if ((groupingRule && level == 1) || !groupingRule) return 1;
}
*searchIC = transRule->dotslen;
break;
default:
if (_lou_handlePassVariableTest(passInstructions, searchIC, &itsTrue))
break;
break;
}
if ((!not&&!itsTrue) || (not&&itsTrue)) break;
not = 0;
}
pos++;
}
return 0;
}
static int
passDoTest(const TranslationTableHeader *table, int pos, const InString *input,
int transOpcode, const TranslationTableRule *transRule, int *passCharDots,
widechar const **passInstructions, int *passIC, PassRuleMatch *match,
TranslationTableRule **groupingRule, widechar *groupingOp) {
int searchIC, searchPos;
int k;
int not = 0; // whether next operand should be reversed
TranslationTableOffset ruleOffset = 0;
TranslationTableRule *rule = NULL;
TranslationTableCharacterAttributes attributes = 0;
int startMatch = pos;
int endMatch = pos;
int startReplace = -1;
int endReplace = -1;
*groupingRule = NULL;
*passInstructions = &transRule->charsdots[transRule->charslen];
*passIC = 0;
if (transOpcode == CTO_Context || transOpcode == CTO_Correct)
*passCharDots = 0;
else
*passCharDots = 1;
while (*passIC < transRule->dotslen) {
int itsTrue = 1; // whether we have a match or not
if (pos > input->length) return 0;
switch ((*passInstructions)[*passIC]) {
case pass_first:
if (pos != 0) itsTrue = 0;
(*passIC)++;
break;
case pass_last:
if (pos != input->length) itsTrue = 0;
(*passIC)++;
break;
case pass_lookback:
pos -= (*passInstructions)[*passIC + 1];
if (pos < 0) {
searchPos = 0;
itsTrue = 0;
}
*passIC += 2;
break;
case pass_not:
not = !not;
(*passIC)++;
continue;
case pass_string:
case pass_dots:
itsTrue = matchCurrentInput(input, pos, *passInstructions, *passIC);
pos += (*passInstructions)[*passIC + 1];
*passIC += (*passInstructions)[*passIC + 1] + 2;
break;
case pass_startReplace:
startReplace = pos;
(*passIC)++;
break;
case pass_endReplace:
endReplace = pos;
(*passIC)++;
break;
case pass_attributes:
attributes = ((*passInstructions)[*passIC + 1] << 16) |
(*passInstructions)[*passIC + 2];
for (k = 0; k < (*passInstructions)[*passIC + 3]; k++) {
if (pos >= input->length) {
itsTrue = 0;
break;
}
if (input->chars[pos] == ENDSEGMENT) {
itsTrue = 0;
break;
}
if (!(findCharOrDots(input->chars[pos], *passCharDots,
table)->attributes &
attributes)) {
if (!not) {
itsTrue = 0;
break;
}
} else if (not) {
itsTrue = 0;
break;
}
pos++;
}
if (itsTrue) {
for (k = (*passInstructions)[*passIC + 3];
k < (*passInstructions)[*passIC + 4] && pos < input->length;
k++) {
if (input->chars[pos] == ENDSEGMENT) {
itsTrue = 0;
break;
}
if (!(findCharOrDots(input->chars[pos], *passCharDots,
table)->attributes &
attributes)) {
if (!not) break;
} else if (not)
break;
pos++;
}
}
not = 0;
*passIC += 5;
break;
case pass_groupstart:
case pass_groupend:
ruleOffset = ((*passInstructions)[*passIC + 1] << 16) |
(*passInstructions)[*passIC + 2];
rule = (TranslationTableRule *)&table->ruleArea[ruleOffset];
if (*passIC == 0 ||
(*passIC > 0 &&
(*passInstructions)[*passIC - 1] == pass_startReplace)) {
*groupingRule = rule;
*groupingOp = (*passInstructions)[*passIC];
}
if ((*passInstructions)[*passIC] == pass_groupstart)
itsTrue =
(input->chars[pos] == rule->charsdots[2 * *passCharDots]) ? 1 : 0;
else
itsTrue = (input->chars[pos] == rule->charsdots[2 * *passCharDots + 1])
? 1
: 0;
pos++;
*passIC += 3;
break;
case pass_swap:
itsTrue = swapTest(*passIC, &pos, table, input, *passInstructions);
*passIC += 5;
break;
case pass_search:
itsTrue = doPassSearch(table, input, transRule, *passCharDots, pos,
*passInstructions, *passIC, &searchIC, &searchPos, *groupingRule,
*groupingOp);
if ((!not&&!itsTrue) || (not&&itsTrue)) return 0;
*passIC = searchIC;
pos = searchPos;
case pass_endTest:
(*passIC)++;
endMatch = pos;
if (startReplace == -1) {
startReplace = startMatch;
endReplace = endMatch;
}
*match = (PassRuleMatch){.startMatch = startMatch,
.startReplace = startReplace,
.endReplace = endReplace,
.endMatch = endMatch };
return 1;
break;
default:
if (_lou_handlePassVariableTest(*passInstructions, passIC, &itsTrue)) break;
return 0;
}
if ((!not&&!itsTrue) || (not&&itsTrue)) return 0;
not = 0;
}
return 0;
}
static int
copyCharacters(int from, int to, const TranslationTableHeader *table,
const InString *input, OutString *output, int *posMapping, int transOpcode,
int *cursorPosition, int *cursorStatus) {
if (transOpcode == CTO_Context) {
while (from < to) {
if (!putCharacter(input->chars[from], table, from, input, output, posMapping,
cursorPosition, cursorStatus))
return 0;
from++;
}
} else {
if (to > from) {
if ((output->length + to - from) > output->maxlength) return 0;
while (to > from) {
posMapping[output->length] = from;
output->chars[output->length] = input->chars[from];
output->length++;
from++;
}
}
}
return 1;
}
static int
passDoAction(const TranslationTableHeader *table, const InString **input,
OutString *output, int *posMapping, int transOpcode,
const TranslationTableRule **transRule, int passCharDots,
const widechar *passInstructions, int passIC, int *pos, PassRuleMatch match,
int *cursorPosition, int *cursorStatus, TranslationTableRule *groupingRule,
widechar groupingOp) {
int k;
TranslationTableOffset ruleOffset = 0;
TranslationTableRule *rule = NULL;
int destStartMatch = output->length;
int destStartReplace;
int newPos = match.endReplace;
if (!copyCharacters(match.startMatch, match.startReplace, table, *input, output,
posMapping, transOpcode, cursorPosition, cursorStatus))
return 0;
destStartReplace = output->length;
while (passIC < (*transRule)->dotslen) switch (passInstructions[passIC]) {
case pass_string:
case pass_dots:
if ((output->length + passInstructions[passIC + 1]) > output->maxlength)
return 0;
for (k = 0; k < passInstructions[passIC + 1]; ++k)
posMapping[output->length + k] = match.startReplace;
memcpy(&output->chars[output->length], &passInstructions[passIC + 2],
passInstructions[passIC + 1] * CHARSIZE);
output->length += passInstructions[passIC + 1];
passIC += passInstructions[passIC + 1] + 2;
break;
case pass_groupstart:
ruleOffset =
(passInstructions[passIC + 1] << 16) | passInstructions[passIC + 2];
rule = (TranslationTableRule *)&table->ruleArea[ruleOffset];
posMapping[output->length] = match.startMatch;
output->chars[output->length++] = rule->charsdots[2 * passCharDots];
passIC += 3;
break;
case pass_groupend:
ruleOffset =
(passInstructions[passIC + 1] << 16) | passInstructions[passIC + 2];
rule = (TranslationTableRule *)&table->ruleArea[ruleOffset];
posMapping[output->length] = match.startMatch;
output->chars[output->length++] = rule->charsdots[2 * passCharDots + 1];
passIC += 3;
break;
case pass_swap:
if (!swapReplace(match.startReplace, match.endReplace, table, *input, output,
posMapping, passInstructions, passIC))
return 0;
passIC += 3;
break;
case pass_groupreplace:
if (!groupingRule ||
!replaceGrouping(table, input, output, transOpcode, passCharDots,
passInstructions, passIC, match.startReplace, groupingRule,
groupingOp))
return 0;
passIC += 3;
break;
case pass_omit:
if (groupingRule)
removeGrouping(input, output, passCharDots, match.startReplace,
groupingRule, groupingOp);
passIC++;
break;
case pass_copy: {
int count = destStartReplace - destStartMatch;
if (count > 0) {
memmove(&output->chars[destStartMatch], &output->chars[destStartReplace],
count * sizeof(*output->chars));
output->length -= count;
destStartReplace = destStartMatch;
}
}
if (!copyCharacters(match.startReplace, match.endReplace, table, *input,
output, posMapping, transOpcode, cursorPosition, cursorStatus))
return 0;
newPos = match.endMatch;
passIC++;
break;
default:
if (_lou_handlePassVariableAction(passInstructions, &passIC)) break;
return 0;
}
*pos = newPos;
return 1;
}
static void
passSelectRule(const TranslationTableHeader *table, int pos, int currentPass,
const InString *input, int *transOpcode, const TranslationTableRule **transRule,
int *transCharslen, int *passCharDots, widechar const **passInstructions,
int *passIC, PassRuleMatch *match, TranslationTableRule **groupingRule,
widechar *groupingOp) {
if (!findForPassRule(table, pos, currentPass, input, transOpcode, transRule,
transCharslen, passCharDots, passInstructions, passIC, match,
groupingRule, groupingOp)) {
*transOpcode = CTO_Always;
}
}
static int
translatePass(const TranslationTableHeader *table, int currentPass, const InString *input,
OutString *output, int *posMapping, int *realInlen, int *posIncremented,
int *cursorPosition, int *cursorStatus) {
int pos;
int transOpcode;
const TranslationTableRule *transRule;
int transCharslen;
int passCharDots;
const widechar *passInstructions;
int passIC; /* Instruction counter */
PassRuleMatch patternMatch;
TranslationTableRule *groupingRule;
widechar groupingOp;
const InString *origInput = input;
pos = output->length = 0;
*posIncremented = 1;
_lou_resetPassVariables();
while (pos < input->length) { /* the main multipass translation loop */
passSelectRule(table, pos, currentPass, input, &transOpcode, &transRule,
&transCharslen, &passCharDots, &passInstructions, &passIC, &patternMatch,
&groupingRule, &groupingOp);
*posIncremented = 1;
switch (transOpcode) {
case CTO_Context:
case CTO_Pass2:
case CTO_Pass3:
case CTO_Pass4: {
const InString *inputBefore = input;
int posBefore = pos;
if (appliedRules != NULL && appliedRulesCount < maxAppliedRules)
appliedRules[appliedRulesCount++] = transRule;
if (!passDoAction(table, &input, output, posMapping, transOpcode, &transRule,
passCharDots, passInstructions, passIC, &pos, patternMatch,
cursorPosition, cursorStatus, groupingRule, groupingOp))
goto failure;
if (input->bufferIndex != inputBefore->bufferIndex &&
inputBefore->bufferIndex != origInput->bufferIndex)
releaseStringBuffer(inputBefore->bufferIndex);
if (pos == posBefore) *posIncremented = 0;
break;
}
case CTO_Always:
if ((output->length + 1) > output->maxlength) goto failure;
posMapping[output->length] = pos;
output->chars[output->length++] = input->chars[pos++];
break;
default:
goto failure;
}
}
failure:
if (pos < input->length) {
while (checkAttr(input->chars[pos], CTC_Space, 1, table))
if (++pos == input->length) break;
}
*realInlen = pos;
if (input->bufferIndex != origInput->bufferIndex)
releaseStringBuffer(input->bufferIndex);
return 1;
}
#define MIN(a, b) (((a) < (b)) ? (a) : (b))
static int
translateString(const TranslationTableHeader *table, int mode, int currentPass,
const InString *input, OutString *output, int *posMapping, formtype *typebuf,
unsigned char *srcSpacing, unsigned char *destSpacing, unsigned int *wordBuffer,
EmphasisInfo *emphasisBuffer, int haveEmphasis, int *realInlen,
int *posIncremented, int *cursorPosition, int *cursorStatus, int compbrlStart,
int compbrlEnd);
int EXPORT_CALL
lou_translateString(const char *tableList, const widechar *inbufx, int *inlen,
widechar *outbuf, int *outlen, formtype *typeform, char *spacing, int mode) {
return lou_translate(tableList, inbufx, inlen, outbuf, outlen, typeform, spacing,
NULL, NULL, NULL, mode);
}
int EXPORT_CALL
lou_translate(const char *tableList, const widechar *inbufx, int *inlen, widechar *outbuf,
int *outlen, formtype *typeform, char *spacing, int *outputPos, int *inputPos,
int *cursorPos, int mode) {
return _lou_translateWithTracing(tableList, inbufx, inlen, outbuf, outlen, typeform,
spacing, outputPos, inputPos, cursorPos, mode, NULL, NULL);
}
int EXPORT_CALL
_lou_translateWithTracing(const char *tableList, const widechar *inbufx, int *inlen,
widechar *outbuf, int *outlen, formtype *typeform, char *spacing, int *outputPos,
int *inputPos, int *cursorPos, int mode, const TranslationTableRule **rules,
int *rulesLen) {
// int i;
// for(i = 0; i < *inlen; i++)
// {
// outbuf[i] = inbufx[i];
// if(inputPos)
// inputPos[i] = i;
// if(outputPos)
// outputPos[i] = i;
// }
// *inlen = i;
// *outlen = i;
// return 1;
const TranslationTableHeader *table;
const InString *input;
OutString output;
// posMapping contains position mapping info between the initial input and the output
// of the current pass. It is 1 longer than the output. The values are monotonically
// increasing and can range between -1 and the input length. At the end the position
// info is passed to the user as an inputPos and outputPos array. inputPos has the
// length of the final output and has values ranging from 0 to inlen-1. outputPos has
// the length of the initial input and has values ranging from 0 to outlen-1.
int *posMapping;
int *posMapping1;
int *posMapping2;
int *posMapping3;
formtype *typebuf;
unsigned char *srcSpacing;
unsigned char *destSpacing;
unsigned int *wordBuffer;
EmphasisInfo *emphasisBuffer;
int cursorPosition;
int cursorStatus;
int haveEmphasis;
int compbrlStart = -1;
int compbrlEnd = -1;
int k;
int goodTrans = 1;
int posIncremented;
if (tableList == NULL || inbufx == NULL || inlen == NULL || outbuf == NULL ||
outlen == NULL)
return 0;
_lou_logMessage(
LOG_ALL, "Performing translation: tableList=%s, inlen=%d", tableList, *inlen);
_lou_logWidecharBuf(LOG_ALL, "Inbuf=", inbufx, *inlen);
if (mode & pass1Only) {
_lou_logMessage(LOG_WARN, "warning: pass1Only mode is no longer supported.");
}
table = lou_getTable(tableList);
if (table == NULL || *inlen < 0 || *outlen < 0) return 0;
k = 0;
while (k < *inlen && inbufx[k]) k++;
input = &(InString){.chars = inbufx, .length = k, .bufferIndex = -1 };
haveEmphasis = 0;
if (!(typebuf = _lou_allocMem(alloc_typebuf, 0, input->length, *outlen))) return 0;
if (typeform != NULL) {
for (k = 0; k < input->length; k++) {
typebuf[k] = typeform[k];
if (typebuf[k] & EMPHASIS) haveEmphasis = 1;
}
} else
memset(typebuf, 0, input->length * sizeof(formtype));
if ((wordBuffer = _lou_allocMem(alloc_wordBuffer, 0, input->length, *outlen)))
memset(wordBuffer, 0, (input->length + 4) * sizeof(unsigned int));
else
return 0;
if ((emphasisBuffer = _lou_allocMem(alloc_emphasisBuffer, 0, input->length, *outlen)))
memset(emphasisBuffer, 0, (input->length + 4) * sizeof(EmphasisInfo));
else
return 0;
if (!(spacing == NULL || *spacing == 'X'))
srcSpacing = (unsigned char *)spacing;
else
srcSpacing = NULL;
if (outputPos != NULL)
for (k = 0; k < input->length; k++) outputPos[k] = -1;
if (cursorPos != NULL && *cursorPos >= 0) {
cursorStatus = 0;
cursorPosition = *cursorPos;
if ((mode & (compbrlAtCursor | compbrlLeftCursor))) {
compbrlStart = cursorPosition;
if (checkAttr(input->chars[compbrlStart], CTC_Space, 0, table))
compbrlEnd = compbrlStart + 1;
else {
while (compbrlStart >= 0 &&
!checkAttr(input->chars[compbrlStart], CTC_Space, 0, table))
compbrlStart--;
compbrlStart++;
compbrlEnd = cursorPosition;
if (!(mode & compbrlLeftCursor))
while (compbrlEnd < input->length &&
!checkAttr(input->chars[compbrlEnd], CTC_Space, 0, table))
compbrlEnd++;
}
}
} else {
cursorPosition = -1;
cursorStatus = 1; /* so it won't check cursor position */
}
if (!(posMapping1 = _lou_allocMem(alloc_posMapping1, 0, input->length, *outlen)))
return 0;
if (table->numPasses > 1 || table->corrections) {
if (!(posMapping2 = _lou_allocMem(alloc_posMapping2, 0, input->length, *outlen)))
return 0;
if (!(posMapping3 = _lou_allocMem(alloc_posMapping3, 0, input->length, *outlen)))
return 0;
}
if (srcSpacing != NULL) {
if (!(destSpacing = _lou_allocMem(alloc_destSpacing, 0, input->length, *outlen)))
goodTrans = 0;
else
memset(destSpacing, '*', *outlen);
} else
destSpacing = NULL;
appliedRulesCount = 0;
if (rules != NULL && rulesLen != NULL) {
appliedRules = rules;
maxAppliedRules = *rulesLen;
} else {
appliedRules = NULL;
maxAppliedRules = 0;
}
{
int idx;
if (!stringBufferPool) initStringBufferPool();
for (idx = 0; idx < stringBufferPool->size; idx++) releaseStringBuffer(idx);
idx = getStringBuffer(*outlen);
output = (OutString){.chars = stringBufferPool->buffers[idx],
.maxlength = *outlen,
.length = 0,
.bufferIndex = idx };
}
posMapping = posMapping1;
int currentPass = table->corrections ? 0 : 1;
int *passPosMapping = posMapping;
while (1) {
int realInlen;
switch (currentPass) {
case 0:
goodTrans = makeCorrections(table, input, &output, passPosMapping, typebuf,
&realInlen, &posIncremented, &cursorPosition, &cursorStatus);
break;
case 1: {
goodTrans = translateString(table, mode, currentPass, input, &output,
passPosMapping, typebuf, srcSpacing, destSpacing, wordBuffer,
emphasisBuffer, haveEmphasis, &realInlen, &posIncremented,
&cursorPosition, &cursorStatus, compbrlStart, compbrlEnd);
break;
}
default:
goodTrans = translatePass(table, currentPass, input, &output, passPosMapping,
&realInlen, &posIncremented, &cursorPosition, &cursorStatus);
break;
}
passPosMapping[output.length] = realInlen;
if (passPosMapping == posMapping) {
passPosMapping = posMapping2;
} else {
int *prevPosMapping = posMapping3;
memcpy((int *)prevPosMapping, posMapping, (*outlen + 1) * sizeof(int));
for (k = 0; k <= output.length; k++)
if (passPosMapping[k] < 0)
posMapping[k] = prevPosMapping[0];
else
posMapping[k] = prevPosMapping[passPosMapping[k]];
}
currentPass++;
if (currentPass <= table->numPasses && goodTrans) {
int idx;
releaseStringBuffer(input->bufferIndex);
input = &(InString){.chars = output.chars,
.length = output.length,
.bufferIndex = output.bufferIndex };
idx = getStringBuffer(*outlen);
output = (OutString){.chars = stringBufferPool->buffers[idx],
.maxlength = *outlen,
.length = 0,
.bufferIndex = idx };
continue;
}
break;
}
if (goodTrans) {
for (k = 0; k < output.length; k++) {
if (typeform != NULL) {
if ((output.chars[k] & (B7 | B8)))
typeform[k] = '8';
else
typeform[k] = '0';
}
if ((mode & dotsIO)) {
if ((mode & ucBrl))
outbuf[k] = ((output.chars[k] & 0xff) | 0x2800);
else
outbuf[k] = output.chars[k];
} else
outbuf[k] = _lou_getCharFromDots(output.chars[k]);
}
*inlen = posMapping[output.length];
*outlen = output.length;
// Compute inputPos and outputPos from posMapping. The value at the last index of
// posMapping is currectly not used.
if (inputPos != NULL) {
for (k = 0; k < *outlen; k++)
if (posMapping[k] < 0)
inputPos[k] = 0;
else if (posMapping[k] > *inlen - 1)
inputPos[k] = *inlen - 1;
else
inputPos[k] = posMapping[k];
}
if (outputPos != NULL) {
int inpos = -1;
int outpos = -1;
for (k = 0; k < *outlen; k++)
if (posMapping[k] > inpos) {
while (inpos < posMapping[k]) {
if (inpos >= 0 && inpos < *inlen)
outputPos[inpos] = outpos < 0 ? 0 : outpos;
inpos++;
}
outpos = k;
}
if (inpos < 0) inpos = 0;
while (inpos < *inlen) outputPos[inpos++] = outpos;
}
}
if (destSpacing != NULL) {
memcpy(srcSpacing, destSpacing, input->length);
srcSpacing[input->length] = 0;
}
if (cursorPos != NULL && *cursorPos != -1) {
if (outputPos != NULL)
*cursorPos = outputPos[*cursorPos];
else
*cursorPos = cursorPosition;
}
if (rulesLen != NULL) *rulesLen = appliedRulesCount;
_lou_logMessage(LOG_ALL, "Translation complete: outlen=%d", *outlen);
_lou_logWidecharBuf(LOG_ALL, "Outbuf=", (const widechar *)outbuf, *outlen);
return goodTrans;
}
int EXPORT_CALL
lou_translatePrehyphenated(const char *tableList, const widechar *inbufx, int *inlen,
widechar *outbuf, int *outlen, formtype *typeform, char *spacing, int *outputPos,
int *inputPos, int *cursorPos, char *inputHyphens, char *outputHyphens,
int mode) {
int rv = 1;
int *alloc_inputPos = NULL;
if (inputHyphens != NULL) {
if (outputHyphens == NULL) return 0;
if (inputPos == NULL) {
if ((alloc_inputPos = malloc(*outlen * sizeof(int))) == NULL)
_lou_outOfMemory();
inputPos = alloc_inputPos;
}
}
if (lou_translate(tableList, inbufx, inlen, outbuf, outlen, typeform, spacing,
outputPos, inputPos, cursorPos, mode)) {
if (inputHyphens != NULL) {
int inpos = 0;
int outpos;
for (outpos = 0; outpos < *outlen; outpos++) {
int new_inpos = inputPos[outpos];
if (new_inpos < inpos) {
rv = 0;
break;
}
if (new_inpos > inpos)
outputHyphens[outpos] = inputHyphens[new_inpos];
else
outputHyphens[outpos] = '0';
inpos = new_inpos;
}
}
}
if (alloc_inputPos != NULL) free(alloc_inputPos);
return rv;
}
static int
hyphenate(const widechar *word, int wordSize, char *hyphens,
const TranslationTableHeader *table) {
widechar *prepWord;
int i, k, limit;
int stateNum;
widechar ch;
HyphenationState *statesArray =
(HyphenationState *)&table->ruleArea[table->hyphenStatesArray];
HyphenationState *currentState;
HyphenationTrans *transitionsArray;
char *hyphenPattern;
int patternOffset;
if (!table->hyphenStatesArray || (wordSize + 3) > MAXSTRING) return 0;
prepWord = (widechar *)calloc(wordSize + 3, sizeof(widechar));
/* prepWord is of the format ".hello."
* hyphens is the length of the word "hello" "00000" */
prepWord[0] = '.';
for (i = 0; i < wordSize; i++) {
prepWord[i + 1] = (findCharOrDots(word[i], 0, table))->lowercase;
hyphens[i] = '0';
}
prepWord[wordSize + 1] = '.';
/* now, run the finite state machine */
stateNum = 0;
// we need to walk all of ".hello."
for (i = 0; i < wordSize + 2; i++) {
ch = prepWord[i];
while (1) {
if (stateNum == 0xffff) {
stateNum = 0;
goto nextLetter;
}
currentState = &statesArray[stateNum];
if (currentState->trans.offset) {
transitionsArray =
(HyphenationTrans *)&table->ruleArea[currentState->trans.offset];
for (k = 0; k < currentState->numTrans; k++) {
if (transitionsArray[k].ch == ch) {
stateNum = transitionsArray[k].newState;
goto stateFound;
}
}
}
stateNum = currentState->fallbackState;
}
stateFound:
currentState = &statesArray[stateNum];
if (currentState->hyphenPattern) {
hyphenPattern = (char *)&table->ruleArea[currentState->hyphenPattern];
patternOffset = i + 1 - (int)strlen(hyphenPattern);
/* Need to ensure that we don't overrun hyphens,
* in some cases hyphenPattern is longer than the remaining letters,
* and if we write out all of it we would have overshot our buffer. */
limit = MIN((int)strlen(hyphenPattern), wordSize - patternOffset);
for (k = 0; k < limit; k++) {
if (hyphens[patternOffset + k] < hyphenPattern[k])
hyphens[patternOffset + k] = hyphenPattern[k];
}
}
nextLetter:;
}
hyphens[wordSize] = 0;
free(prepWord);
return 1;
}
static int
doCompTrans(int start, int end, const TranslationTableHeader *table, int *pos,
const InString *input, OutString *output, int *posMapping,
EmphasisInfo *emphasisBuffer, const TranslationTableRule **transRule,
int *cursorPosition, int *cursorStatus);
static int
for_updatePositions(const widechar *outChars, int inLength, int outLength, int shift,
int pos, const InString *input, OutString *output, int *posMapping,
int *cursorPosition, int *cursorStatus) {
int k;
if ((output->length + outLength) > output->maxlength ||
(pos + inLength) > input->length)
return 0;
memcpy(&output->chars[output->length], outChars, outLength * CHARSIZE);
if (!*cursorStatus) {
if (*cursorPosition >= pos && *cursorPosition < (pos + inLength)) {
*cursorPosition = output->length;
*cursorStatus = 1;
} else if (input->chars[*cursorPosition] == 0 &&
*cursorPosition == (pos + inLength)) {
*cursorPosition = output->length + outLength / 2 + 1;
*cursorStatus = 1;
}
} else if (*cursorStatus == 2 && *cursorPosition == pos)
*cursorPosition = output->length;
for (k = 0; k < outLength; k++) posMapping[output->length + k] = pos + shift;
output->length += outLength;
return 1;
}
static int
syllableBreak(const TranslationTableHeader *table, int pos, const InString *input,
int transCharslen) {
int wordStart = 0;
int wordEnd = 0;
int wordSize = 0;
int k = 0;
char *hyphens = NULL;
for (wordStart = pos; wordStart >= 0; wordStart--)
if (!((findCharOrDots(input->chars[wordStart], 0, table))->attributes &
CTC_Letter)) {
wordStart++;
break;
}
if (wordStart < 0) wordStart = 0;
for (wordEnd = pos; wordEnd < input->length; wordEnd++)
if (!((findCharOrDots(input->chars[wordEnd], 0, table))->attributes &
CTC_Letter)) {
wordEnd--;
break;
}
if (wordEnd == input->length) wordEnd--;
/* At this stage wordStart is the 0 based index of the first letter in the word,
* wordEnd is the 0 based index of the last letter in the word.
* example: "hello" wordstart=0, wordEnd=4. */
wordSize = wordEnd - wordStart + 1;
hyphens = (char *)calloc(wordSize + 1, sizeof(char));
if (!hyphenate(&input->chars[wordStart], wordSize, hyphens, table)) {
free(hyphens);
return 0;
}
for (k = pos - wordStart + 1; k < (pos - wordStart + transCharslen); k++)
if (hyphens[k] & 1) {
free(hyphens);
return 1;
}
free(hyphens);
return 0;
}
static void
setBefore(const TranslationTableHeader *table, int pos, const InString *input,
TranslationTableCharacterAttributes *beforeAttributes) {
widechar before;
if (pos >= 2 && input->chars[pos - 1] == ENDSEGMENT)
before = input->chars[pos - 2];
else
before = (pos == 0) ? ' ' : input->chars[pos - 1];
*beforeAttributes = (findCharOrDots(before, 0, table))->attributes;
}
static void
setAfter(int length, const TranslationTableHeader *table, int pos, const InString *input,
TranslationTableCharacterAttributes *afterAttributes) {
widechar after;
if ((pos + length + 2) < input->length && input->chars[pos + 1] == ENDSEGMENT)
after = input->chars[pos + 2];
else
after = (pos + length < input->length) ? input->chars[pos + length] : ' ';
*afterAttributes = (findCharOrDots(after, 0, table))->attributes;
}
static int
brailleIndicatorDefined(TranslationTableOffset offset,
const TranslationTableHeader *table, const TranslationTableRule **indicRule) {
if (!offset) return 0;
*indicRule = (TranslationTableRule *)&table->ruleArea[offset];
return 1;
}
static int
validMatch(const TranslationTableHeader *table, int pos, const InString *input,
formtype *typebuf, const TranslationTableRule *transRule, int transCharslen) {
/* Analyze the typeform parameter and also check for capitalization */
TranslationTableCharacter *inputChar;
TranslationTableCharacter *ruleChar;
TranslationTableCharacterAttributes prevAttr = 0;
int k;
int kk = 0;
if (!transCharslen) return 0;
for (k = pos; k < pos + transCharslen; k++) {
if (input->chars[k] == ENDSEGMENT) {
if (k == pos && transCharslen == 1)
return 1;
else
return 0;
}
inputChar = findCharOrDots(input->chars[k], 0, table);
if (k == pos) prevAttr = inputChar->attributes;
ruleChar = findCharOrDots(transRule->charsdots[kk++], 0, table);
if ((inputChar->lowercase != ruleChar->lowercase)) return 0;
if (typebuf != NULL && (typebuf[pos] & CAPSEMPH) == 0 &&
(typebuf[k] | typebuf[pos]) != typebuf[pos])
return 0;
if (inputChar->attributes != CTC_Letter) {
if (k != (pos + 1) && (prevAttr & CTC_Letter) &&
(inputChar->attributes & CTC_Letter) &&
((inputChar->attributes &
(CTC_LowerCase | CTC_UpperCase | CTC_Letter)) !=
(prevAttr & (CTC_LowerCase | CTC_UpperCase | CTC_Letter))))
return 0;
}
prevAttr = inputChar->attributes;
}
return 1;
}
static int
insertBrailleIndicators(int finish, const TranslationTableHeader *table, int pos,
const InString *input, OutString *output, int *posMapping, formtype *typebuf,
int haveEmphasis, int transOpcode, int prevTransOpcode, int *cursorPosition,
int *cursorStatus, TranslationTableCharacterAttributes beforeAttributes,
int *prevType, int *curType, int *prevTypeform, int prevPos) {
/* Insert braille indicators such as letter, number, etc. */
typedef enum {
checkNothing,
checkBeginTypeform,
checkEndTypeform,
checkNumber,
checkLetter
} checkThis;
checkThis checkWhat = checkNothing;
int ok = 0;
int k;
{
if (pos == prevPos && !finish) return 1;
if (pos != prevPos) {
if (haveEmphasis && (typebuf[pos] & EMPHASIS) != *prevTypeform) {
*prevType = *prevTypeform & EMPHASIS;
*curType = typebuf[pos] & EMPHASIS;
checkWhat = checkEndTypeform;
} else if (!finish)
checkWhat = checkNothing;
else
checkWhat = checkNumber;
}
if (finish == 1) checkWhat = checkNumber;
}
do {
const TranslationTableRule *indicRule;
ok = 0;
switch (checkWhat) {
case checkNothing:
ok = 0;
break;
case checkBeginTypeform:
if (haveEmphasis) {
ok = 0;
*curType = 0;
}
if (*curType == plain_text) {
if (!finish)
checkWhat = checkNothing;
else
checkWhat = checkNumber;
}
break;
case checkEndTypeform:
if (haveEmphasis) {
ok = 0;
*prevType = plain_text;
}
if (*prevType == plain_text) {
checkWhat = checkBeginTypeform;
*prevTypeform = typebuf[pos] & EMPHASIS;
}
break;
case checkNumber:
if (brailleIndicatorDefined(table->numberSign, table, &indicRule) &&
checkAttr_safe(input, pos, CTC_Digit, 0, table) &&
(prevTransOpcode == CTO_ExactDots ||
!(beforeAttributes & CTC_Digit)) &&
prevTransOpcode != CTO_MidNum) {
ok = !table->usesNumericMode;
checkWhat = checkNothing;
} else
checkWhat = checkLetter;
break;
case checkLetter:
if (!brailleIndicatorDefined(table->letterSign, table, &indicRule)) {
ok = 0;
checkWhat = checkNothing;
break;
}
if (transOpcode == CTO_Contraction) {
ok = 1;
checkWhat = checkNothing;
break;
}
if ((checkAttr_safe(input, pos, CTC_Letter, 0, table) &&
!(beforeAttributes & CTC_Letter)) &&
(!checkAttr_safe(input, pos + 1, CTC_Letter, 0, table) ||
(beforeAttributes & CTC_Digit))) {
ok = 1;
if (pos > 0)
for (k = 0; k < table->noLetsignBeforeCount; k++)
if (input->chars[pos - 1] == table->noLetsignBefore[k]) {
ok = 0;
break;
}
for (k = 0; k < table->noLetsignCount; k++)
if (input->chars[pos] == table->noLetsign[k]) {
ok = 0;
break;
}
if (pos + 1 < input->length)
for (k = 0; k < table->noLetsignAfterCount; k++)
if (input->chars[pos + 1] == table->noLetsignAfter[k]) {
ok = 0;
break;
}
}
checkWhat = checkNothing;
break;
default:
ok = 0;
checkWhat = checkNothing;
break;
}
if (ok && indicRule != NULL) {
if (!for_updatePositions(&indicRule->charsdots[0], 0, indicRule->dotslen, 0,
pos, input, output, posMapping, cursorPosition, cursorStatus))
return 0;
}
} while (checkWhat != checkNothing);
return 1;
}
static int
onlyLettersBehind(const TranslationTableHeader *table, int pos, const InString *input,
TranslationTableCharacterAttributes beforeAttributes) {
/* Actually, spaces, then letters */
int k;
if (!(beforeAttributes & CTC_Space)) return 0;
for (k = pos - 2; k >= 0; k--) {
TranslationTableCharacterAttributes attr =
(findCharOrDots(input->chars[k], 0, table))->attributes;
if ((attr & CTC_Space)) continue;
if ((attr & CTC_Letter))
return 1;
else
return 0;
}
return 1;
}
static int
onlyLettersAhead(const TranslationTableHeader *table, int pos, const InString *input,
int transCharslen, TranslationTableCharacterAttributes afterAttributes) {
/* Actullly, spaces, then letters */
int k;
if (!(afterAttributes & CTC_Space)) return 0;
for (k = pos + transCharslen + 1; k < input->length; k++) {
TranslationTableCharacterAttributes attr =
(findCharOrDots(input->chars[k], 0, table))->attributes;
if ((attr & CTC_Space)) continue;
if ((attr & (CTC_Letter | CTC_LitDigit)))
return 1;
else
return 0;
}
return 0;
}
static int
noCompbrlAhead(const TranslationTableHeader *table, int pos, int mode,
const InString *input, int transOpcode, int transCharslen, int cursorPosition) {
int start = pos + transCharslen;
int end;
int p;
if (start >= input->length) return 1;
while (start < input->length && checkAttr(input->chars[start], CTC_Space, 0, table))
start++;
if (start == input->length ||
(transOpcode == CTO_JoinableWord &&
(!checkAttr(input->chars[start], CTC_Letter | CTC_Digit, 0, table) ||
!checkAttr(input->chars[start - 1], CTC_Space, 0, table))))
return 1;
end = start;
while (end < input->length && !checkAttr(input->chars[end], CTC_Space, 0, table))
end++;
if ((mode & (compbrlAtCursor | compbrlLeftCursor)) && cursorPosition >= start &&
cursorPosition < end)
return 0;
/* Look ahead for rules with CTO_CompBrl */
for (p = start; p < end; p++) {
int length = input->length - p;
int tryThis;
const TranslationTableCharacter *character1;
const TranslationTableCharacter *character2;
int k;
character1 = findCharOrDots(input->chars[p], 0, table);
for (tryThis = 0; tryThis < 2; tryThis++) {
TranslationTableOffset ruleOffset = 0;
TranslationTableRule *testRule;
unsigned long int makeHash = 0;
switch (tryThis) {
case 0:
if (!(length >= 2)) break;
/* Hash function optimized for forward translation */
makeHash = (unsigned long int)character1->lowercase << 8;
character2 = findCharOrDots(input->chars[p + 1], 0, table);
makeHash += (unsigned long int)character2->lowercase;
makeHash %= HASHNUM;
ruleOffset = table->forRules[makeHash];
break;
case 1:
if (!(length >= 1)) break;
length = 1;
ruleOffset = character1->otherRules;
break;
}
while (ruleOffset) {
testRule = (TranslationTableRule *)&table->ruleArea[ruleOffset];
for (k = 0; k < testRule->charslen; k++) {
character1 = findCharOrDots(testRule->charsdots[k], 0, table);
character2 = findCharOrDots(input->chars[p + k], 0, table);
if (character1->lowercase != character2->lowercase) break;
}
if (tryThis == 1 || k == testRule->charslen) {
if (testRule->opcode == CTO_CompBrl ||
testRule->opcode == CTO_Literal)
return 0;
}
ruleOffset = testRule->charsnext;
}
}
}
return 1;
}
static int
isRepeatedWord(const TranslationTableHeader *table, int pos, const InString *input,
int transCharslen, const widechar **repwordStart, int *repwordLength) {
int start;
if (pos == 0 || !checkAttr(input->chars[pos - 1], CTC_Letter, 0, table)) return 0;
if ((pos + transCharslen) >= input->length ||
!checkAttr(input->chars[pos + transCharslen], CTC_Letter, 0, table))
return 0;
for (start = pos - 2;
start >= 0 && checkAttr(input->chars[start], CTC_Letter, 0, table); start--)
;
start++;
*repwordStart = &input->chars[start];
*repwordLength = pos - start;
if (compareChars(*repwordStart, &input->chars[pos + transCharslen], *repwordLength, 0,
table))
return 1;
return 0;
}
static int
checkEmphasisChange(const int skip, int pos, EmphasisInfo *emphasisBuffer,
const TranslationTableRule *transRule) {
int i;
for (i = pos + (skip + 1); i < pos + transRule->charslen; i++)
if (emphasisBuffer[i].begin || emphasisBuffer[i].end || emphasisBuffer[i].word ||
emphasisBuffer[i].symbol)
return 1;
return 0;
}
static int
inSequence(const TranslationTableHeader *table, int pos, const InString *input,
const TranslationTableRule *transRule) {
int i, j, s, match;
// TODO: all caps words
// const TranslationTableCharacter *c = NULL;
/* check before sequence */
for (i = pos - 1; i >= 0; i--) {
if (checkAttr(input->chars[i], CTC_SeqBefore, 0, table)) continue;
if (!(checkAttr(input->chars[i], CTC_Space | CTC_SeqDelimiter, 0, table)))
return 0;
break;
}
/* check after sequence */
for (i = pos + transRule->charslen; i < input->length; i++) {
/* check sequence after patterns */
if (table->seqPatternsCount) {
match = 0;
for (j = i, s = 0; j <= input->length && s < table->seqPatternsCount;
j++, s++) {
/* matching */
if (match == 1) {
if (table->seqPatterns[s]) {
if (input->chars[j] == table->seqPatterns[s])
match = 1;
else {
match = -1;
j = i - 1;
}
}
/* found match */
else {
/* pattern at end of input */
if (j >= input->length) return 1;
i = j;
break;
}
}
/* looking for match */
else if (match == 0) {
if (table->seqPatterns[s]) {
if (input->chars[j] == table->seqPatterns[s])
match = 1;
else {
match = -1;
j = i - 1;
}
}
}
/* next pattarn */
else if (match == -1) {
if (!table->seqPatterns[s]) {
match = 0;
j = i - 1;
}
}
}
}
if (checkAttr(input->chars[i], CTC_SeqAfter, 0, table)) continue;
if (!(checkAttr(input->chars[i], CTC_Space | CTC_SeqDelimiter, 0, table)))
return 0;
break;
}
return 1;
}
static void
for_selectRule(const TranslationTableHeader *table, int pos, OutString output, int mode,
const InString *input, formtype *typebuf, EmphasisInfo *emphasisBuffer,
int *transOpcode, int prevTransOpcode, const TranslationTableRule **transRule,
int *transCharslen, int *passCharDots, widechar const **passInstructions,
int *passIC, PassRuleMatch *patternMatch, int posIncremented, int cursorPosition,
const widechar **repwordStart, int *repwordLength, int dontContract,
int compbrlStart, int compbrlEnd,
TranslationTableCharacterAttributes beforeAttributes,
TranslationTableCharacter **curCharDef, TranslationTableRule **groupingRule,
widechar *groupingOp) {
/* check for valid Translations. Return value is in transRule. */
static TranslationTableRule pseudoRule = { 0 };
int length = ((pos < compbrlStart) ? compbrlStart : input->length) - pos;
int tryThis;
const TranslationTableCharacter *character2;
int k;
TranslationTableOffset ruleOffset = 0;
*curCharDef = findCharOrDots(input->chars[pos], 0, table);
for (tryThis = 0; tryThis < 3; tryThis++) {
unsigned long int makeHash = 0;
switch (tryThis) {
case 0:
if (!(length >= 2)) break;
/* Hash function optimized for forward translation */
makeHash = (unsigned long int)(*curCharDef)->lowercase << 8;
character2 = findCharOrDots(input->chars[pos + 1], 0, table);
makeHash += (unsigned long int)character2->lowercase;
makeHash %= HASHNUM;
ruleOffset = table->forRules[makeHash];
break;
case 1:
if (!(length >= 1)) break;
length = 1;
ruleOffset = (*curCharDef)->otherRules;
break;
case 2: /* No rule found */
*transRule = &pseudoRule;
*transOpcode = pseudoRule.opcode = CTO_None;
*transCharslen = pseudoRule.charslen = 1;
pseudoRule.charsdots[0] = input->chars[pos];
pseudoRule.dotslen = 0;
return;
break;
}
while (ruleOffset) {
*transRule = (TranslationTableRule *)&table->ruleArea[ruleOffset];
*transOpcode = (*transRule)->opcode;
*transCharslen = (*transRule)->charslen;
if (tryThis == 1 ||
((*transCharslen <= length) && validMatch(table, pos, input, typebuf,
*transRule, *transCharslen))) {
TranslationTableCharacterAttributes afterAttributes;
/* check before emphasis match */
if ((*transRule)->before & CTC_EmpMatch) {
if (emphasisBuffer[pos].begin || emphasisBuffer[pos].end ||
emphasisBuffer[pos].word || emphasisBuffer[pos].symbol)
break;
}
/* check after emphasis match */
if ((*transRule)->after & CTC_EmpMatch) {
if (emphasisBuffer[pos + *transCharslen].begin ||
emphasisBuffer[pos + *transCharslen].end ||
emphasisBuffer[pos + *transCharslen].word ||
emphasisBuffer[pos + *transCharslen].symbol)
break;
}
/* check this rule */
setAfter(*transCharslen, table, pos, input, &afterAttributes);
if ((!((*transRule)->after & ~CTC_EmpMatch) ||
(beforeAttributes & (*transRule)->after)) &&
(!((*transRule)->before & ~CTC_EmpMatch) ||
(afterAttributes & (*transRule)->before)))
switch (*transOpcode) { /* check validity of this Translation */
case CTO_Space:
case CTO_Letter:
case CTO_UpperCase:
case CTO_LowerCase:
case CTO_Digit:
case CTO_LitDigit:
case CTO_Punctuation:
case CTO_Math:
case CTO_Sign:
case CTO_Hyphen:
case CTO_Replace:
case CTO_CompBrl:
case CTO_Literal:
return;
case CTO_Repeated:
if ((mode & (compbrlAtCursor | compbrlLeftCursor)) &&
pos >= compbrlStart && pos <= compbrlEnd)
break;
return;
case CTO_RepWord:
if (dontContract || (mode & noContractions)) break;
if (isRepeatedWord(table, pos, input, *transCharslen,
repwordStart, repwordLength))
return;
break;
case CTO_NoCont:
if (dontContract || (mode & noContractions)) break;
return;
case CTO_Syllable:
*transOpcode = CTO_Always;
case CTO_Always:
if (checkEmphasisChange(0, pos, emphasisBuffer, *transRule))
break;
if (dontContract || (mode & noContractions)) break;
return;
case CTO_ExactDots:
return;
case CTO_NoCross:
if (dontContract || (mode & noContractions)) break;
if (syllableBreak(table, pos, input, *transCharslen)) break;
return;
case CTO_Context:
if (!posIncremented ||
!passDoTest(table, pos, input, *transOpcode, *transRule,
passCharDots, passInstructions, passIC,
patternMatch, groupingRule, groupingOp))
break;
return;
case CTO_LargeSign:
if (dontContract || (mode & noContractions)) break;
if (!((beforeAttributes & (CTC_Space | CTC_Punctuation)) ||
onlyLettersBehind(
table, pos, input, beforeAttributes)) ||
!((afterAttributes & CTC_Space) ||
prevTransOpcode == CTO_LargeSign) ||
(afterAttributes & CTC_Letter) ||
!noCompbrlAhead(table, pos, mode, input, *transOpcode,
*transCharslen, cursorPosition))
*transOpcode = CTO_Always;
return;
case CTO_WholeWord:
if (dontContract || (mode & noContractions)) break;
if (checkEmphasisChange(0, pos, emphasisBuffer, *transRule))
break;
case CTO_Contraction:
if (table->usesSequences) {
if (inSequence(table, pos, input, *transRule)) return;
} else {
if ((beforeAttributes & (CTC_Space | CTC_Punctuation)) &&
(afterAttributes & (CTC_Space | CTC_Punctuation)))
return;
}
break;
case CTO_PartWord:
if (dontContract || (mode & noContractions)) break;
if ((beforeAttributes & CTC_Letter) ||
(afterAttributes & CTC_Letter))
return;
break;
case CTO_JoinNum:
if (dontContract || (mode & noContractions)) break;
if ((beforeAttributes & (CTC_Space | CTC_Punctuation)) &&
(afterAttributes & CTC_Space) &&
(output.length + (*transRule)->dotslen <
output.maxlength)) {
int p = pos + *transCharslen + 1;
while (p < input->length) {
if (!checkAttr(input->chars[p], CTC_Space, 0, table)) {
if (checkAttr(input->chars[p], CTC_Digit, 0, table))
return;
break;
}
p++;
}
}
break;
case CTO_LowWord:
if (dontContract || (mode & noContractions)) break;
if ((beforeAttributes & CTC_Space) &&
(afterAttributes & CTC_Space) &&
(prevTransOpcode != CTO_JoinableWord))
return;
break;
case CTO_JoinableWord:
if (dontContract || (mode & noContractions)) break;
if (beforeAttributes & (CTC_Space | CTC_Punctuation) &&
onlyLettersAhead(table, pos, input, *transCharslen,
afterAttributes) &&
noCompbrlAhead(table, pos, mode, input, *transOpcode,
*transCharslen, cursorPosition))
return;
break;
case CTO_SuffixableWord:
if (dontContract || (mode & noContractions)) break;
if ((beforeAttributes & (CTC_Space | CTC_Punctuation)) &&
(afterAttributes &
(CTC_Space | CTC_Letter | CTC_Punctuation)))
return;
break;
case CTO_PrefixableWord:
if (dontContract || (mode & noContractions)) break;
if ((beforeAttributes &
(CTC_Space | CTC_Letter | CTC_Punctuation)) &&
(afterAttributes & (CTC_Space | CTC_Punctuation)))
return;
break;
case CTO_BegWord:
if (dontContract || (mode & noContractions)) break;
if ((beforeAttributes & (CTC_Space | CTC_Punctuation)) &&
(afterAttributes & CTC_Letter))
return;
break;
case CTO_BegMidWord:
if (dontContract || (mode & noContractions)) break;
if ((beforeAttributes &
(CTC_Letter | CTC_Space | CTC_Punctuation)) &&
(afterAttributes & CTC_Letter))
return;
break;
case CTO_MidWord:
if (dontContract || (mode & noContractions)) break;
if (beforeAttributes & CTC_Letter && afterAttributes & CTC_Letter)
return;
break;
case CTO_MidEndWord:
if (dontContract || (mode & noContractions)) break;
if (beforeAttributes & CTC_Letter &&
afterAttributes &
(CTC_Letter | CTC_Space | CTC_Punctuation))
return;
break;
case CTO_EndWord:
if (dontContract || (mode & noContractions)) break;
if (beforeAttributes & CTC_Letter &&
afterAttributes & (CTC_Space | CTC_Punctuation))
return;
break;
case CTO_BegNum:
if (beforeAttributes & (CTC_Space | CTC_Punctuation) &&
afterAttributes & CTC_Digit)
return;
break;
case CTO_MidNum:
if (prevTransOpcode != CTO_ExactDots &&
beforeAttributes & CTC_Digit &&
afterAttributes & CTC_Digit)
return;
break;
case CTO_EndNum:
if (beforeAttributes & CTC_Digit &&
prevTransOpcode != CTO_ExactDots)
return;
break;
case CTO_DecPoint:
if (!(afterAttributes & CTC_Digit)) break;
if (beforeAttributes & CTC_Digit) *transOpcode = CTO_MidNum;
return;
case CTO_PrePunc:
if (!checkAttr(input->chars[pos], CTC_Punctuation, 0, table) ||
(pos > 0 && checkAttr(input->chars[pos - 1], CTC_Letter,
0, table)))
break;
for (k = pos + *transCharslen; k < input->length; k++) {
if (checkAttr(input->chars[k], (CTC_Letter | CTC_Digit), 0,
table))
return;
if (checkAttr(input->chars[k], CTC_Space, 0, table)) break;
}
break;
case CTO_PostPunc:
if (!checkAttr(input->chars[pos], CTC_Punctuation, 0, table) ||
(pos < (input->length - 1) &&
checkAttr(input->chars[pos + 1], CTC_Letter, 0,
table)))
break;
for (k = pos; k >= 0; k--) {
if (checkAttr(input->chars[k], (CTC_Letter | CTC_Digit), 0,
table))
return;
if (checkAttr(input->chars[k], CTC_Space, 0, table)) break;
}
break;
case CTO_Match: {
widechar *patterns, *pattern;
if (dontContract || (mode & noContractions)) break;
if (checkEmphasisChange(0, pos, emphasisBuffer, *transRule))
break;
patterns = (widechar *)&table->ruleArea[(*transRule)->patterns];
/* check before pattern */
pattern = &patterns[1];
if (!_lou_pattern_check(
input->chars, pos - 1, -1, -1, pattern, table))
break;
/* check after pattern */
pattern = &patterns[patterns[0]];
if (!_lou_pattern_check(input->chars,
pos + (*transRule)->charslen, input->length, 1,
pattern, table))
break;
return;
}
default:
break;
}
}
/* Done with checking this rule */
ruleOffset = (*transRule)->charsnext;
}
}
}
static int
undefinedCharacter(widechar c, const TranslationTableHeader *table, int pos,
const InString *input, OutString *output, int *posMapping, int *cursorPosition,
int *cursorStatus) {
/* Display an undefined character in the output buffer */
int k;
char *display;
widechar displayDots[20];
if (table->undefined) {
TranslationTableRule *rule =
(TranslationTableRule *)&table->ruleArea[table->undefined];
if (!for_updatePositions(&rule->charsdots[rule->charslen], rule->charslen,
rule->dotslen, 0, pos, input, output, posMapping, cursorPosition,
cursorStatus))
return 0;
return 1;
}
display = _lou_showString(&c, 1);
for (k = 0; k < (int)strlen(display); k++)
displayDots[k] = _lou_getDotsForChar(display[k]);
if (!for_updatePositions(displayDots, 1, (int)strlen(display), 0, pos, input, output,
posMapping, cursorPosition, cursorStatus))
return 0;
return 1;
}
static int
putCharacter(widechar character, const TranslationTableHeader *table, int pos,
const InString *input, OutString *output, int *posMapping, int *cursorPosition,
int *cursorStatus) {
/* Insert the dots equivalent of a character into the output buffer */
const TranslationTableRule *rule = NULL;
TranslationTableCharacter *chardef = NULL;
TranslationTableOffset offset;
widechar d;
chardef = (findCharOrDots(character, 0, table));
if ((chardef->attributes & CTC_Letter) && (chardef->attributes & CTC_UpperCase))
chardef = findCharOrDots(chardef->lowercase, 0, table);
// TODO: for_selectRule and this function screw up Digit and LitDigit
// NOTE: removed Litdigit from tables.
// if(!chardef->otherRules)
offset = chardef->definitionRule;
// else
//{
// offset = chardef->otherRules;
// rule = (TranslationTableRule *)&table->ruleArea[offset];
// while(rule->charsnext && rule->charsnext != chardef->definitionRule)
// {
// rule = (TranslationTableRule *)&table->ruleArea[offset];
// if(rule->charsnext)
// offset = rule->charsnext;
// }
//}
if (offset) {
rule = (TranslationTableRule *)&table->ruleArea[offset];
if (rule->dotslen)
return for_updatePositions(&rule->charsdots[1], 1, rule->dotslen, 0, pos,
input, output, posMapping, cursorPosition, cursorStatus);
d = _lou_getDotsForChar(character);
return for_updatePositions(&d, 1, 1, 0, pos, input, output, posMapping,
cursorPosition, cursorStatus);
}
return undefinedCharacter(character, table, pos, input, output, posMapping,
cursorPosition, cursorStatus);
}
static int
putCharacters(const widechar *characters, int count, const TranslationTableHeader *table,
int pos, const InString *input, OutString *output, int *posMapping,
int *cursorPosition, int *cursorStatus) {
/* Insert the dot equivalents of a series of characters in the output
* buffer */
int k;
for (k = 0; k < count; k++)
if (!putCharacter(characters[k], table, pos, input, output, posMapping,
cursorPosition, cursorStatus))
return 0;
return 1;
}
static int
doCompbrl(const TranslationTableHeader *table, int *pos, const InString *input,
OutString *output, int *posMapping, EmphasisInfo *emphasisBuffer,
const TranslationTableRule **transRule, int *cursorPosition, int *cursorStatus,
int destword, int srcword) {
/* Handle strings containing substrings defined by the compbrl opcode */
int stringStart, stringEnd;
if (checkAttr(input->chars[*pos], CTC_Space, 0, table)) return 1;
if (destword) {
*pos = srcword;
output->length = destword;
} else {
*pos = 0;
output->length = 0;
}
for (stringStart = *pos; stringStart >= 0; stringStart--)
if (checkAttr(input->chars[stringStart], CTC_Space, 0, table)) break;
stringStart++;
for (stringEnd = *pos; stringEnd < input->length; stringEnd++)
if (checkAttr(input->chars[stringEnd], CTC_Space, 0, table)) break;
return doCompTrans(stringStart, stringEnd, table, pos, input, output, posMapping,
emphasisBuffer, transRule, cursorPosition, cursorStatus);
}
static int
putCompChar(widechar character, const TranslationTableHeader *table, int pos,
const InString *input, OutString *output, int *posMapping, int *cursorPosition,
int *cursorStatus) {
/* Insert the dots equivalent of a character into the output buffer */
widechar d;
TranslationTableOffset offset = (findCharOrDots(character, 0, table))->definitionRule;
if (offset) {
const TranslationTableRule *rule =
(TranslationTableRule *)&table->ruleArea[offset];
if (rule->dotslen)
return for_updatePositions(&rule->charsdots[1], 1, rule->dotslen, 0, pos,
input, output, posMapping, cursorPosition, cursorStatus);
d = _lou_getDotsForChar(character);
return for_updatePositions(&d, 1, 1, 0, pos, input, output, posMapping,
cursorPosition, cursorStatus);
}
return undefinedCharacter(character, table, pos, input, output, posMapping,
cursorPosition, cursorStatus);
}
static int
doCompTrans(int start, int end, const TranslationTableHeader *table, int *pos,
const InString *input, OutString *output, int *posMapping,
EmphasisInfo *emphasisBuffer, const TranslationTableRule **transRule,
int *cursorPosition, int *cursorStatus) {
const TranslationTableRule *indicRule;
int k;
int haveEndsegment = 0;
if (*cursorStatus != 2 && brailleIndicatorDefined(table->begComp, table, &indicRule))
if (!for_updatePositions(&indicRule->charsdots[0], 0, indicRule->dotslen, 0, *pos,
input, output, posMapping, cursorPosition, cursorStatus))
return 0;
for (k = start; k < end; k++) {
TranslationTableOffset compdots = 0;
/* HACK: computer braille is one-to-one so it
* can't have any emphasis indicators.
* A better solution is to treat computer braille as its own mode. */
emphasisBuffer[k] = (EmphasisInfo){ 0 };
if (input->chars[k] == ENDSEGMENT) {
haveEndsegment = 1;
continue;
}
*pos = k;
if (input->chars[k] < 256) compdots = table->compdotsPattern[input->chars[k]];
if (compdots != 0) {
*transRule = (TranslationTableRule *)&table->ruleArea[compdots];
if (!for_updatePositions(&(*transRule)->charsdots[(*transRule)->charslen],
(*transRule)->charslen, (*transRule)->dotslen, 0, *pos, input,
output, posMapping, cursorPosition, cursorStatus))
return 0;
} else if (!putCompChar(input->chars[k], table, *pos, input, output, posMapping,
cursorPosition, cursorStatus))
return 0;
}
if (*cursorStatus != 2 && brailleIndicatorDefined(table->endComp, table, &indicRule))
if (!for_updatePositions(&indicRule->charsdots[0], 0, indicRule->dotslen, 0, *pos,
input, output, posMapping, cursorPosition, cursorStatus))
return 0;
*pos = end;
if (haveEndsegment) {
widechar endSegment = ENDSEGMENT;
if (!for_updatePositions(&endSegment, 0, 1, 0, *pos, input, output, posMapping,
cursorPosition, cursorStatus))
return 0;
}
return 1;
}
static int
doNocont(const TranslationTableHeader *table, int *pos, OutString *output, int mode,
const InString *input, int destword, int srcword, int *dontContract) {
/* Handle strings containing substrings defined by the nocont opcode */
if (checkAttr(input->chars[*pos], CTC_Space, 0, table) || *dontContract ||
(mode & noContractions))
return 1;
if (destword) {
*pos = srcword;
output->length = destword;
} else {
*pos = 0;
output->length = 0;
}
*dontContract = 1;
return 1;
}
static int
markSyllables(const TranslationTableHeader *table, const InString *input,
formtype *typebuf, int *transOpcode, const TranslationTableRule **transRule,
int *transCharslen) {
int pos;
int k;
int currentMark = 0;
int const syllable_marks[] = { SYLLABLE_MARKER_1, SYLLABLE_MARKER_2 };
int syllable_mark_selector = 0;
if (typebuf == NULL || !table->syllables) return 1;
pos = 0;
while (pos < input->length) { /* the main multipass translation loop */
int length = input->length - pos;
const TranslationTableCharacter *character =
findCharOrDots(input->chars[pos], 0, table);
const TranslationTableCharacter *character2;
int tryThis = 0;
while (tryThis < 3) {
TranslationTableOffset ruleOffset = 0;
unsigned long int makeHash = 0;
switch (tryThis) {
case 0:
if (!(length >= 2)) break;
makeHash = (unsigned long int)character->lowercase << 8;
// memory overflow when pos == input->length - 1
character2 = findCharOrDots(input->chars[pos + 1], 0, table);
makeHash += (unsigned long int)character2->lowercase;
makeHash %= HASHNUM;
ruleOffset = table->forRules[makeHash];
break;
case 1:
if (!(length >= 1)) break;
length = 1;
ruleOffset = character->otherRules;
break;
case 2: /* No rule found */
*transOpcode = CTO_Always;
ruleOffset = 0;
break;
}
while (ruleOffset) {
*transRule = (TranslationTableRule *)&table->ruleArea[ruleOffset];
*transOpcode = (*transRule)->opcode;
*transCharslen = (*transRule)->charslen;
if (tryThis == 1 ||
(*transCharslen <= length &&
compareChars(&(*transRule)->charsdots[0],
&input->chars[pos], *transCharslen, 0, table))) {
if (*transOpcode == CTO_Syllable) {
tryThis = 4;
break;
}
}
ruleOffset = (*transRule)->charsnext;
}
tryThis++;
}
switch (*transOpcode) {
case CTO_Always:
if (pos >= input->length) return 0;
typebuf[pos++] |= currentMark;
break;
case CTO_Syllable:
/* cycle between SYLLABLE_MARKER_1 and SYLLABLE_MARKER_2 so
* we can distinguinsh two consequtive syllables */
currentMark = syllable_marks[syllable_mark_selector];
syllable_mark_selector = (syllable_mark_selector + 1) % 2;
if ((pos + *transCharslen) > input->length) return 0;
for (k = 0; k < *transCharslen; k++) typebuf[pos++] |= currentMark;
break;
default:
break;
}
}
return 1;
}
static const EmphasisClass capsEmphClass = 0x1;
static const EmphasisClass *emphClasses = NULL;
/* An emphasis class is a bit field that contains a single "1" */
static void
initEmphClasses() {
EmphasisClass *classes = malloc(10 * sizeof(EmphasisClass));
int j;
if (!classes) _lou_outOfMemory();
for (j = 0; j < 10; j++) {
classes[j] = 0x1 << (j + 1);
}
emphClasses = classes;
}
static void
resolveEmphasisWords(EmphasisInfo *buffer, const EmphasisClass class,
const InString *input, unsigned int *wordBuffer) {
int in_word = 0, in_emp = 0, word_stop; // booleans
int word_start = -1; // input position
unsigned int word_whole = 0; // wordBuffer value
int i;
for (i = 0; i < input->length; i++) {
// TODO: give each emphasis its own whole word bit?
/* clear out previous whole word markings */
wordBuffer[i] &= ~WORD_WHOLE;
/* check if at beginning of emphasis */
if (!in_emp)
if (buffer[i].begin & class) {
in_emp = 1;
buffer[i].begin &= ~class;
/* emphasis started inside word */
if (in_word) {
word_start = i;
word_whole = 0;
}
/* emphasis started on space */
if (!(wordBuffer[i] & WORD_CHAR)) word_start = -1;
}
/* check if at end of emphasis */
if (in_emp)
if (buffer[i].end & class) {
in_emp = 0;
buffer[i].end &= ~class;
if (in_word && word_start >= 0) {
/* check if emphasis ended inside a word */
word_stop = 1;
if (wordBuffer[i] & WORD_CHAR)
word_whole = 0;
else
word_stop = 0;
/* if whole word is one symbol,
* turn it into a symbol */
if (word_start + 1 == i)
buffer[word_start].symbol |= class;
else {
buffer[word_start].word |= class;
if (word_stop) {
buffer[i].end |= class;
buffer[i].word |= class;
}
}
wordBuffer[word_start] |= word_whole;
}
}
/* check if at beginning of word */
if (!in_word)
if (wordBuffer[i] & WORD_CHAR) {
in_word = 1;
if (in_emp) {
word_whole = WORD_WHOLE;
word_start = i;
}
}
/* check if at end of word */
if (in_word)
if (!(wordBuffer[i] & WORD_CHAR)) {
/* made it through whole word */
if (in_emp && word_start >= 0) {
/* if word is one symbol,
* turn it into a symbol */
if (word_start + 1 == i)
buffer[word_start].symbol |= class;
else
buffer[word_start].word |= class;
wordBuffer[word_start] |= word_whole;
}
in_word = 0;
word_whole = 0;
word_start = -1;
}
}
/* clean up end */
if (in_emp) {
buffer[i].end &= ~class;
if (in_word)
if (word_start >= 0) {
/* if word is one symbol,
* turn it into a symbol */
if (word_start + 1 == i)
buffer[word_start].symbol |= class;
else
buffer[word_start].word |= class;
wordBuffer[word_start] |= word_whole;
}
}
}
static void
convertToPassage(const int pass_start, const int pass_end, const int word_start,
EmphasisInfo *buffer, const EmphRuleNumber emphRule, const EmphasisClass class,
const TranslationTableHeader *table, unsigned int *wordBuffer) {
int i;
const TranslationTableRule *indicRule;
for (i = pass_start; i <= pass_end; i++)
if (wordBuffer[i] & WORD_WHOLE) {
buffer[i].symbol &= ~class;
buffer[i].word &= ~class;
wordBuffer[i] &= ~WORD_WHOLE;
}
buffer[pass_start].begin |= class;
if (brailleIndicatorDefined(
table->emphRules[emphRule][endOffset], table, &indicRule) ||
brailleIndicatorDefined(
table->emphRules[emphRule][endPhraseAfterOffset], table, &indicRule))
buffer[pass_end].end |= class;
else if (brailleIndicatorDefined(table->emphRules[emphRule][endPhraseBeforeOffset],
table, &indicRule))
buffer[word_start].end |= class;
}
static void
resolveEmphasisPassages(EmphasisInfo *buffer, const EmphRuleNumber emphRule,
const EmphasisClass class, const TranslationTableHeader *table,
const InString *input, unsigned int *wordBuffer) {
unsigned int word_cnt = 0;
int pass_start = -1, pass_end = -1, word_start = -1, in_word = 0, in_pass = 0;
int i;
for (i = 0; i < input->length; i++) {
/* check if at beginning of word */
if (!in_word)
if (wordBuffer[i] & WORD_CHAR) {
in_word = 1;
if (wordBuffer[i] & WORD_WHOLE) {
if (!in_pass) {
in_pass = 1;
pass_start = i;
pass_end = -1;
word_cnt = 1;
} else
word_cnt++;
word_start = i;
continue;
} else if (in_pass) {
if (word_cnt >= table->emphRules[emphRule][lenPhraseOffset])
if (pass_end >= 0) {
convertToPassage(pass_start, pass_end, word_start, buffer,
emphRule, class, table, wordBuffer);
}
in_pass = 0;
}
}
/* check if at end of word */
if (in_word)
if (!(wordBuffer[i] & WORD_CHAR)) {
in_word = 0;
if (in_pass) pass_end = i;
}
if (in_pass)
if ((buffer[i].begin | buffer[i].end | buffer[i].word | buffer[i].symbol) &
class) {
if (word_cnt >= table->emphRules[emphRule][lenPhraseOffset])
if (pass_end >= 0) {
convertToPassage(pass_start, pass_end, word_start, buffer,
emphRule, class, table, wordBuffer);
}
in_pass = 0;
}
}
if (in_pass) {
if (word_cnt >= table->emphRules[emphRule][lenPhraseOffset]) {
if (pass_end >= 0) {
if (in_word) {
convertToPassage(pass_start, i, word_start, buffer, emphRule, class,
table, wordBuffer);
} else {
convertToPassage(pass_start, pass_end, word_start, buffer, emphRule,
class, table, wordBuffer);
}
}
}
}
}
static void
resolveEmphasisSingleSymbols(
EmphasisInfo *buffer, const EmphasisClass class, const InString *input) {
int i;
for (i = 0; i < input->length; i++) {
if (buffer[i].begin & class)
if (buffer[i + 1].end & class) {
buffer[i].begin &= ~class;
buffer[i + 1].end &= ~class;
buffer[i].symbol |= class;
}
}
}
static void
resolveEmphasisAllCapsSymbols(
EmphasisInfo *buffer, formtype *typebuf, const InString *input) {
/* Marks every caps letter with capsEmphClass symbol.
* Used in the special case where capsnocont has been defined and capsword has not
* been defined. */
int inEmphasis = 0, i;
for (i = 0; i < input->length; i++) {
if (buffer[i].end & capsEmphClass) {
inEmphasis = 0;
buffer[i].end &= ~capsEmphClass;
} else {
if (buffer[i].begin & capsEmphClass) {
buffer[i].begin &= ~capsEmphClass;
inEmphasis = 1;
}
if (inEmphasis) {
if (typebuf[i] & CAPSEMPH)
/* Only mark if actually a capital letter (don't mark spaces or
* punctuation). */
buffer[i].symbol |= capsEmphClass;
} /* In emphasis */
} /* Not caps end */
}
}
static void
resolveEmphasisResets(EmphasisInfo *buffer, const EmphasisClass class,
const TranslationTableHeader *table, const InString *input,
unsigned int *wordBuffer) {
int in_word = 0, in_pass = 0, word_start = -1, word_reset = 0, orig_reset = -1,
letter_cnt = 0;
int i, j;
for (i = 0; i < input->length; i++) {
if (in_pass)
if (buffer[i].end & class) in_pass = 0;
if (!in_pass) {
if (buffer[i].begin & class)
in_pass = 1;
else {
if (!in_word) {
if (buffer[i].word & class) {
/* deal with case when reset
* was at beginning of word */
if (wordBuffer[i] & WORD_RESET ||
!checkAttr(input->chars[i], CTC_Letter, 0, table)) {
/* not just one reset by itself */
if (wordBuffer[i + 1] & WORD_CHAR) {
buffer[i + 1].word |= class;
if (wordBuffer[i] & WORD_WHOLE)
wordBuffer[i + 1] |= WORD_WHOLE;
}
buffer[i].word &= ~class;
wordBuffer[i] &= ~WORD_WHOLE;
/* if reset is a letter, make it a symbol */
if (checkAttr(input->chars[i], CTC_Letter, 0, table))
buffer[i].symbol |= class;
continue;
}
in_word = 1;
word_start = i;
letter_cnt = 0;
word_reset = 0;
}
/* it is possible for a character to have been
* marked as a symbol when it should not be one */
else if (buffer[i].symbol & class) {
if (wordBuffer[i] & WORD_RESET ||
!checkAttr(input->chars[i], CTC_Letter, 0, table))
buffer[i].symbol &= ~class;
}
}
if (in_word) {
/* at end of word */
if (!(wordBuffer[i] & WORD_CHAR) ||
(buffer[i].word & class && buffer[i].end & class)) {
in_word = 0;
/* check if symbol */
if (letter_cnt == 1) {
buffer[word_start].symbol |= class;
buffer[word_start].word &= ~class;
wordBuffer[word_start] &= ~WORD_WHOLE;
buffer[i].end &= ~class;
buffer[i].word &= ~class;
}
/* if word ended on a reset or last char was a reset,
* get rid of end bits */
if (word_reset || wordBuffer[i] & WORD_RESET ||
!checkAttr(input->chars[i], CTC_Letter, 0, table)) {
buffer[i].end &= ~class;
buffer[i].word &= ~class;
}
/* if word ended when it began, get rid of all bits */
if (i == word_start) {
wordBuffer[word_start] &= ~WORD_WHOLE;
buffer[i].end &= ~class;
buffer[i].word &= ~class;
}
orig_reset = -1;
} else {
/* hit reset */
if (wordBuffer[i] & WORD_RESET ||
!checkAttr(input->chars[i], CTC_Letter, 0, table)) {
if (!checkAttr(input->chars[i], CTC_Letter, 0, table)) {
if (checkAttr(input->chars[i], CTC_CapsMode, 0, table)) {
/* chars marked as not resetting */
orig_reset = i;
continue;
} else if (orig_reset >= 0) {
/* invalid no reset sequence */
for (j = orig_reset; j < i; j++)
buffer[j].word &= ~class;
// word_reset = 1;
orig_reset = -1;
}
}
/* check if symbol is not already resetting */
if (letter_cnt == 1) {
buffer[word_start].symbol |= class;
buffer[word_start].word &= ~class;
wordBuffer[word_start] &= ~WORD_WHOLE;
}
/* if reset is a letter, make it the new word_start */
if (checkAttr(input->chars[i], CTC_Letter, 0, table)) {
word_reset = 0;
word_start = i;
letter_cnt = 1;
buffer[i].word |= class;
} else
word_reset = 1;
continue;
}
if (word_reset) {
word_reset = 0;
word_start = i;
letter_cnt = 0;
buffer[i].word |= class;
}
letter_cnt++;
}
}
}
}
}
/* clean up end */
if (in_word) {
/* check if symbol */
if (letter_cnt == 1) {
buffer[word_start].symbol |= class;
buffer[word_start].word &= ~class;
wordBuffer[word_start] &= ~WORD_WHOLE;
buffer[i].end &= ~class;
buffer[i].word &= ~class;
}
if (word_reset) {
buffer[i].end &= ~class;
buffer[i].word &= ~class;
}
}
}
static void
markEmphases(const TranslationTableHeader *table, const InString *input,
formtype *typebuf, unsigned int *wordBuffer, EmphasisInfo *emphasisBuffer,
int haveEmphasis) {
/* Relies on the order of typeforms emph_1..emph_10. */
int caps_start = -1, last_caps = -1, caps_cnt = 0;
int emph_start[10] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 };
int i, j;
// initialize static variable emphClasses
if (haveEmphasis && !emphClasses) {
initEmphClasses();
}
for (i = 0; i < input->length; i++) {
if (!checkAttr(input->chars[i], CTC_Space, 0, table)) {
wordBuffer[i] |= WORD_CHAR;
} else if (caps_cnt > 0) {
last_caps = i;
caps_cnt = 0;
}
if (checkAttr(input->chars[i], CTC_UpperCase, 0, table)) {
if (caps_start < 0) caps_start = i;
caps_cnt++;
} else if (caps_start >= 0) {
/* caps should keep going until this */
if (checkAttr(input->chars[i], CTC_Letter, 0, table) &&
checkAttr(input->chars[i], CTC_LowerCase, 0, table)) {
emphasisBuffer[caps_start].begin |= capsEmphClass;
if (caps_cnt > 0)
emphasisBuffer[i].end |= capsEmphClass;
else
emphasisBuffer[last_caps].end |= capsEmphClass;
caps_start = -1;
last_caps = -1;
caps_cnt = 0;
}
}
if (!haveEmphasis) continue;
for (j = 0; j < 10; j++) {
if (typebuf[i] & (emph_1 << j)) {
if (emph_start[j] < 0) emph_start[j] = i;
} else if (emph_start[j] >= 0) {
emphasisBuffer[emph_start[j]].begin |= emphClasses[j];
emphasisBuffer[i].end |= emphClasses[j];
emph_start[j] = -1;
}
}
}
/* clean up input->length */
if (caps_start >= 0) {
emphasisBuffer[caps_start].begin |= capsEmphClass;
if (caps_cnt > 0)
emphasisBuffer[input->length].end |= capsEmphClass;
else
emphasisBuffer[last_caps].end |= capsEmphClass;
}
if (haveEmphasis) {
for (j = 0; j < 10; j++) {
if (emph_start[j] >= 0) {
emphasisBuffer[emph_start[j]].begin |= emphClasses[j];
emphasisBuffer[input->length].end |= emphClasses[j];
}
}
}
/* Handle capsnocont */
if (table->capsNoCont) {
int inCaps = 0;
for (i = 0; i < input->length; i++) {
if (emphasisBuffer[i].end & capsEmphClass) {
inCaps = 0;
} else {
if ((emphasisBuffer[i].begin & capsEmphClass) &&
!(emphasisBuffer[i + 1].end & capsEmphClass))
inCaps = 1;
if (inCaps) typebuf[i] |= no_contract;
}
}
}
if (table->emphRules[capsRule][begWordOffset]) {
resolveEmphasisWords(emphasisBuffer, capsEmphClass, input, wordBuffer);
if (table->emphRules[capsRule][lenPhraseOffset])
resolveEmphasisPassages(
emphasisBuffer, capsRule, capsEmphClass, table, input, wordBuffer);
resolveEmphasisResets(emphasisBuffer, capsEmphClass, table, input, wordBuffer);
} else if (table->emphRules[capsRule][letterOffset]) {
if (table->capsNoCont) /* capsnocont and no capsword */
resolveEmphasisAllCapsSymbols(emphasisBuffer, typebuf, input);
else
resolveEmphasisSingleSymbols(emphasisBuffer, capsEmphClass, input);
}
if (!haveEmphasis) return;
for (j = 0; j < 10; j++) {
if (table->emphRules[emph1Rule + j][begWordOffset]) {
resolveEmphasisWords(emphasisBuffer, emphClasses[j], input, wordBuffer);
if (table->emphRules[emph1Rule + j][lenPhraseOffset])
resolveEmphasisPassages(emphasisBuffer, emph1Rule + j, emphClasses[j],
table, input, wordBuffer);
} else if (table->emphRules[emph1Rule + j][letterOffset])
resolveEmphasisSingleSymbols(emphasisBuffer, emphClasses[j], input);
}
}
static void
insertEmphasisSymbol(const EmphasisInfo *buffer, const int at,
const EmphRuleNumber emphRule, const EmphasisClass class,
const TranslationTableHeader *table, int pos, const InString *input,
OutString *output, int *posMapping, int *cursorPosition, int *cursorStatus) {
if (buffer[at].symbol & class) {
const TranslationTableRule *indicRule;
if (brailleIndicatorDefined(
table->emphRules[emphRule][letterOffset], table, &indicRule))
for_updatePositions(&indicRule->charsdots[0], 0, indicRule->dotslen, 0, pos,
input, output, posMapping, cursorPosition, cursorStatus);
}
}
static void
insertEmphasisBegin(const EmphasisInfo *buffer, const int at,
const EmphRuleNumber emphRule, const EmphasisClass class,
const TranslationTableHeader *table, int pos, const InString *input,
OutString *output, int *posMapping, int *cursorPosition, int *cursorStatus) {
const TranslationTableRule *indicRule;
if (buffer[at].begin & class) {
if (brailleIndicatorDefined(
table->emphRules[emphRule][begPhraseOffset], table, &indicRule))
for_updatePositions(&indicRule->charsdots[0], 0, indicRule->dotslen, 0, pos,
input, output, posMapping, cursorPosition, cursorStatus);
else if (brailleIndicatorDefined(
table->emphRules[emphRule][begOffset], table, &indicRule))
for_updatePositions(&indicRule->charsdots[0], 0, indicRule->dotslen, 0, pos,
input, output, posMapping, cursorPosition, cursorStatus);
}
if (buffer[at].word & class
// && !(buffer[at].begin & class)
&& !(buffer[at].end & class)) {
if (brailleIndicatorDefined(
table->emphRules[emphRule][begWordOffset], table, &indicRule))
for_updatePositions(&indicRule->charsdots[0], 0, indicRule->dotslen, 0, pos,
input, output, posMapping, cursorPosition, cursorStatus);
}
}
static void
insertEmphasisEnd(const EmphasisInfo *buffer, const int at, const EmphRuleNumber emphRule,
const EmphasisClass class, const TranslationTableHeader *table, int pos,
const InString *input, OutString *output, int *posMapping, int *cursorPosition,
int *cursorStatus) {
if (buffer[at].end & class) {
const TranslationTableRule *indicRule;
if (buffer[at].word & class) {
if (brailleIndicatorDefined(
table->emphRules[emphRule][endWordOffset], table, &indicRule))
for_updatePositions(&indicRule->charsdots[0], 0, indicRule->dotslen, -1,
pos, input, output, posMapping, cursorPosition, cursorStatus);
} else {
if (brailleIndicatorDefined(
table->emphRules[emphRule][endOffset], table, &indicRule))
for_updatePositions(&indicRule->charsdots[0], 0, indicRule->dotslen, -1,
pos, input, output, posMapping, cursorPosition, cursorStatus);
else if (brailleIndicatorDefined(
table->emphRules[emphRule][endPhraseAfterOffset], table,
&indicRule))
for_updatePositions(&indicRule->charsdots[0], 0, indicRule->dotslen, -1,
pos, input, output, posMapping, cursorPosition, cursorStatus);
else if (brailleIndicatorDefined(
table->emphRules[emphRule][endPhraseBeforeOffset], table,
&indicRule))
for_updatePositions(&indicRule->charsdots[0], 0, indicRule->dotslen, 0,
pos, input, output, posMapping, cursorPosition, cursorStatus);
}
}
}
static int
endCount(const EmphasisInfo *buffer, const int at, const EmphasisClass class) {
int i, cnt = 1;
if (!(buffer[at].end & class)) return 0;
for (i = at - 1; i >= 0; i--)
if (buffer[i].begin & class || buffer[i].word & class)
break;
else
cnt++;
return cnt;
}
static int
beginCount(const EmphasisInfo *buffer, const int at, const EmphasisClass class,
const TranslationTableHeader *table, const InString *input) {
if (buffer[at].begin & class) {
int i, cnt = 1;
for (i = at + 1; i < input->length; i++)
if (buffer[i].end & class)
break;
else
cnt++;
return cnt;
} else if (buffer[at].word & class) {
int i, cnt = 1;
for (i = at + 1; i < input->length; i++)
if (buffer[i].end & class) break;
// TODO: WORD_RESET?
else if (checkAttr(input->chars[i], CTC_SeqDelimiter | CTC_Space, 0, table))
break;
else
cnt++;
return cnt;
}
return 0;
}
static void
insertEmphasesAt(const int at, const TranslationTableHeader *table, int pos,
const InString *input, OutString *output, int *posMapping,
const EmphasisInfo *emphasisBuffer, int haveEmphasis, int transOpcode,
int *cursorPosition, int *cursorStatus) {
int type_counts[10];
int i, j, min, max;
/* simple case */
if (!haveEmphasis) {
/* insert graded 1 mode indicator */
if (transOpcode == CTO_Contraction) {
const TranslationTableRule *indicRule;
if (brailleIndicatorDefined(table->noContractSign, table, &indicRule))
for_updatePositions(&indicRule->charsdots[0], 0, indicRule->dotslen, 0,
pos, input, output, posMapping, cursorPosition, cursorStatus);
}
if ((emphasisBuffer[at].begin | emphasisBuffer[at].end | emphasisBuffer[at].word |
emphasisBuffer[at].symbol) &
capsEmphClass) {
insertEmphasisEnd(emphasisBuffer, at, capsRule, capsEmphClass, table, pos,
input, output, posMapping, cursorPosition, cursorStatus);
insertEmphasisBegin(emphasisBuffer, at, capsRule, capsEmphClass, table, pos,
input, output, posMapping, cursorPosition, cursorStatus);
insertEmphasisSymbol(emphasisBuffer, at, capsRule, capsEmphClass, table, pos,
input, output, posMapping, cursorPosition, cursorStatus);
}
return;
}
/* The order of inserting the end symbols must be the reverse
* of the insertions of the begin symbols so that they will
* nest properly when multiple emphases start and end at
* the same place */
// TODO: ordering with partial word
if ((emphasisBuffer[at].begin | emphasisBuffer[at].end | emphasisBuffer[at].word |
emphasisBuffer[at].symbol) &
capsEmphClass)
insertEmphasisEnd(emphasisBuffer, at, capsRule, capsEmphClass, table, pos, input,
output, posMapping, cursorPosition, cursorStatus);
/* end bits */
for (i = 0; i < 10; i++)
type_counts[i] = endCount(emphasisBuffer, at, emphClasses[i]);
for (i = 0; i < 10; i++) {
min = -1;
for (j = 0; j < 10; j++)
if (type_counts[j] > 0)
if (min < 0 || type_counts[j] < type_counts[min]) min = j;
if (min < 0) break;
type_counts[min] = 0;
insertEmphasisEnd(emphasisBuffer, at, emph1Rule + min, emphClasses[min], table,
pos, input, output, posMapping, cursorPosition, cursorStatus);
}
/* begin and word bits */
for (i = 0; i < 10; i++)
type_counts[i] = beginCount(emphasisBuffer, at, emphClasses[i], table, input);
for (i = 9; i >= 0; i--) {
max = 9;
for (j = 9; j >= 0; j--)
if (type_counts[max] < type_counts[j]) max = j;
if (!type_counts[max]) break;
type_counts[max] = 0;
insertEmphasisBegin(emphasisBuffer, at, emph1Rule + max, emphClasses[max], table,
pos, input, output, posMapping, cursorPosition, cursorStatus);
}
/* symbol bits */
for (i = 9; i >= 0; i--)
if ((emphasisBuffer[at].begin | emphasisBuffer[at].end | emphasisBuffer[at].word |
emphasisBuffer[at].symbol) &
emphClasses[i])
insertEmphasisSymbol(emphasisBuffer, at, emph1Rule + i, emphClasses[i], table,
pos, input, output, posMapping, cursorPosition, cursorStatus);
/* insert graded 1 mode indicator */
if (transOpcode == CTO_Contraction) {
const TranslationTableRule *indicRule;
if (brailleIndicatorDefined(table->noContractSign, table, &indicRule))
for_updatePositions(&indicRule->charsdots[0], 0, indicRule->dotslen, 0, pos,
input, output, posMapping, cursorPosition, cursorStatus);
}
/* insert capitalization last so it will be closest to word */
if ((emphasisBuffer[at].begin | emphasisBuffer[at].end | emphasisBuffer[at].word |
emphasisBuffer[at].symbol) &
capsEmphClass) {
insertEmphasisBegin(emphasisBuffer, at, capsRule, capsEmphClass, table, pos,
input, output, posMapping, cursorPosition, cursorStatus);
insertEmphasisSymbol(emphasisBuffer, at, capsRule, capsEmphClass, table, pos,
input, output, posMapping, cursorPosition, cursorStatus);
}
}
static void
insertEmphases(const TranslationTableHeader *table, int pos, const InString *input,
OutString *output, int *posMapping, const EmphasisInfo *emphasisBuffer,
int haveEmphasis, int transOpcode, int *cursorPosition, int *cursorStatus,
int *pre_src) {
int at;
for (at = *pre_src; at <= pos; at++)
insertEmphasesAt(at, table, pos, input, output, posMapping, emphasisBuffer,
haveEmphasis, transOpcode, cursorPosition, cursorStatus);
*pre_src = pos + 1;
}
static void
checkNumericMode(const TranslationTableHeader *table, int pos, const InString *input,
OutString *output, int *posMapping, int *cursorPosition, int *cursorStatus,
int *dontContract, int *numericMode) {
int i;
const TranslationTableRule *indicRule;
if (!brailleIndicatorDefined(table->numberSign, table, &indicRule)) return;
/* not in numeric mode */
if (!*numericMode) {
if (checkAttr(input->chars[pos], CTC_Digit | CTC_LitDigit, 0, table)) {
*numericMode = 1;
*dontContract = 1;
for_updatePositions(&indicRule->charsdots[0], 0, indicRule->dotslen, 0, pos,
input, output, posMapping, cursorPosition, cursorStatus);
} else if (checkAttr(input->chars[pos], CTC_NumericMode, 0, table)) {
for (i = pos + 1; i < input->length; i++) {
if (checkAttr(input->chars[i], CTC_Digit | CTC_LitDigit, 0, table)) {
*numericMode = 1;
for_updatePositions(&indicRule->charsdots[0], 0, indicRule->dotslen,
0, pos, input, output, posMapping, cursorPosition,
cursorStatus);
break;
} else if (!checkAttr(input->chars[i], CTC_NumericMode, 0, table))
break;
}
}
}
/* in numeric mode */
else {
if (!checkAttr(input->chars[pos],
CTC_Digit | CTC_LitDigit | CTC_NumericMode | CTC_MidEndNumericMode, 0,
table)) {
*numericMode = 0;
if (brailleIndicatorDefined(table->noContractSign, table, &indicRule))
if (checkAttr(input->chars[pos], CTC_NumericNoContract, 0, table))
for_updatePositions(&indicRule->charsdots[0], 0, indicRule->dotslen,
0, pos, input, output, posMapping, cursorPosition,
cursorStatus);
}
}
}
static int
translateString(const TranslationTableHeader *table, int mode, int currentPass,
const InString *input, OutString *output, int *posMapping, formtype *typebuf,
unsigned char *srcSpacing, unsigned char *destSpacing, unsigned int *wordBuffer,
EmphasisInfo *emphasisBuffer, int haveEmphasis, int *realInlen,
int *posIncremented, int *cursorPosition, int *cursorStatus, int compbrlStart,
int compbrlEnd) {
int pos;
int transOpcode;
int prevTransOpcode;
const TranslationTableRule *transRule;
int transCharslen;
int passCharDots;
const widechar *passInstructions;
int passIC; /* Instruction counter */
PassRuleMatch patternMatch;
TranslationTableRule *groupingRule;
widechar groupingOp;
int numericMode;
int dontContract;
int destword;
int srcword;
int pre_src;
TranslationTableCharacter *curCharDef;
const widechar *repwordStart;
int repwordLength;
int curType;
int prevType;
int prevTypeform;
int prevPos;
const InString *origInput = input;
/* Main translation routine */
int k;
translation_direction = 1;
markSyllables(table, input, typebuf, &transOpcode, &transRule, &transCharslen);
numericMode = 0;
srcword = 0;
destword = 0; /* last word translated */
dontContract = 0;
prevTransOpcode = CTO_None;
prevType = curType = prevTypeform = plain_text;
prevPos = -1;
pos = output->length = 0;
*posIncremented = 1;
pre_src = 0;
_lou_resetPassVariables();
if (typebuf && table->emphRules[capsRule][letterOffset])
for (k = 0; k < input->length; k++)
if (checkAttr(input->chars[k], CTC_UpperCase, 0, table))
typebuf[k] |= CAPSEMPH;
markEmphases(table, input, typebuf, wordBuffer, emphasisBuffer, haveEmphasis);
while (pos < input->length) { /* the main translation loop */
if ((pos >= compbrlStart) && (pos < compbrlEnd)) {
int cs = 2; // cursor status for this call
if (!doCompTrans(pos, compbrlEnd, table, &pos, input, output, posMapping,
emphasisBuffer, &transRule, cursorPosition, &cs))
goto failure;
continue;
}
TranslationTableCharacterAttributes beforeAttributes;
setBefore(table, pos, input, &beforeAttributes);
if (!insertBrailleIndicators(0, table, pos, input, output, posMapping, typebuf,
haveEmphasis, transOpcode, prevTransOpcode, cursorPosition,
cursorStatus, beforeAttributes, &prevType, &curType, &prevTypeform,
prevPos))
goto failure;
if (pos >= input->length) break;
// insertEmphases();
if (!dontContract) dontContract = typebuf[pos] & no_contract;
if (typebuf[pos] & no_translate) {
widechar c = _lou_getDotsForChar(input->chars[pos]);
if (input->chars[pos] < 32 || input->chars[pos] > 126) goto failure;
if (!for_updatePositions(&c, 1, 1, 0, pos, input, output, posMapping,
cursorPosition, cursorStatus))
goto failure;
pos++;
/* because we don't call insertEmphasis */
pre_src = pos;
continue;
}
for_selectRule(table, pos, *output, mode, input, typebuf, emphasisBuffer,
&transOpcode, prevTransOpcode, &transRule, &transCharslen, &passCharDots,
&passInstructions, &passIC, &patternMatch, *posIncremented,
*cursorPosition, &repwordStart, &repwordLength, dontContract,
compbrlStart, compbrlEnd, beforeAttributes, &curCharDef, &groupingRule,
&groupingOp);
if (transOpcode != CTO_Context)
if (appliedRules != NULL && appliedRulesCount < maxAppliedRules)
appliedRules[appliedRulesCount++] = transRule;
*posIncremented = 1;
prevPos = pos;
switch (transOpcode) /* Rules that pre-empt context and swap */
{
case CTO_CompBrl:
case CTO_Literal:
if (!doCompbrl(table, &pos, input, output, posMapping, emphasisBuffer,
&transRule, cursorPosition, cursorStatus, destword, srcword))
goto failure;
continue;
default:
break;
}
if (!insertBrailleIndicators(1, table, pos, input, output, posMapping, typebuf,
haveEmphasis, transOpcode, prevTransOpcode, cursorPosition,
cursorStatus, beforeAttributes, &prevType, &curType, &prevTypeform,
prevPos))
goto failure;
// if(transOpcode == CTO_Contraction)
// if(brailleIndicatorDefined(table->noContractSign))
// if(!for_updatePositions(
// &indicRule->charsdots[0], 0, indicRule->dotslen, 0))
// goto failure;
insertEmphases(table, pos, input, output, posMapping, emphasisBuffer,
haveEmphasis, transOpcode, cursorPosition, cursorStatus, &pre_src);
if (table->usesNumericMode)
checkNumericMode(table, pos, input, output, posMapping, cursorPosition,
cursorStatus, &dontContract, &numericMode);
if (transOpcode == CTO_Context ||
findForPassRule(table, pos, currentPass, input, &transOpcode, &transRule,
&transCharslen, &passCharDots, &passInstructions, &passIC,
&patternMatch, &groupingRule, &groupingOp))
switch (transOpcode) {
case CTO_Context: {
const InString *inputBefore = input;
int posBefore = pos;
if (appliedRules != NULL && appliedRulesCount < maxAppliedRules)
appliedRules[appliedRulesCount++] = transRule;
if (!passDoAction(table, &input, output, posMapping, transOpcode,
&transRule, passCharDots, passInstructions, passIC, &pos,
patternMatch, cursorPosition, cursorStatus, groupingRule,
groupingOp))
goto failure;
if (input->bufferIndex != inputBefore->bufferIndex &&
inputBefore->bufferIndex != origInput->bufferIndex)
releaseStringBuffer(inputBefore->bufferIndex);
if (pos == posBefore) *posIncremented = 0;
continue;
}
default:
break;
}
/* Processing before replacement */
/* check if leaving no contraction (grade 1) mode */
if (checkAttr(input->chars[pos], CTC_SeqDelimiter | CTC_Space, 0, table))
dontContract = 0;
switch (transOpcode) {
case CTO_EndNum:
if (table->letterSign && checkAttr(input->chars[pos], CTC_Letter, 0, table))
output->length--;
break;
case CTO_Repeated:
case CTO_Space:
dontContract = 0;
break;
case CTO_LargeSign:
if (prevTransOpcode == CTO_LargeSign) {
int hasEndSegment = 0;
while (output->length > 0 && checkAttr(output->chars[output->length - 1],
CTC_Space, 1, table)) {
if (output->chars[output->length - 1] == ENDSEGMENT) {
hasEndSegment = 1;
}
output->length--;
}
if (hasEndSegment != 0) {
output->chars[output->length] = 0xffff;
output->length++;
}
}
break;
case CTO_DecPoint:
if (!table->usesNumericMode && table->numberSign) {
TranslationTableRule *numRule =
(TranslationTableRule *)&table->ruleArea[table->numberSign];
if (!for_updatePositions(&numRule->charsdots[numRule->charslen],
numRule->charslen, numRule->dotslen, 0, pos, input, output,
posMapping, cursorPosition, cursorStatus))
goto failure;
}
transOpcode = CTO_MidNum;
break;
case CTO_NoCont:
if (!dontContract)
doNocont(table, &pos, output, mode, input, destword, srcword,
&dontContract);
continue;
default:
break;
} /* end of action */
/* replacement processing */
switch (transOpcode) {
case CTO_Replace:
pos += transCharslen;
if (!putCharacters(&transRule->charsdots[transCharslen], transRule->dotslen,
table, pos, input, output, posMapping, cursorPosition,
cursorStatus))
goto failure;
break;
case CTO_None:
if (!undefinedCharacter(input->chars[pos], table, pos, input, output,
posMapping, cursorPosition, cursorStatus))
goto failure;
pos++;
break;
case CTO_UpperCase:
/* Only needs special handling if not within compbrl and
* the table defines a capital sign. */
if (!(mode & (compbrlAtCursor | compbrlLeftCursor)) &&
(transRule->dotslen == 1 &&
table->emphRules[capsRule][letterOffset])) {
if (!putCharacter(curCharDef->lowercase, table, pos, input, output,
posMapping, cursorPosition, cursorStatus))
goto failure;
pos++;
break;
}
// case CTO_Contraction:
//
// if(brailleIndicatorDefined(table->noContractSign))
// if(!for_updatePositions(
// &indicRule->charsdots[0], 0, indicRule->dotslen, 0))
// goto failure;
default:
if (transRule->dotslen) {
if (!for_updatePositions(&transRule->charsdots[transCharslen],
transCharslen, transRule->dotslen, 0, pos, input, output,
posMapping, cursorPosition, cursorStatus))
goto failure;
pos += transCharslen;
} else {
for (k = 0; k < transCharslen; k++) {
if (!putCharacter(input->chars[pos], table, pos, input, output,
posMapping, cursorPosition, cursorStatus))
goto failure;
pos++;
}
}
break;
}
/* processing after replacement */
switch (transOpcode) {
case CTO_Repeated: {
/* Skip repeated characters. */
int srclim = input->length - transCharslen;
if (mode & (compbrlAtCursor | compbrlLeftCursor) && compbrlStart < srclim)
/* Don't skip characters from compbrlStart onwards. */
srclim = compbrlStart - 1;
while ((pos <= srclim) &&
compareChars(&transRule->charsdots[0], &input->chars[pos],
transCharslen, 0, table)) {
/* Map skipped input positions to the previous output position. */
/* if (posMapping.outputPositions != NULL) { */
/* int tcc; */
/* for (tcc = 0; tcc < transCharslen; tcc++) */
/* posMapping.outputPositions[posMapping.prev[pos + tcc]] = */
/* output->length - 1; */
/* } */
if (!*cursorStatus && pos <= *cursorPosition &&
*cursorPosition < pos + transCharslen) {
*cursorStatus = 1;
*cursorPosition = output->length - 1;
}
pos += transCharslen;
}
break;
}
case CTO_RepWord: {
/* Skip repeated characters. */
int srclim = input->length - transCharslen;
if (mode & (compbrlAtCursor | compbrlLeftCursor) && compbrlStart < srclim)
/* Don't skip characters from compbrlStart onwards. */
srclim = compbrlStart - 1;
while ((pos <= srclim) && compareChars(repwordStart, &input->chars[pos],
repwordLength, 0, table)) {
/* Map skipped input positions to the previous output position. */
/* if (posMapping.outputPositions != NULL) { */
/* int tcc; */
/* for (tcc = 0; tcc < transCharslen; tcc++) */
/* posMapping.outputPositions[posMapping.prev[pos + tcc]] = */
/* output->length - 1; */
/* } */
if (!*cursorStatus && pos <= *cursorPosition &&
*cursorPosition < pos + transCharslen) {
*cursorStatus = 1;
*cursorPosition = output->length - 1;
}
pos += repwordLength + transCharslen;
}
pos -= transCharslen;
break;
}
case CTO_JoinNum:
case CTO_JoinableWord:
while (pos < input->length &&
checkAttr(input->chars[pos], CTC_Space, 0, table) &&
input->chars[pos] != ENDSEGMENT)
pos++;
break;
default:
break;
}
if (((pos > 0) && checkAttr(input->chars[pos - 1], CTC_Space, 0, table) &&
(transOpcode != CTO_JoinableWord))) {
srcword = pos;
destword = output->length;
}
if (srcSpacing != NULL && srcSpacing[pos] >= '0' && srcSpacing[pos] <= '9')
destSpacing[output->length] = srcSpacing[pos];
if ((transOpcode >= CTO_Always && transOpcode <= CTO_None) ||
(transOpcode >= CTO_Digit && transOpcode <= CTO_LitDigit))
prevTransOpcode = transOpcode;
}
transOpcode = CTO_Space;
insertEmphases(table, pos, input, output, posMapping, emphasisBuffer, haveEmphasis,
transOpcode, cursorPosition, cursorStatus, &pre_src);
failure:
if (destword != 0 && pos < input->length &&
!checkAttr(input->chars[pos], CTC_Space, 0, table)) {
pos = srcword;
output->length = destword;
}
if (pos < input->length) {
while (checkAttr(input->chars[pos], CTC_Space, 0, table))
if (++pos == input->length) break;
}
*realInlen = pos;
if (input->bufferIndex != origInput->bufferIndex)
releaseStringBuffer(input->bufferIndex);
return 1;
} /* first pass translation completed */
int EXPORT_CALL
lou_hyphenate(const char *tableList, const widechar *inbuf, int inlen, char *hyphens,
int mode) {
#define HYPHSTRING 100
const TranslationTableHeader *table;
widechar workingBuffer[HYPHSTRING];
int k, kk;
int wordStart;
int wordEnd;
table = lou_getTable(tableList);
if (table == NULL || inbuf == NULL || hyphens == NULL ||
table->hyphenStatesArray == 0 || inlen >= HYPHSTRING)
return 0;
if (mode != 0) {
k = inlen;
kk = HYPHSTRING;
if (!lou_backTranslate(tableList, inbuf, &k, &workingBuffer[0], &kk, NULL, NULL,
NULL, NULL, NULL, 0))
return 0;
} else {
memcpy(&workingBuffer[0], inbuf, CHARSIZE * inlen);
kk = inlen;
}
for (wordStart = 0; wordStart < kk; wordStart++)
if (((findCharOrDots(workingBuffer[wordStart], 0, table))->attributes &
CTC_Letter))
break;
if (wordStart == kk) return 0;
for (wordEnd = kk - 1; wordEnd >= 0; wordEnd--)
if (((findCharOrDots(workingBuffer[wordEnd], 0, table))->attributes & CTC_Letter))
break;
for (k = wordStart; k <= wordEnd; k++) {
TranslationTableCharacter *c = findCharOrDots(workingBuffer[k], 0, table);
if (!(c->attributes & CTC_Letter)) return 0;
}
if (!hyphenate(&workingBuffer[wordStart], wordEnd - wordStart + 1,
&hyphens[wordStart], table))
return 0;
for (k = 0; k <= wordStart; k++) hyphens[k] = '0';
if (mode != 0) {
widechar workingBuffer2[HYPHSTRING];
int outputPos[HYPHSTRING];
char hyphens2[HYPHSTRING];
kk = wordEnd - wordStart + 1;
k = HYPHSTRING;
if (!lou_translate(tableList, &workingBuffer[wordStart], &kk, &workingBuffer2[0],
&k, NULL, NULL, &outputPos[0], NULL, NULL, 0))
return 0;
for (kk = 0; kk < k; kk++) {
int hyphPos = outputPos[kk];
if (hyphPos > k || hyphPos < 0) break;
if (hyphens[wordStart + kk] & 1)
hyphens2[hyphPos] = '1';
else
hyphens2[hyphPos] = '0';
}
for (kk = wordStart; kk < wordStart + k; kk++)
if (hyphens2[kk] == '0') hyphens[kk] = hyphens2[kk];
}
for (k = 0; k < inlen; k++)
if (hyphens[k] & 1)
hyphens[k] = '1';
else
hyphens[k] = '0';
hyphens[inlen] = 0;
return 1;
}
int EXPORT_CALL
lou_dotsToChar(
const char *tableList, widechar *inbuf, widechar *outbuf, int length, int mode) {
const TranslationTableHeader *table;
int k;
widechar dots;
if (tableList == NULL || inbuf == NULL || outbuf == NULL) return 0;
table = lou_getTable(tableList);
if (table == NULL || length <= 0) return 0;
for (k = 0; k < length; k++) {
dots = inbuf[k];
if (!(dots & B16) && (dots & 0xff00) == 0x2800) /* Unicode braille */
dots = (dots & 0x00ff) | B16;
outbuf[k] = _lou_getCharFromDots(dots);
}
return 1;
}
int EXPORT_CALL
lou_charToDots(const char *tableList, const widechar *inbuf, widechar *outbuf, int length,
int mode) {
const TranslationTableHeader *table;
int k;
if (tableList == NULL || inbuf == NULL || outbuf == NULL) return 0;
table = lou_getTable(tableList);
if (table == NULL || length <= 0) return 0;
for (k = 0; k < length; k++)
if ((mode & ucBrl))
outbuf[k] = ((_lou_getDotsForChar(inbuf[k]) & 0xff) | 0x2800);
else
outbuf[k] = _lou_getDotsForChar(inbuf[k]);
return 1;
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_394_0 |
crossvul-cpp_data_bad_3953_0 | /**
* WinPR: Windows Portable Runtime
* NTLM Security Package (AV_PAIRs)
*
* Copyright 2011-2014 Marc-Andre Moreau <marcandre.moreau@gmail.com>
*
* 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 HAVE_CONFIG_H
#include "config.h"
#endif
#include <assert.h>
#include "ntlm.h"
#include "../sspi.h"
#include <winpr/crt.h>
#include <winpr/print.h>
#include <winpr/sysinfo.h>
#include <winpr/tchar.h>
#include <winpr/crypto.h>
#include "ntlm_compute.h"
#include "ntlm_av_pairs.h"
#include "../../log.h"
#define TAG WINPR_TAG("sspi.NTLM")
static const char* const AV_PAIR_STRINGS[] = {
"MsvAvEOL", "MsvAvNbComputerName", "MsvAvNbDomainName", "MsvAvDnsComputerName",
"MsvAvDnsDomainName", "MsvAvDnsTreeName", "MsvAvFlags", "MsvAvTimestamp",
"MsvAvRestrictions", "MsvAvTargetName", "MsvChannelBindings"
};
static BOOL ntlm_av_pair_check(NTLM_AV_PAIR* pAvPair, size_t cbAvPair);
static NTLM_AV_PAIR* ntlm_av_pair_next(NTLM_AV_PAIR* pAvPairList, size_t* pcbAvPairList);
static INLINE void ntlm_av_pair_set_id(NTLM_AV_PAIR* pAvPair, UINT16 id)
{
Data_Write_UINT16(&pAvPair->AvId, id);
}
static INLINE void ntlm_av_pair_set_len(NTLM_AV_PAIR* pAvPair, UINT16 len)
{
Data_Write_UINT16(&pAvPair->AvLen, len);
}
static BOOL ntlm_av_pair_list_init(NTLM_AV_PAIR* pAvPairList, size_t cbAvPairList)
{
NTLM_AV_PAIR* pAvPair = pAvPairList;
if (!pAvPair || (cbAvPairList < sizeof(NTLM_AV_PAIR)))
return FALSE;
ntlm_av_pair_set_id(pAvPair, MsvAvEOL);
ntlm_av_pair_set_len(pAvPair, 0);
return TRUE;
}
static INLINE UINT16 ntlm_av_pair_get_id(const NTLM_AV_PAIR* pAvPair)
{
UINT16 AvId;
Data_Read_UINT16(&pAvPair->AvId, AvId);
return AvId;
}
ULONG ntlm_av_pair_list_length(NTLM_AV_PAIR* pAvPairList, size_t cbAvPairList)
{
size_t cbAvPair;
NTLM_AV_PAIR* pAvPair;
pAvPair = ntlm_av_pair_get(pAvPairList, cbAvPairList, MsvAvEOL, &cbAvPair);
if (!pAvPair)
return 0;
return ((PBYTE)pAvPair - (PBYTE)pAvPairList) + sizeof(NTLM_AV_PAIR);
}
static INLINE SIZE_T ntlm_av_pair_get_len(const NTLM_AV_PAIR* pAvPair)
{
UINT16 AvLen;
Data_Read_UINT16(&pAvPair->AvLen, AvLen);
return AvLen;
}
void ntlm_print_av_pair_list(NTLM_AV_PAIR* pAvPairList, size_t cbAvPairList)
{
size_t cbAvPair = cbAvPairList;
NTLM_AV_PAIR* pAvPair = pAvPairList;
if (!ntlm_av_pair_check(pAvPair, cbAvPair))
return;
WLog_INFO(TAG, "AV_PAIRs =");
while (pAvPair && ntlm_av_pair_get_id(pAvPair) != MsvAvEOL)
{
WLog_INFO(TAG, "\t%s AvId: %" PRIu16 " AvLen: %" PRIu16 "",
AV_PAIR_STRINGS[ntlm_av_pair_get_id(pAvPair)], ntlm_av_pair_get_id(pAvPair),
ntlm_av_pair_get_len(pAvPair));
winpr_HexDump(TAG, WLOG_INFO, ntlm_av_pair_get_value_pointer(pAvPair),
ntlm_av_pair_get_len(pAvPair));
pAvPair = ntlm_av_pair_next(pAvPair, &cbAvPair);
}
}
static ULONG ntlm_av_pair_list_size(ULONG AvPairsCount, ULONG AvPairsValueLength)
{
/* size of headers + value lengths + terminating MsvAvEOL AV_PAIR */
return ((AvPairsCount + 1) * 4) + AvPairsValueLength;
}
PBYTE ntlm_av_pair_get_value_pointer(NTLM_AV_PAIR* pAvPair)
{
return (PBYTE)pAvPair + sizeof(NTLM_AV_PAIR);
}
static size_t ntlm_av_pair_get_next_offset(NTLM_AV_PAIR* pAvPair)
{
return ntlm_av_pair_get_len(pAvPair) + sizeof(NTLM_AV_PAIR);
}
static BOOL ntlm_av_pair_check(NTLM_AV_PAIR* pAvPair, size_t cbAvPair)
{
if (!pAvPair || cbAvPair < sizeof(NTLM_AV_PAIR))
return FALSE;
return cbAvPair >= ntlm_av_pair_get_next_offset(pAvPair);
}
static NTLM_AV_PAIR* ntlm_av_pair_next(NTLM_AV_PAIR* pAvPair, size_t* pcbAvPair)
{
size_t offset;
if (!pcbAvPair)
return NULL;
if (!ntlm_av_pair_check(pAvPair, *pcbAvPair))
return NULL;
offset = ntlm_av_pair_get_next_offset(pAvPair);
*pcbAvPair -= offset;
return (NTLM_AV_PAIR*)((PBYTE)pAvPair + offset);
}
NTLM_AV_PAIR* ntlm_av_pair_get(NTLM_AV_PAIR* pAvPairList, size_t cbAvPairList, NTLM_AV_ID AvId,
size_t* pcbAvPairListRemaining)
{
size_t cbAvPair = cbAvPairList;
NTLM_AV_PAIR* pAvPair = pAvPairList;
if (!ntlm_av_pair_check(pAvPair, cbAvPair))
pAvPair = NULL;
while (pAvPair)
{
UINT16 id = ntlm_av_pair_get_id(pAvPair);
if (id == AvId)
break;
if (id == MsvAvEOL)
{
pAvPair = NULL;
break;
}
pAvPair = ntlm_av_pair_next(pAvPair, &cbAvPair);
}
if (!pAvPair)
cbAvPair = 0;
if (pcbAvPairListRemaining)
*pcbAvPairListRemaining = cbAvPair;
return pAvPair;
}
static BOOL ntlm_av_pair_add(NTLM_AV_PAIR* pAvPairList, size_t cbAvPairList, NTLM_AV_ID AvId,
PBYTE Value, UINT16 AvLen)
{
size_t cbAvPair;
NTLM_AV_PAIR* pAvPair;
pAvPair = ntlm_av_pair_get(pAvPairList, cbAvPairList, MsvAvEOL, &cbAvPair);
/* size of header + value length + terminating MsvAvEOL AV_PAIR */
if (!pAvPair || cbAvPair < 2 * sizeof(NTLM_AV_PAIR) + AvLen)
return FALSE;
ntlm_av_pair_set_id(pAvPair, AvId);
ntlm_av_pair_set_len(pAvPair, AvLen);
if (AvLen)
{
assert(Value != NULL);
CopyMemory(ntlm_av_pair_get_value_pointer(pAvPair), Value, AvLen);
}
pAvPair = ntlm_av_pair_next(pAvPair, &cbAvPair);
return ntlm_av_pair_list_init(pAvPair, cbAvPair);
}
static BOOL ntlm_av_pair_add_copy(NTLM_AV_PAIR* pAvPairList, size_t cbAvPairList,
NTLM_AV_PAIR* pAvPair, size_t cbAvPair)
{
if (!ntlm_av_pair_check(pAvPair, cbAvPair))
return FALSE;
return ntlm_av_pair_add(pAvPairList, cbAvPairList, ntlm_av_pair_get_id(pAvPair),
ntlm_av_pair_get_value_pointer(pAvPair), ntlm_av_pair_get_len(pAvPair));
}
static int ntlm_get_target_computer_name(PUNICODE_STRING pName, COMPUTER_NAME_FORMAT type)
{
char* name;
int status;
DWORD nSize = 0;
CHAR* computerName;
if (GetComputerNameExA(ComputerNameNetBIOS, NULL, &nSize) || GetLastError() != ERROR_MORE_DATA)
return -1;
computerName = calloc(nSize, sizeof(CHAR));
if (!computerName)
return -1;
if (!GetComputerNameExA(ComputerNameNetBIOS, computerName, &nSize))
{
free(computerName);
return -1;
}
if (nSize > MAX_COMPUTERNAME_LENGTH)
computerName[MAX_COMPUTERNAME_LENGTH] = '\0';
name = computerName;
if (!name)
return -1;
if (type == ComputerNameNetBIOS)
CharUpperA(name);
status = ConvertToUnicode(CP_UTF8, 0, name, -1, &pName->Buffer, 0);
if (status <= 0)
{
free(name);
return status;
}
pName->Length = (USHORT)((status - 1) * 2);
pName->MaximumLength = pName->Length;
free(name);
return 1;
}
static void ntlm_free_unicode_string(PUNICODE_STRING string)
{
if (string)
{
if (string->Length > 0)
{
free(string->Buffer);
string->Buffer = NULL;
string->Length = 0;
string->MaximumLength = 0;
}
}
}
/**
* From http://www.ietf.org/proceedings/72/slides/sasl-2.pdf:
*
* tls-server-end-point:
*
* The hash of the TLS server's end entity certificate as it appears, octet for octet,
* in the server's Certificate message (note that the Certificate message contains a
* certificate_list, the first element of which is the server's end entity certificate.)
* The hash function to be selected is as follows: if the certificate's signature hash
* algorithm is either MD5 or SHA-1, then use SHA-256, otherwise use the certificate's
* signature hash algorithm.
*/
/**
* Channel Bindings sample usage:
* https://raw.github.com/mozilla/mozilla-central/master/extensions/auth/nsAuthSSPI.cpp
*/
/*
typedef struct gss_channel_bindings_struct {
OM_uint32 initiator_addrtype;
gss_buffer_desc initiator_address;
OM_uint32 acceptor_addrtype;
gss_buffer_desc acceptor_address;
gss_buffer_desc application_data;
} *gss_channel_bindings_t;
*/
static BOOL ntlm_md5_update_uint32_be(WINPR_DIGEST_CTX* md5, UINT32 num)
{
BYTE be32[4];
be32[0] = (num >> 0) & 0xFF;
be32[1] = (num >> 8) & 0xFF;
be32[2] = (num >> 16) & 0xFF;
be32[3] = (num >> 24) & 0xFF;
return winpr_Digest_Update(md5, be32, 4);
}
static void ntlm_compute_channel_bindings(NTLM_CONTEXT* context)
{
WINPR_DIGEST_CTX* md5;
BYTE* ChannelBindingToken;
UINT32 ChannelBindingTokenLength;
SEC_CHANNEL_BINDINGS* ChannelBindings;
ZeroMemory(context->ChannelBindingsHash, WINPR_MD5_DIGEST_LENGTH);
ChannelBindings = context->Bindings.Bindings;
if (!ChannelBindings)
return;
if (!(md5 = winpr_Digest_New()))
return;
if (!winpr_Digest_Init(md5, WINPR_MD_MD5))
goto out;
ChannelBindingTokenLength = context->Bindings.BindingsLength - sizeof(SEC_CHANNEL_BINDINGS);
ChannelBindingToken = &((BYTE*)ChannelBindings)[ChannelBindings->dwApplicationDataOffset];
if (!ntlm_md5_update_uint32_be(md5, ChannelBindings->dwInitiatorAddrType))
goto out;
if (!ntlm_md5_update_uint32_be(md5, ChannelBindings->cbInitiatorLength))
goto out;
if (!ntlm_md5_update_uint32_be(md5, ChannelBindings->dwAcceptorAddrType))
goto out;
if (!ntlm_md5_update_uint32_be(md5, ChannelBindings->cbAcceptorLength))
goto out;
if (!ntlm_md5_update_uint32_be(md5, ChannelBindings->cbApplicationDataLength))
goto out;
if (!winpr_Digest_Update(md5, (void*)ChannelBindingToken, ChannelBindingTokenLength))
goto out;
if (!winpr_Digest_Final(md5, context->ChannelBindingsHash, WINPR_MD5_DIGEST_LENGTH))
goto out;
out:
winpr_Digest_Free(md5);
}
static void ntlm_compute_single_host_data(NTLM_CONTEXT* context)
{
/**
* The Single_Host_Data structure allows a client to send machine-specific information
* within an authentication exchange to services on the same machine. The client can
* produce additional information to be processed in an implementation-specific way when
* the client and server are on the same host. If the server and client platforms are
* different or if they are on different hosts, then the information MUST be ignored.
* Any fields after the MachineID field MUST be ignored on receipt.
*/
Data_Write_UINT32(&context->SingleHostData.Size, 48);
Data_Write_UINT32(&context->SingleHostData.Z4, 0);
Data_Write_UINT32(&context->SingleHostData.DataPresent, 1);
Data_Write_UINT32(&context->SingleHostData.CustomData, SECURITY_MANDATORY_MEDIUM_RID);
FillMemory(context->SingleHostData.MachineID, 32, 0xAA);
}
int ntlm_construct_challenge_target_info(NTLM_CONTEXT* context)
{
int rc = -1;
int length;
ULONG AvPairsCount;
ULONG AvPairsLength;
NTLM_AV_PAIR* pAvPairList;
size_t cbAvPairList;
UNICODE_STRING NbDomainName = { 0 };
UNICODE_STRING NbComputerName = { 0 };
UNICODE_STRING DnsDomainName = { 0 };
UNICODE_STRING DnsComputerName = { 0 };
if (ntlm_get_target_computer_name(&NbDomainName, ComputerNameNetBIOS) < 0)
goto fail;
NbComputerName.Buffer = NULL;
if (ntlm_get_target_computer_name(&NbComputerName, ComputerNameNetBIOS) < 0)
goto fail;
DnsDomainName.Buffer = NULL;
if (ntlm_get_target_computer_name(&DnsDomainName, ComputerNameDnsDomain) < 0)
goto fail;
DnsComputerName.Buffer = NULL;
if (ntlm_get_target_computer_name(&DnsComputerName, ComputerNameDnsHostname) < 0)
goto fail;
AvPairsCount = 5;
AvPairsLength = NbDomainName.Length + NbComputerName.Length + DnsDomainName.Length +
DnsComputerName.Length + 8;
length = ntlm_av_pair_list_size(AvPairsCount, AvPairsLength);
if (!sspi_SecBufferAlloc(&context->ChallengeTargetInfo, length))
goto fail;
pAvPairList = (NTLM_AV_PAIR*)context->ChallengeTargetInfo.pvBuffer;
cbAvPairList = context->ChallengeTargetInfo.cbBuffer;
if (!ntlm_av_pair_list_init(pAvPairList, cbAvPairList))
goto fail;
if (!ntlm_av_pair_add(pAvPairList, cbAvPairList, MsvAvNbDomainName, (PBYTE)NbDomainName.Buffer,
NbDomainName.Length))
goto fail;
if (!ntlm_av_pair_add(pAvPairList, cbAvPairList, MsvAvNbComputerName,
(PBYTE)NbComputerName.Buffer, NbComputerName.Length))
goto fail;
if (!ntlm_av_pair_add(pAvPairList, cbAvPairList, MsvAvDnsDomainName,
(PBYTE)DnsDomainName.Buffer, DnsDomainName.Length))
goto fail;
if (!ntlm_av_pair_add(pAvPairList, cbAvPairList, MsvAvDnsComputerName,
(PBYTE)DnsComputerName.Buffer, DnsComputerName.Length))
goto fail;
if (!ntlm_av_pair_add(pAvPairList, cbAvPairList, MsvAvTimestamp, context->Timestamp,
sizeof(context->Timestamp)))
goto fail;
rc = 1;
fail:
ntlm_free_unicode_string(&NbDomainName);
ntlm_free_unicode_string(&NbComputerName);
ntlm_free_unicode_string(&DnsDomainName);
ntlm_free_unicode_string(&DnsComputerName);
return rc;
}
int ntlm_construct_authenticate_target_info(NTLM_CONTEXT* context)
{
ULONG size;
ULONG AvPairsCount;
ULONG AvPairsValueLength;
NTLM_AV_PAIR* AvTimestamp;
NTLM_AV_PAIR* AvNbDomainName;
NTLM_AV_PAIR* AvNbComputerName;
NTLM_AV_PAIR* AvDnsDomainName;
NTLM_AV_PAIR* AvDnsComputerName;
NTLM_AV_PAIR* AvDnsTreeName;
NTLM_AV_PAIR* ChallengeTargetInfo;
NTLM_AV_PAIR* AuthenticateTargetInfo;
size_t cbAvTimestamp;
size_t cbAvNbDomainName;
size_t cbAvNbComputerName;
size_t cbAvDnsDomainName;
size_t cbAvDnsComputerName;
size_t cbAvDnsTreeName;
size_t cbChallengeTargetInfo;
size_t cbAuthenticateTargetInfo;
AvPairsCount = 1;
AvPairsValueLength = 0;
ChallengeTargetInfo = (NTLM_AV_PAIR*)context->ChallengeTargetInfo.pvBuffer;
cbChallengeTargetInfo = context->ChallengeTargetInfo.cbBuffer;
AvNbDomainName = ntlm_av_pair_get(ChallengeTargetInfo, cbChallengeTargetInfo, MsvAvNbDomainName,
&cbAvNbDomainName);
AvNbComputerName = ntlm_av_pair_get(ChallengeTargetInfo, cbChallengeTargetInfo,
MsvAvNbComputerName, &cbAvNbComputerName);
AvDnsDomainName = ntlm_av_pair_get(ChallengeTargetInfo, cbChallengeTargetInfo,
MsvAvDnsDomainName, &cbAvDnsDomainName);
AvDnsComputerName = ntlm_av_pair_get(ChallengeTargetInfo, cbChallengeTargetInfo,
MsvAvDnsComputerName, &cbAvDnsComputerName);
AvDnsTreeName = ntlm_av_pair_get(ChallengeTargetInfo, cbChallengeTargetInfo, MsvAvDnsTreeName,
&cbAvDnsTreeName);
AvTimestamp = ntlm_av_pair_get(ChallengeTargetInfo, cbChallengeTargetInfo, MsvAvTimestamp,
&cbAvTimestamp);
if (AvNbDomainName)
{
AvPairsCount++; /* MsvAvNbDomainName */
AvPairsValueLength += ntlm_av_pair_get_len(AvNbDomainName);
}
if (AvNbComputerName)
{
AvPairsCount++; /* MsvAvNbComputerName */
AvPairsValueLength += ntlm_av_pair_get_len(AvNbComputerName);
}
if (AvDnsDomainName)
{
AvPairsCount++; /* MsvAvDnsDomainName */
AvPairsValueLength += ntlm_av_pair_get_len(AvDnsDomainName);
}
if (AvDnsComputerName)
{
AvPairsCount++; /* MsvAvDnsComputerName */
AvPairsValueLength += ntlm_av_pair_get_len(AvDnsComputerName);
}
if (AvDnsTreeName)
{
AvPairsCount++; /* MsvAvDnsTreeName */
AvPairsValueLength += ntlm_av_pair_get_len(AvDnsTreeName);
}
AvPairsCount++; /* MsvAvTimestamp */
AvPairsValueLength += 8;
if (context->UseMIC)
{
AvPairsCount++; /* MsvAvFlags */
AvPairsValueLength += 4;
}
if (context->SendSingleHostData)
{
AvPairsCount++; /* MsvAvSingleHost */
ntlm_compute_single_host_data(context);
AvPairsValueLength += context->SingleHostData.Size;
}
/**
* Extended Protection for Authentication:
* http://blogs.technet.com/b/srd/archive/2009/12/08/extended-protection-for-authentication.aspx
*/
if (!context->SuppressExtendedProtection)
{
/**
* SEC_CHANNEL_BINDINGS structure
* http://msdn.microsoft.com/en-us/library/windows/desktop/dd919963/
*/
AvPairsCount++; /* MsvChannelBindings */
AvPairsValueLength += 16;
ntlm_compute_channel_bindings(context);
if (context->ServicePrincipalName.Length > 0)
{
AvPairsCount++; /* MsvAvTargetName */
AvPairsValueLength += context->ServicePrincipalName.Length;
}
}
size = ntlm_av_pair_list_size(AvPairsCount, AvPairsValueLength);
if (context->NTLMv2)
size += 8; /* unknown 8-byte padding */
if (!sspi_SecBufferAlloc(&context->AuthenticateTargetInfo, size))
goto fail;
AuthenticateTargetInfo = (NTLM_AV_PAIR*)context->AuthenticateTargetInfo.pvBuffer;
cbAuthenticateTargetInfo = context->AuthenticateTargetInfo.cbBuffer;
if (!ntlm_av_pair_list_init(AuthenticateTargetInfo, cbAuthenticateTargetInfo))
goto fail;
if (AvNbDomainName)
{
if (!ntlm_av_pair_add_copy(AuthenticateTargetInfo, cbAuthenticateTargetInfo, AvNbDomainName,
cbAvNbDomainName))
goto fail;
}
if (AvNbComputerName)
{
if (!ntlm_av_pair_add_copy(AuthenticateTargetInfo, cbAuthenticateTargetInfo,
AvNbComputerName, cbAvNbComputerName))
goto fail;
}
if (AvDnsDomainName)
{
if (!ntlm_av_pair_add_copy(AuthenticateTargetInfo, cbAuthenticateTargetInfo,
AvDnsDomainName, cbAvDnsDomainName))
goto fail;
}
if (AvDnsComputerName)
{
if (!ntlm_av_pair_add_copy(AuthenticateTargetInfo, cbAuthenticateTargetInfo,
AvDnsComputerName, cbAvDnsComputerName))
goto fail;
}
if (AvDnsTreeName)
{
if (!ntlm_av_pair_add_copy(AuthenticateTargetInfo, cbAuthenticateTargetInfo, AvDnsTreeName,
cbAvDnsTreeName))
goto fail;
}
if (AvTimestamp)
{
if (!ntlm_av_pair_add_copy(AuthenticateTargetInfo, cbAuthenticateTargetInfo, AvTimestamp,
cbAvTimestamp))
goto fail;
}
if (context->UseMIC)
{
UINT32 flags;
Data_Write_UINT32(&flags, MSV_AV_FLAGS_MESSAGE_INTEGRITY_CHECK);
if (!ntlm_av_pair_add(AuthenticateTargetInfo, cbAuthenticateTargetInfo, MsvAvFlags,
(PBYTE)&flags, 4))
goto fail;
}
if (context->SendSingleHostData)
{
if (!ntlm_av_pair_add(AuthenticateTargetInfo, cbAuthenticateTargetInfo, MsvAvSingleHost,
(PBYTE)&context->SingleHostData, context->SingleHostData.Size))
goto fail;
}
if (!context->SuppressExtendedProtection)
{
if (!ntlm_av_pair_add(AuthenticateTargetInfo, cbAuthenticateTargetInfo, MsvChannelBindings,
context->ChannelBindingsHash, 16))
goto fail;
if (context->ServicePrincipalName.Length > 0)
{
if (!ntlm_av_pair_add(AuthenticateTargetInfo, cbAuthenticateTargetInfo, MsvAvTargetName,
(PBYTE)context->ServicePrincipalName.Buffer,
context->ServicePrincipalName.Length))
goto fail;
}
}
if (context->NTLMv2)
{
NTLM_AV_PAIR* AvEOL;
AvEOL = ntlm_av_pair_get(ChallengeTargetInfo, cbChallengeTargetInfo, MsvAvEOL, NULL);
if (!AvEOL)
goto fail;
ZeroMemory(AvEOL, sizeof(NTLM_AV_PAIR));
}
return 1;
fail:
sspi_SecBufferFree(&context->AuthenticateTargetInfo);
return -1;
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_3953_0 |
crossvul-cpp_data_bad_2694_0 | /*
* Copyright (c) 1998-2007 The TCPDUMP project
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that: (1) source code
* distributions retain the above copyright notice and this paragraph
* in its entirety, and (2) distributions including binary code include
* the above copyright notice and this paragraph in its entirety in
* the documentation or other materials provided with the distribution.
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND
* WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, WITHOUT
* LIMITATION, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE.
*
* Reference documentation:
* http://www.cisco.com/en/US/tech/tk389/tk689/technologies_tech_note09186a0080094c52.shtml
* http://www.cisco.com/warp/public/473/21.html
* http://www.cisco.com/univercd/cc/td/doc/product/lan/trsrb/frames.htm
*
* Original code ode by Carles Kishimoto <carles.kishimoto@gmail.com>
*/
/* \summary: Cisco VLAN Trunking Protocol (VTP) printer */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <netdissect-stdinc.h>
#include "netdissect.h"
#include "addrtoname.h"
#include "extract.h"
#define VTP_HEADER_LEN 36
#define VTP_DOMAIN_NAME_LEN 32
#define VTP_MD5_DIGEST_LEN 16
#define VTP_UPDATE_TIMESTAMP_LEN 12
#define VTP_VLAN_INFO_OFFSET 12
#define VTP_SUMMARY_ADV 0x01
#define VTP_SUBSET_ADV 0x02
#define VTP_ADV_REQUEST 0x03
#define VTP_JOIN_MESSAGE 0x04
struct vtp_vlan_ {
uint8_t len;
uint8_t status;
uint8_t type;
uint8_t name_len;
uint16_t vlanid;
uint16_t mtu;
uint32_t index;
};
static const struct tok vtp_message_type_values[] = {
{ VTP_SUMMARY_ADV, "Summary advertisement"},
{ VTP_SUBSET_ADV, "Subset advertisement"},
{ VTP_ADV_REQUEST, "Advertisement request"},
{ VTP_JOIN_MESSAGE, "Join message"},
{ 0, NULL }
};
static const struct tok vtp_header_values[] = {
{ 0x01, "Followers"}, /* On Summary advertisement, 3rd byte is Followers */
{ 0x02, "Seq number"}, /* On Subset advertisement, 3rd byte is Sequence number */
{ 0x03, "Rsvd"}, /* On Adver. requests 3rd byte is Rsvd */
{ 0x04, "Rsvd"}, /* On Adver. requests 3rd byte is Rsvd */
{ 0, NULL }
};
static const struct tok vtp_vlan_type_values[] = {
{ 0x01, "Ethernet"},
{ 0x02, "FDDI"},
{ 0x03, "TrCRF"},
{ 0x04, "FDDI-net"},
{ 0x05, "TrBRF"},
{ 0, NULL }
};
static const struct tok vtp_vlan_status[] = {
{ 0x00, "Operational"},
{ 0x01, "Suspended"},
{ 0, NULL }
};
#define VTP_VLAN_SOURCE_ROUTING_RING_NUMBER 0x01
#define VTP_VLAN_SOURCE_ROUTING_BRIDGE_NUMBER 0x02
#define VTP_VLAN_STP_TYPE 0x03
#define VTP_VLAN_PARENT_VLAN 0x04
#define VTP_VLAN_TRANS_BRIDGED_VLAN 0x05
#define VTP_VLAN_PRUNING 0x06
#define VTP_VLAN_BRIDGE_TYPE 0x07
#define VTP_VLAN_ARP_HOP_COUNT 0x08
#define VTP_VLAN_STE_HOP_COUNT 0x09
#define VTP_VLAN_BACKUP_CRF_MODE 0x0A
static const struct tok vtp_vlan_tlv_values[] = {
{ VTP_VLAN_SOURCE_ROUTING_RING_NUMBER, "Source-Routing Ring Number TLV"},
{ VTP_VLAN_SOURCE_ROUTING_BRIDGE_NUMBER, "Source-Routing Bridge Number TLV"},
{ VTP_VLAN_STP_TYPE, "STP type TLV"},
{ VTP_VLAN_PARENT_VLAN, "Parent VLAN TLV"},
{ VTP_VLAN_TRANS_BRIDGED_VLAN, "Translationally bridged VLANs TLV"},
{ VTP_VLAN_PRUNING, "Pruning TLV"},
{ VTP_VLAN_BRIDGE_TYPE, "Bridge Type TLV"},
{ VTP_VLAN_ARP_HOP_COUNT, "Max ARP Hop Count TLV"},
{ VTP_VLAN_STE_HOP_COUNT, "Max STE Hop Count TLV"},
{ VTP_VLAN_BACKUP_CRF_MODE, "Backup CRF Mode TLV"},
{ 0, NULL }
};
static const struct tok vtp_stp_type_values[] = {
{ 1, "SRT"},
{ 2, "SRB"},
{ 3, "Auto"},
{ 0, NULL }
};
void
vtp_print (netdissect_options *ndo,
const u_char *pptr, u_int length)
{
int type, len, tlv_len, tlv_value, mgmtd_len;
const u_char *tptr;
const struct vtp_vlan_ *vtp_vlan;
if (length < VTP_HEADER_LEN)
goto trunc;
tptr = pptr;
ND_TCHECK2(*tptr, VTP_HEADER_LEN);
type = *(tptr+1);
ND_PRINT((ndo, "VTPv%u, Message %s (0x%02x), length %u",
*tptr,
tok2str(vtp_message_type_values,"Unknown message type", type),
type,
length));
/* In non-verbose mode, just print version and message type */
if (ndo->ndo_vflag < 1) {
return;
}
/* verbose mode print all fields */
ND_PRINT((ndo, "\n\tDomain name: "));
mgmtd_len = *(tptr + 3);
if (mgmtd_len < 1 || mgmtd_len > 32) {
ND_PRINT((ndo, " [invalid MgmtD Len %d]", mgmtd_len));
return;
}
fn_printzp(ndo, tptr + 4, mgmtd_len, NULL);
ND_PRINT((ndo, ", %s: %u",
tok2str(vtp_header_values, "Unknown", type),
*(tptr+2)));
tptr += VTP_HEADER_LEN;
switch (type) {
case VTP_SUMMARY_ADV:
/*
* SUMMARY ADVERTISEMENT
*
* 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Version | Code | Followers | MgmtD Len |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Management Domain Name (zero-padded to 32 bytes) |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Configuration revision number |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Updater Identity IP address |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Update Timestamp (12 bytes) |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | MD5 digest (16 bytes) |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*
*/
ND_TCHECK2(*tptr, 8);
ND_PRINT((ndo, "\n\t Config Rev %x, Updater %s",
EXTRACT_32BITS(tptr),
ipaddr_string(ndo, tptr+4)));
tptr += 8;
ND_TCHECK2(*tptr, VTP_UPDATE_TIMESTAMP_LEN);
ND_PRINT((ndo, ", Timestamp 0x%08x 0x%08x 0x%08x",
EXTRACT_32BITS(tptr),
EXTRACT_32BITS(tptr + 4),
EXTRACT_32BITS(tptr + 8)));
tptr += VTP_UPDATE_TIMESTAMP_LEN;
ND_TCHECK2(*tptr, VTP_MD5_DIGEST_LEN);
ND_PRINT((ndo, ", MD5 digest: %08x%08x%08x%08x",
EXTRACT_32BITS(tptr),
EXTRACT_32BITS(tptr + 4),
EXTRACT_32BITS(tptr + 8),
EXTRACT_32BITS(tptr + 12)));
tptr += VTP_MD5_DIGEST_LEN;
break;
case VTP_SUBSET_ADV:
/*
* SUBSET ADVERTISEMENT
*
* 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Version | Code | Seq number | MgmtD Len |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Management Domain Name (zero-padded to 32 bytes) |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Configuration revision number |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | VLAN info field 1 |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | ................ |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | VLAN info field N |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*
*/
ND_PRINT((ndo, ", Config Rev %x", EXTRACT_32BITS(tptr)));
/*
* VLAN INFORMATION
* 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | V info len | Status | VLAN type | VLAN name len |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | ISL vlan id | MTU size |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | 802.10 index (SAID) |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | VLAN name |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*
*/
tptr += 4;
while (tptr < (pptr+length)) {
len = *tptr;
if (len == 0)
break;
ND_TCHECK2(*tptr, len);
vtp_vlan = (const struct vtp_vlan_*)tptr;
ND_TCHECK(*vtp_vlan);
ND_PRINT((ndo, "\n\tVLAN info status %s, type %s, VLAN-id %u, MTU %u, SAID 0x%08x, Name ",
tok2str(vtp_vlan_status,"Unknown",vtp_vlan->status),
tok2str(vtp_vlan_type_values,"Unknown",vtp_vlan->type),
EXTRACT_16BITS(&vtp_vlan->vlanid),
EXTRACT_16BITS(&vtp_vlan->mtu),
EXTRACT_32BITS(&vtp_vlan->index)));
fn_printzp(ndo, tptr + VTP_VLAN_INFO_OFFSET, vtp_vlan->name_len, NULL);
/*
* Vlan names are aligned to 32-bit boundaries.
*/
len -= VTP_VLAN_INFO_OFFSET + 4*((vtp_vlan->name_len + 3)/4);
tptr += VTP_VLAN_INFO_OFFSET + 4*((vtp_vlan->name_len + 3)/4);
/* TLV information follows */
while (len > 0) {
/*
* Cisco specs says 2 bytes for type + 2 bytes for length, take only 1
* See: http://www.cisco.com/univercd/cc/td/doc/product/lan/trsrb/frames.htm
*/
type = *tptr;
tlv_len = *(tptr+1);
ND_PRINT((ndo, "\n\t\t%s (0x%04x) TLV",
tok2str(vtp_vlan_tlv_values, "Unknown", type),
type));
/*
* infinite loop check
*/
if (type == 0 || tlv_len == 0) {
return;
}
ND_TCHECK2(*tptr, tlv_len * 2 +2);
tlv_value = EXTRACT_16BITS(tptr+2);
switch (type) {
case VTP_VLAN_STE_HOP_COUNT:
ND_PRINT((ndo, ", %u", tlv_value));
break;
case VTP_VLAN_PRUNING:
ND_PRINT((ndo, ", %s (%u)",
tlv_value == 1 ? "Enabled" : "Disabled",
tlv_value));
break;
case VTP_VLAN_STP_TYPE:
ND_PRINT((ndo, ", %s (%u)",
tok2str(vtp_stp_type_values, "Unknown", tlv_value),
tlv_value));
break;
case VTP_VLAN_BRIDGE_TYPE:
ND_PRINT((ndo, ", %s (%u)",
tlv_value == 1 ? "SRB" : "SRT",
tlv_value));
break;
case VTP_VLAN_BACKUP_CRF_MODE:
ND_PRINT((ndo, ", %s (%u)",
tlv_value == 1 ? "Backup" : "Not backup",
tlv_value));
break;
/*
* FIXME those are the defined TLVs that lack a decoder
* you are welcome to contribute code ;-)
*/
case VTP_VLAN_SOURCE_ROUTING_RING_NUMBER:
case VTP_VLAN_SOURCE_ROUTING_BRIDGE_NUMBER:
case VTP_VLAN_PARENT_VLAN:
case VTP_VLAN_TRANS_BRIDGED_VLAN:
case VTP_VLAN_ARP_HOP_COUNT:
default:
print_unknown_data(ndo, tptr, "\n\t\t ", 2 + tlv_len*2);
break;
}
len -= 2 + tlv_len*2;
tptr += 2 + tlv_len*2;
}
}
break;
case VTP_ADV_REQUEST:
/*
* ADVERTISEMENT REQUEST
*
* 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Version | Code | Reserved | MgmtD Len |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Management Domain Name (zero-padded to 32 bytes) |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Start value |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*
*/
ND_TCHECK2(*tptr, 4);
ND_PRINT((ndo, "\n\tStart value: %u", EXTRACT_32BITS(tptr)));
break;
case VTP_JOIN_MESSAGE:
/* FIXME - Could not find message format */
break;
default:
break;
}
return;
trunc:
ND_PRINT((ndo, "[|vtp]"));
}
/*
* Local Variables:
* c-style: whitesmith
* c-basic-offset: 4
* End:
*/
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_2694_0 |
crossvul-cpp_data_good_486_5 | /* -*- c-basic-offset: 8 -*-
rdesktop: A Remote Desktop Protocol client.
Support for the Matrox "lspci" channel
Copyright (C) 2005 Matrox Graphics Inc.
Copyright 2018 Henrik Andersson <hean01@cendio.se> for Cendio AB
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "rdesktop.h"
#include <sys/types.h>
#include <unistd.h>
static VCHANNEL *lspci_channel;
typedef struct _pci_device
{
uint16 klass;
uint16 vendor;
uint16 device;
uint16 subvendor;
uint16 subdevice;
uint8 revision;
uint8 progif;
} pci_device;
static pci_device current_device;
static void lspci_send(const char *output);
/* Handle one line of output from the lspci subprocess */
static RD_BOOL
handle_child_line(const char *line, void *data)
{
UNUSED(data);
const char *val;
char buf[1024];
if (str_startswith(line, "Class:"))
{
val = line + sizeof("Class:");
/* Skip whitespace and second Class: occurrence */
val += strspn(val, " \t") + sizeof("Class");
current_device.klass = strtol(val, NULL, 16);
}
else if (str_startswith(line, "Vendor:"))
{
val = line + sizeof("Vendor:");
current_device.vendor = strtol(val, NULL, 16);
}
else if (str_startswith(line, "Device:"))
{
val = line + sizeof("Device:");
/* Sigh, there are *two* lines tagged as Device:. We
are not interested in the domain/bus/slot/func */
if (!strchr(val, ':'))
current_device.device = strtol(val, NULL, 16);
}
else if (str_startswith(line, "SVendor:"))
{
val = line + sizeof("SVendor:");
current_device.subvendor = strtol(val, NULL, 16);
}
else if (str_startswith(line, "SDevice:"))
{
val = line + sizeof("SDevice:");
current_device.subdevice = strtol(val, NULL, 16);
}
else if (str_startswith(line, "Rev:"))
{
val = line + sizeof("Rev:");
current_device.revision = strtol(val, NULL, 16);
}
else if (str_startswith(line, "ProgIf:"))
{
val = line + sizeof("ProgIf:");
current_device.progif = strtol(val, NULL, 16);
}
else if (strspn(line, " \t") == strlen(line))
{
/* Blank line. Send collected information over channel */
snprintf(buf, sizeof(buf), "%04x,%04x,%04x,%04x,%04x,%02x,%02x\n",
current_device.klass, current_device.vendor,
current_device.device, current_device.subvendor,
current_device.subdevice, current_device.revision, current_device.progif);
lspci_send(buf);
memset(¤t_device, 0, sizeof(current_device));
}
else
{
logger(Core, Warning, "handle_child_line(), Unrecognized lspci line '%s'", line);
}
return True;
}
/* Process one line of input from virtual channel */
static RD_BOOL
lspci_process_line(const char *line, void *data)
{
UNUSED(data);
char *lspci_command[5] = { "lspci", "-m", "-n", "-v", NULL };
if (!strcmp(line, "LSPCI"))
{
memset(¤t_device, 0, sizeof(current_device));
subprocess(lspci_command, handle_child_line, NULL);
/* Send single dot to indicate end of enumeration */
lspci_send(".\n");
}
else
{
logger(Core, Error, "lspci_process_line(), invalid line '%s'", line);
}
return True;
}
/* Process new data from the virtual channel */
static void
lspci_process(STREAM s)
{
unsigned int pkglen;
static char *rest = NULL;
char *buf;
struct stream packet = *s;
if (!s_check(s))
{
rdp_protocol_error("lspci_process(), stream is in unstable state", &packet);
}
pkglen = s->end - s->p;
/* str_handle_lines requires null terminated strings */
buf = xmalloc(pkglen + 1);
STRNCPY(buf, (char *) s->p, pkglen + 1);
str_handle_lines(buf, &rest, lspci_process_line, NULL);
xfree(buf);
}
/* Initialize this module: Register the lspci channel */
RD_BOOL
lspci_init(void)
{
lspci_channel =
channel_register("lspci", CHANNEL_OPTION_INITIALIZED | CHANNEL_OPTION_ENCRYPT_RDP,
lspci_process);
return (lspci_channel != NULL);
}
/* Send data to channel */
static void
lspci_send(const char *output)
{
STREAM s;
size_t len;
len = strlen(output);
s = channel_init(lspci_channel, len);
out_uint8p(s, output, len) s_mark_end(s);
channel_send(s, lspci_channel);
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/good_486_5 |
crossvul-cpp_data_bad_2704_0 | /*
* Copyright (c) 1990, 1991, 1993, 1994, 1995, 1996, 1997
* The Regents of the University of California. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that: (1) source code distributions
* retain the above copyright notice and this paragraph in its entirety, (2)
* distributions including binary code include the above copyright notice and
* this paragraph in its entirety in the documentation or other materials
* provided with the distribution, and (3) all advertising materials mentioning
* features or use of this software display the following acknowledgement:
* ``This product includes software developed by the University of California,
* Lawrence Berkeley Laboratory and its contributors.'' Neither the name of
* the University nor the names of its contributors may be used to endorse
* or promote products derived from this software without specific prior
* written permission.
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
/* \summary: BOOTP and IPv4 DHCP printer */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <netdissect-stdinc.h>
#include <string.h>
#include "netdissect.h"
#include "addrtoname.h"
#include "extract.h"
static const char tstr[] = " [|bootp]";
/*
* Bootstrap Protocol (BOOTP). RFC951 and RFC1048.
*
* This file specifies the "implementation-independent" BOOTP protocol
* information which is common to both client and server.
*
* Copyright 1988 by Carnegie Mellon.
*
* Permission to use, copy, modify, and distribute this program for any
* purpose and without fee is hereby granted, provided that this copyright
* and permission notice appear on all copies and supporting documentation,
* the name of Carnegie Mellon not be used in advertising or publicity
* pertaining to distribution of the program without specific prior
* permission, and notice be given in supporting documentation that copying
* and distribution is by permission of Carnegie Mellon and Stanford
* University. Carnegie Mellon makes no representations about the
* suitability of this software for any purpose. It is provided "as is"
* without express or implied warranty.
*/
struct bootp {
uint8_t bp_op; /* packet opcode type */
uint8_t bp_htype; /* hardware addr type */
uint8_t bp_hlen; /* hardware addr length */
uint8_t bp_hops; /* gateway hops */
uint32_t bp_xid; /* transaction ID */
uint16_t bp_secs; /* seconds since boot began */
uint16_t bp_flags; /* flags - see bootp_flag_values[]
in print-bootp.c */
struct in_addr bp_ciaddr; /* client IP address */
struct in_addr bp_yiaddr; /* 'your' IP address */
struct in_addr bp_siaddr; /* server IP address */
struct in_addr bp_giaddr; /* gateway IP address */
uint8_t bp_chaddr[16]; /* client hardware address */
uint8_t bp_sname[64]; /* server host name */
uint8_t bp_file[128]; /* boot file name */
uint8_t bp_vend[64]; /* vendor-specific area */
} UNALIGNED;
#define BOOTPREPLY 2
#define BOOTPREQUEST 1
/*
* Vendor magic cookie (v_magic) for CMU
*/
#define VM_CMU "CMU"
/*
* Vendor magic cookie (v_magic) for RFC1048
*/
#define VM_RFC1048 { 99, 130, 83, 99 }
/*
* RFC1048 tag values used to specify what information is being supplied in
* the vendor field of the packet.
*/
#define TAG_PAD ((uint8_t) 0)
#define TAG_SUBNET_MASK ((uint8_t) 1)
#define TAG_TIME_OFFSET ((uint8_t) 2)
#define TAG_GATEWAY ((uint8_t) 3)
#define TAG_TIME_SERVER ((uint8_t) 4)
#define TAG_NAME_SERVER ((uint8_t) 5)
#define TAG_DOMAIN_SERVER ((uint8_t) 6)
#define TAG_LOG_SERVER ((uint8_t) 7)
#define TAG_COOKIE_SERVER ((uint8_t) 8)
#define TAG_LPR_SERVER ((uint8_t) 9)
#define TAG_IMPRESS_SERVER ((uint8_t) 10)
#define TAG_RLP_SERVER ((uint8_t) 11)
#define TAG_HOSTNAME ((uint8_t) 12)
#define TAG_BOOTSIZE ((uint8_t) 13)
#define TAG_END ((uint8_t) 255)
/* RFC1497 tags */
#define TAG_DUMPPATH ((uint8_t) 14)
#define TAG_DOMAINNAME ((uint8_t) 15)
#define TAG_SWAP_SERVER ((uint8_t) 16)
#define TAG_ROOTPATH ((uint8_t) 17)
#define TAG_EXTPATH ((uint8_t) 18)
/* RFC2132 */
#define TAG_IP_FORWARD ((uint8_t) 19)
#define TAG_NL_SRCRT ((uint8_t) 20)
#define TAG_PFILTERS ((uint8_t) 21)
#define TAG_REASS_SIZE ((uint8_t) 22)
#define TAG_DEF_TTL ((uint8_t) 23)
#define TAG_MTU_TIMEOUT ((uint8_t) 24)
#define TAG_MTU_TABLE ((uint8_t) 25)
#define TAG_INT_MTU ((uint8_t) 26)
#define TAG_LOCAL_SUBNETS ((uint8_t) 27)
#define TAG_BROAD_ADDR ((uint8_t) 28)
#define TAG_DO_MASK_DISC ((uint8_t) 29)
#define TAG_SUPPLY_MASK ((uint8_t) 30)
#define TAG_DO_RDISC ((uint8_t) 31)
#define TAG_RTR_SOL_ADDR ((uint8_t) 32)
#define TAG_STATIC_ROUTE ((uint8_t) 33)
#define TAG_USE_TRAILERS ((uint8_t) 34)
#define TAG_ARP_TIMEOUT ((uint8_t) 35)
#define TAG_ETH_ENCAP ((uint8_t) 36)
#define TAG_TCP_TTL ((uint8_t) 37)
#define TAG_TCP_KEEPALIVE ((uint8_t) 38)
#define TAG_KEEPALIVE_GO ((uint8_t) 39)
#define TAG_NIS_DOMAIN ((uint8_t) 40)
#define TAG_NIS_SERVERS ((uint8_t) 41)
#define TAG_NTP_SERVERS ((uint8_t) 42)
#define TAG_VENDOR_OPTS ((uint8_t) 43)
#define TAG_NETBIOS_NS ((uint8_t) 44)
#define TAG_NETBIOS_DDS ((uint8_t) 45)
#define TAG_NETBIOS_NODE ((uint8_t) 46)
#define TAG_NETBIOS_SCOPE ((uint8_t) 47)
#define TAG_XWIN_FS ((uint8_t) 48)
#define TAG_XWIN_DM ((uint8_t) 49)
#define TAG_NIS_P_DOMAIN ((uint8_t) 64)
#define TAG_NIS_P_SERVERS ((uint8_t) 65)
#define TAG_MOBILE_HOME ((uint8_t) 68)
#define TAG_SMPT_SERVER ((uint8_t) 69)
#define TAG_POP3_SERVER ((uint8_t) 70)
#define TAG_NNTP_SERVER ((uint8_t) 71)
#define TAG_WWW_SERVER ((uint8_t) 72)
#define TAG_FINGER_SERVER ((uint8_t) 73)
#define TAG_IRC_SERVER ((uint8_t) 74)
#define TAG_STREETTALK_SRVR ((uint8_t) 75)
#define TAG_STREETTALK_STDA ((uint8_t) 76)
/* DHCP options */
#define TAG_REQUESTED_IP ((uint8_t) 50)
#define TAG_IP_LEASE ((uint8_t) 51)
#define TAG_OPT_OVERLOAD ((uint8_t) 52)
#define TAG_TFTP_SERVER ((uint8_t) 66)
#define TAG_BOOTFILENAME ((uint8_t) 67)
#define TAG_DHCP_MESSAGE ((uint8_t) 53)
#define TAG_SERVER_ID ((uint8_t) 54)
#define TAG_PARM_REQUEST ((uint8_t) 55)
#define TAG_MESSAGE ((uint8_t) 56)
#define TAG_MAX_MSG_SIZE ((uint8_t) 57)
#define TAG_RENEWAL_TIME ((uint8_t) 58)
#define TAG_REBIND_TIME ((uint8_t) 59)
#define TAG_VENDOR_CLASS ((uint8_t) 60)
#define TAG_CLIENT_ID ((uint8_t) 61)
/* RFC 2241 */
#define TAG_NDS_SERVERS ((uint8_t) 85)
#define TAG_NDS_TREE_NAME ((uint8_t) 86)
#define TAG_NDS_CONTEXT ((uint8_t) 87)
/* RFC 2242 */
#define TAG_NDS_IPDOMAIN ((uint8_t) 62)
#define TAG_NDS_IPINFO ((uint8_t) 63)
/* RFC 2485 */
#define TAG_OPEN_GROUP_UAP ((uint8_t) 98)
/* RFC 2563 */
#define TAG_DISABLE_AUTOCONF ((uint8_t) 116)
/* RFC 2610 */
#define TAG_SLP_DA ((uint8_t) 78)
#define TAG_SLP_SCOPE ((uint8_t) 79)
/* RFC 2937 */
#define TAG_NS_SEARCH ((uint8_t) 117)
/* RFC 3004 - The User Class Option for DHCP */
#define TAG_USER_CLASS ((uint8_t) 77)
/* RFC 3011 */
#define TAG_IP4_SUBNET_SELECT ((uint8_t) 118)
/* RFC 3442 */
#define TAG_CLASSLESS_STATIC_RT ((uint8_t) 121)
#define TAG_CLASSLESS_STA_RT_MS ((uint8_t) 249)
/* RFC 5859 - TFTP Server Address Option for DHCPv4 */
#define TAG_TFTP_SERVER_ADDRESS ((uint8_t) 150)
/* ftp://ftp.isi.edu/.../assignments/bootp-dhcp-extensions */
#define TAG_SLP_NAMING_AUTH ((uint8_t) 80)
#define TAG_CLIENT_FQDN ((uint8_t) 81)
#define TAG_AGENT_CIRCUIT ((uint8_t) 82)
#define TAG_AGENT_REMOTE ((uint8_t) 83)
#define TAG_AGENT_MASK ((uint8_t) 84)
#define TAG_TZ_STRING ((uint8_t) 88)
#define TAG_FQDN_OPTION ((uint8_t) 89)
#define TAG_AUTH ((uint8_t) 90)
#define TAG_VINES_SERVERS ((uint8_t) 91)
#define TAG_SERVER_RANK ((uint8_t) 92)
#define TAG_CLIENT_ARCH ((uint8_t) 93)
#define TAG_CLIENT_NDI ((uint8_t) 94)
#define TAG_CLIENT_GUID ((uint8_t) 97)
#define TAG_LDAP_URL ((uint8_t) 95)
#define TAG_6OVER4 ((uint8_t) 96)
/* RFC 4833, TZ codes */
#define TAG_TZ_PCODE ((uint8_t) 100)
#define TAG_TZ_TCODE ((uint8_t) 101)
#define TAG_IPX_COMPAT ((uint8_t) 110)
#define TAG_NETINFO_PARENT ((uint8_t) 112)
#define TAG_NETINFO_PARENT_TAG ((uint8_t) 113)
#define TAG_URL ((uint8_t) 114)
#define TAG_FAILOVER ((uint8_t) 115)
#define TAG_EXTENDED_REQUEST ((uint8_t) 126)
#define TAG_EXTENDED_OPTION ((uint8_t) 127)
#define TAG_MUDURL ((uint8_t) 161)
/* DHCP Message types (values for TAG_DHCP_MESSAGE option) */
#define DHCPDISCOVER 1
#define DHCPOFFER 2
#define DHCPREQUEST 3
#define DHCPDECLINE 4
#define DHCPACK 5
#define DHCPNAK 6
#define DHCPRELEASE 7
#define DHCPINFORM 8
/*
* "vendor" data permitted for CMU bootp clients.
*/
struct cmu_vend {
uint8_t v_magic[4]; /* magic number */
uint32_t v_flags; /* flags/opcodes, etc. */
struct in_addr v_smask; /* Subnet mask */
struct in_addr v_dgate; /* Default gateway */
struct in_addr v_dns1, v_dns2; /* Domain name servers */
struct in_addr v_ins1, v_ins2; /* IEN-116 name servers */
struct in_addr v_ts1, v_ts2; /* Time servers */
uint8_t v_unused[24]; /* currently unused */
} UNALIGNED;
/* v_flags values */
#define VF_SMASK 1 /* Subnet mask field contains valid data */
/* RFC 4702 DHCP Client FQDN Option */
#define CLIENT_FQDN_FLAGS_S 0x01
#define CLIENT_FQDN_FLAGS_O 0x02
#define CLIENT_FQDN_FLAGS_E 0x04
#define CLIENT_FQDN_FLAGS_N 0x08
/* end of original bootp.h */
static void rfc1048_print(netdissect_options *, const u_char *);
static void cmu_print(netdissect_options *, const u_char *);
static char *client_fqdn_flags(u_int flags);
static const struct tok bootp_flag_values[] = {
{ 0x8000, "Broadcast" },
{ 0, NULL}
};
static const struct tok bootp_op_values[] = {
{ BOOTPREQUEST, "Request" },
{ BOOTPREPLY, "Reply" },
{ 0, NULL}
};
/*
* Print bootp requests
*/
void
bootp_print(netdissect_options *ndo,
register const u_char *cp, u_int length)
{
register const struct bootp *bp;
static const u_char vm_cmu[4] = VM_CMU;
static const u_char vm_rfc1048[4] = VM_RFC1048;
bp = (const struct bootp *)cp;
ND_TCHECK(bp->bp_op);
ND_PRINT((ndo, "BOOTP/DHCP, %s",
tok2str(bootp_op_values, "unknown (0x%02x)", bp->bp_op)));
ND_TCHECK(bp->bp_hlen);
if (bp->bp_htype == 1 && bp->bp_hlen == 6 && bp->bp_op == BOOTPREQUEST) {
ND_TCHECK2(bp->bp_chaddr[0], 6);
ND_PRINT((ndo, " from %s", etheraddr_string(ndo, bp->bp_chaddr)));
}
ND_PRINT((ndo, ", length %u", length));
if (!ndo->ndo_vflag)
return;
ND_TCHECK(bp->bp_secs);
/* The usual hardware address type is 1 (10Mb Ethernet) */
if (bp->bp_htype != 1)
ND_PRINT((ndo, ", htype %d", bp->bp_htype));
/* The usual length for 10Mb Ethernet address is 6 bytes */
if (bp->bp_htype != 1 || bp->bp_hlen != 6)
ND_PRINT((ndo, ", hlen %d", bp->bp_hlen));
/* Only print interesting fields */
if (bp->bp_hops)
ND_PRINT((ndo, ", hops %d", bp->bp_hops));
if (EXTRACT_32BITS(&bp->bp_xid))
ND_PRINT((ndo, ", xid 0x%x", EXTRACT_32BITS(&bp->bp_xid)));
if (EXTRACT_16BITS(&bp->bp_secs))
ND_PRINT((ndo, ", secs %d", EXTRACT_16BITS(&bp->bp_secs)));
ND_PRINT((ndo, ", Flags [%s]",
bittok2str(bootp_flag_values, "none", EXTRACT_16BITS(&bp->bp_flags))));
if (ndo->ndo_vflag > 1)
ND_PRINT((ndo, " (0x%04x)", EXTRACT_16BITS(&bp->bp_flags)));
/* Client's ip address */
ND_TCHECK(bp->bp_ciaddr);
if (EXTRACT_32BITS(&bp->bp_ciaddr.s_addr))
ND_PRINT((ndo, "\n\t Client-IP %s", ipaddr_string(ndo, &bp->bp_ciaddr)));
/* 'your' ip address (bootp client) */
ND_TCHECK(bp->bp_yiaddr);
if (EXTRACT_32BITS(&bp->bp_yiaddr.s_addr))
ND_PRINT((ndo, "\n\t Your-IP %s", ipaddr_string(ndo, &bp->bp_yiaddr)));
/* Server's ip address */
ND_TCHECK(bp->bp_siaddr);
if (EXTRACT_32BITS(&bp->bp_siaddr.s_addr))
ND_PRINT((ndo, "\n\t Server-IP %s", ipaddr_string(ndo, &bp->bp_siaddr)));
/* Gateway's ip address */
ND_TCHECK(bp->bp_giaddr);
if (EXTRACT_32BITS(&bp->bp_giaddr.s_addr))
ND_PRINT((ndo, "\n\t Gateway-IP %s", ipaddr_string(ndo, &bp->bp_giaddr)));
/* Client's Ethernet address */
if (bp->bp_htype == 1 && bp->bp_hlen == 6) {
ND_TCHECK2(bp->bp_chaddr[0], 6);
ND_PRINT((ndo, "\n\t Client-Ethernet-Address %s", etheraddr_string(ndo, bp->bp_chaddr)));
}
ND_TCHECK2(bp->bp_sname[0], 1); /* check first char only */
if (*bp->bp_sname) {
ND_PRINT((ndo, "\n\t sname \""));
if (fn_printztn(ndo, bp->bp_sname, (u_int)sizeof bp->bp_sname,
ndo->ndo_snapend)) {
ND_PRINT((ndo, "\""));
ND_PRINT((ndo, "%s", tstr + 1));
return;
}
ND_PRINT((ndo, "\""));
}
ND_TCHECK2(bp->bp_file[0], 1); /* check first char only */
if (*bp->bp_file) {
ND_PRINT((ndo, "\n\t file \""));
if (fn_printztn(ndo, bp->bp_file, (u_int)sizeof bp->bp_file,
ndo->ndo_snapend)) {
ND_PRINT((ndo, "\""));
ND_PRINT((ndo, "%s", tstr + 1));
return;
}
ND_PRINT((ndo, "\""));
}
/* Decode the vendor buffer */
ND_TCHECK(bp->bp_vend[0]);
if (memcmp((const char *)bp->bp_vend, vm_rfc1048,
sizeof(uint32_t)) == 0)
rfc1048_print(ndo, bp->bp_vend);
else if (memcmp((const char *)bp->bp_vend, vm_cmu,
sizeof(uint32_t)) == 0)
cmu_print(ndo, bp->bp_vend);
else {
uint32_t ul;
ul = EXTRACT_32BITS(&bp->bp_vend);
if (ul != 0)
ND_PRINT((ndo, "\n\t Vendor-#0x%x", ul));
}
return;
trunc:
ND_PRINT((ndo, "%s", tstr));
}
/*
* The first character specifies the format to print:
* i - ip address (32 bits)
* p - ip address pairs (32 bits + 32 bits)
* l - long (32 bits)
* L - unsigned long (32 bits)
* s - short (16 bits)
* b - period-seperated decimal bytes (variable length)
* x - colon-seperated hex bytes (variable length)
* a - ASCII string (variable length)
* B - on/off (8 bits)
* $ - special (explicit code to handle)
*/
static const struct tok tag2str[] = {
/* RFC1048 tags */
{ TAG_PAD, " PAD" },
{ TAG_SUBNET_MASK, "iSubnet-Mask" }, /* subnet mask (RFC950) */
{ TAG_TIME_OFFSET, "LTime-Zone" }, /* seconds from UTC */
{ TAG_GATEWAY, "iDefault-Gateway" }, /* default gateway */
{ TAG_TIME_SERVER, "iTime-Server" }, /* time servers (RFC868) */
{ TAG_NAME_SERVER, "iIEN-Name-Server" }, /* IEN name servers (IEN116) */
{ TAG_DOMAIN_SERVER, "iDomain-Name-Server" }, /* domain name (RFC1035) */
{ TAG_LOG_SERVER, "iLOG" }, /* MIT log servers */
{ TAG_COOKIE_SERVER, "iCS" }, /* cookie servers (RFC865) */
{ TAG_LPR_SERVER, "iLPR-Server" }, /* lpr server (RFC1179) */
{ TAG_IMPRESS_SERVER, "iIM" }, /* impress servers (Imagen) */
{ TAG_RLP_SERVER, "iRL" }, /* resource location (RFC887) */
{ TAG_HOSTNAME, "aHostname" }, /* ASCII hostname */
{ TAG_BOOTSIZE, "sBS" }, /* 512 byte blocks */
{ TAG_END, " END" },
/* RFC1497 tags */
{ TAG_DUMPPATH, "aDP" },
{ TAG_DOMAINNAME, "aDomain-Name" },
{ TAG_SWAP_SERVER, "iSS" },
{ TAG_ROOTPATH, "aRP" },
{ TAG_EXTPATH, "aEP" },
/* RFC2132 tags */
{ TAG_IP_FORWARD, "BIPF" },
{ TAG_NL_SRCRT, "BSRT" },
{ TAG_PFILTERS, "pPF" },
{ TAG_REASS_SIZE, "sRSZ" },
{ TAG_DEF_TTL, "bTTL" },
{ TAG_MTU_TIMEOUT, "lMTU-Timeout" },
{ TAG_MTU_TABLE, "sMTU-Table" },
{ TAG_INT_MTU, "sMTU" },
{ TAG_LOCAL_SUBNETS, "BLSN" },
{ TAG_BROAD_ADDR, "iBR" },
{ TAG_DO_MASK_DISC, "BMD" },
{ TAG_SUPPLY_MASK, "BMS" },
{ TAG_DO_RDISC, "BRouter-Discovery" },
{ TAG_RTR_SOL_ADDR, "iRSA" },
{ TAG_STATIC_ROUTE, "pStatic-Route" },
{ TAG_USE_TRAILERS, "BUT" },
{ TAG_ARP_TIMEOUT, "lAT" },
{ TAG_ETH_ENCAP, "BIE" },
{ TAG_TCP_TTL, "bTT" },
{ TAG_TCP_KEEPALIVE, "lKI" },
{ TAG_KEEPALIVE_GO, "BKG" },
{ TAG_NIS_DOMAIN, "aYD" },
{ TAG_NIS_SERVERS, "iYS" },
{ TAG_NTP_SERVERS, "iNTP" },
{ TAG_VENDOR_OPTS, "bVendor-Option" },
{ TAG_NETBIOS_NS, "iNetbios-Name-Server" },
{ TAG_NETBIOS_DDS, "iWDD" },
{ TAG_NETBIOS_NODE, "$Netbios-Node" },
{ TAG_NETBIOS_SCOPE, "aNetbios-Scope" },
{ TAG_XWIN_FS, "iXFS" },
{ TAG_XWIN_DM, "iXDM" },
{ TAG_NIS_P_DOMAIN, "sN+D" },
{ TAG_NIS_P_SERVERS, "iN+S" },
{ TAG_MOBILE_HOME, "iMH" },
{ TAG_SMPT_SERVER, "iSMTP" },
{ TAG_POP3_SERVER, "iPOP3" },
{ TAG_NNTP_SERVER, "iNNTP" },
{ TAG_WWW_SERVER, "iWWW" },
{ TAG_FINGER_SERVER, "iFG" },
{ TAG_IRC_SERVER, "iIRC" },
{ TAG_STREETTALK_SRVR, "iSTS" },
{ TAG_STREETTALK_STDA, "iSTDA" },
{ TAG_REQUESTED_IP, "iRequested-IP" },
{ TAG_IP_LEASE, "lLease-Time" },
{ TAG_OPT_OVERLOAD, "$OO" },
{ TAG_TFTP_SERVER, "aTFTP" },
{ TAG_BOOTFILENAME, "aBF" },
{ TAG_DHCP_MESSAGE, " DHCP-Message" },
{ TAG_SERVER_ID, "iServer-ID" },
{ TAG_PARM_REQUEST, "bParameter-Request" },
{ TAG_MESSAGE, "aMSG" },
{ TAG_MAX_MSG_SIZE, "sMSZ" },
{ TAG_RENEWAL_TIME, "lRN" },
{ TAG_REBIND_TIME, "lRB" },
{ TAG_VENDOR_CLASS, "aVendor-Class" },
{ TAG_CLIENT_ID, "$Client-ID" },
/* RFC 2485 */
{ TAG_OPEN_GROUP_UAP, "aUAP" },
/* RFC 2563 */
{ TAG_DISABLE_AUTOCONF, "BNOAUTO" },
/* RFC 2610 */
{ TAG_SLP_DA, "bSLP-DA" }, /*"b" is a little wrong */
{ TAG_SLP_SCOPE, "bSLP-SCOPE" }, /*"b" is a little wrong */
/* RFC 2937 */
{ TAG_NS_SEARCH, "sNSSEARCH" }, /* XXX 's' */
/* RFC 3004 - The User Class Option for DHCP */
{ TAG_USER_CLASS, "$User-Class" },
/* RFC 3011 */
{ TAG_IP4_SUBNET_SELECT, "iSUBNET" },
/* RFC 3442 */
{ TAG_CLASSLESS_STATIC_RT, "$Classless-Static-Route" },
{ TAG_CLASSLESS_STA_RT_MS, "$Classless-Static-Route-Microsoft" },
/* RFC 5859 - TFTP Server Address Option for DHCPv4 */
{ TAG_TFTP_SERVER_ADDRESS, "iTFTP-Server-Address" },
/* http://www.iana.org/assignments/bootp-dhcp-extensions/index.htm */
{ TAG_SLP_NAMING_AUTH, "aSLP-NA" },
{ TAG_CLIENT_FQDN, "$FQDN" },
{ TAG_AGENT_CIRCUIT, "$Agent-Information" },
{ TAG_AGENT_REMOTE, "bARMT" },
{ TAG_AGENT_MASK, "bAMSK" },
{ TAG_TZ_STRING, "aTZSTR" },
{ TAG_FQDN_OPTION, "bFQDNS" }, /* XXX 'b' */
{ TAG_AUTH, "bAUTH" }, /* XXX 'b' */
{ TAG_VINES_SERVERS, "iVINES" },
{ TAG_SERVER_RANK, "sRANK" },
{ TAG_CLIENT_ARCH, "sARCH" },
{ TAG_CLIENT_NDI, "bNDI" }, /* XXX 'b' */
{ TAG_CLIENT_GUID, "bGUID" }, /* XXX 'b' */
{ TAG_LDAP_URL, "aLDAP" },
{ TAG_6OVER4, "i6o4" },
{ TAG_TZ_PCODE, "aPOSIX-TZ" },
{ TAG_TZ_TCODE, "aTZ-Name" },
{ TAG_IPX_COMPAT, "bIPX" }, /* XXX 'b' */
{ TAG_NETINFO_PARENT, "iNI" },
{ TAG_NETINFO_PARENT_TAG, "aNITAG" },
{ TAG_URL, "aURL" },
{ TAG_FAILOVER, "bFAIL" }, /* XXX 'b' */
{ TAG_MUDURL, "aMUD-URL" },
{ 0, NULL }
};
/* 2-byte extended tags */
static const struct tok xtag2str[] = {
{ 0, NULL }
};
/* DHCP "options overload" types */
static const struct tok oo2str[] = {
{ 1, "file" },
{ 2, "sname" },
{ 3, "file+sname" },
{ 0, NULL }
};
/* NETBIOS over TCP/IP node type options */
static const struct tok nbo2str[] = {
{ 0x1, "b-node" },
{ 0x2, "p-node" },
{ 0x4, "m-node" },
{ 0x8, "h-node" },
{ 0, NULL }
};
/* ARP Hardware types, for Client-ID option */
static const struct tok arp2str[] = {
{ 0x1, "ether" },
{ 0x6, "ieee802" },
{ 0x7, "arcnet" },
{ 0xf, "frelay" },
{ 0x17, "strip" },
{ 0x18, "ieee1394" },
{ 0, NULL }
};
static const struct tok dhcp_msg_values[] = {
{ DHCPDISCOVER, "Discover" },
{ DHCPOFFER, "Offer" },
{ DHCPREQUEST, "Request" },
{ DHCPDECLINE, "Decline" },
{ DHCPACK, "ACK" },
{ DHCPNAK, "NACK" },
{ DHCPRELEASE, "Release" },
{ DHCPINFORM, "Inform" },
{ 0, NULL }
};
#define AGENT_SUBOPTION_CIRCUIT_ID 1 /* RFC 3046 */
#define AGENT_SUBOPTION_REMOTE_ID 2 /* RFC 3046 */
#define AGENT_SUBOPTION_SUBSCRIBER_ID 6 /* RFC 3993 */
static const struct tok agent_suboption_values[] = {
{ AGENT_SUBOPTION_CIRCUIT_ID, "Circuit-ID" },
{ AGENT_SUBOPTION_REMOTE_ID, "Remote-ID" },
{ AGENT_SUBOPTION_SUBSCRIBER_ID, "Subscriber-ID" },
{ 0, NULL }
};
static void
rfc1048_print(netdissect_options *ndo,
register const u_char *bp)
{
register uint16_t tag;
register u_int len;
register const char *cp;
register char c;
int first, idx;
uint32_t ul;
uint16_t us;
uint8_t uc, subopt, suboptlen;
ND_PRINT((ndo, "\n\t Vendor-rfc1048 Extensions"));
/* Step over magic cookie */
ND_PRINT((ndo, "\n\t Magic Cookie 0x%08x", EXTRACT_32BITS(bp)));
bp += sizeof(int32_t);
/* Loop while we there is a tag left in the buffer */
while (ND_TTEST2(*bp, 1)) {
tag = *bp++;
if (tag == TAG_PAD && ndo->ndo_vflag < 3)
continue;
if (tag == TAG_END && ndo->ndo_vflag < 3)
return;
if (tag == TAG_EXTENDED_OPTION) {
ND_TCHECK2(*(bp + 1), 2);
tag = EXTRACT_16BITS(bp + 1);
/* XXX we don't know yet if the IANA will
* preclude overlap of 1-byte and 2-byte spaces.
* If not, we need to offset tag after this step.
*/
cp = tok2str(xtag2str, "?xT%u", tag);
} else
cp = tok2str(tag2str, "?T%u", tag);
c = *cp++;
if (tag == TAG_PAD || tag == TAG_END)
len = 0;
else {
/* Get the length; check for truncation */
ND_TCHECK2(*bp, 1);
len = *bp++;
}
ND_PRINT((ndo, "\n\t %s Option %u, length %u%s", cp, tag, len,
len > 0 ? ": " : ""));
if (tag == TAG_PAD && ndo->ndo_vflag > 2) {
u_int ntag = 1;
while (ND_TTEST2(*bp, 1) && *bp == TAG_PAD) {
bp++;
ntag++;
}
if (ntag > 1)
ND_PRINT((ndo, ", occurs %u", ntag));
}
if (!ND_TTEST2(*bp, len)) {
ND_PRINT((ndo, "[|rfc1048 %u]", len));
return;
}
if (tag == TAG_DHCP_MESSAGE && len == 1) {
uc = *bp++;
ND_PRINT((ndo, "%s", tok2str(dhcp_msg_values, "Unknown (%u)", uc)));
continue;
}
if (tag == TAG_PARM_REQUEST) {
idx = 0;
while (len-- > 0) {
uc = *bp++;
cp = tok2str(tag2str, "?Option %u", uc);
if (idx % 4 == 0)
ND_PRINT((ndo, "\n\t "));
else
ND_PRINT((ndo, ", "));
ND_PRINT((ndo, "%s", cp + 1));
idx++;
}
continue;
}
if (tag == TAG_EXTENDED_REQUEST) {
first = 1;
while (len > 1) {
len -= 2;
us = EXTRACT_16BITS(bp);
bp += 2;
cp = tok2str(xtag2str, "?xT%u", us);
if (!first)
ND_PRINT((ndo, "+"));
ND_PRINT((ndo, "%s", cp + 1));
first = 0;
}
continue;
}
/* Print data */
if (c == '?') {
/* Base default formats for unknown tags on data size */
if (len & 1)
c = 'b';
else if (len & 2)
c = 's';
else
c = 'l';
}
first = 1;
switch (c) {
case 'a':
/* ASCII strings */
ND_PRINT((ndo, "\""));
if (fn_printn(ndo, bp, len, ndo->ndo_snapend)) {
ND_PRINT((ndo, "\""));
goto trunc;
}
ND_PRINT((ndo, "\""));
bp += len;
len = 0;
break;
case 'i':
case 'l':
case 'L':
/* ip addresses/32-bit words */
while (len >= sizeof(ul)) {
if (!first)
ND_PRINT((ndo, ","));
ul = EXTRACT_32BITS(bp);
if (c == 'i') {
ul = htonl(ul);
ND_PRINT((ndo, "%s", ipaddr_string(ndo, &ul)));
} else if (c == 'L')
ND_PRINT((ndo, "%d", ul));
else
ND_PRINT((ndo, "%u", ul));
bp += sizeof(ul);
len -= sizeof(ul);
first = 0;
}
break;
case 'p':
/* IP address pairs */
while (len >= 2*sizeof(ul)) {
if (!first)
ND_PRINT((ndo, ","));
memcpy((char *)&ul, (const char *)bp, sizeof(ul));
ND_PRINT((ndo, "(%s:", ipaddr_string(ndo, &ul)));
bp += sizeof(ul);
memcpy((char *)&ul, (const char *)bp, sizeof(ul));
ND_PRINT((ndo, "%s)", ipaddr_string(ndo, &ul)));
bp += sizeof(ul);
len -= 2*sizeof(ul);
first = 0;
}
break;
case 's':
/* shorts */
while (len >= sizeof(us)) {
if (!first)
ND_PRINT((ndo, ","));
us = EXTRACT_16BITS(bp);
ND_PRINT((ndo, "%u", us));
bp += sizeof(us);
len -= sizeof(us);
first = 0;
}
break;
case 'B':
/* boolean */
while (len > 0) {
if (!first)
ND_PRINT((ndo, ","));
switch (*bp) {
case 0:
ND_PRINT((ndo, "N"));
break;
case 1:
ND_PRINT((ndo, "Y"));
break;
default:
ND_PRINT((ndo, "%u?", *bp));
break;
}
++bp;
--len;
first = 0;
}
break;
case 'b':
case 'x':
default:
/* Bytes */
while (len > 0) {
if (!first)
ND_PRINT((ndo, c == 'x' ? ":" : "."));
if (c == 'x')
ND_PRINT((ndo, "%02x", *bp));
else
ND_PRINT((ndo, "%u", *bp));
++bp;
--len;
first = 0;
}
break;
case '$':
/* Guys we can't handle with one of the usual cases */
switch (tag) {
case TAG_NETBIOS_NODE:
/* this option should be at least 1 byte long */
if (len < 1) {
ND_PRINT((ndo, "ERROR: length < 1 bytes"));
break;
}
tag = *bp++;
--len;
ND_PRINT((ndo, "%s", tok2str(nbo2str, NULL, tag)));
break;
case TAG_OPT_OVERLOAD:
/* this option should be at least 1 byte long */
if (len < 1) {
ND_PRINT((ndo, "ERROR: length < 1 bytes"));
break;
}
tag = *bp++;
--len;
ND_PRINT((ndo, "%s", tok2str(oo2str, NULL, tag)));
break;
case TAG_CLIENT_FQDN:
/* this option should be at least 3 bytes long */
if (len < 3) {
ND_PRINT((ndo, "ERROR: length < 3 bytes"));
bp += len;
len = 0;
break;
}
if (*bp)
ND_PRINT((ndo, "[%s] ", client_fqdn_flags(*bp)));
bp++;
if (*bp || *(bp+1))
ND_PRINT((ndo, "%u/%u ", *bp, *(bp+1)));
bp += 2;
ND_PRINT((ndo, "\""));
if (fn_printn(ndo, bp, len - 3, ndo->ndo_snapend)) {
ND_PRINT((ndo, "\""));
goto trunc;
}
ND_PRINT((ndo, "\""));
bp += len - 3;
len = 0;
break;
case TAG_CLIENT_ID:
{
int type;
/* this option should be at least 1 byte long */
if (len < 1) {
ND_PRINT((ndo, "ERROR: length < 1 bytes"));
break;
}
type = *bp++;
len--;
if (type == 0) {
ND_PRINT((ndo, "\""));
if (fn_printn(ndo, bp, len, ndo->ndo_snapend)) {
ND_PRINT((ndo, "\""));
goto trunc;
}
ND_PRINT((ndo, "\""));
bp += len;
len = 0;
break;
} else {
ND_PRINT((ndo, "%s ", tok2str(arp2str, "hardware-type %u,", type)));
while (len > 0) {
if (!first)
ND_PRINT((ndo, ":"));
ND_PRINT((ndo, "%02x", *bp));
++bp;
--len;
first = 0;
}
}
break;
}
case TAG_AGENT_CIRCUIT:
while (len >= 2) {
subopt = *bp++;
suboptlen = *bp++;
len -= 2;
if (suboptlen > len) {
ND_PRINT((ndo, "\n\t %s SubOption %u, length %u: length goes past end of option",
tok2str(agent_suboption_values, "Unknown", subopt),
subopt,
suboptlen));
bp += len;
len = 0;
break;
}
ND_PRINT((ndo, "\n\t %s SubOption %u, length %u: ",
tok2str(agent_suboption_values, "Unknown", subopt),
subopt,
suboptlen));
switch (subopt) {
case AGENT_SUBOPTION_CIRCUIT_ID: /* fall through */
case AGENT_SUBOPTION_REMOTE_ID:
case AGENT_SUBOPTION_SUBSCRIBER_ID:
if (fn_printn(ndo, bp, suboptlen, ndo->ndo_snapend))
goto trunc;
break;
default:
print_unknown_data(ndo, bp, "\n\t\t", suboptlen);
}
len -= suboptlen;
bp += suboptlen;
}
break;
case TAG_CLASSLESS_STATIC_RT:
case TAG_CLASSLESS_STA_RT_MS:
{
u_int mask_width, significant_octets, i;
/* this option should be at least 5 bytes long */
if (len < 5) {
ND_PRINT((ndo, "ERROR: length < 5 bytes"));
bp += len;
len = 0;
break;
}
while (len > 0) {
if (!first)
ND_PRINT((ndo, ","));
mask_width = *bp++;
len--;
/* mask_width <= 32 */
if (mask_width > 32) {
ND_PRINT((ndo, "[ERROR: Mask width (%d) > 32]", mask_width));
bp += len;
len = 0;
break;
}
significant_octets = (mask_width + 7) / 8;
/* significant octets + router(4) */
if (len < significant_octets + 4) {
ND_PRINT((ndo, "[ERROR: Remaining length (%u) < %u bytes]", len, significant_octets + 4));
bp += len;
len = 0;
break;
}
ND_PRINT((ndo, "("));
if (mask_width == 0)
ND_PRINT((ndo, "default"));
else {
for (i = 0; i < significant_octets ; i++) {
if (i > 0)
ND_PRINT((ndo, "."));
ND_PRINT((ndo, "%d", *bp++));
}
for (i = significant_octets ; i < 4 ; i++)
ND_PRINT((ndo, ".0"));
ND_PRINT((ndo, "/%d", mask_width));
}
memcpy((char *)&ul, (const char *)bp, sizeof(ul));
ND_PRINT((ndo, ":%s)", ipaddr_string(ndo, &ul)));
bp += sizeof(ul);
len -= (significant_octets + 4);
first = 0;
}
break;
}
case TAG_USER_CLASS:
{
u_int suboptnumber = 1;
first = 1;
if (len < 2) {
ND_PRINT((ndo, "ERROR: length < 2 bytes"));
bp += len;
len = 0;
break;
}
while (len > 0) {
suboptlen = *bp++;
len--;
ND_PRINT((ndo, "\n\t "));
ND_PRINT((ndo, "instance#%u: ", suboptnumber));
if (suboptlen == 0) {
ND_PRINT((ndo, "ERROR: suboption length must be non-zero"));
bp += len;
len = 0;
break;
}
if (len < suboptlen) {
ND_PRINT((ndo, "ERROR: invalid option"));
bp += len;
len = 0;
break;
}
ND_PRINT((ndo, "\""));
if (fn_printn(ndo, bp, suboptlen, ndo->ndo_snapend)) {
ND_PRINT((ndo, "\""));
goto trunc;
}
ND_PRINT((ndo, "\""));
ND_PRINT((ndo, ", length %d", suboptlen));
suboptnumber++;
len -= suboptlen;
bp += suboptlen;
}
break;
}
default:
ND_PRINT((ndo, "[unknown special tag %u, size %u]",
tag, len));
bp += len;
len = 0;
break;
}
break;
}
/* Data left over? */
if (len) {
ND_PRINT((ndo, "\n\t trailing data length %u", len));
bp += len;
}
}
return;
trunc:
ND_PRINT((ndo, "|[rfc1048]"));
}
static void
cmu_print(netdissect_options *ndo,
register const u_char *bp)
{
register const struct cmu_vend *cmu;
#define PRINTCMUADDR(m, s) { ND_TCHECK(cmu->m); \
if (cmu->m.s_addr != 0) \
ND_PRINT((ndo, " %s:%s", s, ipaddr_string(ndo, &cmu->m.s_addr))); }
ND_PRINT((ndo, " vend-cmu"));
cmu = (const struct cmu_vend *)bp;
/* Only print if there are unknown bits */
ND_TCHECK(cmu->v_flags);
if ((cmu->v_flags & ~(VF_SMASK)) != 0)
ND_PRINT((ndo, " F:0x%x", cmu->v_flags));
PRINTCMUADDR(v_dgate, "DG");
PRINTCMUADDR(v_smask, cmu->v_flags & VF_SMASK ? "SM" : "SM*");
PRINTCMUADDR(v_dns1, "NS1");
PRINTCMUADDR(v_dns2, "NS2");
PRINTCMUADDR(v_ins1, "IEN1");
PRINTCMUADDR(v_ins2, "IEN2");
PRINTCMUADDR(v_ts1, "TS1");
PRINTCMUADDR(v_ts2, "TS2");
return;
trunc:
ND_PRINT((ndo, "%s", tstr));
#undef PRINTCMUADDR
}
static char *
client_fqdn_flags(u_int flags)
{
static char buf[8+1];
int i = 0;
if (flags & CLIENT_FQDN_FLAGS_S)
buf[i++] = 'S';
if (flags & CLIENT_FQDN_FLAGS_O)
buf[i++] = 'O';
if (flags & CLIENT_FQDN_FLAGS_E)
buf[i++] = 'E';
if (flags & CLIENT_FQDN_FLAGS_N)
buf[i++] = 'N';
buf[i] = '\0';
return buf;
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_2704_0 |
crossvul-cpp_data_good_3293_0 | /* radare2 - LGPL - Copyright 2017 - pancake, cgvwzq */
#include <r_types.h>
#include <r_util.h>
#include <r_lib.h>
#include <r_bin.h>
#include "wasm.h"
// Consume functions
static size_t consume_u32 (ut8 *buf, ut8 *max, ut32 *out, ut32 *offset) {
size_t n;
if (!buf || !max || !out) {
return 0;
}
if (!(n = read_u32_leb128 (buf, max, out)) || n > 5) {
return 0;
}
if (offset) {
*offset += n;
}
return n;
}
static size_t consume_s32 (ut8 *buf, ut8 *max, st32 *out, ut32 *offset) {
size_t n;
if (!buf || !max || !out) {
return 0;
}
if (!(n = read_i32_leb128 (buf, max, out)) || n > 5) {
return 0;
}
if (offset) {
*offset += n;
}
return n;
}
static size_t consume_u8 (ut8 *buf, ut8 *max, ut8 *out, ut32 *offset) {
size_t n;
ut32 tmp;
if (!(n = consume_u32 (buf, max, &tmp, offset)) || n > 1) {
return 0;
}
*out = tmp & 0x7f;
return 1;
}
static size_t consume_s8 (ut8 *buf, ut8 *max, st8 *out, ut32 *offset) {
size_t n;
ut32 tmp;
if (!(n = consume_u32 (buf, max, &tmp, offset)) || n > 1) {
return 0;
}
*out = (st8)(tmp & 0x7f);
return 1;
}
static size_t consume_str (ut8 *buf, ut8 *max, size_t sz, char *out, ut32 *offset) {
if (!buf || !max || !out || !sz) {
return 0;
}
if (!(buf + sz < max)) {
return 0;
}
strncpy ((char*)out, (char*)buf, R_MIN (R_BIN_WASM_STRING_LENGTH-1, sz));
if (offset) *offset += sz;
return sz;
}
static size_t consume_init_expr (ut8 *buf, ut8 *max, ut8 eoc, void *out, ut32 *offset) {
ut32 i = 0;
while (buf + i < max && buf[i] != eoc) {
// TODO: calc the expresion with the bytcode (ESIL?)
i++;
}
if (buf[i] != eoc) {
return 0;
}
if (offset) {
*offset += i + 1;
}
return i + 1;
}
static size_t consume_locals (ut8 *buf, ut8 *max, ut32 count, RBinWasmCodeEntry *out, ut32 *offset) {
ut32 i = 0, j = 0;
if (count < 1) return 0;
// memory leak
if (!(out->locals = (struct r_bin_wasm_local_entry_t*) malloc (sizeof(struct r_bin_wasm_local_entry_t) * count))) {
return 0;
}
while (buf + i < max && j < count) {
if (!(consume_u32 (buf + i, max, &out->locals[j].count, &i))) {
free (out->locals);
return 0;
}
if (!(consume_s8 (buf + i, max, (st8*)&out->locals[j].type, &i))) {
free (out->locals);
return 0;
}
j += 1;
}
if (offset) *offset += i;
return j;
}
static size_t consume_limits (ut8 *buf, ut8 *max, struct r_bin_wasm_resizable_limits_t *out, ut32 *offset) {
ut32 i = 0;
if (!(consume_u8 (buf + i, max, &out->flags, &i))) return 0;
if (!(consume_u32 (buf + i, max, &out->initial, &i))) return 0;
if (out->flags && (!(consume_u32 (buf + i, max, &out->maximum, &i)))) return 0;
if (offset) *offset += i;
return i;
}
// Utils
static RList *r_bin_wasm_get_sections_by_id (RList *sections, ut8 id) {
RBinWasmSection *sec = NULL;
RList *ret = NULL;
RListIter *iter = NULL;
// memory leak
if (!(ret = r_list_new ())) {
return NULL;
}
r_list_foreach (sections, iter, sec) {
if (sec->id == id) {
r_list_append(ret, sec);
}
}
return ret;
}
#define R_BIN_WASM_VALUETYPETOSTRING(p, type, i) {\
switch(type) {\
case R_BIN_WASM_VALUETYPE_i32:\
strcpy(p, "i32");\
break;\
case R_BIN_WASM_VALUETYPE_i64:\
strcpy(p, "i64");\
break;\
case R_BIN_WASM_VALUETYPE_f32:\
strcpy(p, "f32");\
break;\
case R_BIN_WASM_VALUETYPE_f64:\
strcpy(p, "f64");\
break;\
}\
i+= 3;\
}
static char *r_bin_wasm_type_entry_to_string (RBinWasmTypeEntry *ptr) {
if (!ptr || ptr->to_str) {
return NULL;
}
char *ret;
int p, i = 0, sz;
sz = (ptr->param_count + ptr->return_count) * 5 + 9;
// memory leak
if (!(ret = (char*) malloc (sz * sizeof(char)))) {
return NULL;
}
strcpy (ret + i, "(");
i++;
for (p = 0; p < ptr->param_count; p++ ) {
R_BIN_WASM_VALUETYPETOSTRING (ret+i, ptr->param_types[p], i); // i+=3
if (p < ptr->param_count - 1) {
strcpy (ret+i, ", ");
i += 2;
}
}
strcpy (ret + i, ") -> (");
i += 6;
if (ptr->return_count == 1) {
R_BIN_WASM_VALUETYPETOSTRING (ret + i, ptr->return_type, i);
}
strcpy (ret + i, ")");
return ret;
}
// Parsing
static RList *r_bin_wasm_get_type_entries (RBinWasmObj *bin, RBinWasmSection *sec) {
RList *ret = NULL;
RBinWasmTypeEntry *ptr = NULL;
if (!(ret = r_list_newf ((RListFree)free))) {
return NULL;
}
ut8* buf = bin->buf->buf + (ut32)sec->payload_data;
ut32 len = sec->payload_len;
ut32 count = sec->count;
ut32 i = 0, r = 0;
while (i < len && r < count) {
if (!(ptr = R_NEW0 (RBinWasmTypeEntry))) {
return ret;
}
if (!(consume_u8 (buf + i, buf + len, &ptr->form, &i))) {
free (ptr);
return ret;
}
if (!(consume_u32 (buf + i, buf + len, &ptr->param_count, &i))) {
free (ptr);
return ret;
}
if (!(i + ptr->param_count < len)) {
free (ptr);
return ret;
}
int j;
for (j = 0; j < ptr->param_count; j++) {
if (!(consume_s8 (buf + i, buf + len, (st8*)&ptr->param_types[j], &i))) {
free (ptr);
return ret;
}
}
if (!(consume_s8 (buf + i, buf + len, &ptr->return_count, &i))) {
free (ptr);
return ret;
}
if (ptr->return_count > 1) {
free(ptr);
return ret;
}
if (ptr->return_count == 1) {
if (!(consume_s8 (buf + i, buf + len, (st8*)&ptr->return_type, &i))) {
free(ptr);
return ret;
}
}
ptr->to_str = r_bin_wasm_type_entry_to_string (ptr);
r_list_append (ret, ptr);
r += 1;
}
return ret;
}
static RList *r_bin_wasm_get_import_entries (RBinWasmObj *bin, RBinWasmSection *sec) {
RList *ret = NULL;
RBinWasmImportEntry *ptr = NULL;
if (!(ret = r_list_newf ((RListFree)free))) {
return NULL;
}
ut8* buf = bin->buf->buf + (ut32)sec->payload_data;
ut32 len = sec->payload_len;
ut32 count = sec->count;
ut32 i = 0, r = 0;
while (i < len && r < count) {
if (!(ptr = R_NEW0 (RBinWasmImportEntry))) {
return ret;
}
if (!(consume_u32 (buf + i, buf + len, &ptr->module_len, &i))) {
goto culvert;
}
if (!(consume_str (buf + i, buf + len, ptr->module_len, ptr->module_str, &i))) {
goto culvert;
}
if (!(consume_u32 (buf + i, buf + len, &ptr->field_len, &i))) {
goto culvert;
}
if (!(consume_str (buf + i, buf + len, ptr->field_len, ptr->field_str, &i))) {
goto culvert;
}
if (!(consume_u8 (buf + i, buf + len, &ptr->kind, &i))) {
goto culvert;
}
switch (ptr->kind) {
case 0: // Function
if (!(consume_u32 (buf + i, buf + len, &ptr->type_f, &i))) {
goto sewer;
}
break;
case 1: // Table
if (!(consume_u8 (buf + i, buf + len, (ut8*)&ptr->type_t.elem_type, &i))) {
goto sewer; // varint7
}
if (!(consume_limits (buf + i, buf + len, &ptr->type_t.limits, &i))) {
goto sewer;
}
break;
case 2: // Memory
if (!(consume_limits (buf + i, buf + len, &ptr->type_m.limits, &i))) {
goto sewer;
}
break;
case 3: // Global
if (!(consume_u8 (buf + i, buf + len, (ut8*)&ptr->type_g.content_type, &i))) {
goto sewer; // varint7
}
if (!(consume_u8 (buf + i, buf + len, (ut8*)&ptr->type_g.mutability, &i))) {
goto sewer; // varuint1
}
break;
default:
goto sewer;
}
r_list_append (ret, ptr);
r++;
}
return ret;
sewer:
ret = NULL;
culvert:
free (ptr);
return ret;
}
static RList *r_bin_wasm_get_export_entries (RBinWasmObj *bin, RBinWasmSection *sec) {
RList *ret = NULL;
RBinWasmExportEntry *ptr = NULL;
if (!(ret = r_list_newf ((RListFree)free))) {
return NULL;
}
ut8* buf = bin->buf->buf + (ut32)sec->payload_data;
ut32 len = sec->payload_len;
ut32 count = sec->count;
ut32 i = 0, r = 0;
while (i < len && r < count) {
if (!(ptr = R_NEW0 (RBinWasmExportEntry))) {
return ret;
}
if (!(consume_u32 (buf + i, buf + len, &ptr->field_len, &i))) {
free (ptr);
return ret;
}
if (!(consume_str (buf + i, buf + len, ptr->field_len, ptr->field_str, &i))) {
free (ptr);
return ret;
}
if (!(consume_u8 (buf + i, buf + len, &ptr->kind, &i))) {
free (ptr);
return ret;
}
if (!(consume_u32 (buf + i, buf + len, &ptr->index, &i))) {
free (ptr);
return ret;
}
r_list_append (ret, ptr);
r++;
}
return ret;
}
static RList *r_bin_wasm_get_code_entries (RBinWasmObj *bin, RBinWasmSection *sec) {
RList *ret = NULL;
RBinWasmCodeEntry *ptr = NULL;
if (!(ret = r_list_newf ((RListFree)free))) {
return NULL;
}
ut8* buf = bin->buf->buf + (ut32)sec->payload_data;
ut32 len = sec->payload_len;
ut32 count = sec->count;
ut32 i = 0, j = 0, r = 0;
size_t n = 0;
while (i < len && r < count) {
if (!(ptr = R_NEW0 (RBinWasmCodeEntry))) {
return ret;
}
if (!(n = consume_u32 (buf + i, buf + len, &ptr->body_size, &i))) {
free (ptr);
return ret;
}
if (!(i + ptr->body_size - 1 < len)) {
free (ptr);
return ret;
}
j = i;
if (!(n = consume_u32 (buf + i, buf + len, &ptr->local_count, &i))) {
free (ptr);
return ret;
}
if ((n = consume_locals (buf + i, buf + len, ptr->local_count,ptr, &i)) < ptr->local_count) {
free (ptr);
return ret;
}
ptr->code = sec->payload_data + i;
ptr->len = ptr->body_size - (i - j);
i += ptr->len - 1; // consume bytecode
if (!(consume_u8 (buf + i, buf + len, &ptr->byte, &i))) {
free (ptr);
return ret;
}
if (ptr->byte != R_BIN_WASM_END_OF_CODE) {
free (ptr);
return ret;
}
// search 'r' in function_space, if present get signature from types
// if export get name
r_list_append (ret, ptr);
r += 1;
}
return ret;
}
static RList *r_bin_wasm_get_data_entries (RBinWasmObj *bin, RBinWasmSection *sec) {
RList *ret = NULL;
RBinWasmDataEntry *ptr = NULL;
ut32 len = sec->payload_len;
if (!(ret = r_list_newf ((RListFree)free))) {
return NULL;
}
ut8* buf = bin->buf->buf + (ut32)sec->payload_data;
int buflen = bin->buf->length - (ut32)sec->payload_data;
ut32 count = sec->count;
ut32 i = 0, r = 0;
size_t n = 0;
while (i < len && len < buflen && r < count) {
if (!(ptr = R_NEW0 (RBinWasmDataEntry))) {
return ret;
}
if (!(consume_u32 (buf + i, buf + len, &ptr->index, &i))) {
goto beach;
}
if (i + 4 >= buflen) {
goto beach;
}
if (!(n = consume_init_expr (buf + i, buf + len, R_BIN_WASM_END_OF_CODE, NULL, &i))) {
goto beach;
}
ptr->offset.len = n;
if (!(consume_u32 (buf + i, buf + len, &ptr->size, &i))) {
goto beach;
}
if (i + 4 >= buflen) {
goto beach;
}
ptr->data = sec->payload_data + i;
r_list_append (ret, ptr);
r += 1;
}
return ret;
beach:
free (ptr);
return ret;
}
static RBinWasmStartEntry *r_bin_wasm_get_start (RBinWasmObj *bin, RBinWasmSection *sec) {
RBinWasmStartEntry *ptr;
if (!(ptr = R_NEW0 (RBinWasmStartEntry))) {
return NULL;
}
ut8* buf = bin->buf->buf + (ut32)sec->payload_data;
ut32 len = sec->payload_len;
ut32 i = 0;
if (!(consume_u32 (buf + i, buf + len, &ptr->index, &i))) {
free (ptr);
return NULL;
}
return ptr;
}
static RList *r_bin_wasm_get_memory_entries (RBinWasmObj *bin, RBinWasmSection *sec) {
RList *ret = NULL;
RBinWasmMemoryEntry *ptr = NULL;
if (!(ret = r_list_newf ((RListFree)free))) {
return NULL;
}
ut8* buf = bin->buf->buf + (ut32)sec->payload_data;
ut32 len = sec->payload_len;
ut32 count = sec->count;
ut32 i = 0, r = 0;
while (i < len && r < count) {
if (!(ptr = R_NEW0 (RBinWasmMemoryEntry))) {
return ret;
}
if (!(consume_limits (buf + i, buf + len, &ptr->limits, &i))) {
free (ptr);
return ret;
}
r_list_append (ret, ptr);
r += 1;
}
return ret;
}
static RList *r_bin_wasm_get_table_entries (RBinWasmObj *bin, RBinWasmSection *sec) {
RList *ret = NULL;
RBinWasmTableEntry *ptr = NULL;
if (!(ret = r_list_newf ((RListFree)free))) {
return NULL;
}
ut8* buf = bin->buf->buf + (ut32)sec->payload_data;
ut32 len = sec->payload_len;
ut32 count = sec->count;
ut32 i = 0, r = 0;
while (i < len && r < count) {
if (!(ptr = R_NEW0 (RBinWasmTableEntry))) {
return ret;
}
if (!(consume_u8 (buf + i, buf + len, &ptr->element_type, &i))) {
free (ptr);
return ret;
}
if (!(consume_limits (buf + i, buf + len, &ptr->limits, &i))) {
free (ptr);
return ret;
}
r_list_append (ret, ptr);
r += 1;
}
return ret;
}
static RList *r_bin_wasm_get_global_entries (RBinWasmObj *bin, RBinWasmSection *sec) {
RList *ret = NULL;
RBinWasmGlobalEntry *ptr = NULL;
if (!(ret = r_list_newf ((RListFree)free))) {
return NULL;
}
ut8* buf = bin->buf->buf + (ut32)sec->payload_data;
int buflen = bin->buf->length - (ut32)sec->payload_data;
ut32 len = sec->payload_len;
ut32 count = sec->count;
ut32 i = 0, r = 0;
while (i < len && len < buflen && r < count) {
if (!(ptr = R_NEW0 (RBinWasmGlobalEntry))) {
return ret;
}
if (len + 8 > buflen || !(consume_u8 (buf + i, buf + len, (ut8*)&ptr->content_type, &i))) {
goto beach;
}
if (len + 8 > buflen || !(consume_u8 (buf + i, buf + len, &ptr->mutability, &i))) {
goto beach;
}
if (len + 8 > buflen || !(consume_init_expr (buf + i, buf + len, R_BIN_WASM_END_OF_CODE, NULL, &i))) {
goto beach;
}
r_list_append (ret, ptr);
r++;
}
return ret;
beach:
free (ptr);
return ret;
}
static RList *r_bin_wasm_get_element_entries (RBinWasmObj *bin, RBinWasmSection *sec) {
RList *ret = NULL;
RBinWasmElementEntry *ptr = NULL;
if (!(ret = r_list_newf ((RListFree)free))) {
return NULL;
}
ut8* buf = bin->buf->buf + (ut32)sec->payload_data;
int buflen = bin->buf->length - (ut32)sec->payload_data;
ut32 len = sec->payload_len;
ut32 count = sec->count;
ut32 i = 0, r = 0;
while (i < len && len < buflen && r < count) {
if (!(ptr = R_NEW0 (RBinWasmElementEntry))) {
return ret;
}
if (!(consume_u32 (buf + i, buf + len, &ptr->index, &i))) {
goto beach;
}
if (!(consume_init_expr (buf + i, buf + len, R_BIN_WASM_END_OF_CODE, NULL, &i))) {
goto beach;
}
if (!(consume_u32 (buf + i, buf + len, &ptr->num_elem, &i))) {
goto beach;
}
ut32 j = 0;
while (i < len && j < ptr->num_elem) {
// TODO: allocate space and fill entry
ut32 e;
if (!(consume_u32 (buf + i, buf + len, &e, &i))) {
free (ptr);
return ret;
}
}
r_list_append (ret, ptr);
r += 1;
}
return ret;
beach:
free (ptr);
return ret;
}
// Public functions
RBinWasmObj *r_bin_wasm_init (RBinFile *arch) {
RBinWasmObj *bin = R_NEW0 (RBinWasmObj);
if (!bin) {
return NULL;
}
if (!(bin->buf = r_buf_new ())) {
free (bin);
return NULL;
}
bin->size = (ut32)arch->buf->length;
if (!r_buf_set_bytes (bin->buf, arch->buf->buf, bin->size)) {
r_bin_wasm_destroy (arch);
free (bin);
return NULL;
}
bin->g_sections = r_bin_wasm_get_sections (bin);
// TODO: recursive invocation more natural with streamed parsing
// but dependency problems when sections are disordered (against spec)
bin->g_types = r_bin_wasm_get_types (bin);
bin->g_imports = r_bin_wasm_get_imports (bin);
bin->g_exports = r_bin_wasm_get_exports (bin);
bin->g_tables = r_bin_wasm_get_tables (bin);
bin->g_memories = r_bin_wasm_get_memories (bin);
bin->g_globals = r_bin_wasm_get_globals (bin);
bin->g_codes = r_bin_wasm_get_codes (bin);
bin->g_datas = r_bin_wasm_get_datas (bin);
// entrypoint from Start section
bin->entrypoint = r_bin_wasm_get_entrypoint (bin);
return bin;
}
void r_bin_wasm_destroy (RBinFile *arch) {
RBinWasmObj *bin;
if (!arch || !arch->o || !arch->o->bin_obj) {
return;
}
bin = arch->o->bin_obj;
r_buf_free (bin->buf);
r_list_free (bin->g_sections);
r_list_free (bin->g_types);
r_list_free (bin->g_imports);
r_list_free (bin->g_exports);
r_list_free (bin->g_tables);
r_list_free (bin->g_memories);
r_list_free (bin->g_globals);
r_list_free (bin->g_codes);
r_list_free (bin->g_datas);
free (bin->g_start);
free (bin);
arch->o->bin_obj = NULL;
}
RList *r_bin_wasm_get_sections (RBinWasmObj *bin) {
RList *ret = NULL;
RBinWasmSection *ptr = NULL;
if (!bin) {
return NULL;
}
if (bin->g_sections) {
return bin->g_sections;
}
if (!(ret = r_list_newf ((RListFree)free))) {
return NULL;
}
ut8* buf = bin->buf->buf;
ut32 len = bin->size, i = 8; // skip magic bytes + version
while (i < len) {
//r_buf_read_* api but it makes sense going through the array directly
if (!(ptr = R_NEW0 (RBinWasmSection))) {
return ret;
}
if (!(consume_u8 (buf + i, buf + len, &ptr->id, &i))) {
return ret;
}
if (!(consume_u32 (buf + i, buf + len, &ptr->size, &i))) {
free(ptr);
return NULL;
}
ptr->count = 0;
ptr->offset = i;
switch (ptr->id) {
case R_BIN_WASM_SECTION_CUSTOM:
//eprintf("custom section: 0x%x, ", i);
if (!(consume_u32 (buf + i, buf + len, &ptr->name_len, &i))) {
free(ptr);
return ret;
}
if (!(consume_str (buf + i, buf + len, ptr->name_len,
ptr->name, &i))) {
free(ptr);
return ret;
}
//eprintf("%s\n", ptr->name);
break;
case R_BIN_WASM_SECTION_TYPE:
//eprintf("section type: 0x%x, ", i);
strcpy (ptr->name, "type");
ptr->name_len = 4;
break;
case R_BIN_WASM_SECTION_IMPORT:
//eprintf("section import: 0x%x, ", i);
strcpy (ptr->name, "import");
ptr->name_len = 6;
break;
case R_BIN_WASM_SECTION_FUNCTION:
//eprintf("section function: 0x%x, ", i);
strcpy (ptr->name, "function");
ptr->name_len = 8;
break;
case R_BIN_WASM_SECTION_TABLE:
//eprintf("section table: 0x%x, ", i);
strcpy (ptr->name, "table");
ptr->name_len = 5;
break;
case R_BIN_WASM_SECTION_MEMORY:
//eprintf("section memory: 0x%x, ", i);
strcpy (ptr->name, "memory");
ptr->name_len = 6;
break;
case R_BIN_WASM_SECTION_GLOBAL:
//eprintf("section global: 0x%x, ", i);
strcpy (ptr->name, "global");
ptr->name_len = 6;
break;
case R_BIN_WASM_SECTION_EXPORT:
//eprintf("section export: 0x%x, ", i);
strcpy (ptr->name, "export");
ptr->name_len = 6;
break;
case R_BIN_WASM_SECTION_START:
//eprintf("section start: 0x%x\n", i);
strcpy (ptr->name, "start");
ptr->name_len = 5;
break;
case R_BIN_WASM_SECTION_ELEMENT:
//eprintf("section element: 0x%x, ", i);
strncpy (ptr->name, "element", R_BIN_WASM_STRING_LENGTH);
ptr->name_len = 7;
break;
case R_BIN_WASM_SECTION_CODE:
//eprintf("section code: 0x%x, ", i);
strncpy (ptr->name, "code", R_BIN_WASM_STRING_LENGTH);
ptr->name_len = 4;
break;
case R_BIN_WASM_SECTION_DATA:
//eprintf("section data: 0x%x, ", i);
strncpy (ptr->name, "data", R_BIN_WASM_STRING_LENGTH);
ptr->name_len = 4;
break;
default:
eprintf("unkown section id: %d\n", ptr->id);
i += ptr->size - 1; // next
continue;
}
if (ptr->id != R_BIN_WASM_SECTION_START
&& ptr->id != R_BIN_WASM_SECTION_CUSTOM) {
if (!(consume_u32 (buf + i, buf + len, &ptr->count, &i))) {
free (ptr);
return ret;
}
//eprintf("count %d\n", ptr->count);
}
ptr->payload_data = i;
ptr->payload_len = ptr->size - (i - ptr->offset);
r_list_append (ret, ptr);
i += ptr->payload_len; // next
}
bin->g_sections = ret;
return ret;
}
ut32 r_bin_wasm_get_entrypoint (RBinWasmObj *bin) {
RList *secs = NULL;
RBinWasmStartEntry *start = NULL;
RBinWasmSection *sec = NULL;
RBinWasmCodeEntry *func = NULL;
if (!bin || !bin->g_sections) {
return 0;
}
if (bin->entrypoint) {
return bin->entrypoint;
}
if (bin->g_start) {
start = bin->g_start;
} else if (!(secs = r_bin_wasm_get_sections_by_id (bin->g_sections, R_BIN_WASM_SECTION_START))) {
return 0;
} else if (!(sec = (RBinWasmSection*) r_list_first (secs))) {
return 0;
} else {
start = r_bin_wasm_get_start (bin, sec);
bin->g_start = start;
}
if (!start) {
return 0;
}
// FIX: entrypoint can be also an import
func = r_list_get_n (r_bin_wasm_get_codes (bin), start->index);
return (ut32)func? func->code: 0;
}
RList *r_bin_wasm_get_imports (RBinWasmObj *bin) {
RBinWasmSection *import = NULL;
RList *imports = NULL;
if (!bin || !bin->g_sections) {
return NULL;
}
if (bin->g_imports) {
return bin->g_imports;
}
if (!(imports = r_bin_wasm_get_sections_by_id (bin->g_sections,
R_BIN_WASM_SECTION_IMPORT))) {
return r_list_new();
}
// support for multiple import sections against spec
if (!(import = (RBinWasmSection*) r_list_first (imports))) {
return r_list_new();
}
return bin->g_imports = r_bin_wasm_get_import_entries (bin, import);
}
RList *r_bin_wasm_get_exports (RBinWasmObj *bin) {
RBinWasmSection *export = NULL;
RList *exports = NULL;
if (!bin || !bin->g_sections) {
return NULL;
}
if (bin->g_exports) {
return bin->g_exports;
}
if (!(exports= r_bin_wasm_get_sections_by_id (bin->g_sections,
R_BIN_WASM_SECTION_EXPORT))) {
return r_list_new();
}
// support for multiple export sections against spec
if (!(export = (RBinWasmSection*) r_list_first (exports))) {
return r_list_new();
}
bin->g_exports = r_bin_wasm_get_export_entries (bin, export);
return bin->g_exports;
}
RList *r_bin_wasm_get_types (RBinWasmObj *bin) {
RBinWasmSection *type = NULL;
RList *types = NULL;
if (!bin || !bin->g_sections) {
return NULL;
}
if (bin->g_types) {
return bin->g_types;
}
if (!(types = r_bin_wasm_get_sections_by_id (bin->g_sections,
R_BIN_WASM_SECTION_TYPE))) {
return r_list_new();
}
// support for multiple export sections against spec
if (!(type = (RBinWasmSection*) r_list_first (types))) {
return r_list_new();
}
bin->g_types = r_bin_wasm_get_type_entries (bin, type);
return bin->g_types;
}
RList *r_bin_wasm_get_tables (RBinWasmObj *bin) {
RBinWasmSection *table = NULL;
RList *tables = NULL;
if (!bin || !bin->g_sections) {
return NULL;
}
if (bin->g_tables) {
return bin->g_tables;
}
if (!(tables = r_bin_wasm_get_sections_by_id (bin->g_sections,
R_BIN_WASM_SECTION_TABLE))) {
return r_list_new();
}
// support for multiple export sections against spec
if (!(table = (RBinWasmSection*) r_list_first (tables))) {
r_list_free (tables);
return r_list_new();
}
bin->g_tables = r_bin_wasm_get_table_entries (bin, table);
r_list_free (tables);
return bin->g_tables;
}
RList *r_bin_wasm_get_memories (RBinWasmObj *bin) {
RBinWasmSection *memory;
RList *memories;
if (!bin || !bin->g_sections) {
return NULL;
}
if (bin->g_memories) {
return bin->g_memories;
}
if (!(memories = r_bin_wasm_get_sections_by_id (bin->g_sections,
R_BIN_WASM_SECTION_MEMORY))) {
return r_list_new();
}
// support for multiple export sections against spec
if (!(memory = (RBinWasmSection*) r_list_first (memories))) {
return r_list_new();
}
bin->g_memories = r_bin_wasm_get_memory_entries (bin, memory);
return bin->g_memories;
}
RList *r_bin_wasm_get_globals (RBinWasmObj *bin) {
RBinWasmSection *global = NULL;
RList *globals = NULL;
if (!bin || !bin->g_sections) {
return NULL;
}
if (bin->g_globals) {
return bin->g_globals;
}
if (!(globals = r_bin_wasm_get_sections_by_id (bin->g_sections,
R_BIN_WASM_SECTION_GLOBAL))) {
return r_list_new();
}
// support for multiple export sections against spec
if (!(global = (RBinWasmSection*) r_list_first (globals))) {
return r_list_new();
}
bin->g_globals = r_bin_wasm_get_global_entries (bin, global);
return bin->g_globals;
}
RList *r_bin_wasm_get_elements (RBinWasmObj *bin) {
RBinWasmSection *element = NULL;
RList *elements = NULL;
if (!bin || !bin->g_sections) {
return NULL;
}
if (bin->g_elements) {
return bin->g_elements;
}
if (!(elements = r_bin_wasm_get_sections_by_id (bin->g_sections,
R_BIN_WASM_SECTION_ELEMENT))) {
return r_list_new();
}
// support for multiple export sections against spec
if (!(element = (RBinWasmSection*) r_list_first (elements))) {
return r_list_new();
}
bin->g_elements = r_bin_wasm_get_element_entries (bin, element);
return bin->g_elements;
}
RList *r_bin_wasm_get_codes (RBinWasmObj *bin) {
RBinWasmSection *code = NULL;;
RList *codes = NULL;
if (!bin || !bin->g_sections) {
return NULL;
}
if (bin->g_codes) {
return bin->g_codes;
}
if (!(codes = r_bin_wasm_get_sections_by_id (bin->g_sections,
R_BIN_WASM_SECTION_CODE))) {
return r_list_new();
}
// support for multiple export sections against spec
if (!(code = (RBinWasmSection*) r_list_first (codes))) {
return r_list_new();
}
bin->g_codes = r_bin_wasm_get_code_entries (bin, code);
return bin->g_codes;
}
RList *r_bin_wasm_get_datas (RBinWasmObj *bin) {
RBinWasmSection *data = NULL;
RList *datas = NULL;
if (!bin || !bin->g_sections) {
return NULL;
}
if (bin->g_datas) {
return bin->g_datas;
}
if (!(datas = r_bin_wasm_get_sections_by_id (bin->g_sections,
R_BIN_WASM_SECTION_DATA))) {
return r_list_new();
}
// support for multiple export sections against spec
if (!(data = (RBinWasmSection*) r_list_first (datas))) {
return r_list_new();
}
bin->g_datas = r_bin_wasm_get_data_entries (bin, data);
return bin->g_datas;
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/good_3293_0 |
crossvul-cpp_data_bad_699_0 | /*
* SSLv3/TLSv1 client-side functions
*
* Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
* SPDX-License-Identifier: Apache-2.0
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* This file is part of mbed TLS (https://tls.mbed.org)
*/
#if !defined(MBEDTLS_CONFIG_FILE)
#include "mbedtls/config.h"
#else
#include MBEDTLS_CONFIG_FILE
#endif
#if defined(MBEDTLS_SSL_CLI_C)
#if defined(MBEDTLS_PLATFORM_C)
#include "mbedtls/platform.h"
#else
#include <stdlib.h>
#define mbedtls_calloc calloc
#define mbedtls_free free
#endif
#include "mbedtls/debug.h"
#include "mbedtls/ssl.h"
#include "mbedtls/ssl_internal.h"
#include <string.h>
#include <stdint.h>
#if defined(MBEDTLS_HAVE_TIME)
#include "mbedtls/platform_time.h"
#endif
#if defined(MBEDTLS_SSL_SESSION_TICKETS)
/* Implementation that should never be optimized out by the compiler */
static void mbedtls_zeroize( void *v, size_t n ) {
volatile unsigned char *p = v; while( n-- ) *p++ = 0;
}
#endif
#if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION)
static void ssl_write_hostname_ext( mbedtls_ssl_context *ssl,
unsigned char *buf,
size_t *olen )
{
unsigned char *p = buf;
const unsigned char *end = ssl->out_msg + MBEDTLS_SSL_MAX_CONTENT_LEN;
size_t hostname_len;
*olen = 0;
if( ssl->hostname == NULL )
return;
MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, adding server name extension: %s",
ssl->hostname ) );
hostname_len = strlen( ssl->hostname );
if( end < p || (size_t)( end - p ) < hostname_len + 9 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "buffer too small" ) );
return;
}
/*
* Sect. 3, RFC 6066 (TLS Extensions Definitions)
*
* In order to provide any of the server names, clients MAY include an
* extension of type "server_name" in the (extended) client hello. The
* "extension_data" field of this extension SHALL contain
* "ServerNameList" where:
*
* struct {
* NameType name_type;
* select (name_type) {
* case host_name: HostName;
* } name;
* } ServerName;
*
* enum {
* host_name(0), (255)
* } NameType;
*
* opaque HostName<1..2^16-1>;
*
* struct {
* ServerName server_name_list<1..2^16-1>
* } ServerNameList;
*
*/
*p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_SERVERNAME >> 8 ) & 0xFF );
*p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_SERVERNAME ) & 0xFF );
*p++ = (unsigned char)( ( (hostname_len + 5) >> 8 ) & 0xFF );
*p++ = (unsigned char)( ( (hostname_len + 5) ) & 0xFF );
*p++ = (unsigned char)( ( (hostname_len + 3) >> 8 ) & 0xFF );
*p++ = (unsigned char)( ( (hostname_len + 3) ) & 0xFF );
*p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_SERVERNAME_HOSTNAME ) & 0xFF );
*p++ = (unsigned char)( ( hostname_len >> 8 ) & 0xFF );
*p++ = (unsigned char)( ( hostname_len ) & 0xFF );
memcpy( p, ssl->hostname, hostname_len );
*olen = hostname_len + 9;
}
#endif /* MBEDTLS_SSL_SERVER_NAME_INDICATION */
#if defined(MBEDTLS_SSL_RENEGOTIATION)
static void ssl_write_renegotiation_ext( mbedtls_ssl_context *ssl,
unsigned char *buf,
size_t *olen )
{
unsigned char *p = buf;
const unsigned char *end = ssl->out_msg + MBEDTLS_SSL_MAX_CONTENT_LEN;
*olen = 0;
/* We're always including an TLS_EMPTY_RENEGOTIATION_INFO_SCSV in the
* initial ClientHello, in which case also adding the renegotiation
* info extension is NOT RECOMMENDED as per RFC 5746 Section 3.4. */
if( ssl->renego_status != MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS )
return;
MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, adding renegotiation extension" ) );
if( end < p || (size_t)( end - p ) < 5 + ssl->verify_data_len )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "buffer too small" ) );
return;
}
/*
* Secure renegotiation
*/
*p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_RENEGOTIATION_INFO >> 8 ) & 0xFF );
*p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_RENEGOTIATION_INFO ) & 0xFF );
*p++ = 0x00;
*p++ = ( ssl->verify_data_len + 1 ) & 0xFF;
*p++ = ssl->verify_data_len & 0xFF;
memcpy( p, ssl->own_verify_data, ssl->verify_data_len );
*olen = 5 + ssl->verify_data_len;
}
#endif /* MBEDTLS_SSL_RENEGOTIATION */
/*
* Only if we handle at least one key exchange that needs signatures.
*/
#if defined(MBEDTLS_SSL_PROTO_TLS1_2) && \
defined(MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED)
static void ssl_write_signature_algorithms_ext( mbedtls_ssl_context *ssl,
unsigned char *buf,
size_t *olen )
{
unsigned char *p = buf;
const unsigned char *end = ssl->out_msg + MBEDTLS_SSL_MAX_CONTENT_LEN;
size_t sig_alg_len = 0;
const int *md;
#if defined(MBEDTLS_RSA_C) || defined(MBEDTLS_ECDSA_C)
unsigned char *sig_alg_list = buf + 6;
#endif
*olen = 0;
if( ssl->conf->max_minor_ver != MBEDTLS_SSL_MINOR_VERSION_3 )
return;
MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, adding signature_algorithms extension" ) );
for( md = ssl->conf->sig_hashes; *md != MBEDTLS_MD_NONE; md++ )
{
#if defined(MBEDTLS_ECDSA_C)
sig_alg_len += 2;
#endif
#if defined(MBEDTLS_RSA_C)
sig_alg_len += 2;
#endif
}
if( end < p || (size_t)( end - p ) < sig_alg_len + 6 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "buffer too small" ) );
return;
}
/*
* Prepare signature_algorithms extension (TLS 1.2)
*/
sig_alg_len = 0;
for( md = ssl->conf->sig_hashes; *md != MBEDTLS_MD_NONE; md++ )
{
#if defined(MBEDTLS_ECDSA_C)
sig_alg_list[sig_alg_len++] = mbedtls_ssl_hash_from_md_alg( *md );
sig_alg_list[sig_alg_len++] = MBEDTLS_SSL_SIG_ECDSA;
#endif
#if defined(MBEDTLS_RSA_C)
sig_alg_list[sig_alg_len++] = mbedtls_ssl_hash_from_md_alg( *md );
sig_alg_list[sig_alg_len++] = MBEDTLS_SSL_SIG_RSA;
#endif
}
/*
* enum {
* none(0), md5(1), sha1(2), sha224(3), sha256(4), sha384(5),
* sha512(6), (255)
* } HashAlgorithm;
*
* enum { anonymous(0), rsa(1), dsa(2), ecdsa(3), (255) }
* SignatureAlgorithm;
*
* struct {
* HashAlgorithm hash;
* SignatureAlgorithm signature;
* } SignatureAndHashAlgorithm;
*
* SignatureAndHashAlgorithm
* supported_signature_algorithms<2..2^16-2>;
*/
*p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_SIG_ALG >> 8 ) & 0xFF );
*p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_SIG_ALG ) & 0xFF );
*p++ = (unsigned char)( ( ( sig_alg_len + 2 ) >> 8 ) & 0xFF );
*p++ = (unsigned char)( ( ( sig_alg_len + 2 ) ) & 0xFF );
*p++ = (unsigned char)( ( sig_alg_len >> 8 ) & 0xFF );
*p++ = (unsigned char)( ( sig_alg_len ) & 0xFF );
*olen = 6 + sig_alg_len;
}
#endif /* MBEDTLS_SSL_PROTO_TLS1_2 &&
MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED */
#if defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_ECDSA_C) || \
defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
static void ssl_write_supported_elliptic_curves_ext( mbedtls_ssl_context *ssl,
unsigned char *buf,
size_t *olen )
{
unsigned char *p = buf;
const unsigned char *end = ssl->out_msg + MBEDTLS_SSL_MAX_CONTENT_LEN;
unsigned char *elliptic_curve_list = p + 6;
size_t elliptic_curve_len = 0;
const mbedtls_ecp_curve_info *info;
#if defined(MBEDTLS_ECP_C)
const mbedtls_ecp_group_id *grp_id;
#else
((void) ssl);
#endif
*olen = 0;
MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, adding supported_elliptic_curves extension" ) );
#if defined(MBEDTLS_ECP_C)
for( grp_id = ssl->conf->curve_list; *grp_id != MBEDTLS_ECP_DP_NONE; grp_id++ )
#else
for( info = mbedtls_ecp_curve_list(); info->grp_id != MBEDTLS_ECP_DP_NONE; info++ )
#endif
{
#if defined(MBEDTLS_ECP_C)
info = mbedtls_ecp_curve_info_from_grp_id( *grp_id );
#endif
if( info == NULL )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "invalid curve in ssl configuration" ) );
return;
}
elliptic_curve_len += 2;
}
if( end < p || (size_t)( end - p ) < 6 + elliptic_curve_len )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "buffer too small" ) );
return;
}
elliptic_curve_len = 0;
#if defined(MBEDTLS_ECP_C)
for( grp_id = ssl->conf->curve_list; *grp_id != MBEDTLS_ECP_DP_NONE; grp_id++ )
#else
for( info = mbedtls_ecp_curve_list(); info->grp_id != MBEDTLS_ECP_DP_NONE; info++ )
#endif
{
#if defined(MBEDTLS_ECP_C)
info = mbedtls_ecp_curve_info_from_grp_id( *grp_id );
#endif
elliptic_curve_list[elliptic_curve_len++] = info->tls_id >> 8;
elliptic_curve_list[elliptic_curve_len++] = info->tls_id & 0xFF;
}
if( elliptic_curve_len == 0 )
return;
*p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_SUPPORTED_ELLIPTIC_CURVES >> 8 ) & 0xFF );
*p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_SUPPORTED_ELLIPTIC_CURVES ) & 0xFF );
*p++ = (unsigned char)( ( ( elliptic_curve_len + 2 ) >> 8 ) & 0xFF );
*p++ = (unsigned char)( ( ( elliptic_curve_len + 2 ) ) & 0xFF );
*p++ = (unsigned char)( ( ( elliptic_curve_len ) >> 8 ) & 0xFF );
*p++ = (unsigned char)( ( ( elliptic_curve_len ) ) & 0xFF );
*olen = 6 + elliptic_curve_len;
}
static void ssl_write_supported_point_formats_ext( mbedtls_ssl_context *ssl,
unsigned char *buf,
size_t *olen )
{
unsigned char *p = buf;
const unsigned char *end = ssl->out_msg + MBEDTLS_SSL_MAX_CONTENT_LEN;
*olen = 0;
MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, adding supported_point_formats extension" ) );
if( end < p || (size_t)( end - p ) < 6 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "buffer too small" ) );
return;
}
*p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_SUPPORTED_POINT_FORMATS >> 8 ) & 0xFF );
*p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_SUPPORTED_POINT_FORMATS ) & 0xFF );
*p++ = 0x00;
*p++ = 2;
*p++ = 1;
*p++ = MBEDTLS_ECP_PF_UNCOMPRESSED;
*olen = 6;
}
#endif /* MBEDTLS_ECDH_C || MBEDTLS_ECDSA_C ||
MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
#if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
static void ssl_write_ecjpake_kkpp_ext( mbedtls_ssl_context *ssl,
unsigned char *buf,
size_t *olen )
{
int ret;
unsigned char *p = buf;
const unsigned char *end = ssl->out_msg + MBEDTLS_SSL_MAX_CONTENT_LEN;
size_t kkpp_len;
*olen = 0;
/* Skip costly extension if we can't use EC J-PAKE anyway */
if( mbedtls_ecjpake_check( &ssl->handshake->ecjpake_ctx ) != 0 )
return;
MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, adding ecjpake_kkpp extension" ) );
if( end - p < 4 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "buffer too small" ) );
return;
}
*p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_ECJPAKE_KKPP >> 8 ) & 0xFF );
*p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_ECJPAKE_KKPP ) & 0xFF );
/*
* We may need to send ClientHello multiple times for Hello verification.
* We don't want to compute fresh values every time (both for performance
* and consistency reasons), so cache the extension content.
*/
if( ssl->handshake->ecjpake_cache == NULL ||
ssl->handshake->ecjpake_cache_len == 0 )
{
MBEDTLS_SSL_DEBUG_MSG( 3, ( "generating new ecjpake parameters" ) );
ret = mbedtls_ecjpake_write_round_one( &ssl->handshake->ecjpake_ctx,
p + 2, end - p - 2, &kkpp_len,
ssl->conf->f_rng, ssl->conf->p_rng );
if( ret != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1 , "mbedtls_ecjpake_write_round_one", ret );
return;
}
ssl->handshake->ecjpake_cache = mbedtls_calloc( 1, kkpp_len );
if( ssl->handshake->ecjpake_cache == NULL )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "allocation failed" ) );
return;
}
memcpy( ssl->handshake->ecjpake_cache, p + 2, kkpp_len );
ssl->handshake->ecjpake_cache_len = kkpp_len;
}
else
{
MBEDTLS_SSL_DEBUG_MSG( 3, ( "re-using cached ecjpake parameters" ) );
kkpp_len = ssl->handshake->ecjpake_cache_len;
if( (size_t)( end - p - 2 ) < kkpp_len )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "buffer too small" ) );
return;
}
memcpy( p + 2, ssl->handshake->ecjpake_cache, kkpp_len );
}
*p++ = (unsigned char)( ( kkpp_len >> 8 ) & 0xFF );
*p++ = (unsigned char)( ( kkpp_len ) & 0xFF );
*olen = kkpp_len + 4;
}
#endif /* MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
#if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)
static void ssl_write_max_fragment_length_ext( mbedtls_ssl_context *ssl,
unsigned char *buf,
size_t *olen )
{
unsigned char *p = buf;
const unsigned char *end = ssl->out_msg + MBEDTLS_SSL_MAX_CONTENT_LEN;
*olen = 0;
if( ssl->conf->mfl_code == MBEDTLS_SSL_MAX_FRAG_LEN_NONE ) {
return;
}
MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, adding max_fragment_length extension" ) );
if( end < p || (size_t)( end - p ) < 5 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "buffer too small" ) );
return;
}
*p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_MAX_FRAGMENT_LENGTH >> 8 ) & 0xFF );
*p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_MAX_FRAGMENT_LENGTH ) & 0xFF );
*p++ = 0x00;
*p++ = 1;
*p++ = ssl->conf->mfl_code;
*olen = 5;
}
#endif /* MBEDTLS_SSL_MAX_FRAGMENT_LENGTH */
#if defined(MBEDTLS_SSL_TRUNCATED_HMAC)
static void ssl_write_truncated_hmac_ext( mbedtls_ssl_context *ssl,
unsigned char *buf, size_t *olen )
{
unsigned char *p = buf;
const unsigned char *end = ssl->out_msg + MBEDTLS_SSL_MAX_CONTENT_LEN;
*olen = 0;
if( ssl->conf->trunc_hmac == MBEDTLS_SSL_TRUNC_HMAC_DISABLED )
{
return;
}
MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, adding truncated_hmac extension" ) );
if( end < p || (size_t)( end - p ) < 4 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "buffer too small" ) );
return;
}
*p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_TRUNCATED_HMAC >> 8 ) & 0xFF );
*p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_TRUNCATED_HMAC ) & 0xFF );
*p++ = 0x00;
*p++ = 0x00;
*olen = 4;
}
#endif /* MBEDTLS_SSL_TRUNCATED_HMAC */
#if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
static void ssl_write_encrypt_then_mac_ext( mbedtls_ssl_context *ssl,
unsigned char *buf, size_t *olen )
{
unsigned char *p = buf;
const unsigned char *end = ssl->out_msg + MBEDTLS_SSL_MAX_CONTENT_LEN;
*olen = 0;
if( ssl->conf->encrypt_then_mac == MBEDTLS_SSL_ETM_DISABLED ||
ssl->conf->max_minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 )
{
return;
}
MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, adding encrypt_then_mac "
"extension" ) );
if( end < p || (size_t)( end - p ) < 4 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "buffer too small" ) );
return;
}
*p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_ENCRYPT_THEN_MAC >> 8 ) & 0xFF );
*p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_ENCRYPT_THEN_MAC ) & 0xFF );
*p++ = 0x00;
*p++ = 0x00;
*olen = 4;
}
#endif /* MBEDTLS_SSL_ENCRYPT_THEN_MAC */
#if defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET)
static void ssl_write_extended_ms_ext( mbedtls_ssl_context *ssl,
unsigned char *buf, size_t *olen )
{
unsigned char *p = buf;
const unsigned char *end = ssl->out_msg + MBEDTLS_SSL_MAX_CONTENT_LEN;
*olen = 0;
if( ssl->conf->extended_ms == MBEDTLS_SSL_EXTENDED_MS_DISABLED ||
ssl->conf->max_minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 )
{
return;
}
MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, adding extended_master_secret "
"extension" ) );
if( end < p || (size_t)( end - p ) < 4 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "buffer too small" ) );
return;
}
*p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_EXTENDED_MASTER_SECRET >> 8 ) & 0xFF );
*p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_EXTENDED_MASTER_SECRET ) & 0xFF );
*p++ = 0x00;
*p++ = 0x00;
*olen = 4;
}
#endif /* MBEDTLS_SSL_EXTENDED_MASTER_SECRET */
#if defined(MBEDTLS_SSL_SESSION_TICKETS)
static void ssl_write_session_ticket_ext( mbedtls_ssl_context *ssl,
unsigned char *buf, size_t *olen )
{
unsigned char *p = buf;
const unsigned char *end = ssl->out_msg + MBEDTLS_SSL_MAX_CONTENT_LEN;
size_t tlen = ssl->session_negotiate->ticket_len;
*olen = 0;
if( ssl->conf->session_tickets == MBEDTLS_SSL_SESSION_TICKETS_DISABLED )
{
return;
}
MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, adding session ticket extension" ) );
if( end < p || (size_t)( end - p ) < 4 + tlen )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "buffer too small" ) );
return;
}
*p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_SESSION_TICKET >> 8 ) & 0xFF );
*p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_SESSION_TICKET ) & 0xFF );
*p++ = (unsigned char)( ( tlen >> 8 ) & 0xFF );
*p++ = (unsigned char)( ( tlen ) & 0xFF );
*olen = 4;
if( ssl->session_negotiate->ticket == NULL || tlen == 0 )
{
return;
}
MBEDTLS_SSL_DEBUG_MSG( 3, ( "sending session ticket of length %d", tlen ) );
memcpy( p, ssl->session_negotiate->ticket, tlen );
*olen += tlen;
}
#endif /* MBEDTLS_SSL_SESSION_TICKETS */
#if defined(MBEDTLS_SSL_ALPN)
static void ssl_write_alpn_ext( mbedtls_ssl_context *ssl,
unsigned char *buf, size_t *olen )
{
unsigned char *p = buf;
const unsigned char *end = ssl->out_msg + MBEDTLS_SSL_MAX_CONTENT_LEN;
size_t alpnlen = 0;
const char **cur;
*olen = 0;
if( ssl->conf->alpn_list == NULL )
{
return;
}
MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, adding alpn extension" ) );
for( cur = ssl->conf->alpn_list; *cur != NULL; cur++ )
alpnlen += (unsigned char)( strlen( *cur ) & 0xFF ) + 1;
if( end < p || (size_t)( end - p ) < 6 + alpnlen )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "buffer too small" ) );
return;
}
*p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_ALPN >> 8 ) & 0xFF );
*p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_ALPN ) & 0xFF );
/*
* opaque ProtocolName<1..2^8-1>;
*
* struct {
* ProtocolName protocol_name_list<2..2^16-1>
* } ProtocolNameList;
*/
/* Skip writing extension and list length for now */
p += 4;
for( cur = ssl->conf->alpn_list; *cur != NULL; cur++ )
{
*p = (unsigned char)( strlen( *cur ) & 0xFF );
memcpy( p + 1, *cur, *p );
p += 1 + *p;
}
*olen = p - buf;
/* List length = olen - 2 (ext_type) - 2 (ext_len) - 2 (list_len) */
buf[4] = (unsigned char)( ( ( *olen - 6 ) >> 8 ) & 0xFF );
buf[5] = (unsigned char)( ( ( *olen - 6 ) ) & 0xFF );
/* Extension length = olen - 2 (ext_type) - 2 (ext_len) */
buf[2] = (unsigned char)( ( ( *olen - 4 ) >> 8 ) & 0xFF );
buf[3] = (unsigned char)( ( ( *olen - 4 ) ) & 0xFF );
}
#endif /* MBEDTLS_SSL_ALPN */
/*
* Generate random bytes for ClientHello
*/
static int ssl_generate_random( mbedtls_ssl_context *ssl )
{
int ret;
unsigned char *p = ssl->handshake->randbytes;
#if defined(MBEDTLS_HAVE_TIME)
mbedtls_time_t t;
#endif
/*
* When responding to a verify request, MUST reuse random (RFC 6347 4.2.1)
*/
#if defined(MBEDTLS_SSL_PROTO_DTLS)
if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
ssl->handshake->verify_cookie != NULL )
{
return( 0 );
}
#endif
#if defined(MBEDTLS_HAVE_TIME)
t = mbedtls_time( NULL );
*p++ = (unsigned char)( t >> 24 );
*p++ = (unsigned char)( t >> 16 );
*p++ = (unsigned char)( t >> 8 );
*p++ = (unsigned char)( t );
MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, current time: %lu", t ) );
#else
if( ( ret = ssl->conf->f_rng( ssl->conf->p_rng, p, 4 ) ) != 0 )
return( ret );
p += 4;
#endif /* MBEDTLS_HAVE_TIME */
if( ( ret = ssl->conf->f_rng( ssl->conf->p_rng, p, 28 ) ) != 0 )
return( ret );
return( 0 );
}
static int ssl_write_client_hello( mbedtls_ssl_context *ssl )
{
int ret;
size_t i, n, olen, ext_len = 0;
unsigned char *buf;
unsigned char *p, *q;
unsigned char offer_compress;
const int *ciphersuites;
const mbedtls_ssl_ciphersuite_t *ciphersuite_info;
MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write client hello" ) );
if( ssl->conf->f_rng == NULL )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "no RNG provided") );
return( MBEDTLS_ERR_SSL_NO_RNG );
}
#if defined(MBEDTLS_SSL_RENEGOTIATION)
if( ssl->renego_status == MBEDTLS_SSL_INITIAL_HANDSHAKE )
#endif
{
ssl->major_ver = ssl->conf->min_major_ver;
ssl->minor_ver = ssl->conf->min_minor_ver;
}
if( ssl->conf->max_major_ver == 0 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "configured max major version is invalid, "
"consider using mbedtls_ssl_config_defaults()" ) );
return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
}
/*
* 0 . 0 handshake type
* 1 . 3 handshake length
* 4 . 5 highest version supported
* 6 . 9 current UNIX time
* 10 . 37 random bytes
*/
buf = ssl->out_msg;
p = buf + 4;
mbedtls_ssl_write_version( ssl->conf->max_major_ver, ssl->conf->max_minor_ver,
ssl->conf->transport, p );
p += 2;
MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, max version: [%d:%d]",
buf[4], buf[5] ) );
if( ( ret = ssl_generate_random( ssl ) ) != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, "ssl_generate_random", ret );
return( ret );
}
memcpy( p, ssl->handshake->randbytes, 32 );
MBEDTLS_SSL_DEBUG_BUF( 3, "client hello, random bytes", p, 32 );
p += 32;
/*
* 38 . 38 session id length
* 39 . 39+n session id
* 39+n . 39+n DTLS only: cookie length (1 byte)
* 40+n . .. DTSL only: cookie
* .. . .. ciphersuitelist length (2 bytes)
* .. . .. ciphersuitelist
* .. . .. compression methods length (1 byte)
* .. . .. compression methods
* .. . .. extensions length (2 bytes)
* .. . .. extensions
*/
n = ssl->session_negotiate->id_len;
if( n < 16 || n > 32 ||
#if defined(MBEDTLS_SSL_RENEGOTIATION)
ssl->renego_status != MBEDTLS_SSL_INITIAL_HANDSHAKE ||
#endif
ssl->handshake->resume == 0 )
{
n = 0;
}
#if defined(MBEDTLS_SSL_SESSION_TICKETS)
/*
* RFC 5077 section 3.4: "When presenting a ticket, the client MAY
* generate and include a Session ID in the TLS ClientHello."
*/
#if defined(MBEDTLS_SSL_RENEGOTIATION)
if( ssl->renego_status == MBEDTLS_SSL_INITIAL_HANDSHAKE )
#endif
{
if( ssl->session_negotiate->ticket != NULL &&
ssl->session_negotiate->ticket_len != 0 )
{
ret = ssl->conf->f_rng( ssl->conf->p_rng, ssl->session_negotiate->id, 32 );
if( ret != 0 )
return( ret );
ssl->session_negotiate->id_len = n = 32;
}
}
#endif /* MBEDTLS_SSL_SESSION_TICKETS */
*p++ = (unsigned char) n;
for( i = 0; i < n; i++ )
*p++ = ssl->session_negotiate->id[i];
MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, session id len.: %d", n ) );
MBEDTLS_SSL_DEBUG_BUF( 3, "client hello, session id", buf + 39, n );
/*
* DTLS cookie
*/
#if defined(MBEDTLS_SSL_PROTO_DTLS)
if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
{
if( ssl->handshake->verify_cookie == NULL )
{
MBEDTLS_SSL_DEBUG_MSG( 3, ( "no verify cookie to send" ) );
*p++ = 0;
}
else
{
MBEDTLS_SSL_DEBUG_BUF( 3, "client hello, cookie",
ssl->handshake->verify_cookie,
ssl->handshake->verify_cookie_len );
*p++ = ssl->handshake->verify_cookie_len;
memcpy( p, ssl->handshake->verify_cookie,
ssl->handshake->verify_cookie_len );
p += ssl->handshake->verify_cookie_len;
}
}
#endif
/*
* Ciphersuite list
*/
ciphersuites = ssl->conf->ciphersuite_list[ssl->minor_ver];
/* Skip writing ciphersuite length for now */
n = 0;
q = p;
p += 2;
for( i = 0; ciphersuites[i] != 0; i++ )
{
ciphersuite_info = mbedtls_ssl_ciphersuite_from_id( ciphersuites[i] );
if( ciphersuite_info == NULL )
continue;
if( ciphersuite_info->min_minor_ver > ssl->conf->max_minor_ver ||
ciphersuite_info->max_minor_ver < ssl->conf->min_minor_ver )
continue;
#if defined(MBEDTLS_SSL_PROTO_DTLS)
if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
( ciphersuite_info->flags & MBEDTLS_CIPHERSUITE_NODTLS ) )
continue;
#endif
#if defined(MBEDTLS_ARC4_C)
if( ssl->conf->arc4_disabled == MBEDTLS_SSL_ARC4_DISABLED &&
ciphersuite_info->cipher == MBEDTLS_CIPHER_ARC4_128 )
continue;
#endif
#if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECJPAKE &&
mbedtls_ecjpake_check( &ssl->handshake->ecjpake_ctx ) != 0 )
continue;
#endif
MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, add ciphersuite: %04x",
ciphersuites[i] ) );
n++;
*p++ = (unsigned char)( ciphersuites[i] >> 8 );
*p++ = (unsigned char)( ciphersuites[i] );
}
/*
* Add TLS_EMPTY_RENEGOTIATION_INFO_SCSV
*/
#if defined(MBEDTLS_SSL_RENEGOTIATION)
if( ssl->renego_status == MBEDTLS_SSL_INITIAL_HANDSHAKE )
#endif
{
*p++ = (unsigned char)( MBEDTLS_SSL_EMPTY_RENEGOTIATION_INFO >> 8 );
*p++ = (unsigned char)( MBEDTLS_SSL_EMPTY_RENEGOTIATION_INFO );
n++;
}
/* Some versions of OpenSSL don't handle it correctly if not at end */
#if defined(MBEDTLS_SSL_FALLBACK_SCSV)
if( ssl->conf->fallback == MBEDTLS_SSL_IS_FALLBACK )
{
MBEDTLS_SSL_DEBUG_MSG( 3, ( "adding FALLBACK_SCSV" ) );
*p++ = (unsigned char)( MBEDTLS_SSL_FALLBACK_SCSV_VALUE >> 8 );
*p++ = (unsigned char)( MBEDTLS_SSL_FALLBACK_SCSV_VALUE );
n++;
}
#endif
*q++ = (unsigned char)( n >> 7 );
*q++ = (unsigned char)( n << 1 );
MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, got %d ciphersuites", n ) );
#if defined(MBEDTLS_ZLIB_SUPPORT)
offer_compress = 1;
#else
offer_compress = 0;
#endif
/*
* We don't support compression with DTLS right now: is many records come
* in the same datagram, uncompressing one could overwrite the next one.
* We don't want to add complexity for handling that case unless there is
* an actual need for it.
*/
#if defined(MBEDTLS_SSL_PROTO_DTLS)
if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
offer_compress = 0;
#endif
if( offer_compress )
{
MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, compress len.: %d", 2 ) );
MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, compress alg.: %d %d",
MBEDTLS_SSL_COMPRESS_DEFLATE, MBEDTLS_SSL_COMPRESS_NULL ) );
*p++ = 2;
*p++ = MBEDTLS_SSL_COMPRESS_DEFLATE;
*p++ = MBEDTLS_SSL_COMPRESS_NULL;
}
else
{
MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, compress len.: %d", 1 ) );
MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, compress alg.: %d",
MBEDTLS_SSL_COMPRESS_NULL ) );
*p++ = 1;
*p++ = MBEDTLS_SSL_COMPRESS_NULL;
}
// First write extensions, then the total length
//
#if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION)
ssl_write_hostname_ext( ssl, p + 2 + ext_len, &olen );
ext_len += olen;
#endif
/* Note that TLS_EMPTY_RENEGOTIATION_INFO_SCSV is always added
* even if MBEDTLS_SSL_RENEGOTIATION is not defined. */
#if defined(MBEDTLS_SSL_RENEGOTIATION)
ssl_write_renegotiation_ext( ssl, p + 2 + ext_len, &olen );
ext_len += olen;
#endif
#if defined(MBEDTLS_SSL_PROTO_TLS1_2) && \
defined(MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED)
ssl_write_signature_algorithms_ext( ssl, p + 2 + ext_len, &olen );
ext_len += olen;
#endif
#if defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_ECDSA_C) || \
defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
ssl_write_supported_elliptic_curves_ext( ssl, p + 2 + ext_len, &olen );
ext_len += olen;
ssl_write_supported_point_formats_ext( ssl, p + 2 + ext_len, &olen );
ext_len += olen;
#endif
#if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
ssl_write_ecjpake_kkpp_ext( ssl, p + 2 + ext_len, &olen );
ext_len += olen;
#endif
#if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)
ssl_write_max_fragment_length_ext( ssl, p + 2 + ext_len, &olen );
ext_len += olen;
#endif
#if defined(MBEDTLS_SSL_TRUNCATED_HMAC)
ssl_write_truncated_hmac_ext( ssl, p + 2 + ext_len, &olen );
ext_len += olen;
#endif
#if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
ssl_write_encrypt_then_mac_ext( ssl, p + 2 + ext_len, &olen );
ext_len += olen;
#endif
#if defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET)
ssl_write_extended_ms_ext( ssl, p + 2 + ext_len, &olen );
ext_len += olen;
#endif
#if defined(MBEDTLS_SSL_ALPN)
ssl_write_alpn_ext( ssl, p + 2 + ext_len, &olen );
ext_len += olen;
#endif
#if defined(MBEDTLS_SSL_SESSION_TICKETS)
ssl_write_session_ticket_ext( ssl, p + 2 + ext_len, &olen );
ext_len += olen;
#endif
/* olen unused if all extensions are disabled */
((void) olen);
MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, total extension length: %d",
ext_len ) );
if( ext_len > 0 )
{
*p++ = (unsigned char)( ( ext_len >> 8 ) & 0xFF );
*p++ = (unsigned char)( ( ext_len ) & 0xFF );
p += ext_len;
}
ssl->out_msglen = p - buf;
ssl->out_msgtype = MBEDTLS_SSL_MSG_HANDSHAKE;
ssl->out_msg[0] = MBEDTLS_SSL_HS_CLIENT_HELLO;
ssl->state++;
#if defined(MBEDTLS_SSL_PROTO_DTLS)
if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
mbedtls_ssl_send_flight_completed( ssl );
#endif
if( ( ret = mbedtls_ssl_write_record( ssl ) ) != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_write_record", ret );
return( ret );
}
MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write client hello" ) );
return( 0 );
}
static int ssl_parse_renegotiation_info( mbedtls_ssl_context *ssl,
const unsigned char *buf,
size_t len )
{
#if defined(MBEDTLS_SSL_RENEGOTIATION)
if( ssl->renego_status != MBEDTLS_SSL_INITIAL_HANDSHAKE )
{
/* Check verify-data in constant-time. The length OTOH is no secret */
if( len != 1 + ssl->verify_data_len * 2 ||
buf[0] != ssl->verify_data_len * 2 ||
mbedtls_ssl_safer_memcmp( buf + 1,
ssl->own_verify_data, ssl->verify_data_len ) != 0 ||
mbedtls_ssl_safer_memcmp( buf + 1 + ssl->verify_data_len,
ssl->peer_verify_data, ssl->verify_data_len ) != 0 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "non-matching renegotiation info" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
}
}
else
#endif /* MBEDTLS_SSL_RENEGOTIATION */
{
if( len != 1 || buf[0] != 0x00 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "non-zero length renegotiation info" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
}
ssl->secure_renegotiation = MBEDTLS_SSL_SECURE_RENEGOTIATION;
}
return( 0 );
}
#if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)
static int ssl_parse_max_fragment_length_ext( mbedtls_ssl_context *ssl,
const unsigned char *buf,
size_t len )
{
/*
* server should use the extension only if we did,
* and if so the server's value should match ours (and len is always 1)
*/
if( ssl->conf->mfl_code == MBEDTLS_SSL_MAX_FRAG_LEN_NONE ||
len != 1 ||
buf[0] != ssl->conf->mfl_code )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "non-matching max fragment length extension" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
}
return( 0 );
}
#endif /* MBEDTLS_SSL_MAX_FRAGMENT_LENGTH */
#if defined(MBEDTLS_SSL_TRUNCATED_HMAC)
static int ssl_parse_truncated_hmac_ext( mbedtls_ssl_context *ssl,
const unsigned char *buf,
size_t len )
{
if( ssl->conf->trunc_hmac == MBEDTLS_SSL_TRUNC_HMAC_DISABLED ||
len != 0 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "non-matching truncated HMAC extension" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
}
((void) buf);
ssl->session_negotiate->trunc_hmac = MBEDTLS_SSL_TRUNC_HMAC_ENABLED;
return( 0 );
}
#endif /* MBEDTLS_SSL_TRUNCATED_HMAC */
#if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
static int ssl_parse_encrypt_then_mac_ext( mbedtls_ssl_context *ssl,
const unsigned char *buf,
size_t len )
{
if( ssl->conf->encrypt_then_mac == MBEDTLS_SSL_ETM_DISABLED ||
ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 ||
len != 0 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "non-matching encrypt-then-MAC extension" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
}
((void) buf);
ssl->session_negotiate->encrypt_then_mac = MBEDTLS_SSL_ETM_ENABLED;
return( 0 );
}
#endif /* MBEDTLS_SSL_ENCRYPT_THEN_MAC */
#if defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET)
static int ssl_parse_extended_ms_ext( mbedtls_ssl_context *ssl,
const unsigned char *buf,
size_t len )
{
if( ssl->conf->extended_ms == MBEDTLS_SSL_EXTENDED_MS_DISABLED ||
ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 ||
len != 0 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "non-matching extended master secret extension" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
}
((void) buf);
ssl->handshake->extended_ms = MBEDTLS_SSL_EXTENDED_MS_ENABLED;
return( 0 );
}
#endif /* MBEDTLS_SSL_EXTENDED_MASTER_SECRET */
#if defined(MBEDTLS_SSL_SESSION_TICKETS)
static int ssl_parse_session_ticket_ext( mbedtls_ssl_context *ssl,
const unsigned char *buf,
size_t len )
{
if( ssl->conf->session_tickets == MBEDTLS_SSL_SESSION_TICKETS_DISABLED ||
len != 0 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "non-matching session ticket extension" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
}
((void) buf);
ssl->handshake->new_session_ticket = 1;
return( 0 );
}
#endif /* MBEDTLS_SSL_SESSION_TICKETS */
#if defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_ECDSA_C) || \
defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
static int ssl_parse_supported_point_formats_ext( mbedtls_ssl_context *ssl,
const unsigned char *buf,
size_t len )
{
size_t list_size;
const unsigned char *p;
list_size = buf[0];
if( list_size + 1 != len )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server hello message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
}
p = buf + 1;
while( list_size > 0 )
{
if( p[0] == MBEDTLS_ECP_PF_UNCOMPRESSED ||
p[0] == MBEDTLS_ECP_PF_COMPRESSED )
{
#if defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_ECDSA_C)
ssl->handshake->ecdh_ctx.point_format = p[0];
#endif
#if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
ssl->handshake->ecjpake_ctx.point_format = p[0];
#endif
MBEDTLS_SSL_DEBUG_MSG( 4, ( "point format selected: %d", p[0] ) );
return( 0 );
}
list_size--;
p++;
}
MBEDTLS_SSL_DEBUG_MSG( 1, ( "no point format in common" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
}
#endif /* MBEDTLS_ECDH_C || MBEDTLS_ECDSA_C ||
MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
#if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
static int ssl_parse_ecjpake_kkpp( mbedtls_ssl_context *ssl,
const unsigned char *buf,
size_t len )
{
int ret;
if( ssl->transform_negotiate->ciphersuite_info->key_exchange !=
MBEDTLS_KEY_EXCHANGE_ECJPAKE )
{
MBEDTLS_SSL_DEBUG_MSG( 3, ( "skip ecjpake kkpp extension" ) );
return( 0 );
}
/* If we got here, we no longer need our cached extension */
mbedtls_free( ssl->handshake->ecjpake_cache );
ssl->handshake->ecjpake_cache = NULL;
ssl->handshake->ecjpake_cache_len = 0;
if( ( ret = mbedtls_ecjpake_read_round_one( &ssl->handshake->ecjpake_ctx,
buf, len ) ) != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ecjpake_read_round_one", ret );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );
return( ret );
}
return( 0 );
}
#endif /* MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
#if defined(MBEDTLS_SSL_ALPN)
static int ssl_parse_alpn_ext( mbedtls_ssl_context *ssl,
const unsigned char *buf, size_t len )
{
size_t list_len, name_len;
const char **p;
/* If we didn't send it, the server shouldn't send it */
if( ssl->conf->alpn_list == NULL )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "non-matching ALPN extension" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
}
/*
* opaque ProtocolName<1..2^8-1>;
*
* struct {
* ProtocolName protocol_name_list<2..2^16-1>
* } ProtocolNameList;
*
* the "ProtocolNameList" MUST contain exactly one "ProtocolName"
*/
/* Min length is 2 (list_len) + 1 (name_len) + 1 (name) */
if( len < 4 )
{
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
}
list_len = ( buf[0] << 8 ) | buf[1];
if( list_len != len - 2 )
{
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
}
name_len = buf[2];
if( name_len != list_len - 1 )
{
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
}
/* Check that the server chosen protocol was in our list and save it */
for( p = ssl->conf->alpn_list; *p != NULL; p++ )
{
if( name_len == strlen( *p ) &&
memcmp( buf + 3, *p, name_len ) == 0 )
{
ssl->alpn_chosen = *p;
return( 0 );
}
}
MBEDTLS_SSL_DEBUG_MSG( 1, ( "ALPN extension: no matching protocol" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
}
#endif /* MBEDTLS_SSL_ALPN */
/*
* Parse HelloVerifyRequest. Only called after verifying the HS type.
*/
#if defined(MBEDTLS_SSL_PROTO_DTLS)
static int ssl_parse_hello_verify_request( mbedtls_ssl_context *ssl )
{
const unsigned char *p = ssl->in_msg + mbedtls_ssl_hs_hdr_len( ssl );
int major_ver, minor_ver;
unsigned char cookie_len;
MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse hello verify request" ) );
/*
* struct {
* ProtocolVersion server_version;
* opaque cookie<0..2^8-1>;
* } HelloVerifyRequest;
*/
MBEDTLS_SSL_DEBUG_BUF( 3, "server version", p, 2 );
mbedtls_ssl_read_version( &major_ver, &minor_ver, ssl->conf->transport, p );
p += 2;
/*
* Since the RFC is not clear on this point, accept DTLS 1.0 (TLS 1.1)
* even is lower than our min version.
*/
if( major_ver < MBEDTLS_SSL_MAJOR_VERSION_3 ||
minor_ver < MBEDTLS_SSL_MINOR_VERSION_2 ||
major_ver > ssl->conf->max_major_ver ||
minor_ver > ssl->conf->max_minor_ver )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server version" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_PROTOCOL_VERSION );
return( MBEDTLS_ERR_SSL_BAD_HS_PROTOCOL_VERSION );
}
cookie_len = *p++;
MBEDTLS_SSL_DEBUG_BUF( 3, "cookie", p, cookie_len );
if( ( ssl->in_msg + ssl->in_msglen ) - p < cookie_len )
{
MBEDTLS_SSL_DEBUG_MSG( 1,
( "cookie length does not match incoming message size" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
}
mbedtls_free( ssl->handshake->verify_cookie );
ssl->handshake->verify_cookie = mbedtls_calloc( 1, cookie_len );
if( ssl->handshake->verify_cookie == NULL )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "alloc failed (%d bytes)", cookie_len ) );
return( MBEDTLS_ERR_SSL_ALLOC_FAILED );
}
memcpy( ssl->handshake->verify_cookie, p, cookie_len );
ssl->handshake->verify_cookie_len = cookie_len;
/* Start over at ClientHello */
ssl->state = MBEDTLS_SSL_CLIENT_HELLO;
mbedtls_ssl_reset_checksum( ssl );
mbedtls_ssl_recv_flight_completed( ssl );
MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= parse hello verify request" ) );
return( 0 );
}
#endif /* MBEDTLS_SSL_PROTO_DTLS */
static int ssl_parse_server_hello( mbedtls_ssl_context *ssl )
{
int ret, i;
size_t n;
size_t ext_len;
unsigned char *buf, *ext;
unsigned char comp;
#if defined(MBEDTLS_ZLIB_SUPPORT)
int accept_comp;
#endif
#if defined(MBEDTLS_SSL_RENEGOTIATION)
int renegotiation_info_seen = 0;
#endif
int handshake_failure = 0;
const mbedtls_ssl_ciphersuite_t *suite_info;
MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse server hello" ) );
buf = ssl->in_msg;
if( ( ret = mbedtls_ssl_read_record( ssl ) ) != 0 )
{
/* No alert on a read error. */
MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_read_record", ret );
return( ret );
}
if( ssl->in_msgtype != MBEDTLS_SSL_MSG_HANDSHAKE )
{
#if defined(MBEDTLS_SSL_RENEGOTIATION)
if( ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS )
{
ssl->renego_records_seen++;
if( ssl->conf->renego_max_records >= 0 &&
ssl->renego_records_seen > ssl->conf->renego_max_records )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "renegotiation requested, "
"but not honored by server" ) );
return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );
}
MBEDTLS_SSL_DEBUG_MSG( 1, ( "non-handshake message during renego" ) );
ssl->keep_current_message = 1;
return( MBEDTLS_ERR_SSL_WAITING_SERVER_HELLO_RENEGO );
}
#endif /* MBEDTLS_SSL_RENEGOTIATION */
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server hello message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_UNEXPECTED_MESSAGE );
return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );
}
#if defined(MBEDTLS_SSL_PROTO_DTLS)
if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
{
if( buf[0] == MBEDTLS_SSL_HS_HELLO_VERIFY_REQUEST )
{
MBEDTLS_SSL_DEBUG_MSG( 2, ( "received hello verify request" ) );
MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= parse server hello" ) );
return( ssl_parse_hello_verify_request( ssl ) );
}
else
{
/* We made it through the verification process */
mbedtls_free( ssl->handshake->verify_cookie );
ssl->handshake->verify_cookie = NULL;
ssl->handshake->verify_cookie_len = 0;
}
}
#endif /* MBEDTLS_SSL_PROTO_DTLS */
if( ssl->in_hslen < 38 + mbedtls_ssl_hs_hdr_len( ssl ) ||
buf[0] != MBEDTLS_SSL_HS_SERVER_HELLO )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server hello message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
}
/*
* 0 . 1 server_version
* 2 . 33 random (maybe including 4 bytes of Unix time)
* 34 . 34 session_id length = n
* 35 . 34+n session_id
* 35+n . 36+n cipher_suite
* 37+n . 37+n compression_method
*
* 38+n . 39+n extensions length (optional)
* 40+n . .. extensions
*/
buf += mbedtls_ssl_hs_hdr_len( ssl );
MBEDTLS_SSL_DEBUG_BUF( 3, "server hello, version", buf + 0, 2 );
mbedtls_ssl_read_version( &ssl->major_ver, &ssl->minor_ver,
ssl->conf->transport, buf + 0 );
if( ssl->major_ver < ssl->conf->min_major_ver ||
ssl->minor_ver < ssl->conf->min_minor_ver ||
ssl->major_ver > ssl->conf->max_major_ver ||
ssl->minor_ver > ssl->conf->max_minor_ver )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "server version out of bounds - "
" min: [%d:%d], server: [%d:%d], max: [%d:%d]",
ssl->conf->min_major_ver, ssl->conf->min_minor_ver,
ssl->major_ver, ssl->minor_ver,
ssl->conf->max_major_ver, ssl->conf->max_minor_ver ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_PROTOCOL_VERSION );
return( MBEDTLS_ERR_SSL_BAD_HS_PROTOCOL_VERSION );
}
MBEDTLS_SSL_DEBUG_MSG( 3, ( "server hello, current time: %lu",
( (uint32_t) buf[2] << 24 ) |
( (uint32_t) buf[3] << 16 ) |
( (uint32_t) buf[4] << 8 ) |
( (uint32_t) buf[5] ) ) );
memcpy( ssl->handshake->randbytes + 32, buf + 2, 32 );
n = buf[34];
MBEDTLS_SSL_DEBUG_BUF( 3, "server hello, random bytes", buf + 2, 32 );
if( n > 32 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server hello message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
}
if( ssl->in_hslen > mbedtls_ssl_hs_hdr_len( ssl ) + 39 + n )
{
ext_len = ( ( buf[38 + n] << 8 )
| ( buf[39 + n] ) );
if( ( ext_len > 0 && ext_len < 4 ) ||
ssl->in_hslen != mbedtls_ssl_hs_hdr_len( ssl ) + 40 + n + ext_len )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server hello message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
}
}
else if( ssl->in_hslen == mbedtls_ssl_hs_hdr_len( ssl ) + 38 + n )
{
ext_len = 0;
}
else
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server hello message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
}
/* ciphersuite (used later) */
i = ( buf[35 + n] << 8 ) | buf[36 + n];
/*
* Read and check compression
*/
comp = buf[37 + n];
#if defined(MBEDTLS_ZLIB_SUPPORT)
/* See comments in ssl_write_client_hello() */
#if defined(MBEDTLS_SSL_PROTO_DTLS)
if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
accept_comp = 0;
else
#endif
accept_comp = 1;
if( comp != MBEDTLS_SSL_COMPRESS_NULL &&
( comp != MBEDTLS_SSL_COMPRESS_DEFLATE || accept_comp == 0 ) )
#else /* MBEDTLS_ZLIB_SUPPORT */
if( comp != MBEDTLS_SSL_COMPRESS_NULL )
#endif/* MBEDTLS_ZLIB_SUPPORT */
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "server hello, bad compression: %d", comp ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER );
return( MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE );
}
/*
* Initialize update checksum functions
*/
ssl->transform_negotiate->ciphersuite_info = mbedtls_ssl_ciphersuite_from_id( i );
if( ssl->transform_negotiate->ciphersuite_info == NULL )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "ciphersuite info for %04x not found", i ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_INTERNAL_ERROR );
return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
}
mbedtls_ssl_optimize_checksum( ssl, ssl->transform_negotiate->ciphersuite_info );
MBEDTLS_SSL_DEBUG_MSG( 3, ( "server hello, session id len.: %d", n ) );
MBEDTLS_SSL_DEBUG_BUF( 3, "server hello, session id", buf + 35, n );
/*
* Check if the session can be resumed
*/
if( ssl->handshake->resume == 0 || n == 0 ||
#if defined(MBEDTLS_SSL_RENEGOTIATION)
ssl->renego_status != MBEDTLS_SSL_INITIAL_HANDSHAKE ||
#endif
ssl->session_negotiate->ciphersuite != i ||
ssl->session_negotiate->compression != comp ||
ssl->session_negotiate->id_len != n ||
memcmp( ssl->session_negotiate->id, buf + 35, n ) != 0 )
{
ssl->state++;
ssl->handshake->resume = 0;
#if defined(MBEDTLS_HAVE_TIME)
ssl->session_negotiate->start = mbedtls_time( NULL );
#endif
ssl->session_negotiate->ciphersuite = i;
ssl->session_negotiate->compression = comp;
ssl->session_negotiate->id_len = n;
memcpy( ssl->session_negotiate->id, buf + 35, n );
}
else
{
ssl->state = MBEDTLS_SSL_SERVER_CHANGE_CIPHER_SPEC;
if( ( ret = mbedtls_ssl_derive_keys( ssl ) ) != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_derive_keys", ret );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_INTERNAL_ERROR );
return( ret );
}
}
MBEDTLS_SSL_DEBUG_MSG( 3, ( "%s session has been resumed",
ssl->handshake->resume ? "a" : "no" ) );
MBEDTLS_SSL_DEBUG_MSG( 3, ( "server hello, chosen ciphersuite: %04x", i ) );
MBEDTLS_SSL_DEBUG_MSG( 3, ( "server hello, compress alg.: %d", buf[37 + n] ) );
suite_info = mbedtls_ssl_ciphersuite_from_id( ssl->session_negotiate->ciphersuite );
if( suite_info == NULL
#if defined(MBEDTLS_ARC4_C)
|| ( ssl->conf->arc4_disabled &&
suite_info->cipher == MBEDTLS_CIPHER_ARC4_128 )
#endif
)
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server hello message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
}
MBEDTLS_SSL_DEBUG_MSG( 3, ( "server hello, chosen ciphersuite: %s", suite_info->name ) );
i = 0;
while( 1 )
{
if( ssl->conf->ciphersuite_list[ssl->minor_ver][i] == 0 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server hello message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
}
if( ssl->conf->ciphersuite_list[ssl->minor_ver][i++] ==
ssl->session_negotiate->ciphersuite )
{
break;
}
}
if( comp != MBEDTLS_SSL_COMPRESS_NULL
#if defined(MBEDTLS_ZLIB_SUPPORT)
&& comp != MBEDTLS_SSL_COMPRESS_DEFLATE
#endif
)
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server hello message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
}
ssl->session_negotiate->compression = comp;
ext = buf + 40 + n;
MBEDTLS_SSL_DEBUG_MSG( 2, ( "server hello, total extension length: %d", ext_len ) );
while( ext_len )
{
unsigned int ext_id = ( ( ext[0] << 8 )
| ( ext[1] ) );
unsigned int ext_size = ( ( ext[2] << 8 )
| ( ext[3] ) );
if( ext_size + 4 > ext_len )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server hello message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
}
switch( ext_id )
{
case MBEDTLS_TLS_EXT_RENEGOTIATION_INFO:
MBEDTLS_SSL_DEBUG_MSG( 3, ( "found renegotiation extension" ) );
#if defined(MBEDTLS_SSL_RENEGOTIATION)
renegotiation_info_seen = 1;
#endif
if( ( ret = ssl_parse_renegotiation_info( ssl, ext + 4,
ext_size ) ) != 0 )
return( ret );
break;
#if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)
case MBEDTLS_TLS_EXT_MAX_FRAGMENT_LENGTH:
MBEDTLS_SSL_DEBUG_MSG( 3, ( "found max_fragment_length extension" ) );
if( ( ret = ssl_parse_max_fragment_length_ext( ssl,
ext + 4, ext_size ) ) != 0 )
{
return( ret );
}
break;
#endif /* MBEDTLS_SSL_MAX_FRAGMENT_LENGTH */
#if defined(MBEDTLS_SSL_TRUNCATED_HMAC)
case MBEDTLS_TLS_EXT_TRUNCATED_HMAC:
MBEDTLS_SSL_DEBUG_MSG( 3, ( "found truncated_hmac extension" ) );
if( ( ret = ssl_parse_truncated_hmac_ext( ssl,
ext + 4, ext_size ) ) != 0 )
{
return( ret );
}
break;
#endif /* MBEDTLS_SSL_TRUNCATED_HMAC */
#if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
case MBEDTLS_TLS_EXT_ENCRYPT_THEN_MAC:
MBEDTLS_SSL_DEBUG_MSG( 3, ( "found encrypt_then_mac extension" ) );
if( ( ret = ssl_parse_encrypt_then_mac_ext( ssl,
ext + 4, ext_size ) ) != 0 )
{
return( ret );
}
break;
#endif /* MBEDTLS_SSL_ENCRYPT_THEN_MAC */
#if defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET)
case MBEDTLS_TLS_EXT_EXTENDED_MASTER_SECRET:
MBEDTLS_SSL_DEBUG_MSG( 3, ( "found extended_master_secret extension" ) );
if( ( ret = ssl_parse_extended_ms_ext( ssl,
ext + 4, ext_size ) ) != 0 )
{
return( ret );
}
break;
#endif /* MBEDTLS_SSL_EXTENDED_MASTER_SECRET */
#if defined(MBEDTLS_SSL_SESSION_TICKETS)
case MBEDTLS_TLS_EXT_SESSION_TICKET:
MBEDTLS_SSL_DEBUG_MSG( 3, ( "found session_ticket extension" ) );
if( ( ret = ssl_parse_session_ticket_ext( ssl,
ext + 4, ext_size ) ) != 0 )
{
return( ret );
}
break;
#endif /* MBEDTLS_SSL_SESSION_TICKETS */
#if defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_ECDSA_C) || \
defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
case MBEDTLS_TLS_EXT_SUPPORTED_POINT_FORMATS:
MBEDTLS_SSL_DEBUG_MSG( 3, ( "found supported_point_formats extension" ) );
if( ( ret = ssl_parse_supported_point_formats_ext( ssl,
ext + 4, ext_size ) ) != 0 )
{
return( ret );
}
break;
#endif /* MBEDTLS_ECDH_C || MBEDTLS_ECDSA_C ||
MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
#if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
case MBEDTLS_TLS_EXT_ECJPAKE_KKPP:
MBEDTLS_SSL_DEBUG_MSG( 3, ( "found ecjpake_kkpp extension" ) );
if( ( ret = ssl_parse_ecjpake_kkpp( ssl,
ext + 4, ext_size ) ) != 0 )
{
return( ret );
}
break;
#endif /* MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
#if defined(MBEDTLS_SSL_ALPN)
case MBEDTLS_TLS_EXT_ALPN:
MBEDTLS_SSL_DEBUG_MSG( 3, ( "found alpn extension" ) );
if( ( ret = ssl_parse_alpn_ext( ssl, ext + 4, ext_size ) ) != 0 )
return( ret );
break;
#endif /* MBEDTLS_SSL_ALPN */
default:
MBEDTLS_SSL_DEBUG_MSG( 3, ( "unknown extension found: %d (ignoring)",
ext_id ) );
}
ext_len -= 4 + ext_size;
ext += 4 + ext_size;
if( ext_len > 0 && ext_len < 4 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server hello message" ) );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
}
}
/*
* Renegotiation security checks
*/
if( ssl->secure_renegotiation == MBEDTLS_SSL_LEGACY_RENEGOTIATION &&
ssl->conf->allow_legacy_renegotiation == MBEDTLS_SSL_LEGACY_BREAK_HANDSHAKE )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "legacy renegotiation, breaking off handshake" ) );
handshake_failure = 1;
}
#if defined(MBEDTLS_SSL_RENEGOTIATION)
else if( ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS &&
ssl->secure_renegotiation == MBEDTLS_SSL_SECURE_RENEGOTIATION &&
renegotiation_info_seen == 0 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "renegotiation_info extension missing (secure)" ) );
handshake_failure = 1;
}
else if( ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS &&
ssl->secure_renegotiation == MBEDTLS_SSL_LEGACY_RENEGOTIATION &&
ssl->conf->allow_legacy_renegotiation == MBEDTLS_SSL_LEGACY_NO_RENEGOTIATION )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "legacy renegotiation not allowed" ) );
handshake_failure = 1;
}
else if( ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS &&
ssl->secure_renegotiation == MBEDTLS_SSL_LEGACY_RENEGOTIATION &&
renegotiation_info_seen == 1 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "renegotiation_info extension present (legacy)" ) );
handshake_failure = 1;
}
#endif /* MBEDTLS_SSL_RENEGOTIATION */
if( handshake_failure == 1 )
{
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
}
MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= parse server hello" ) );
return( 0 );
}
#if defined(MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED)
static int ssl_parse_server_dh_params( mbedtls_ssl_context *ssl, unsigned char **p,
unsigned char *end )
{
int ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE;
/*
* Ephemeral DH parameters:
*
* struct {
* opaque dh_p<1..2^16-1>;
* opaque dh_g<1..2^16-1>;
* opaque dh_Ys<1..2^16-1>;
* } ServerDHParams;
*/
if( ( ret = mbedtls_dhm_read_params( &ssl->handshake->dhm_ctx, p, end ) ) != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 2, ( "mbedtls_dhm_read_params" ), ret );
return( ret );
}
if( ssl->handshake->dhm_ctx.len * 8 < ssl->conf->dhm_min_bitlen )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "DHM prime too short: %d < %d",
ssl->handshake->dhm_ctx.len * 8,
ssl->conf->dhm_min_bitlen ) );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
}
MBEDTLS_SSL_DEBUG_MPI( 3, "DHM: P ", &ssl->handshake->dhm_ctx.P );
MBEDTLS_SSL_DEBUG_MPI( 3, "DHM: G ", &ssl->handshake->dhm_ctx.G );
MBEDTLS_SSL_DEBUG_MPI( 3, "DHM: GY", &ssl->handshake->dhm_ctx.GY );
return( ret );
}
#endif /* MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED ||
MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED */
#if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED)
static int ssl_check_server_ecdh_params( const mbedtls_ssl_context *ssl )
{
const mbedtls_ecp_curve_info *curve_info;
curve_info = mbedtls_ecp_curve_info_from_grp_id( ssl->handshake->ecdh_ctx.grp.id );
if( curve_info == NULL )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
}
MBEDTLS_SSL_DEBUG_MSG( 2, ( "ECDH curve: %s", curve_info->name ) );
#if defined(MBEDTLS_ECP_C)
if( mbedtls_ssl_check_curve( ssl, ssl->handshake->ecdh_ctx.grp.id ) != 0 )
#else
if( ssl->handshake->ecdh_ctx.grp.nbits < 163 ||
ssl->handshake->ecdh_ctx.grp.nbits > 521 )
#endif
return( -1 );
MBEDTLS_SSL_DEBUG_ECP( 3, "ECDH: Qp", &ssl->handshake->ecdh_ctx.Qp );
return( 0 );
}
#endif /* MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED ||
MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED ||
MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED ||
MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED ||
MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED */
#if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED)
static int ssl_parse_server_ecdh_params( mbedtls_ssl_context *ssl,
unsigned char **p,
unsigned char *end )
{
int ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE;
/*
* Ephemeral ECDH parameters:
*
* struct {
* ECParameters curve_params;
* ECPoint public;
* } ServerECDHParams;
*/
if( ( ret = mbedtls_ecdh_read_params( &ssl->handshake->ecdh_ctx,
(const unsigned char **) p, end ) ) != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, ( "mbedtls_ecdh_read_params" ), ret );
return( ret );
}
if( ssl_check_server_ecdh_params( ssl ) != 0 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message (ECDHE curve)" ) );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
}
return( ret );
}
#endif /* MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED ||
MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED ||
MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED */
#if defined(MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED)
static int ssl_parse_server_psk_hint( mbedtls_ssl_context *ssl,
unsigned char **p,
unsigned char *end )
{
int ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE;
size_t len;
((void) ssl);
/*
* PSK parameters:
*
* opaque psk_identity_hint<0..2^16-1>;
*/
len = (*p)[0] << 8 | (*p)[1];
*p += 2;
if( (*p) + len > end )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message "
"(psk_identity_hint length)" ) );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
}
/*
* Note: we currently ignore the PKS identity hint, as we only allow one
* PSK to be provisionned on the client. This could be changed later if
* someone needs that feature.
*/
*p += len;
ret = 0;
return( ret );
}
#endif /* MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED */
#if defined(MBEDTLS_KEY_EXCHANGE_RSA_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED)
/*
* Generate a pre-master secret and encrypt it with the server's RSA key
*/
static int ssl_write_encrypted_pms( mbedtls_ssl_context *ssl,
size_t offset, size_t *olen,
size_t pms_offset )
{
int ret;
size_t len_bytes = ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 ? 0 : 2;
unsigned char *p = ssl->handshake->premaster + pms_offset;
if( offset + len_bytes > MBEDTLS_SSL_MAX_CONTENT_LEN )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "buffer too small for encrypted pms" ) );
return( MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL );
}
/*
* Generate (part of) the pre-master as
* struct {
* ProtocolVersion client_version;
* opaque random[46];
* } PreMasterSecret;
*/
mbedtls_ssl_write_version( ssl->conf->max_major_ver, ssl->conf->max_minor_ver,
ssl->conf->transport, p );
if( ( ret = ssl->conf->f_rng( ssl->conf->p_rng, p + 2, 46 ) ) != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, "f_rng", ret );
return( ret );
}
ssl->handshake->pmslen = 48;
if( ssl->session_negotiate->peer_cert == NULL )
{
MBEDTLS_SSL_DEBUG_MSG( 2, ( "certificate required" ) );
return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );
}
/*
* Now write it out, encrypted
*/
if( ! mbedtls_pk_can_do( &ssl->session_negotiate->peer_cert->pk,
MBEDTLS_PK_RSA ) )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "certificate key type mismatch" ) );
return( MBEDTLS_ERR_SSL_PK_TYPE_MISMATCH );
}
if( ( ret = mbedtls_pk_encrypt( &ssl->session_negotiate->peer_cert->pk,
p, ssl->handshake->pmslen,
ssl->out_msg + offset + len_bytes, olen,
MBEDTLS_SSL_MAX_CONTENT_LEN - offset - len_bytes,
ssl->conf->f_rng, ssl->conf->p_rng ) ) != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_rsa_pkcs1_encrypt", ret );
return( ret );
}
#if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) || \
defined(MBEDTLS_SSL_PROTO_TLS1_2)
if( len_bytes == 2 )
{
ssl->out_msg[offset+0] = (unsigned char)( *olen >> 8 );
ssl->out_msg[offset+1] = (unsigned char)( *olen );
*olen += 2;
}
#endif
return( 0 );
}
#endif /* MBEDTLS_KEY_EXCHANGE_RSA_ENABLED ||
MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED */
#if defined(MBEDTLS_SSL_PROTO_TLS1_2)
#if defined(MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED)
static int ssl_parse_signature_algorithm( mbedtls_ssl_context *ssl,
unsigned char **p,
unsigned char *end,
mbedtls_md_type_t *md_alg,
mbedtls_pk_type_t *pk_alg )
{
((void) ssl);
*md_alg = MBEDTLS_MD_NONE;
*pk_alg = MBEDTLS_PK_NONE;
/* Only in TLS 1.2 */
if( ssl->minor_ver != MBEDTLS_SSL_MINOR_VERSION_3 )
{
return( 0 );
}
if( (*p) + 2 > end )
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
/*
* Get hash algorithm
*/
if( ( *md_alg = mbedtls_ssl_md_alg_from_hash( (*p)[0] ) ) == MBEDTLS_MD_NONE )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "Server used unsupported "
"HashAlgorithm %d", *(p)[0] ) );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
}
/*
* Get signature algorithm
*/
if( ( *pk_alg = mbedtls_ssl_pk_alg_from_sig( (*p)[1] ) ) == MBEDTLS_PK_NONE )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "server used unsupported "
"SignatureAlgorithm %d", (*p)[1] ) );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
}
/*
* Check if the hash is acceptable
*/
if( mbedtls_ssl_check_sig_hash( ssl, *md_alg ) != 0 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "server used HashAlgorithm %d that was not offered",
*(p)[0] ) );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
}
MBEDTLS_SSL_DEBUG_MSG( 2, ( "Server used SignatureAlgorithm %d", (*p)[1] ) );
MBEDTLS_SSL_DEBUG_MSG( 2, ( "Server used HashAlgorithm %d", (*p)[0] ) );
*p += 2;
return( 0 );
}
#endif /* MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED ||
MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED ||
MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED */
#endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
#if defined(MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED)
static int ssl_get_ecdh_params_from_cert( mbedtls_ssl_context *ssl )
{
int ret;
const mbedtls_ecp_keypair *peer_key;
if( ssl->session_negotiate->peer_cert == NULL )
{
MBEDTLS_SSL_DEBUG_MSG( 2, ( "certificate required" ) );
return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );
}
if( ! mbedtls_pk_can_do( &ssl->session_negotiate->peer_cert->pk,
MBEDTLS_PK_ECKEY ) )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "server key not ECDH capable" ) );
return( MBEDTLS_ERR_SSL_PK_TYPE_MISMATCH );
}
peer_key = mbedtls_pk_ec( ssl->session_negotiate->peer_cert->pk );
if( ( ret = mbedtls_ecdh_get_params( &ssl->handshake->ecdh_ctx, peer_key,
MBEDTLS_ECDH_THEIRS ) ) != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, ( "mbedtls_ecdh_get_params" ), ret );
return( ret );
}
if( ssl_check_server_ecdh_params( ssl ) != 0 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server certificate (ECDH curve)" ) );
return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE );
}
return( ret );
}
#endif /* MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED) ||
MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED */
static int ssl_parse_server_key_exchange( mbedtls_ssl_context *ssl )
{
int ret;
const mbedtls_ssl_ciphersuite_t *ciphersuite_info =
ssl->transform_negotiate->ciphersuite_info;
unsigned char *p = NULL, *end = NULL;
MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse server key exchange" ) );
#if defined(MBEDTLS_KEY_EXCHANGE_RSA_ENABLED)
if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA )
{
MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip parse server key exchange" ) );
ssl->state++;
return( 0 );
}
((void) p);
((void) end);
#endif
#if defined(MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED)
if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDH_RSA ||
ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA )
{
if( ( ret = ssl_get_ecdh_params_from_cert( ssl ) ) != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, "ssl_get_ecdh_params_from_cert", ret );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );
return( ret );
}
MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip parse server key exchange" ) );
ssl->state++;
return( 0 );
}
((void) p);
((void) end);
#endif /* MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED ||
MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED */
if( ( ret = mbedtls_ssl_read_record( ssl ) ) != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_read_record", ret );
return( ret );
}
if( ssl->in_msgtype != MBEDTLS_SSL_MSG_HANDSHAKE )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_UNEXPECTED_MESSAGE );
return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );
}
/*
* ServerKeyExchange may be skipped with PSK and RSA-PSK when the server
* doesn't use a psk_identity_hint
*/
if( ssl->in_msg[0] != MBEDTLS_SSL_HS_SERVER_KEY_EXCHANGE )
{
if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_PSK ||
ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA_PSK )
{
/* Current message is probably either
* CertificateRequest or ServerHelloDone */
ssl->keep_current_message = 1;
goto exit;
}
MBEDTLS_SSL_DEBUG_MSG( 1, ( "server key exchange message must "
"not be skipped" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_UNEXPECTED_MESSAGE );
return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );
}
p = ssl->in_msg + mbedtls_ssl_hs_hdr_len( ssl );
end = ssl->in_msg + ssl->in_hslen;
MBEDTLS_SSL_DEBUG_BUF( 3, "server key exchange", p, end - p );
#if defined(MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED)
if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_PSK ||
ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA_PSK ||
ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_PSK ||
ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK )
{
if( ssl_parse_server_psk_hint( ssl, &p, end ) != 0 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
}
} /* FALLTROUGH */
#endif /* MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED */
#if defined(MBEDTLS_KEY_EXCHANGE_PSK_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED)
if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_PSK ||
ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA_PSK )
; /* nothing more to do */
else
#endif /* MBEDTLS_KEY_EXCHANGE_PSK_ENABLED ||
MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED */
#if defined(MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED)
if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_RSA ||
ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_PSK )
{
if( ssl_parse_server_dh_params( ssl, &p, end ) != 0 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
}
}
else
#endif /* MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED ||
MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED */
#if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED)
if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_RSA ||
ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK ||
ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA )
{
if( ssl_parse_server_ecdh_params( ssl, &p, end ) != 0 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
}
}
else
#endif /* MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED ||
MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED ||
MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED */
#if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECJPAKE )
{
ret = mbedtls_ecjpake_read_round_two( &ssl->handshake->ecjpake_ctx,
p, end - p );
if( ret != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ecjpake_read_round_two", ret );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
}
}
else
#endif /* MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
}
#if defined(MBEDTLS_KEY_EXCHANGE__WITH_SERVER_SIGNATURE__ENABLED)
if( mbedtls_ssl_ciphersuite_uses_server_signature( ciphersuite_info ) )
{
size_t sig_len, hashlen;
unsigned char hash[64];
mbedtls_md_type_t md_alg = MBEDTLS_MD_NONE;
mbedtls_pk_type_t pk_alg = MBEDTLS_PK_NONE;
unsigned char *params = ssl->in_msg + mbedtls_ssl_hs_hdr_len( ssl );
size_t params_len = p - params;
/*
* Handle the digitally-signed structure
*/
#if defined(MBEDTLS_SSL_PROTO_TLS1_2)
if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_3 )
{
if( ssl_parse_signature_algorithm( ssl, &p, end,
&md_alg, &pk_alg ) != 0 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
}
if( pk_alg != mbedtls_ssl_get_ciphersuite_sig_pk_alg( ciphersuite_info ) )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
}
}
else
#endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
#if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \
defined(MBEDTLS_SSL_PROTO_TLS1_1)
if( ssl->minor_ver < MBEDTLS_SSL_MINOR_VERSION_3 )
{
pk_alg = mbedtls_ssl_get_ciphersuite_sig_pk_alg( ciphersuite_info );
/* Default hash for ECDSA is SHA-1 */
if( pk_alg == MBEDTLS_PK_ECDSA && md_alg == MBEDTLS_MD_NONE )
md_alg = MBEDTLS_MD_SHA1;
}
else
#endif
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
}
/*
* Read signature
*/
if( p > end - 2 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
}
sig_len = ( p[0] << 8 ) | p[1];
p += 2;
if( end != p + sig_len )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
}
MBEDTLS_SSL_DEBUG_BUF( 3, "signature", p, sig_len );
/*
* Compute the hash that has been signed
*/
#if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \
defined(MBEDTLS_SSL_PROTO_TLS1_1)
if( md_alg == MBEDTLS_MD_NONE )
{
hashlen = 36;
ret = mbedtls_ssl_get_key_exchange_md_ssl_tls( ssl, hash, params,
params_len );
if( ret != 0 )
return( ret );
}
else
#endif /* MBEDTLS_SSL_PROTO_SSL3 || MBEDTLS_SSL_PROTO_TLS1 || \
MBEDTLS_SSL_PROTO_TLS1_1 */
#if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) || \
defined(MBEDTLS_SSL_PROTO_TLS1_2)
if( md_alg != MBEDTLS_MD_NONE )
{
/* Info from md_alg will be used instead */
hashlen = 0;
ret = mbedtls_ssl_get_key_exchange_md_tls1_2( ssl, hash, params,
params_len, md_alg );
if( ret != 0 )
return( ret );
}
else
#endif /* MBEDTLS_SSL_PROTO_TLS1 || MBEDTLS_SSL_PROTO_TLS1_1 || \
MBEDTLS_SSL_PROTO_TLS1_2 */
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
}
MBEDTLS_SSL_DEBUG_BUF( 3, "parameters hash", hash, hashlen != 0 ? hashlen :
(unsigned int) ( mbedtls_md_get_size( mbedtls_md_info_from_type( md_alg ) ) ) );
if( ssl->session_negotiate->peer_cert == NULL )
{
MBEDTLS_SSL_DEBUG_MSG( 2, ( "certificate required" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );
return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );
}
/*
* Verify signature
*/
if( ! mbedtls_pk_can_do( &ssl->session_negotiate->peer_cert->pk, pk_alg ) )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );
return( MBEDTLS_ERR_SSL_PK_TYPE_MISMATCH );
}
if( ( ret = mbedtls_pk_verify( &ssl->session_negotiate->peer_cert->pk,
md_alg, hash, hashlen, p, sig_len ) ) != 0 )
{
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_DECRYPT_ERROR );
MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_pk_verify", ret );
return( ret );
}
}
#endif /* MBEDTLS_KEY_EXCHANGE__WITH_SERVER_SIGNATURE__ENABLED */
exit:
ssl->state++;
MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= parse server key exchange" ) );
return( 0 );
}
#if ! defined(MBEDTLS_KEY_EXCHANGE__CERT_REQ_ALLOWED__ENABLED)
static int ssl_parse_certificate_request( mbedtls_ssl_context *ssl )
{
const mbedtls_ssl_ciphersuite_t *ciphersuite_info =
ssl->transform_negotiate->ciphersuite_info;
MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse certificate request" ) );
if( ! mbedtls_ssl_ciphersuite_cert_req_allowed( ciphersuite_info ) )
{
MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip parse certificate request" ) );
ssl->state++;
return( 0 );
}
MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
}
#else /* MBEDTLS_KEY_EXCHANGE__CERT_REQ_ALLOWED__ENABLED */
static int ssl_parse_certificate_request( mbedtls_ssl_context *ssl )
{
int ret;
unsigned char *buf;
size_t n = 0;
size_t cert_type_len = 0, dn_len = 0;
const mbedtls_ssl_ciphersuite_t *ciphersuite_info =
ssl->transform_negotiate->ciphersuite_info;
MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse certificate request" ) );
if( ! mbedtls_ssl_ciphersuite_cert_req_allowed( ciphersuite_info ) )
{
MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip parse certificate request" ) );
ssl->state++;
return( 0 );
}
if( ( ret = mbedtls_ssl_read_record( ssl ) ) != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_read_record", ret );
return( ret );
}
if( ssl->in_msgtype != MBEDTLS_SSL_MSG_HANDSHAKE )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate request message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_UNEXPECTED_MESSAGE );
return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );
}
ssl->state++;
ssl->client_auth = ( ssl->in_msg[0] == MBEDTLS_SSL_HS_CERTIFICATE_REQUEST );
MBEDTLS_SSL_DEBUG_MSG( 3, ( "got %s certificate request",
ssl->client_auth ? "a" : "no" ) );
if( ssl->client_auth == 0 )
{
/* Current message is probably the ServerHelloDone */
ssl->keep_current_message = 1;
goto exit;
}
/*
* struct {
* ClientCertificateType certificate_types<1..2^8-1>;
* SignatureAndHashAlgorithm
* supported_signature_algorithms<2^16-1>; -- TLS 1.2 only
* DistinguishedName certificate_authorities<0..2^16-1>;
* } CertificateRequest;
*
* Since we only support a single certificate on clients, let's just
* ignore all the information that's supposed to help us pick a
* certificate.
*
* We could check that our certificate matches the request, and bail out
* if it doesn't, but it's simpler to just send the certificate anyway,
* and give the server the opportunity to decide if it should terminate
* the connection when it doesn't like our certificate.
*
* Same goes for the hash in TLS 1.2's signature_algorithms: at this
* point we only have one hash available (see comments in
* write_certificate_verify), so let's just use what we have.
*
* However, we still minimally parse the message to check it is at least
* superficially sane.
*/
buf = ssl->in_msg;
/* certificate_types */
cert_type_len = buf[mbedtls_ssl_hs_hdr_len( ssl )];
n = cert_type_len;
if( ssl->in_hslen < mbedtls_ssl_hs_hdr_len( ssl ) + 2 + n )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate request message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE_REQUEST );
}
/* supported_signature_algorithms */
#if defined(MBEDTLS_SSL_PROTO_TLS1_2)
if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_3 )
{
size_t sig_alg_len = ( ( buf[mbedtls_ssl_hs_hdr_len( ssl ) + 1 + n] << 8 )
| ( buf[mbedtls_ssl_hs_hdr_len( ssl ) + 2 + n] ) );
#if defined(MBEDTLS_DEBUG_C)
unsigned char* sig_alg = buf + mbedtls_ssl_hs_hdr_len( ssl ) + 3 + n;
size_t i;
for( i = 0; i < sig_alg_len; i += 2 )
{
MBEDTLS_SSL_DEBUG_MSG( 3, ( "Supported Signature Algorithm found: %d"
",%d", sig_alg[i], sig_alg[i + 1] ) );
}
#endif
n += 2 + sig_alg_len;
if( ssl->in_hslen < mbedtls_ssl_hs_hdr_len( ssl ) + 2 + n )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate request message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE_REQUEST );
}
}
#endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
/* certificate_authorities */
dn_len = ( ( buf[mbedtls_ssl_hs_hdr_len( ssl ) + 1 + n] << 8 )
| ( buf[mbedtls_ssl_hs_hdr_len( ssl ) + 2 + n] ) );
n += dn_len;
if( ssl->in_hslen != mbedtls_ssl_hs_hdr_len( ssl ) + 3 + n )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate request message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE_REQUEST );
}
exit:
MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= parse certificate request" ) );
return( 0 );
}
#endif /* MBEDTLS_KEY_EXCHANGE__CERT_REQ_ALLOWED__ENABLED */
static int ssl_parse_server_hello_done( mbedtls_ssl_context *ssl )
{
int ret;
MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse server hello done" ) );
if( ( ret = mbedtls_ssl_read_record( ssl ) ) != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_read_record", ret );
return( ret );
}
if( ssl->in_msgtype != MBEDTLS_SSL_MSG_HANDSHAKE )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server hello done message" ) );
return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );
}
if( ssl->in_hslen != mbedtls_ssl_hs_hdr_len( ssl ) ||
ssl->in_msg[0] != MBEDTLS_SSL_HS_SERVER_HELLO_DONE )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server hello done message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO_DONE );
}
ssl->state++;
#if defined(MBEDTLS_SSL_PROTO_DTLS)
if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
mbedtls_ssl_recv_flight_completed( ssl );
#endif
MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= parse server hello done" ) );
return( 0 );
}
static int ssl_write_client_key_exchange( mbedtls_ssl_context *ssl )
{
int ret;
size_t i, n;
const mbedtls_ssl_ciphersuite_t *ciphersuite_info =
ssl->transform_negotiate->ciphersuite_info;
MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write client key exchange" ) );
#if defined(MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED)
if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_RSA )
{
/*
* DHM key exchange -- send G^X mod P
*/
n = ssl->handshake->dhm_ctx.len;
ssl->out_msg[4] = (unsigned char)( n >> 8 );
ssl->out_msg[5] = (unsigned char)( n );
i = 6;
ret = mbedtls_dhm_make_public( &ssl->handshake->dhm_ctx,
(int) mbedtls_mpi_size( &ssl->handshake->dhm_ctx.P ),
&ssl->out_msg[i], n,
ssl->conf->f_rng, ssl->conf->p_rng );
if( ret != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_dhm_make_public", ret );
return( ret );
}
MBEDTLS_SSL_DEBUG_MPI( 3, "DHM: X ", &ssl->handshake->dhm_ctx.X );
MBEDTLS_SSL_DEBUG_MPI( 3, "DHM: GX", &ssl->handshake->dhm_ctx.GX );
if( ( ret = mbedtls_dhm_calc_secret( &ssl->handshake->dhm_ctx,
ssl->handshake->premaster,
MBEDTLS_PREMASTER_SIZE,
&ssl->handshake->pmslen,
ssl->conf->f_rng, ssl->conf->p_rng ) ) != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_dhm_calc_secret", ret );
return( ret );
}
MBEDTLS_SSL_DEBUG_MPI( 3, "DHM: K ", &ssl->handshake->dhm_ctx.K );
}
else
#endif /* MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED */
#if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED)
if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_RSA ||
ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA ||
ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDH_RSA ||
ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA )
{
/*
* ECDH key exchange -- send client public value
*/
i = 4;
ret = mbedtls_ecdh_make_public( &ssl->handshake->ecdh_ctx,
&n,
&ssl->out_msg[i], 1000,
ssl->conf->f_rng, ssl->conf->p_rng );
if( ret != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ecdh_make_public", ret );
return( ret );
}
MBEDTLS_SSL_DEBUG_ECP( 3, "ECDH: Q", &ssl->handshake->ecdh_ctx.Q );
if( ( ret = mbedtls_ecdh_calc_secret( &ssl->handshake->ecdh_ctx,
&ssl->handshake->pmslen,
ssl->handshake->premaster,
MBEDTLS_MPI_MAX_SIZE,
ssl->conf->f_rng, ssl->conf->p_rng ) ) != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ecdh_calc_secret", ret );
return( ret );
}
MBEDTLS_SSL_DEBUG_MPI( 3, "ECDH: z", &ssl->handshake->ecdh_ctx.z );
}
else
#endif /* MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED ||
MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED ||
MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED ||
MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED */
#if defined(MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED)
if( mbedtls_ssl_ciphersuite_uses_psk( ciphersuite_info ) )
{
/*
* opaque psk_identity<0..2^16-1>;
*/
if( ssl->conf->psk == NULL || ssl->conf->psk_identity == NULL )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "got no private key for PSK" ) );
return( MBEDTLS_ERR_SSL_PRIVATE_KEY_REQUIRED );
}
i = 4;
n = ssl->conf->psk_identity_len;
if( i + 2 + n > MBEDTLS_SSL_MAX_CONTENT_LEN )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "psk identity too long or "
"SSL buffer too short" ) );
return( MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL );
}
ssl->out_msg[i++] = (unsigned char)( n >> 8 );
ssl->out_msg[i++] = (unsigned char)( n );
memcpy( ssl->out_msg + i, ssl->conf->psk_identity, ssl->conf->psk_identity_len );
i += ssl->conf->psk_identity_len;
#if defined(MBEDTLS_KEY_EXCHANGE_PSK_ENABLED)
if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_PSK )
{
n = 0;
}
else
#endif
#if defined(MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED)
if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA_PSK )
{
if( ( ret = ssl_write_encrypted_pms( ssl, i, &n, 2 ) ) != 0 )
return( ret );
}
else
#endif
#if defined(MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED)
if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_PSK )
{
/*
* ClientDiffieHellmanPublic public (DHM send G^X mod P)
*/
n = ssl->handshake->dhm_ctx.len;
if( i + 2 + n > MBEDTLS_SSL_MAX_CONTENT_LEN )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "psk identity or DHM size too long"
" or SSL buffer too short" ) );
return( MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL );
}
ssl->out_msg[i++] = (unsigned char)( n >> 8 );
ssl->out_msg[i++] = (unsigned char)( n );
ret = mbedtls_dhm_make_public( &ssl->handshake->dhm_ctx,
(int) mbedtls_mpi_size( &ssl->handshake->dhm_ctx.P ),
&ssl->out_msg[i], n,
ssl->conf->f_rng, ssl->conf->p_rng );
if( ret != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_dhm_make_public", ret );
return( ret );
}
}
else
#endif /* MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED */
#if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED)
if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK )
{
/*
* ClientECDiffieHellmanPublic public;
*/
ret = mbedtls_ecdh_make_public( &ssl->handshake->ecdh_ctx, &n,
&ssl->out_msg[i], MBEDTLS_SSL_MAX_CONTENT_LEN - i,
ssl->conf->f_rng, ssl->conf->p_rng );
if( ret != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ecdh_make_public", ret );
return( ret );
}
MBEDTLS_SSL_DEBUG_ECP( 3, "ECDH: Q", &ssl->handshake->ecdh_ctx.Q );
}
else
#endif /* MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED */
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
}
if( ( ret = mbedtls_ssl_psk_derive_premaster( ssl,
ciphersuite_info->key_exchange ) ) != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_psk_derive_premaster", ret );
return( ret );
}
}
else
#endif /* MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED */
#if defined(MBEDTLS_KEY_EXCHANGE_RSA_ENABLED)
if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA )
{
i = 4;
if( ( ret = ssl_write_encrypted_pms( ssl, i, &n, 0 ) ) != 0 )
return( ret );
}
else
#endif /* MBEDTLS_KEY_EXCHANGE_RSA_ENABLED */
#if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECJPAKE )
{
i = 4;
ret = mbedtls_ecjpake_write_round_two( &ssl->handshake->ecjpake_ctx,
ssl->out_msg + i, MBEDTLS_SSL_MAX_CONTENT_LEN - i, &n,
ssl->conf->f_rng, ssl->conf->p_rng );
if( ret != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ecjpake_write_round_two", ret );
return( ret );
}
ret = mbedtls_ecjpake_derive_secret( &ssl->handshake->ecjpake_ctx,
ssl->handshake->premaster, 32, &ssl->handshake->pmslen,
ssl->conf->f_rng, ssl->conf->p_rng );
if( ret != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ecjpake_derive_secret", ret );
return( ret );
}
}
else
#endif /* MBEDTLS_KEY_EXCHANGE_RSA_ENABLED */
{
((void) ciphersuite_info);
MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
}
ssl->out_msglen = i + n;
ssl->out_msgtype = MBEDTLS_SSL_MSG_HANDSHAKE;
ssl->out_msg[0] = MBEDTLS_SSL_HS_CLIENT_KEY_EXCHANGE;
ssl->state++;
if( ( ret = mbedtls_ssl_write_record( ssl ) ) != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_write_record", ret );
return( ret );
}
MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write client key exchange" ) );
return( 0 );
}
#if !defined(MBEDTLS_KEY_EXCHANGE_RSA_ENABLED) && \
!defined(MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED) && \
!defined(MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED) && \
!defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED) && \
!defined(MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED)&& \
!defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED)
static int ssl_write_certificate_verify( mbedtls_ssl_context *ssl )
{
const mbedtls_ssl_ciphersuite_t *ciphersuite_info =
ssl->transform_negotiate->ciphersuite_info;
int ret;
MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write certificate verify" ) );
if( ( ret = mbedtls_ssl_derive_keys( ssl ) ) != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_derive_keys", ret );
return( ret );
}
if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_PSK ||
ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA_PSK ||
ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK ||
ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_PSK ||
ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECJPAKE )
{
MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip write certificate verify" ) );
ssl->state++;
return( 0 );
}
MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
}
#else
static int ssl_write_certificate_verify( mbedtls_ssl_context *ssl )
{
int ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE;
const mbedtls_ssl_ciphersuite_t *ciphersuite_info =
ssl->transform_negotiate->ciphersuite_info;
size_t n = 0, offset = 0;
unsigned char hash[48];
unsigned char *hash_start = hash;
mbedtls_md_type_t md_alg = MBEDTLS_MD_NONE;
unsigned int hashlen;
MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write certificate verify" ) );
if( ( ret = mbedtls_ssl_derive_keys( ssl ) ) != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_derive_keys", ret );
return( ret );
}
if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_PSK ||
ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA_PSK ||
ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK ||
ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_PSK ||
ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECJPAKE )
{
MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip write certificate verify" ) );
ssl->state++;
return( 0 );
}
if( ssl->client_auth == 0 || mbedtls_ssl_own_cert( ssl ) == NULL )
{
MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip write certificate verify" ) );
ssl->state++;
return( 0 );
}
if( mbedtls_ssl_own_key( ssl ) == NULL )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "got no private key for certificate" ) );
return( MBEDTLS_ERR_SSL_PRIVATE_KEY_REQUIRED );
}
/*
* Make an RSA signature of the handshake digests
*/
ssl->handshake->calc_verify( ssl, hash );
#if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \
defined(MBEDTLS_SSL_PROTO_TLS1_1)
if( ssl->minor_ver != MBEDTLS_SSL_MINOR_VERSION_3 )
{
/*
* digitally-signed struct {
* opaque md5_hash[16];
* opaque sha_hash[20];
* };
*
* md5_hash
* MD5(handshake_messages);
*
* sha_hash
* SHA(handshake_messages);
*/
hashlen = 36;
md_alg = MBEDTLS_MD_NONE;
/*
* For ECDSA, default hash is SHA-1 only
*/
if( mbedtls_pk_can_do( mbedtls_ssl_own_key( ssl ), MBEDTLS_PK_ECDSA ) )
{
hash_start += 16;
hashlen -= 16;
md_alg = MBEDTLS_MD_SHA1;
}
}
else
#endif /* MBEDTLS_SSL_PROTO_SSL3 || MBEDTLS_SSL_PROTO_TLS1 || \
MBEDTLS_SSL_PROTO_TLS1_1 */
#if defined(MBEDTLS_SSL_PROTO_TLS1_2)
if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_3 )
{
/*
* digitally-signed struct {
* opaque handshake_messages[handshake_messages_length];
* };
*
* Taking shortcut here. We assume that the server always allows the
* PRF Hash function and has sent it in the allowed signature
* algorithms list received in the Certificate Request message.
*
* Until we encounter a server that does not, we will take this
* shortcut.
*
* Reason: Otherwise we should have running hashes for SHA512 and SHA224
* in order to satisfy 'weird' needs from the server side.
*/
if( ssl->transform_negotiate->ciphersuite_info->mac ==
MBEDTLS_MD_SHA384 )
{
md_alg = MBEDTLS_MD_SHA384;
ssl->out_msg[4] = MBEDTLS_SSL_HASH_SHA384;
}
else
{
md_alg = MBEDTLS_MD_SHA256;
ssl->out_msg[4] = MBEDTLS_SSL_HASH_SHA256;
}
ssl->out_msg[5] = mbedtls_ssl_sig_from_pk( mbedtls_ssl_own_key( ssl ) );
/* Info from md_alg will be used instead */
hashlen = 0;
offset = 2;
}
else
#endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
}
if( ( ret = mbedtls_pk_sign( mbedtls_ssl_own_key( ssl ), md_alg, hash_start, hashlen,
ssl->out_msg + 6 + offset, &n,
ssl->conf->f_rng, ssl->conf->p_rng ) ) != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_pk_sign", ret );
return( ret );
}
ssl->out_msg[4 + offset] = (unsigned char)( n >> 8 );
ssl->out_msg[5 + offset] = (unsigned char)( n );
ssl->out_msglen = 6 + n + offset;
ssl->out_msgtype = MBEDTLS_SSL_MSG_HANDSHAKE;
ssl->out_msg[0] = MBEDTLS_SSL_HS_CERTIFICATE_VERIFY;
ssl->state++;
if( ( ret = mbedtls_ssl_write_record( ssl ) ) != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_write_record", ret );
return( ret );
}
MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write certificate verify" ) );
return( ret );
}
#endif /* !MBEDTLS_KEY_EXCHANGE_RSA_ENABLED &&
!MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED &&
!MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED &&
!MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED &&
!MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED &&
!MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED */
#if defined(MBEDTLS_SSL_SESSION_TICKETS)
static int ssl_parse_new_session_ticket( mbedtls_ssl_context *ssl )
{
int ret;
uint32_t lifetime;
size_t ticket_len;
unsigned char *ticket;
const unsigned char *msg;
MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse new session ticket" ) );
if( ( ret = mbedtls_ssl_read_record( ssl ) ) != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_read_record", ret );
return( ret );
}
if( ssl->in_msgtype != MBEDTLS_SSL_MSG_HANDSHAKE )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad new session ticket message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_UNEXPECTED_MESSAGE );
return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );
}
/*
* struct {
* uint32 ticket_lifetime_hint;
* opaque ticket<0..2^16-1>;
* } NewSessionTicket;
*
* 0 . 3 ticket_lifetime_hint
* 4 . 5 ticket_len (n)
* 6 . 5+n ticket content
*/
if( ssl->in_msg[0] != MBEDTLS_SSL_HS_NEW_SESSION_TICKET ||
ssl->in_hslen < 6 + mbedtls_ssl_hs_hdr_len( ssl ) )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad new session ticket message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
return( MBEDTLS_ERR_SSL_BAD_HS_NEW_SESSION_TICKET );
}
msg = ssl->in_msg + mbedtls_ssl_hs_hdr_len( ssl );
lifetime = ( msg[0] << 24 ) | ( msg[1] << 16 ) |
( msg[2] << 8 ) | ( msg[3] );
ticket_len = ( msg[4] << 8 ) | ( msg[5] );
if( ticket_len + 6 + mbedtls_ssl_hs_hdr_len( ssl ) != ssl->in_hslen )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad new session ticket message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
return( MBEDTLS_ERR_SSL_BAD_HS_NEW_SESSION_TICKET );
}
MBEDTLS_SSL_DEBUG_MSG( 3, ( "ticket length: %d", ticket_len ) );
/* We're not waiting for a NewSessionTicket message any more */
ssl->handshake->new_session_ticket = 0;
ssl->state = MBEDTLS_SSL_SERVER_CHANGE_CIPHER_SPEC;
/*
* Zero-length ticket means the server changed his mind and doesn't want
* to send a ticket after all, so just forget it
*/
if( ticket_len == 0 )
return( 0 );
mbedtls_zeroize( ssl->session_negotiate->ticket,
ssl->session_negotiate->ticket_len );
mbedtls_free( ssl->session_negotiate->ticket );
ssl->session_negotiate->ticket = NULL;
ssl->session_negotiate->ticket_len = 0;
if( ( ticket = mbedtls_calloc( 1, ticket_len ) ) == NULL )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "ticket alloc failed" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_INTERNAL_ERROR );
return( MBEDTLS_ERR_SSL_ALLOC_FAILED );
}
memcpy( ticket, msg + 6, ticket_len );
ssl->session_negotiate->ticket = ticket;
ssl->session_negotiate->ticket_len = ticket_len;
ssl->session_negotiate->ticket_lifetime = lifetime;
/*
* RFC 5077 section 3.4:
* "If the client receives a session ticket from the server, then it
* discards any Session ID that was sent in the ServerHello."
*/
MBEDTLS_SSL_DEBUG_MSG( 3, ( "ticket in use, discarding session id" ) );
ssl->session_negotiate->id_len = 0;
MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= parse new session ticket" ) );
return( 0 );
}
#endif /* MBEDTLS_SSL_SESSION_TICKETS */
/*
* SSL handshake -- client side -- single step
*/
int mbedtls_ssl_handshake_client_step( mbedtls_ssl_context *ssl )
{
int ret = 0;
if( ssl->state == MBEDTLS_SSL_HANDSHAKE_OVER || ssl->handshake == NULL )
return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
MBEDTLS_SSL_DEBUG_MSG( 2, ( "client state: %d", ssl->state ) );
if( ( ret = mbedtls_ssl_flush_output( ssl ) ) != 0 )
return( ret );
#if defined(MBEDTLS_SSL_PROTO_DTLS)
if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
ssl->handshake->retransmit_state == MBEDTLS_SSL_RETRANS_SENDING )
{
if( ( ret = mbedtls_ssl_resend( ssl ) ) != 0 )
return( ret );
}
#endif
/* Change state now, so that it is right in mbedtls_ssl_read_record(), used
* by DTLS for dropping out-of-sequence ChangeCipherSpec records */
#if defined(MBEDTLS_SSL_SESSION_TICKETS)
if( ssl->state == MBEDTLS_SSL_SERVER_CHANGE_CIPHER_SPEC &&
ssl->handshake->new_session_ticket != 0 )
{
ssl->state = MBEDTLS_SSL_SERVER_NEW_SESSION_TICKET;
}
#endif
switch( ssl->state )
{
case MBEDTLS_SSL_HELLO_REQUEST:
ssl->state = MBEDTLS_SSL_CLIENT_HELLO;
break;
/*
* ==> ClientHello
*/
case MBEDTLS_SSL_CLIENT_HELLO:
ret = ssl_write_client_hello( ssl );
break;
/*
* <== ServerHello
* Certificate
* ( ServerKeyExchange )
* ( CertificateRequest )
* ServerHelloDone
*/
case MBEDTLS_SSL_SERVER_HELLO:
ret = ssl_parse_server_hello( ssl );
break;
case MBEDTLS_SSL_SERVER_CERTIFICATE:
ret = mbedtls_ssl_parse_certificate( ssl );
break;
case MBEDTLS_SSL_SERVER_KEY_EXCHANGE:
ret = ssl_parse_server_key_exchange( ssl );
break;
case MBEDTLS_SSL_CERTIFICATE_REQUEST:
ret = ssl_parse_certificate_request( ssl );
break;
case MBEDTLS_SSL_SERVER_HELLO_DONE:
ret = ssl_parse_server_hello_done( ssl );
break;
/*
* ==> ( Certificate/Alert )
* ClientKeyExchange
* ( CertificateVerify )
* ChangeCipherSpec
* Finished
*/
case MBEDTLS_SSL_CLIENT_CERTIFICATE:
ret = mbedtls_ssl_write_certificate( ssl );
break;
case MBEDTLS_SSL_CLIENT_KEY_EXCHANGE:
ret = ssl_write_client_key_exchange( ssl );
break;
case MBEDTLS_SSL_CERTIFICATE_VERIFY:
ret = ssl_write_certificate_verify( ssl );
break;
case MBEDTLS_SSL_CLIENT_CHANGE_CIPHER_SPEC:
ret = mbedtls_ssl_write_change_cipher_spec( ssl );
break;
case MBEDTLS_SSL_CLIENT_FINISHED:
ret = mbedtls_ssl_write_finished( ssl );
break;
/*
* <== ( NewSessionTicket )
* ChangeCipherSpec
* Finished
*/
#if defined(MBEDTLS_SSL_SESSION_TICKETS)
case MBEDTLS_SSL_SERVER_NEW_SESSION_TICKET:
ret = ssl_parse_new_session_ticket( ssl );
break;
#endif
case MBEDTLS_SSL_SERVER_CHANGE_CIPHER_SPEC:
ret = mbedtls_ssl_parse_change_cipher_spec( ssl );
break;
case MBEDTLS_SSL_SERVER_FINISHED:
ret = mbedtls_ssl_parse_finished( ssl );
break;
case MBEDTLS_SSL_FLUSH_BUFFERS:
MBEDTLS_SSL_DEBUG_MSG( 2, ( "handshake: done" ) );
ssl->state = MBEDTLS_SSL_HANDSHAKE_WRAPUP;
break;
case MBEDTLS_SSL_HANDSHAKE_WRAPUP:
mbedtls_ssl_handshake_wrapup( ssl );
break;
default:
MBEDTLS_SSL_DEBUG_MSG( 1, ( "invalid state %d", ssl->state ) );
return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
}
return( ret );
}
#endif /* MBEDTLS_SSL_CLI_C */
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_699_0 |
crossvul-cpp_data_good_3951_0 | /**
* FreeRDP: A Remote Desktop Protocol Implementation
* Drawing Orders
*
* Copyright 2011 Marc-Andre Moreau <marcandre.moreau@gmail.com>
* Copyright 2016 Armin Novak <armin.novak@thincast.com>
* Copyright 2016 Thincast Technologies GmbH
*
* 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 HAVE_CONFIG_H
#include "config.h"
#endif
#include "window.h"
#include <winpr/wtypes.h>
#include <winpr/crt.h>
#include <freerdp/api.h>
#include <freerdp/log.h>
#include <freerdp/graphics.h>
#include <freerdp/codec/bitmap.h>
#include <freerdp/gdi/gdi.h>
#include "orders.h"
#include "../cache/glyph.h"
#include "../cache/bitmap.h"
#include "../cache/brush.h"
#include "../cache/cache.h"
#define TAG FREERDP_TAG("core.orders")
BYTE get_primary_drawing_order_field_bytes(UINT32 orderType, BOOL* pValid)
{
if (pValid)
*pValid = TRUE;
switch (orderType)
{
case 0:
return DSTBLT_ORDER_FIELD_BYTES;
case 1:
return PATBLT_ORDER_FIELD_BYTES;
case 2:
return SCRBLT_ORDER_FIELD_BYTES;
case 3:
return 0;
case 4:
return 0;
case 5:
return 0;
case 6:
return 0;
case 7:
return DRAW_NINE_GRID_ORDER_FIELD_BYTES;
case 8:
return MULTI_DRAW_NINE_GRID_ORDER_FIELD_BYTES;
case 9:
return LINE_TO_ORDER_FIELD_BYTES;
case 10:
return OPAQUE_RECT_ORDER_FIELD_BYTES;
case 11:
return SAVE_BITMAP_ORDER_FIELD_BYTES;
case 12:
return 0;
case 13:
return MEMBLT_ORDER_FIELD_BYTES;
case 14:
return MEM3BLT_ORDER_FIELD_BYTES;
case 15:
return MULTI_DSTBLT_ORDER_FIELD_BYTES;
case 16:
return MULTI_PATBLT_ORDER_FIELD_BYTES;
case 17:
return MULTI_SCRBLT_ORDER_FIELD_BYTES;
case 18:
return MULTI_OPAQUE_RECT_ORDER_FIELD_BYTES;
case 19:
return FAST_INDEX_ORDER_FIELD_BYTES;
case 20:
return POLYGON_SC_ORDER_FIELD_BYTES;
case 21:
return POLYGON_CB_ORDER_FIELD_BYTES;
case 22:
return POLYLINE_ORDER_FIELD_BYTES;
case 23:
return 0;
case 24:
return FAST_GLYPH_ORDER_FIELD_BYTES;
case 25:
return ELLIPSE_SC_ORDER_FIELD_BYTES;
case 26:
return ELLIPSE_CB_ORDER_FIELD_BYTES;
case 27:
return GLYPH_INDEX_ORDER_FIELD_BYTES;
default:
if (pValid)
*pValid = FALSE;
WLog_WARN(TAG, "Invalid orderType 0x%08X received", orderType);
return 0;
}
}
static const BYTE CBR2_BPP[] = { 0, 0, 0, 8, 16, 24, 32 };
static const BYTE BPP_CBR2[] = { 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0,
0, 0, 0, 0, 5, 0, 0, 0, 0, 0, 0, 0, 6, 0, 0, 0, 0, 0, 0, 0 };
static const BYTE CBR23_BPP[] = { 0, 0, 0, 8, 16, 24, 32 };
static const BYTE BPP_CBR23[] = { 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0,
0, 0, 0, 0, 5, 0, 0, 0, 0, 0, 0, 0, 6, 0, 0, 0, 0, 0, 0, 0 };
static const BYTE BMF_BPP[] = { 0, 1, 0, 8, 16, 24, 32, 0 };
static const BYTE BPP_BMF[] = { 0, 1, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0,
0, 0, 0, 0, 5, 0, 0, 0, 0, 0, 0, 0, 6, 0, 0, 0, 0, 0, 0, 0 };
static BOOL check_order_activated(wLog* log, rdpSettings* settings, const char* orderName,
BOOL condition)
{
if (!condition)
{
if (settings->AllowUnanouncedOrdersFromServer)
{
WLog_Print(log, WLOG_WARN,
"%s - SERVER BUG: The support for this feature was not announced!",
orderName);
return TRUE;
}
else
{
WLog_Print(log, WLOG_ERROR,
"%s - SERVER BUG: The support for this feature was not announced! Use "
"/relax-order-checks to ignore",
orderName);
return FALSE;
}
}
return TRUE;
}
static BOOL check_alt_order_supported(wLog* log, rdpSettings* settings, BYTE orderType,
const char* orderName)
{
BOOL condition = FALSE;
switch (orderType)
{
case ORDER_TYPE_CREATE_OFFSCREEN_BITMAP:
case ORDER_TYPE_SWITCH_SURFACE:
condition = settings->OffscreenSupportLevel != 0;
break;
case ORDER_TYPE_CREATE_NINE_GRID_BITMAP:
condition = settings->DrawNineGridEnabled;
break;
case ORDER_TYPE_FRAME_MARKER:
condition = settings->FrameMarkerCommandEnabled;
break;
case ORDER_TYPE_GDIPLUS_FIRST:
case ORDER_TYPE_GDIPLUS_NEXT:
case ORDER_TYPE_GDIPLUS_END:
case ORDER_TYPE_GDIPLUS_CACHE_FIRST:
case ORDER_TYPE_GDIPLUS_CACHE_NEXT:
case ORDER_TYPE_GDIPLUS_CACHE_END:
condition = settings->DrawGdiPlusCacheEnabled;
break;
case ORDER_TYPE_WINDOW:
condition = settings->RemoteWndSupportLevel != WINDOW_LEVEL_NOT_SUPPORTED;
break;
case ORDER_TYPE_STREAM_BITMAP_FIRST:
case ORDER_TYPE_STREAM_BITMAP_NEXT:
case ORDER_TYPE_COMPDESK_FIRST:
condition = TRUE;
break;
default:
WLog_Print(log, WLOG_WARN, "%s - Alternate Secondary Drawing Order UNKNOWN", orderName);
condition = FALSE;
break;
}
return check_order_activated(log, settings, orderName, condition);
}
static BOOL check_secondary_order_supported(wLog* log, rdpSettings* settings, BYTE orderType,
const char* orderName)
{
BOOL condition = FALSE;
switch (orderType)
{
case ORDER_TYPE_BITMAP_UNCOMPRESSED:
case ORDER_TYPE_CACHE_BITMAP_COMPRESSED:
condition = settings->BitmapCacheEnabled;
break;
case ORDER_TYPE_BITMAP_UNCOMPRESSED_V2:
case ORDER_TYPE_BITMAP_COMPRESSED_V2:
condition = settings->BitmapCacheEnabled;
break;
case ORDER_TYPE_BITMAP_COMPRESSED_V3:
condition = settings->BitmapCacheV3Enabled;
break;
case ORDER_TYPE_CACHE_COLOR_TABLE:
condition = (settings->OrderSupport[NEG_MEMBLT_INDEX] ||
settings->OrderSupport[NEG_MEM3BLT_INDEX]);
break;
case ORDER_TYPE_CACHE_GLYPH:
{
switch (settings->GlyphSupportLevel)
{
case GLYPH_SUPPORT_PARTIAL:
case GLYPH_SUPPORT_FULL:
case GLYPH_SUPPORT_ENCODE:
condition = TRUE;
break;
case GLYPH_SUPPORT_NONE:
default:
condition = FALSE;
break;
}
}
break;
case ORDER_TYPE_CACHE_BRUSH:
condition = TRUE;
break;
default:
WLog_Print(log, WLOG_WARN, "SECONDARY ORDER %s not supported", orderName);
break;
}
return check_order_activated(log, settings, orderName, condition);
}
static BOOL check_primary_order_supported(wLog* log, rdpSettings* settings, UINT32 orderType,
const char* orderName)
{
BOOL condition = FALSE;
switch (orderType)
{
case ORDER_TYPE_DSTBLT:
condition = settings->OrderSupport[NEG_DSTBLT_INDEX];
break;
case ORDER_TYPE_SCRBLT:
condition = settings->OrderSupport[NEG_SCRBLT_INDEX];
break;
case ORDER_TYPE_DRAW_NINE_GRID:
condition = settings->OrderSupport[NEG_DRAWNINEGRID_INDEX];
break;
case ORDER_TYPE_MULTI_DRAW_NINE_GRID:
condition = settings->OrderSupport[NEG_MULTI_DRAWNINEGRID_INDEX];
break;
case ORDER_TYPE_LINE_TO:
condition = settings->OrderSupport[NEG_LINETO_INDEX];
break;
/* [MS-RDPEGDI] 2.2.2.2.1.1.2.5 OpaqueRect (OPAQUERECT_ORDER)
* suggests that PatBlt and OpaqueRect imply each other. */
case ORDER_TYPE_PATBLT:
case ORDER_TYPE_OPAQUE_RECT:
condition = settings->OrderSupport[NEG_OPAQUE_RECT_INDEX] ||
settings->OrderSupport[NEG_PATBLT_INDEX];
break;
case ORDER_TYPE_SAVE_BITMAP:
condition = settings->OrderSupport[NEG_SAVEBITMAP_INDEX];
break;
case ORDER_TYPE_MEMBLT:
condition = settings->OrderSupport[NEG_MEMBLT_INDEX];
break;
case ORDER_TYPE_MEM3BLT:
condition = settings->OrderSupport[NEG_MEM3BLT_INDEX];
break;
case ORDER_TYPE_MULTI_DSTBLT:
condition = settings->OrderSupport[NEG_MULTIDSTBLT_INDEX];
break;
case ORDER_TYPE_MULTI_PATBLT:
condition = settings->OrderSupport[NEG_MULTIPATBLT_INDEX];
break;
case ORDER_TYPE_MULTI_SCRBLT:
condition = settings->OrderSupport[NEG_MULTIDSTBLT_INDEX];
break;
case ORDER_TYPE_MULTI_OPAQUE_RECT:
condition = settings->OrderSupport[NEG_MULTIOPAQUERECT_INDEX];
break;
case ORDER_TYPE_FAST_INDEX:
condition = settings->OrderSupport[NEG_FAST_INDEX_INDEX];
break;
case ORDER_TYPE_POLYGON_SC:
condition = settings->OrderSupport[NEG_POLYGON_SC_INDEX];
break;
case ORDER_TYPE_POLYGON_CB:
condition = settings->OrderSupport[NEG_POLYGON_CB_INDEX];
break;
case ORDER_TYPE_POLYLINE:
condition = settings->OrderSupport[NEG_POLYLINE_INDEX];
break;
case ORDER_TYPE_FAST_GLYPH:
condition = settings->OrderSupport[NEG_FAST_GLYPH_INDEX];
break;
case ORDER_TYPE_ELLIPSE_SC:
condition = settings->OrderSupport[NEG_ELLIPSE_SC_INDEX];
break;
case ORDER_TYPE_ELLIPSE_CB:
condition = settings->OrderSupport[NEG_ELLIPSE_CB_INDEX];
break;
case ORDER_TYPE_GLYPH_INDEX:
condition = settings->OrderSupport[NEG_GLYPH_INDEX_INDEX];
break;
default:
WLog_Print(log, WLOG_WARN, "%s Primary Drawing Order not supported", orderName);
break;
}
return check_order_activated(log, settings, orderName, condition);
}
static const char* primary_order_string(UINT32 orderType)
{
const char* orders[] = { "[0x%02" PRIx8 "] DstBlt",
"[0x%02" PRIx8 "] PatBlt",
"[0x%02" PRIx8 "] ScrBlt",
"[0x%02" PRIx8 "] UNUSED",
"[0x%02" PRIx8 "] UNUSED",
"[0x%02" PRIx8 "] UNUSED",
"[0x%02" PRIx8 "] UNUSED",
"[0x%02" PRIx8 "] DrawNineGrid",
"[0x%02" PRIx8 "] MultiDrawNineGrid",
"[0x%02" PRIx8 "] LineTo",
"[0x%02" PRIx8 "] OpaqueRect",
"[0x%02" PRIx8 "] SaveBitmap",
"[0x%02" PRIx8 "] UNUSED",
"[0x%02" PRIx8 "] MemBlt",
"[0x%02" PRIx8 "] Mem3Blt",
"[0x%02" PRIx8 "] MultiDstBlt",
"[0x%02" PRIx8 "] MultiPatBlt",
"[0x%02" PRIx8 "] MultiScrBlt",
"[0x%02" PRIx8 "] MultiOpaqueRect",
"[0x%02" PRIx8 "] FastIndex",
"[0x%02" PRIx8 "] PolygonSC",
"[0x%02" PRIx8 "] PolygonCB",
"[0x%02" PRIx8 "] Polyline",
"[0x%02" PRIx8 "] UNUSED",
"[0x%02" PRIx8 "] FastGlyph",
"[0x%02" PRIx8 "] EllipseSC",
"[0x%02" PRIx8 "] EllipseCB",
"[0x%02" PRIx8 "] GlyphIndex" };
const char* fmt = "[0x%02" PRIx8 "] UNKNOWN";
static char buffer[64] = { 0 };
if (orderType < ARRAYSIZE(orders))
fmt = orders[orderType];
sprintf_s(buffer, ARRAYSIZE(buffer), fmt, orderType);
return buffer;
}
static const char* secondary_order_string(UINT32 orderType)
{
const char* orders[] = { "[0x%02" PRIx8 "] Cache Bitmap",
"[0x%02" PRIx8 "] Cache Color Table",
"[0x%02" PRIx8 "] Cache Bitmap (Compressed)",
"[0x%02" PRIx8 "] Cache Glyph",
"[0x%02" PRIx8 "] Cache Bitmap V2",
"[0x%02" PRIx8 "] Cache Bitmap V2 (Compressed)",
"[0x%02" PRIx8 "] UNUSED",
"[0x%02" PRIx8 "] Cache Brush",
"[0x%02" PRIx8 "] Cache Bitmap V3" };
const char* fmt = "[0x%02" PRIx8 "] UNKNOWN";
static char buffer[64] = { 0 };
if (orderType < ARRAYSIZE(orders))
fmt = orders[orderType];
sprintf_s(buffer, ARRAYSIZE(buffer), fmt, orderType);
return buffer;
}
static const char* altsec_order_string(BYTE orderType)
{
const char* orders[] = {
"[0x%02" PRIx8 "] Switch Surface", "[0x%02" PRIx8 "] Create Offscreen Bitmap",
"[0x%02" PRIx8 "] Stream Bitmap First", "[0x%02" PRIx8 "] Stream Bitmap Next",
"[0x%02" PRIx8 "] Create NineGrid Bitmap", "[0x%02" PRIx8 "] Draw GDI+ First",
"[0x%02" PRIx8 "] Draw GDI+ Next", "[0x%02" PRIx8 "] Draw GDI+ End",
"[0x%02" PRIx8 "] Draw GDI+ Cache First", "[0x%02" PRIx8 "] Draw GDI+ Cache Next",
"[0x%02" PRIx8 "] Draw GDI+ Cache End", "[0x%02" PRIx8 "] Windowing",
"[0x%02" PRIx8 "] Desktop Composition", "[0x%02" PRIx8 "] Frame Marker"
};
const char* fmt = "[0x%02" PRIx8 "] UNKNOWN";
static char buffer[64] = { 0 };
if (orderType < ARRAYSIZE(orders))
fmt = orders[orderType];
sprintf_s(buffer, ARRAYSIZE(buffer), fmt, orderType);
return buffer;
}
static INLINE BOOL update_read_coord(wStream* s, INT32* coord, BOOL delta)
{
INT8 lsi8;
INT16 lsi16;
if (delta)
{
if (Stream_GetRemainingLength(s) < 1)
return FALSE;
Stream_Read_INT8(s, lsi8);
*coord += lsi8;
}
else
{
if (Stream_GetRemainingLength(s) < 2)
return FALSE;
Stream_Read_INT16(s, lsi16);
*coord = lsi16;
}
return TRUE;
}
static INLINE BOOL update_write_coord(wStream* s, INT32 coord)
{
Stream_Write_UINT16(s, coord);
return TRUE;
}
static INLINE BOOL update_read_color(wStream* s, UINT32* color)
{
BYTE byte;
if (Stream_GetRemainingLength(s) < 3)
return FALSE;
*color = 0;
Stream_Read_UINT8(s, byte);
*color = (UINT32)byte;
Stream_Read_UINT8(s, byte);
*color |= ((UINT32)byte << 8) & 0xFF00;
Stream_Read_UINT8(s, byte);
*color |= ((UINT32)byte << 16) & 0xFF0000;
return TRUE;
}
static INLINE BOOL update_write_color(wStream* s, UINT32 color)
{
BYTE byte;
byte = (color & 0xFF);
Stream_Write_UINT8(s, byte);
byte = ((color >> 8) & 0xFF);
Stream_Write_UINT8(s, byte);
byte = ((color >> 16) & 0xFF);
Stream_Write_UINT8(s, byte);
return TRUE;
}
static INLINE BOOL update_read_colorref(wStream* s, UINT32* color)
{
BYTE byte;
if (Stream_GetRemainingLength(s) < 4)
return FALSE;
*color = 0;
Stream_Read_UINT8(s, byte);
*color = byte;
Stream_Read_UINT8(s, byte);
*color |= ((UINT32)byte << 8);
Stream_Read_UINT8(s, byte);
*color |= ((UINT32)byte << 16);
Stream_Seek_UINT8(s);
return TRUE;
}
static INLINE BOOL update_read_color_quad(wStream* s, UINT32* color)
{
return update_read_colorref(s, color);
}
static INLINE void update_write_color_quad(wStream* s, UINT32 color)
{
BYTE byte;
byte = (color >> 16) & 0xFF;
Stream_Write_UINT8(s, byte);
byte = (color >> 8) & 0xFF;
Stream_Write_UINT8(s, byte);
byte = color & 0xFF;
Stream_Write_UINT8(s, byte);
}
static INLINE BOOL update_read_2byte_unsigned(wStream* s, UINT32* value)
{
BYTE byte;
if (Stream_GetRemainingLength(s) < 1)
return FALSE;
Stream_Read_UINT8(s, byte);
if (byte & 0x80)
{
if (Stream_GetRemainingLength(s) < 1)
return FALSE;
*value = (byte & 0x7F) << 8;
Stream_Read_UINT8(s, byte);
*value |= byte;
}
else
{
*value = (byte & 0x7F);
}
return TRUE;
}
static INLINE BOOL update_write_2byte_unsigned(wStream* s, UINT32 value)
{
BYTE byte;
if (value > 0x7FFF)
return FALSE;
if (value >= 0x7F)
{
byte = ((value & 0x7F00) >> 8);
Stream_Write_UINT8(s, byte | 0x80);
byte = (value & 0xFF);
Stream_Write_UINT8(s, byte);
}
else
{
byte = (value & 0x7F);
Stream_Write_UINT8(s, byte);
}
return TRUE;
}
static INLINE BOOL update_read_2byte_signed(wStream* s, INT32* value)
{
BYTE byte;
BOOL negative;
if (Stream_GetRemainingLength(s) < 1)
return FALSE;
Stream_Read_UINT8(s, byte);
negative = (byte & 0x40) ? TRUE : FALSE;
*value = (byte & 0x3F);
if (byte & 0x80)
{
if (Stream_GetRemainingLength(s) < 1)
return FALSE;
Stream_Read_UINT8(s, byte);
*value = (*value << 8) | byte;
}
if (negative)
*value *= -1;
return TRUE;
}
static INLINE BOOL update_write_2byte_signed(wStream* s, INT32 value)
{
BYTE byte;
BOOL negative = FALSE;
if (value < 0)
{
negative = TRUE;
value *= -1;
}
if (value > 0x3FFF)
return FALSE;
if (value >= 0x3F)
{
byte = ((value & 0x3F00) >> 8);
if (negative)
byte |= 0x40;
Stream_Write_UINT8(s, byte | 0x80);
byte = (value & 0xFF);
Stream_Write_UINT8(s, byte);
}
else
{
byte = (value & 0x3F);
if (negative)
byte |= 0x40;
Stream_Write_UINT8(s, byte);
}
return TRUE;
}
static INLINE BOOL update_read_4byte_unsigned(wStream* s, UINT32* value)
{
BYTE byte;
BYTE count;
if (Stream_GetRemainingLength(s) < 1)
return FALSE;
Stream_Read_UINT8(s, byte);
count = (byte & 0xC0) >> 6;
if (Stream_GetRemainingLength(s) < count)
return FALSE;
switch (count)
{
case 0:
*value = (byte & 0x3F);
break;
case 1:
*value = (byte & 0x3F) << 8;
Stream_Read_UINT8(s, byte);
*value |= byte;
break;
case 2:
*value = (byte & 0x3F) << 16;
Stream_Read_UINT8(s, byte);
*value |= (byte << 8);
Stream_Read_UINT8(s, byte);
*value |= byte;
break;
case 3:
*value = (byte & 0x3F) << 24;
Stream_Read_UINT8(s, byte);
*value |= (byte << 16);
Stream_Read_UINT8(s, byte);
*value |= (byte << 8);
Stream_Read_UINT8(s, byte);
*value |= byte;
break;
default:
break;
}
return TRUE;
}
static INLINE BOOL update_write_4byte_unsigned(wStream* s, UINT32 value)
{
BYTE byte;
if (value <= 0x3F)
{
Stream_Write_UINT8(s, value);
}
else if (value <= 0x3FFF)
{
byte = (value >> 8) & 0x3F;
Stream_Write_UINT8(s, byte | 0x40);
byte = (value & 0xFF);
Stream_Write_UINT8(s, byte);
}
else if (value <= 0x3FFFFF)
{
byte = (value >> 16) & 0x3F;
Stream_Write_UINT8(s, byte | 0x80);
byte = (value >> 8) & 0xFF;
Stream_Write_UINT8(s, byte);
byte = (value & 0xFF);
Stream_Write_UINT8(s, byte);
}
else if (value <= 0x3FFFFFFF)
{
byte = (value >> 24) & 0x3F;
Stream_Write_UINT8(s, byte | 0xC0);
byte = (value >> 16) & 0xFF;
Stream_Write_UINT8(s, byte);
byte = (value >> 8) & 0xFF;
Stream_Write_UINT8(s, byte);
byte = (value & 0xFF);
Stream_Write_UINT8(s, byte);
}
else
return FALSE;
return TRUE;
}
static INLINE BOOL update_read_delta(wStream* s, INT32* value)
{
BYTE byte;
if (Stream_GetRemainingLength(s) < 1)
{
WLog_ERR(TAG, "Stream_GetRemainingLength(s) < 1");
return FALSE;
}
Stream_Read_UINT8(s, byte);
if (byte & 0x40)
*value = (byte | ~0x3F);
else
*value = (byte & 0x3F);
if (byte & 0x80)
{
if (Stream_GetRemainingLength(s) < 1)
{
WLog_ERR(TAG, "Stream_GetRemainingLength(s) < 1");
return FALSE;
}
Stream_Read_UINT8(s, byte);
*value = (*value << 8) | byte;
}
return TRUE;
}
#if 0
static INLINE void update_read_glyph_delta(wStream* s, UINT16* value)
{
BYTE byte;
Stream_Read_UINT8(s, byte);
if (byte == 0x80)
Stream_Read_UINT16(s, *value);
else
*value = (byte & 0x3F);
}
static INLINE void update_seek_glyph_delta(wStream* s)
{
BYTE byte;
Stream_Read_UINT8(s, byte);
if (byte & 0x80)
Stream_Seek_UINT8(s);
}
#endif
static INLINE BOOL update_read_brush(wStream* s, rdpBrush* brush, BYTE fieldFlags)
{
if (fieldFlags & ORDER_FIELD_01)
{
if (Stream_GetRemainingLength(s) < 1)
return FALSE;
Stream_Read_UINT8(s, brush->x);
}
if (fieldFlags & ORDER_FIELD_02)
{
if (Stream_GetRemainingLength(s) < 1)
return FALSE;
Stream_Read_UINT8(s, brush->y);
}
if (fieldFlags & ORDER_FIELD_03)
{
if (Stream_GetRemainingLength(s) < 1)
return FALSE;
Stream_Read_UINT8(s, brush->style);
}
if (fieldFlags & ORDER_FIELD_04)
{
if (Stream_GetRemainingLength(s) < 1)
return FALSE;
Stream_Read_UINT8(s, brush->hatch);
}
if (brush->style & CACHED_BRUSH)
{
brush->index = brush->hatch;
brush->bpp = BMF_BPP[brush->style & 0x07];
if (brush->bpp == 0)
brush->bpp = 1;
}
if (fieldFlags & ORDER_FIELD_05)
{
if (Stream_GetRemainingLength(s) < 7)
return FALSE;
brush->data = (BYTE*)brush->p8x8;
Stream_Read_UINT8(s, brush->data[7]);
Stream_Read_UINT8(s, brush->data[6]);
Stream_Read_UINT8(s, brush->data[5]);
Stream_Read_UINT8(s, brush->data[4]);
Stream_Read_UINT8(s, brush->data[3]);
Stream_Read_UINT8(s, brush->data[2]);
Stream_Read_UINT8(s, brush->data[1]);
brush->data[0] = brush->hatch;
}
return TRUE;
}
static INLINE BOOL update_write_brush(wStream* s, rdpBrush* brush, BYTE fieldFlags)
{
if (fieldFlags & ORDER_FIELD_01)
{
Stream_Write_UINT8(s, brush->x);
}
if (fieldFlags & ORDER_FIELD_02)
{
Stream_Write_UINT8(s, brush->y);
}
if (fieldFlags & ORDER_FIELD_03)
{
Stream_Write_UINT8(s, brush->style);
}
if (brush->style & CACHED_BRUSH)
{
brush->hatch = brush->index;
brush->bpp = BMF_BPP[brush->style & 0x07];
if (brush->bpp == 0)
brush->bpp = 1;
}
if (fieldFlags & ORDER_FIELD_04)
{
Stream_Write_UINT8(s, brush->hatch);
}
if (fieldFlags & ORDER_FIELD_05)
{
brush->data = (BYTE*)brush->p8x8;
Stream_Write_UINT8(s, brush->data[7]);
Stream_Write_UINT8(s, brush->data[6]);
Stream_Write_UINT8(s, brush->data[5]);
Stream_Write_UINT8(s, brush->data[4]);
Stream_Write_UINT8(s, brush->data[3]);
Stream_Write_UINT8(s, brush->data[2]);
Stream_Write_UINT8(s, brush->data[1]);
brush->data[0] = brush->hatch;
}
return TRUE;
}
static INLINE BOOL update_read_delta_rects(wStream* s, DELTA_RECT* rectangles, UINT32* nr)
{
UINT32 number = *nr;
UINT32 i;
BYTE flags = 0;
BYTE* zeroBits;
UINT32 zeroBitsSize;
if (number > 45)
{
WLog_WARN(TAG, "Invalid number of delta rectangles %" PRIu32, number);
return FALSE;
}
zeroBitsSize = ((number + 1) / 2);
if (Stream_GetRemainingLength(s) < zeroBitsSize)
return FALSE;
Stream_GetPointer(s, zeroBits);
Stream_Seek(s, zeroBitsSize);
ZeroMemory(rectangles, sizeof(DELTA_RECT) * number);
for (i = 0; i < number; i++)
{
if (i % 2 == 0)
flags = zeroBits[i / 2];
if ((~flags & 0x80) && !update_read_delta(s, &rectangles[i].left))
return FALSE;
if ((~flags & 0x40) && !update_read_delta(s, &rectangles[i].top))
return FALSE;
if (~flags & 0x20)
{
if (!update_read_delta(s, &rectangles[i].width))
return FALSE;
}
else if (i > 0)
rectangles[i].width = rectangles[i - 1].width;
else
rectangles[i].width = 0;
if (~flags & 0x10)
{
if (!update_read_delta(s, &rectangles[i].height))
return FALSE;
}
else if (i > 0)
rectangles[i].height = rectangles[i - 1].height;
else
rectangles[i].height = 0;
if (i > 0)
{
rectangles[i].left += rectangles[i - 1].left;
rectangles[i].top += rectangles[i - 1].top;
}
flags <<= 4;
}
return TRUE;
}
static INLINE BOOL update_read_delta_points(wStream* s, DELTA_POINT* points, int number, INT16 x,
INT16 y)
{
int i;
BYTE flags = 0;
BYTE* zeroBits;
UINT32 zeroBitsSize;
zeroBitsSize = ((number + 3) / 4);
if (Stream_GetRemainingLength(s) < zeroBitsSize)
{
WLog_ERR(TAG, "Stream_GetRemainingLength(s) < %" PRIu32 "", zeroBitsSize);
return FALSE;
}
Stream_GetPointer(s, zeroBits);
Stream_Seek(s, zeroBitsSize);
ZeroMemory(points, sizeof(DELTA_POINT) * number);
for (i = 0; i < number; i++)
{
if (i % 4 == 0)
flags = zeroBits[i / 4];
if ((~flags & 0x80) && !update_read_delta(s, &points[i].x))
{
WLog_ERR(TAG, "update_read_delta(x) failed");
return FALSE;
}
if ((~flags & 0x40) && !update_read_delta(s, &points[i].y))
{
WLog_ERR(TAG, "update_read_delta(y) failed");
return FALSE;
}
flags <<= 2;
}
return TRUE;
}
#define ORDER_FIELD_BYTE(NO, TARGET) \
do \
{ \
if (orderInfo->fieldFlags & (1 << (NO - 1))) \
{ \
if (Stream_GetRemainingLength(s) < 1) \
{ \
WLog_ERR(TAG, "error reading %s", #TARGET); \
return FALSE; \
} \
Stream_Read_UINT8(s, TARGET); \
} \
} while (0)
#define ORDER_FIELD_2BYTE(NO, TARGET1, TARGET2) \
do \
{ \
if (orderInfo->fieldFlags & (1 << (NO - 1))) \
{ \
if (Stream_GetRemainingLength(s) < 2) \
{ \
WLog_ERR(TAG, "error reading %s or %s", #TARGET1, #TARGET2); \
return FALSE; \
} \
Stream_Read_UINT8(s, TARGET1); \
Stream_Read_UINT8(s, TARGET2); \
} \
} while (0)
#define ORDER_FIELD_UINT16(NO, TARGET) \
do \
{ \
if (orderInfo->fieldFlags & (1 << (NO - 1))) \
{ \
if (Stream_GetRemainingLength(s) < 2) \
{ \
WLog_ERR(TAG, "error reading %s", #TARGET); \
return FALSE; \
} \
Stream_Read_UINT16(s, TARGET); \
} \
} while (0)
#define ORDER_FIELD_UINT32(NO, TARGET) \
do \
{ \
if (orderInfo->fieldFlags & (1 << (NO - 1))) \
{ \
if (Stream_GetRemainingLength(s) < 4) \
{ \
WLog_ERR(TAG, "error reading %s", #TARGET); \
return FALSE; \
} \
Stream_Read_UINT32(s, TARGET); \
} \
} while (0)
#define ORDER_FIELD_COORD(NO, TARGET) \
do \
{ \
if ((orderInfo->fieldFlags & (1 << (NO - 1))) && \
!update_read_coord(s, &TARGET, orderInfo->deltaCoordinates)) \
{ \
WLog_ERR(TAG, "error reading %s", #TARGET); \
return FALSE; \
} \
} while (0)
static INLINE BOOL ORDER_FIELD_COLOR(const ORDER_INFO* orderInfo, wStream* s, UINT32 NO,
UINT32* TARGET)
{
if (!TARGET || !orderInfo)
return FALSE;
if ((orderInfo->fieldFlags & (1 << (NO - 1))) && !update_read_color(s, TARGET))
return FALSE;
return TRUE;
}
static INLINE BOOL FIELD_SKIP_BUFFER16(wStream* s, UINT32 TARGET_LEN)
{
if (Stream_GetRemainingLength(s) < 2)
return FALSE;
Stream_Read_UINT16(s, TARGET_LEN);
if (!Stream_SafeSeek(s, TARGET_LEN))
{
WLog_ERR(TAG, "error skipping %" PRIu32 " bytes", TARGET_LEN);
return FALSE;
}
return TRUE;
}
/* Primary Drawing Orders */
static BOOL update_read_dstblt_order(wStream* s, const ORDER_INFO* orderInfo, DSTBLT_ORDER* dstblt)
{
ORDER_FIELD_COORD(1, dstblt->nLeftRect);
ORDER_FIELD_COORD(2, dstblt->nTopRect);
ORDER_FIELD_COORD(3, dstblt->nWidth);
ORDER_FIELD_COORD(4, dstblt->nHeight);
ORDER_FIELD_BYTE(5, dstblt->bRop);
return TRUE;
}
int update_approximate_dstblt_order(ORDER_INFO* orderInfo, const DSTBLT_ORDER* dstblt)
{
return 32;
}
BOOL update_write_dstblt_order(wStream* s, ORDER_INFO* orderInfo, const DSTBLT_ORDER* dstblt)
{
if (!Stream_EnsureRemainingCapacity(s, update_approximate_dstblt_order(orderInfo, dstblt)))
return FALSE;
orderInfo->fieldFlags = 0;
orderInfo->fieldFlags |= ORDER_FIELD_01;
update_write_coord(s, dstblt->nLeftRect);
orderInfo->fieldFlags |= ORDER_FIELD_02;
update_write_coord(s, dstblt->nTopRect);
orderInfo->fieldFlags |= ORDER_FIELD_03;
update_write_coord(s, dstblt->nWidth);
orderInfo->fieldFlags |= ORDER_FIELD_04;
update_write_coord(s, dstblt->nHeight);
orderInfo->fieldFlags |= ORDER_FIELD_05;
Stream_Write_UINT8(s, dstblt->bRop);
return TRUE;
}
static BOOL update_read_patblt_order(wStream* s, const ORDER_INFO* orderInfo, PATBLT_ORDER* patblt)
{
ORDER_FIELD_COORD(1, patblt->nLeftRect);
ORDER_FIELD_COORD(2, patblt->nTopRect);
ORDER_FIELD_COORD(3, patblt->nWidth);
ORDER_FIELD_COORD(4, patblt->nHeight);
ORDER_FIELD_BYTE(5, patblt->bRop);
ORDER_FIELD_COLOR(orderInfo, s, 6, &patblt->backColor);
ORDER_FIELD_COLOR(orderInfo, s, 7, &patblt->foreColor);
return update_read_brush(s, &patblt->brush, orderInfo->fieldFlags >> 7);
}
int update_approximate_patblt_order(ORDER_INFO* orderInfo, PATBLT_ORDER* patblt)
{
return 32;
}
BOOL update_write_patblt_order(wStream* s, ORDER_INFO* orderInfo, PATBLT_ORDER* patblt)
{
if (!Stream_EnsureRemainingCapacity(s, update_approximate_patblt_order(orderInfo, patblt)))
return FALSE;
orderInfo->fieldFlags = 0;
orderInfo->fieldFlags |= ORDER_FIELD_01;
update_write_coord(s, patblt->nLeftRect);
orderInfo->fieldFlags |= ORDER_FIELD_02;
update_write_coord(s, patblt->nTopRect);
orderInfo->fieldFlags |= ORDER_FIELD_03;
update_write_coord(s, patblt->nWidth);
orderInfo->fieldFlags |= ORDER_FIELD_04;
update_write_coord(s, patblt->nHeight);
orderInfo->fieldFlags |= ORDER_FIELD_05;
Stream_Write_UINT8(s, patblt->bRop);
orderInfo->fieldFlags |= ORDER_FIELD_06;
update_write_color(s, patblt->backColor);
orderInfo->fieldFlags |= ORDER_FIELD_07;
update_write_color(s, patblt->foreColor);
orderInfo->fieldFlags |= ORDER_FIELD_08;
orderInfo->fieldFlags |= ORDER_FIELD_09;
orderInfo->fieldFlags |= ORDER_FIELD_10;
orderInfo->fieldFlags |= ORDER_FIELD_11;
orderInfo->fieldFlags |= ORDER_FIELD_12;
update_write_brush(s, &patblt->brush, orderInfo->fieldFlags >> 7);
return TRUE;
}
static BOOL update_read_scrblt_order(wStream* s, const ORDER_INFO* orderInfo, SCRBLT_ORDER* scrblt)
{
ORDER_FIELD_COORD(1, scrblt->nLeftRect);
ORDER_FIELD_COORD(2, scrblt->nTopRect);
ORDER_FIELD_COORD(3, scrblt->nWidth);
ORDER_FIELD_COORD(4, scrblt->nHeight);
ORDER_FIELD_BYTE(5, scrblt->bRop);
ORDER_FIELD_COORD(6, scrblt->nXSrc);
ORDER_FIELD_COORD(7, scrblt->nYSrc);
return TRUE;
}
int update_approximate_scrblt_order(ORDER_INFO* orderInfo, const SCRBLT_ORDER* scrblt)
{
return 32;
}
BOOL update_write_scrblt_order(wStream* s, ORDER_INFO* orderInfo, const SCRBLT_ORDER* scrblt)
{
if (!Stream_EnsureRemainingCapacity(s, update_approximate_scrblt_order(orderInfo, scrblt)))
return FALSE;
orderInfo->fieldFlags = 0;
orderInfo->fieldFlags |= ORDER_FIELD_01;
update_write_coord(s, scrblt->nLeftRect);
orderInfo->fieldFlags |= ORDER_FIELD_02;
update_write_coord(s, scrblt->nTopRect);
orderInfo->fieldFlags |= ORDER_FIELD_03;
update_write_coord(s, scrblt->nWidth);
orderInfo->fieldFlags |= ORDER_FIELD_04;
update_write_coord(s, scrblt->nHeight);
orderInfo->fieldFlags |= ORDER_FIELD_05;
Stream_Write_UINT8(s, scrblt->bRop);
orderInfo->fieldFlags |= ORDER_FIELD_06;
update_write_coord(s, scrblt->nXSrc);
orderInfo->fieldFlags |= ORDER_FIELD_07;
update_write_coord(s, scrblt->nYSrc);
return TRUE;
}
static BOOL update_read_opaque_rect_order(wStream* s, const ORDER_INFO* orderInfo,
OPAQUE_RECT_ORDER* opaque_rect)
{
BYTE byte;
ORDER_FIELD_COORD(1, opaque_rect->nLeftRect);
ORDER_FIELD_COORD(2, opaque_rect->nTopRect);
ORDER_FIELD_COORD(3, opaque_rect->nWidth);
ORDER_FIELD_COORD(4, opaque_rect->nHeight);
if (orderInfo->fieldFlags & ORDER_FIELD_05)
{
if (Stream_GetRemainingLength(s) < 1)
return FALSE;
Stream_Read_UINT8(s, byte);
opaque_rect->color = (opaque_rect->color & 0x00FFFF00) | ((UINT32)byte);
}
if (orderInfo->fieldFlags & ORDER_FIELD_06)
{
if (Stream_GetRemainingLength(s) < 1)
return FALSE;
Stream_Read_UINT8(s, byte);
opaque_rect->color = (opaque_rect->color & 0x00FF00FF) | ((UINT32)byte << 8);
}
if (orderInfo->fieldFlags & ORDER_FIELD_07)
{
if (Stream_GetRemainingLength(s) < 1)
return FALSE;
Stream_Read_UINT8(s, byte);
opaque_rect->color = (opaque_rect->color & 0x0000FFFF) | ((UINT32)byte << 16);
}
return TRUE;
}
int update_approximate_opaque_rect_order(ORDER_INFO* orderInfo,
const OPAQUE_RECT_ORDER* opaque_rect)
{
return 32;
}
BOOL update_write_opaque_rect_order(wStream* s, ORDER_INFO* orderInfo,
const OPAQUE_RECT_ORDER* opaque_rect)
{
BYTE byte;
int inf = update_approximate_opaque_rect_order(orderInfo, opaque_rect);
if (!Stream_EnsureRemainingCapacity(s, inf))
return FALSE;
// TODO: Color format conversion
orderInfo->fieldFlags = 0;
orderInfo->fieldFlags |= ORDER_FIELD_01;
update_write_coord(s, opaque_rect->nLeftRect);
orderInfo->fieldFlags |= ORDER_FIELD_02;
update_write_coord(s, opaque_rect->nTopRect);
orderInfo->fieldFlags |= ORDER_FIELD_03;
update_write_coord(s, opaque_rect->nWidth);
orderInfo->fieldFlags |= ORDER_FIELD_04;
update_write_coord(s, opaque_rect->nHeight);
orderInfo->fieldFlags |= ORDER_FIELD_05;
byte = opaque_rect->color & 0x000000FF;
Stream_Write_UINT8(s, byte);
orderInfo->fieldFlags |= ORDER_FIELD_06;
byte = (opaque_rect->color & 0x0000FF00) >> 8;
Stream_Write_UINT8(s, byte);
orderInfo->fieldFlags |= ORDER_FIELD_07;
byte = (opaque_rect->color & 0x00FF0000) >> 16;
Stream_Write_UINT8(s, byte);
return TRUE;
}
static BOOL update_read_draw_nine_grid_order(wStream* s, const ORDER_INFO* orderInfo,
DRAW_NINE_GRID_ORDER* draw_nine_grid)
{
ORDER_FIELD_COORD(1, draw_nine_grid->srcLeft);
ORDER_FIELD_COORD(2, draw_nine_grid->srcTop);
ORDER_FIELD_COORD(3, draw_nine_grid->srcRight);
ORDER_FIELD_COORD(4, draw_nine_grid->srcBottom);
ORDER_FIELD_UINT16(5, draw_nine_grid->bitmapId);
return TRUE;
}
static BOOL update_read_multi_dstblt_order(wStream* s, const ORDER_INFO* orderInfo,
MULTI_DSTBLT_ORDER* multi_dstblt)
{
ORDER_FIELD_COORD(1, multi_dstblt->nLeftRect);
ORDER_FIELD_COORD(2, multi_dstblt->nTopRect);
ORDER_FIELD_COORD(3, multi_dstblt->nWidth);
ORDER_FIELD_COORD(4, multi_dstblt->nHeight);
ORDER_FIELD_BYTE(5, multi_dstblt->bRop);
ORDER_FIELD_BYTE(6, multi_dstblt->numRectangles);
if (orderInfo->fieldFlags & ORDER_FIELD_07)
{
if (Stream_GetRemainingLength(s) < 2)
return FALSE;
Stream_Read_UINT16(s, multi_dstblt->cbData);
return update_read_delta_rects(s, multi_dstblt->rectangles, &multi_dstblt->numRectangles);
}
return TRUE;
}
static BOOL update_read_multi_patblt_order(wStream* s, const ORDER_INFO* orderInfo,
MULTI_PATBLT_ORDER* multi_patblt)
{
ORDER_FIELD_COORD(1, multi_patblt->nLeftRect);
ORDER_FIELD_COORD(2, multi_patblt->nTopRect);
ORDER_FIELD_COORD(3, multi_patblt->nWidth);
ORDER_FIELD_COORD(4, multi_patblt->nHeight);
ORDER_FIELD_BYTE(5, multi_patblt->bRop);
ORDER_FIELD_COLOR(orderInfo, s, 6, &multi_patblt->backColor);
ORDER_FIELD_COLOR(orderInfo, s, 7, &multi_patblt->foreColor);
if (!update_read_brush(s, &multi_patblt->brush, orderInfo->fieldFlags >> 7))
return FALSE;
ORDER_FIELD_BYTE(13, multi_patblt->numRectangles);
if (orderInfo->fieldFlags & ORDER_FIELD_14)
{
if (Stream_GetRemainingLength(s) < 2)
return FALSE;
Stream_Read_UINT16(s, multi_patblt->cbData);
if (!update_read_delta_rects(s, multi_patblt->rectangles, &multi_patblt->numRectangles))
return FALSE;
}
return TRUE;
}
static BOOL update_read_multi_scrblt_order(wStream* s, const ORDER_INFO* orderInfo,
MULTI_SCRBLT_ORDER* multi_scrblt)
{
ORDER_FIELD_COORD(1, multi_scrblt->nLeftRect);
ORDER_FIELD_COORD(2, multi_scrblt->nTopRect);
ORDER_FIELD_COORD(3, multi_scrblt->nWidth);
ORDER_FIELD_COORD(4, multi_scrblt->nHeight);
ORDER_FIELD_BYTE(5, multi_scrblt->bRop);
ORDER_FIELD_COORD(6, multi_scrblt->nXSrc);
ORDER_FIELD_COORD(7, multi_scrblt->nYSrc);
ORDER_FIELD_BYTE(8, multi_scrblt->numRectangles);
if (orderInfo->fieldFlags & ORDER_FIELD_09)
{
if (Stream_GetRemainingLength(s) < 2)
return FALSE;
Stream_Read_UINT16(s, multi_scrblt->cbData);
return update_read_delta_rects(s, multi_scrblt->rectangles, &multi_scrblt->numRectangles);
}
return TRUE;
}
static BOOL update_read_multi_opaque_rect_order(wStream* s, const ORDER_INFO* orderInfo,
MULTI_OPAQUE_RECT_ORDER* multi_opaque_rect)
{
BYTE byte;
ORDER_FIELD_COORD(1, multi_opaque_rect->nLeftRect);
ORDER_FIELD_COORD(2, multi_opaque_rect->nTopRect);
ORDER_FIELD_COORD(3, multi_opaque_rect->nWidth);
ORDER_FIELD_COORD(4, multi_opaque_rect->nHeight);
if (orderInfo->fieldFlags & ORDER_FIELD_05)
{
if (Stream_GetRemainingLength(s) < 1)
return FALSE;
Stream_Read_UINT8(s, byte);
multi_opaque_rect->color = (multi_opaque_rect->color & 0x00FFFF00) | ((UINT32)byte);
}
if (orderInfo->fieldFlags & ORDER_FIELD_06)
{
if (Stream_GetRemainingLength(s) < 1)
return FALSE;
Stream_Read_UINT8(s, byte);
multi_opaque_rect->color = (multi_opaque_rect->color & 0x00FF00FF) | ((UINT32)byte << 8);
}
if (orderInfo->fieldFlags & ORDER_FIELD_07)
{
if (Stream_GetRemainingLength(s) < 1)
return FALSE;
Stream_Read_UINT8(s, byte);
multi_opaque_rect->color = (multi_opaque_rect->color & 0x0000FFFF) | ((UINT32)byte << 16);
}
ORDER_FIELD_BYTE(8, multi_opaque_rect->numRectangles);
if (orderInfo->fieldFlags & ORDER_FIELD_09)
{
if (Stream_GetRemainingLength(s) < 2)
return FALSE;
Stream_Read_UINT16(s, multi_opaque_rect->cbData);
return update_read_delta_rects(s, multi_opaque_rect->rectangles,
&multi_opaque_rect->numRectangles);
}
return TRUE;
}
static BOOL update_read_multi_draw_nine_grid_order(wStream* s, const ORDER_INFO* orderInfo,
MULTI_DRAW_NINE_GRID_ORDER* multi_draw_nine_grid)
{
ORDER_FIELD_COORD(1, multi_draw_nine_grid->srcLeft);
ORDER_FIELD_COORD(2, multi_draw_nine_grid->srcTop);
ORDER_FIELD_COORD(3, multi_draw_nine_grid->srcRight);
ORDER_FIELD_COORD(4, multi_draw_nine_grid->srcBottom);
ORDER_FIELD_UINT16(5, multi_draw_nine_grid->bitmapId);
ORDER_FIELD_BYTE(6, multi_draw_nine_grid->nDeltaEntries);
if (orderInfo->fieldFlags & ORDER_FIELD_07)
{
if (Stream_GetRemainingLength(s) < 2)
return FALSE;
Stream_Read_UINT16(s, multi_draw_nine_grid->cbData);
return update_read_delta_rects(s, multi_draw_nine_grid->rectangles,
&multi_draw_nine_grid->nDeltaEntries);
}
return TRUE;
}
static BOOL update_read_line_to_order(wStream* s, const ORDER_INFO* orderInfo,
LINE_TO_ORDER* line_to)
{
ORDER_FIELD_UINT16(1, line_to->backMode);
ORDER_FIELD_COORD(2, line_to->nXStart);
ORDER_FIELD_COORD(3, line_to->nYStart);
ORDER_FIELD_COORD(4, line_to->nXEnd);
ORDER_FIELD_COORD(5, line_to->nYEnd);
ORDER_FIELD_COLOR(orderInfo, s, 6, &line_to->backColor);
ORDER_FIELD_BYTE(7, line_to->bRop2);
ORDER_FIELD_BYTE(8, line_to->penStyle);
ORDER_FIELD_BYTE(9, line_to->penWidth);
ORDER_FIELD_COLOR(orderInfo, s, 10, &line_to->penColor);
return TRUE;
}
int update_approximate_line_to_order(ORDER_INFO* orderInfo, const LINE_TO_ORDER* line_to)
{
return 32;
}
BOOL update_write_line_to_order(wStream* s, ORDER_INFO* orderInfo, const LINE_TO_ORDER* line_to)
{
if (!Stream_EnsureRemainingCapacity(s, update_approximate_line_to_order(orderInfo, line_to)))
return FALSE;
orderInfo->fieldFlags = 0;
orderInfo->fieldFlags |= ORDER_FIELD_01;
Stream_Write_UINT16(s, line_to->backMode);
orderInfo->fieldFlags |= ORDER_FIELD_02;
update_write_coord(s, line_to->nXStart);
orderInfo->fieldFlags |= ORDER_FIELD_03;
update_write_coord(s, line_to->nYStart);
orderInfo->fieldFlags |= ORDER_FIELD_04;
update_write_coord(s, line_to->nXEnd);
orderInfo->fieldFlags |= ORDER_FIELD_05;
update_write_coord(s, line_to->nYEnd);
orderInfo->fieldFlags |= ORDER_FIELD_06;
update_write_color(s, line_to->backColor);
orderInfo->fieldFlags |= ORDER_FIELD_07;
Stream_Write_UINT8(s, line_to->bRop2);
orderInfo->fieldFlags |= ORDER_FIELD_08;
Stream_Write_UINT8(s, line_to->penStyle);
orderInfo->fieldFlags |= ORDER_FIELD_09;
Stream_Write_UINT8(s, line_to->penWidth);
orderInfo->fieldFlags |= ORDER_FIELD_10;
update_write_color(s, line_to->penColor);
return TRUE;
}
static BOOL update_read_polyline_order(wStream* s, const ORDER_INFO* orderInfo,
POLYLINE_ORDER* polyline)
{
UINT16 word;
UINT32 new_num = polyline->numDeltaEntries;
ORDER_FIELD_COORD(1, polyline->xStart);
ORDER_FIELD_COORD(2, polyline->yStart);
ORDER_FIELD_BYTE(3, polyline->bRop2);
ORDER_FIELD_UINT16(4, word);
ORDER_FIELD_COLOR(orderInfo, s, 5, &polyline->penColor);
ORDER_FIELD_BYTE(6, new_num);
if (orderInfo->fieldFlags & ORDER_FIELD_07)
{
DELTA_POINT* new_points;
if (new_num == 0)
return FALSE;
if (Stream_GetRemainingLength(s) < 1)
{
WLog_ERR(TAG, "Stream_GetRemainingLength(s) < 1");
return FALSE;
}
Stream_Read_UINT8(s, polyline->cbData);
new_points = (DELTA_POINT*)realloc(polyline->points, sizeof(DELTA_POINT) * new_num);
if (!new_points)
{
WLog_ERR(TAG, "realloc(%" PRIu32 ") failed", new_num);
return FALSE;
}
polyline->points = new_points;
polyline->numDeltaEntries = new_num;
return update_read_delta_points(s, polyline->points, polyline->numDeltaEntries,
polyline->xStart, polyline->yStart);
}
return TRUE;
}
static BOOL update_read_memblt_order(wStream* s, const ORDER_INFO* orderInfo, MEMBLT_ORDER* memblt)
{
if (!s || !orderInfo || !memblt)
return FALSE;
ORDER_FIELD_UINT16(1, memblt->cacheId);
ORDER_FIELD_COORD(2, memblt->nLeftRect);
ORDER_FIELD_COORD(3, memblt->nTopRect);
ORDER_FIELD_COORD(4, memblt->nWidth);
ORDER_FIELD_COORD(5, memblt->nHeight);
ORDER_FIELD_BYTE(6, memblt->bRop);
ORDER_FIELD_COORD(7, memblt->nXSrc);
ORDER_FIELD_COORD(8, memblt->nYSrc);
ORDER_FIELD_UINT16(9, memblt->cacheIndex);
memblt->colorIndex = (memblt->cacheId >> 8);
memblt->cacheId = (memblt->cacheId & 0xFF);
memblt->bitmap = NULL;
return TRUE;
}
int update_approximate_memblt_order(ORDER_INFO* orderInfo, const MEMBLT_ORDER* memblt)
{
return 64;
}
BOOL update_write_memblt_order(wStream* s, ORDER_INFO* orderInfo, const MEMBLT_ORDER* memblt)
{
UINT16 cacheId;
if (!Stream_EnsureRemainingCapacity(s, update_approximate_memblt_order(orderInfo, memblt)))
return FALSE;
cacheId = (memblt->cacheId & 0xFF) | ((memblt->colorIndex & 0xFF) << 8);
orderInfo->fieldFlags |= ORDER_FIELD_01;
Stream_Write_UINT16(s, cacheId);
orderInfo->fieldFlags |= ORDER_FIELD_02;
update_write_coord(s, memblt->nLeftRect);
orderInfo->fieldFlags |= ORDER_FIELD_03;
update_write_coord(s, memblt->nTopRect);
orderInfo->fieldFlags |= ORDER_FIELD_04;
update_write_coord(s, memblt->nWidth);
orderInfo->fieldFlags |= ORDER_FIELD_05;
update_write_coord(s, memblt->nHeight);
orderInfo->fieldFlags |= ORDER_FIELD_06;
Stream_Write_UINT8(s, memblt->bRop);
orderInfo->fieldFlags |= ORDER_FIELD_07;
update_write_coord(s, memblt->nXSrc);
orderInfo->fieldFlags |= ORDER_FIELD_08;
update_write_coord(s, memblt->nYSrc);
orderInfo->fieldFlags |= ORDER_FIELD_09;
Stream_Write_UINT16(s, memblt->cacheIndex);
return TRUE;
}
static BOOL update_read_mem3blt_order(wStream* s, const ORDER_INFO* orderInfo,
MEM3BLT_ORDER* mem3blt)
{
ORDER_FIELD_UINT16(1, mem3blt->cacheId);
ORDER_FIELD_COORD(2, mem3blt->nLeftRect);
ORDER_FIELD_COORD(3, mem3blt->nTopRect);
ORDER_FIELD_COORD(4, mem3blt->nWidth);
ORDER_FIELD_COORD(5, mem3blt->nHeight);
ORDER_FIELD_BYTE(6, mem3blt->bRop);
ORDER_FIELD_COORD(7, mem3blt->nXSrc);
ORDER_FIELD_COORD(8, mem3blt->nYSrc);
ORDER_FIELD_COLOR(orderInfo, s, 9, &mem3blt->backColor);
ORDER_FIELD_COLOR(orderInfo, s, 10, &mem3blt->foreColor);
if (!update_read_brush(s, &mem3blt->brush, orderInfo->fieldFlags >> 10))
return FALSE;
ORDER_FIELD_UINT16(16, mem3blt->cacheIndex);
mem3blt->colorIndex = (mem3blt->cacheId >> 8);
mem3blt->cacheId = (mem3blt->cacheId & 0xFF);
mem3blt->bitmap = NULL;
return TRUE;
}
static BOOL update_read_save_bitmap_order(wStream* s, const ORDER_INFO* orderInfo,
SAVE_BITMAP_ORDER* save_bitmap)
{
ORDER_FIELD_UINT32(1, save_bitmap->savedBitmapPosition);
ORDER_FIELD_COORD(2, save_bitmap->nLeftRect);
ORDER_FIELD_COORD(3, save_bitmap->nTopRect);
ORDER_FIELD_COORD(4, save_bitmap->nRightRect);
ORDER_FIELD_COORD(5, save_bitmap->nBottomRect);
ORDER_FIELD_BYTE(6, save_bitmap->operation);
return TRUE;
}
static BOOL update_read_glyph_index_order(wStream* s, const ORDER_INFO* orderInfo,
GLYPH_INDEX_ORDER* glyph_index)
{
ORDER_FIELD_BYTE(1, glyph_index->cacheId);
ORDER_FIELD_BYTE(2, glyph_index->flAccel);
ORDER_FIELD_BYTE(3, glyph_index->ulCharInc);
ORDER_FIELD_BYTE(4, glyph_index->fOpRedundant);
ORDER_FIELD_COLOR(orderInfo, s, 5, &glyph_index->backColor);
ORDER_FIELD_COLOR(orderInfo, s, 6, &glyph_index->foreColor);
ORDER_FIELD_UINT16(7, glyph_index->bkLeft);
ORDER_FIELD_UINT16(8, glyph_index->bkTop);
ORDER_FIELD_UINT16(9, glyph_index->bkRight);
ORDER_FIELD_UINT16(10, glyph_index->bkBottom);
ORDER_FIELD_UINT16(11, glyph_index->opLeft);
ORDER_FIELD_UINT16(12, glyph_index->opTop);
ORDER_FIELD_UINT16(13, glyph_index->opRight);
ORDER_FIELD_UINT16(14, glyph_index->opBottom);
if (!update_read_brush(s, &glyph_index->brush, orderInfo->fieldFlags >> 14))
return FALSE;
ORDER_FIELD_UINT16(20, glyph_index->x);
ORDER_FIELD_UINT16(21, glyph_index->y);
if (orderInfo->fieldFlags & ORDER_FIELD_22)
{
if (Stream_GetRemainingLength(s) < 1)
return FALSE;
Stream_Read_UINT8(s, glyph_index->cbData);
if (Stream_GetRemainingLength(s) < glyph_index->cbData)
return FALSE;
CopyMemory(glyph_index->data, Stream_Pointer(s), glyph_index->cbData);
Stream_Seek(s, glyph_index->cbData);
}
return TRUE;
}
int update_approximate_glyph_index_order(ORDER_INFO* orderInfo,
const GLYPH_INDEX_ORDER* glyph_index)
{
return 64;
}
BOOL update_write_glyph_index_order(wStream* s, ORDER_INFO* orderInfo,
GLYPH_INDEX_ORDER* glyph_index)
{
int inf = update_approximate_glyph_index_order(orderInfo, glyph_index);
if (!Stream_EnsureRemainingCapacity(s, inf))
return FALSE;
orderInfo->fieldFlags = 0;
orderInfo->fieldFlags |= ORDER_FIELD_01;
Stream_Write_UINT8(s, glyph_index->cacheId);
orderInfo->fieldFlags |= ORDER_FIELD_02;
Stream_Write_UINT8(s, glyph_index->flAccel);
orderInfo->fieldFlags |= ORDER_FIELD_03;
Stream_Write_UINT8(s, glyph_index->ulCharInc);
orderInfo->fieldFlags |= ORDER_FIELD_04;
Stream_Write_UINT8(s, glyph_index->fOpRedundant);
orderInfo->fieldFlags |= ORDER_FIELD_05;
update_write_color(s, glyph_index->backColor);
orderInfo->fieldFlags |= ORDER_FIELD_06;
update_write_color(s, glyph_index->foreColor);
orderInfo->fieldFlags |= ORDER_FIELD_07;
Stream_Write_UINT16(s, glyph_index->bkLeft);
orderInfo->fieldFlags |= ORDER_FIELD_08;
Stream_Write_UINT16(s, glyph_index->bkTop);
orderInfo->fieldFlags |= ORDER_FIELD_09;
Stream_Write_UINT16(s, glyph_index->bkRight);
orderInfo->fieldFlags |= ORDER_FIELD_10;
Stream_Write_UINT16(s, glyph_index->bkBottom);
orderInfo->fieldFlags |= ORDER_FIELD_11;
Stream_Write_UINT16(s, glyph_index->opLeft);
orderInfo->fieldFlags |= ORDER_FIELD_12;
Stream_Write_UINT16(s, glyph_index->opTop);
orderInfo->fieldFlags |= ORDER_FIELD_13;
Stream_Write_UINT16(s, glyph_index->opRight);
orderInfo->fieldFlags |= ORDER_FIELD_14;
Stream_Write_UINT16(s, glyph_index->opBottom);
orderInfo->fieldFlags |= ORDER_FIELD_15;
orderInfo->fieldFlags |= ORDER_FIELD_16;
orderInfo->fieldFlags |= ORDER_FIELD_17;
orderInfo->fieldFlags |= ORDER_FIELD_18;
orderInfo->fieldFlags |= ORDER_FIELD_19;
update_write_brush(s, &glyph_index->brush, orderInfo->fieldFlags >> 14);
orderInfo->fieldFlags |= ORDER_FIELD_20;
Stream_Write_UINT16(s, glyph_index->x);
orderInfo->fieldFlags |= ORDER_FIELD_21;
Stream_Write_UINT16(s, glyph_index->y);
orderInfo->fieldFlags |= ORDER_FIELD_22;
Stream_Write_UINT8(s, glyph_index->cbData);
Stream_Write(s, glyph_index->data, glyph_index->cbData);
return TRUE;
}
static BOOL update_read_fast_index_order(wStream* s, const ORDER_INFO* orderInfo,
FAST_INDEX_ORDER* fast_index)
{
ORDER_FIELD_BYTE(1, fast_index->cacheId);
ORDER_FIELD_2BYTE(2, fast_index->ulCharInc, fast_index->flAccel);
ORDER_FIELD_COLOR(orderInfo, s, 3, &fast_index->backColor);
ORDER_FIELD_COLOR(orderInfo, s, 4, &fast_index->foreColor);
ORDER_FIELD_COORD(5, fast_index->bkLeft);
ORDER_FIELD_COORD(6, fast_index->bkTop);
ORDER_FIELD_COORD(7, fast_index->bkRight);
ORDER_FIELD_COORD(8, fast_index->bkBottom);
ORDER_FIELD_COORD(9, fast_index->opLeft);
ORDER_FIELD_COORD(10, fast_index->opTop);
ORDER_FIELD_COORD(11, fast_index->opRight);
ORDER_FIELD_COORD(12, fast_index->opBottom);
ORDER_FIELD_COORD(13, fast_index->x);
ORDER_FIELD_COORD(14, fast_index->y);
if (orderInfo->fieldFlags & ORDER_FIELD_15)
{
if (Stream_GetRemainingLength(s) < 1)
return FALSE;
Stream_Read_UINT8(s, fast_index->cbData);
if (Stream_GetRemainingLength(s) < fast_index->cbData)
return FALSE;
CopyMemory(fast_index->data, Stream_Pointer(s), fast_index->cbData);
Stream_Seek(s, fast_index->cbData);
}
return TRUE;
}
static BOOL update_read_fast_glyph_order(wStream* s, const ORDER_INFO* orderInfo,
FAST_GLYPH_ORDER* fastGlyph)
{
GLYPH_DATA_V2* glyph = &fastGlyph->glyphData;
ORDER_FIELD_BYTE(1, fastGlyph->cacheId);
ORDER_FIELD_2BYTE(2, fastGlyph->ulCharInc, fastGlyph->flAccel);
ORDER_FIELD_COLOR(orderInfo, s, 3, &fastGlyph->backColor);
ORDER_FIELD_COLOR(orderInfo, s, 4, &fastGlyph->foreColor);
ORDER_FIELD_COORD(5, fastGlyph->bkLeft);
ORDER_FIELD_COORD(6, fastGlyph->bkTop);
ORDER_FIELD_COORD(7, fastGlyph->bkRight);
ORDER_FIELD_COORD(8, fastGlyph->bkBottom);
ORDER_FIELD_COORD(9, fastGlyph->opLeft);
ORDER_FIELD_COORD(10, fastGlyph->opTop);
ORDER_FIELD_COORD(11, fastGlyph->opRight);
ORDER_FIELD_COORD(12, fastGlyph->opBottom);
ORDER_FIELD_COORD(13, fastGlyph->x);
ORDER_FIELD_COORD(14, fastGlyph->y);
if (orderInfo->fieldFlags & ORDER_FIELD_15)
{
if (Stream_GetRemainingLength(s) < 1)
return FALSE;
Stream_Read_UINT8(s, fastGlyph->cbData);
if (Stream_GetRemainingLength(s) < fastGlyph->cbData)
return FALSE;
CopyMemory(fastGlyph->data, Stream_Pointer(s), fastGlyph->cbData);
if (Stream_GetRemainingLength(s) < fastGlyph->cbData)
return FALSE;
if (!Stream_SafeSeek(s, 1))
return FALSE;
if (fastGlyph->cbData > 1)
{
UINT32 new_cb;
/* parse optional glyph data */
glyph->cacheIndex = fastGlyph->data[0];
if (!update_read_2byte_signed(s, &glyph->x) ||
!update_read_2byte_signed(s, &glyph->y) ||
!update_read_2byte_unsigned(s, &glyph->cx) ||
!update_read_2byte_unsigned(s, &glyph->cy))
return FALSE;
glyph->cb = ((glyph->cx + 7) / 8) * glyph->cy;
glyph->cb += ((glyph->cb % 4) > 0) ? 4 - (glyph->cb % 4) : 0;
new_cb = ((glyph->cx + 7) / 8) * glyph->cy;
new_cb += ((new_cb % 4) > 0) ? 4 - (new_cb % 4) : 0;
if (fastGlyph->cbData < new_cb)
return FALSE;
if (new_cb > 0)
{
BYTE* new_aj;
new_aj = (BYTE*)realloc(glyph->aj, new_cb);
if (!new_aj)
return FALSE;
glyph->aj = new_aj;
glyph->cb = new_cb;
Stream_Read(s, glyph->aj, glyph->cb);
}
Stream_Seek(s, fastGlyph->cbData - new_cb);
}
}
return TRUE;
}
static BOOL update_read_polygon_sc_order(wStream* s, const ORDER_INFO* orderInfo,
POLYGON_SC_ORDER* polygon_sc)
{
UINT32 num = polygon_sc->numPoints;
ORDER_FIELD_COORD(1, polygon_sc->xStart);
ORDER_FIELD_COORD(2, polygon_sc->yStart);
ORDER_FIELD_BYTE(3, polygon_sc->bRop2);
ORDER_FIELD_BYTE(4, polygon_sc->fillMode);
ORDER_FIELD_COLOR(orderInfo, s, 5, &polygon_sc->brushColor);
ORDER_FIELD_BYTE(6, num);
if (orderInfo->fieldFlags & ORDER_FIELD_07)
{
DELTA_POINT* newpoints;
if (num == 0)
return FALSE;
if (Stream_GetRemainingLength(s) < 1)
return FALSE;
Stream_Read_UINT8(s, polygon_sc->cbData);
newpoints = (DELTA_POINT*)realloc(polygon_sc->points, sizeof(DELTA_POINT) * num);
if (!newpoints)
return FALSE;
polygon_sc->points = newpoints;
polygon_sc->numPoints = num;
return update_read_delta_points(s, polygon_sc->points, polygon_sc->numPoints,
polygon_sc->xStart, polygon_sc->yStart);
}
return TRUE;
}
static BOOL update_read_polygon_cb_order(wStream* s, const ORDER_INFO* orderInfo,
POLYGON_CB_ORDER* polygon_cb)
{
UINT32 num = polygon_cb->numPoints;
ORDER_FIELD_COORD(1, polygon_cb->xStart);
ORDER_FIELD_COORD(2, polygon_cb->yStart);
ORDER_FIELD_BYTE(3, polygon_cb->bRop2);
ORDER_FIELD_BYTE(4, polygon_cb->fillMode);
ORDER_FIELD_COLOR(orderInfo, s, 5, &polygon_cb->backColor);
ORDER_FIELD_COLOR(orderInfo, s, 6, &polygon_cb->foreColor);
if (!update_read_brush(s, &polygon_cb->brush, orderInfo->fieldFlags >> 6))
return FALSE;
ORDER_FIELD_BYTE(12, num);
if (orderInfo->fieldFlags & ORDER_FIELD_13)
{
DELTA_POINT* newpoints;
if (num == 0)
return FALSE;
if (Stream_GetRemainingLength(s) < 1)
return FALSE;
Stream_Read_UINT8(s, polygon_cb->cbData);
newpoints = (DELTA_POINT*)realloc(polygon_cb->points, sizeof(DELTA_POINT) * num);
if (!newpoints)
return FALSE;
polygon_cb->points = newpoints;
polygon_cb->numPoints = num;
if (!update_read_delta_points(s, polygon_cb->points, polygon_cb->numPoints,
polygon_cb->xStart, polygon_cb->yStart))
return FALSE;
}
polygon_cb->backMode = (polygon_cb->bRop2 & 0x80) ? BACKMODE_TRANSPARENT : BACKMODE_OPAQUE;
polygon_cb->bRop2 = (polygon_cb->bRop2 & 0x1F);
return TRUE;
}
static BOOL update_read_ellipse_sc_order(wStream* s, const ORDER_INFO* orderInfo,
ELLIPSE_SC_ORDER* ellipse_sc)
{
ORDER_FIELD_COORD(1, ellipse_sc->leftRect);
ORDER_FIELD_COORD(2, ellipse_sc->topRect);
ORDER_FIELD_COORD(3, ellipse_sc->rightRect);
ORDER_FIELD_COORD(4, ellipse_sc->bottomRect);
ORDER_FIELD_BYTE(5, ellipse_sc->bRop2);
ORDER_FIELD_BYTE(6, ellipse_sc->fillMode);
ORDER_FIELD_COLOR(orderInfo, s, 7, &ellipse_sc->color);
return TRUE;
}
static BOOL update_read_ellipse_cb_order(wStream* s, const ORDER_INFO* orderInfo,
ELLIPSE_CB_ORDER* ellipse_cb)
{
ORDER_FIELD_COORD(1, ellipse_cb->leftRect);
ORDER_FIELD_COORD(2, ellipse_cb->topRect);
ORDER_FIELD_COORD(3, ellipse_cb->rightRect);
ORDER_FIELD_COORD(4, ellipse_cb->bottomRect);
ORDER_FIELD_BYTE(5, ellipse_cb->bRop2);
ORDER_FIELD_BYTE(6, ellipse_cb->fillMode);
ORDER_FIELD_COLOR(orderInfo, s, 7, &ellipse_cb->backColor);
ORDER_FIELD_COLOR(orderInfo, s, 8, &ellipse_cb->foreColor);
return update_read_brush(s, &ellipse_cb->brush, orderInfo->fieldFlags >> 8);
}
/* Secondary Drawing Orders */
static CACHE_BITMAP_ORDER* update_read_cache_bitmap_order(rdpUpdate* update, wStream* s,
BOOL compressed, UINT16 flags)
{
CACHE_BITMAP_ORDER* cache_bitmap;
if (!update || !s)
return NULL;
cache_bitmap = calloc(1, sizeof(CACHE_BITMAP_ORDER));
if (!cache_bitmap)
goto fail;
if (Stream_GetRemainingLength(s) < 9)
goto fail;
Stream_Read_UINT8(s, cache_bitmap->cacheId); /* cacheId (1 byte) */
Stream_Seek_UINT8(s); /* pad1Octet (1 byte) */
Stream_Read_UINT8(s, cache_bitmap->bitmapWidth); /* bitmapWidth (1 byte) */
Stream_Read_UINT8(s, cache_bitmap->bitmapHeight); /* bitmapHeight (1 byte) */
Stream_Read_UINT8(s, cache_bitmap->bitmapBpp); /* bitmapBpp (1 byte) */
if ((cache_bitmap->bitmapBpp < 1) || (cache_bitmap->bitmapBpp > 32))
{
WLog_Print(update->log, WLOG_ERROR, "invalid bitmap bpp %" PRIu32 "",
cache_bitmap->bitmapBpp);
goto fail;
}
Stream_Read_UINT16(s, cache_bitmap->bitmapLength); /* bitmapLength (2 bytes) */
Stream_Read_UINT16(s, cache_bitmap->cacheIndex); /* cacheIndex (2 bytes) */
if (compressed)
{
if ((flags & NO_BITMAP_COMPRESSION_HDR) == 0)
{
BYTE* bitmapComprHdr = (BYTE*)&(cache_bitmap->bitmapComprHdr);
if (Stream_GetRemainingLength(s) < 8)
goto fail;
Stream_Read(s, bitmapComprHdr, 8); /* bitmapComprHdr (8 bytes) */
cache_bitmap->bitmapLength -= 8;
}
}
if (cache_bitmap->bitmapLength == 0)
goto fail;
if (Stream_GetRemainingLength(s) < cache_bitmap->bitmapLength)
goto fail;
cache_bitmap->bitmapDataStream = malloc(cache_bitmap->bitmapLength);
if (!cache_bitmap->bitmapDataStream)
goto fail;
Stream_Read(s, cache_bitmap->bitmapDataStream, cache_bitmap->bitmapLength);
cache_bitmap->compressed = compressed;
return cache_bitmap;
fail:
free_cache_bitmap_order(update->context, cache_bitmap);
return NULL;
}
int update_approximate_cache_bitmap_order(const CACHE_BITMAP_ORDER* cache_bitmap, BOOL compressed,
UINT16* flags)
{
return 64 + cache_bitmap->bitmapLength;
}
BOOL update_write_cache_bitmap_order(wStream* s, const CACHE_BITMAP_ORDER* cache_bitmap,
BOOL compressed, UINT16* flags)
{
UINT32 bitmapLength = cache_bitmap->bitmapLength;
int inf = update_approximate_cache_bitmap_order(cache_bitmap, compressed, flags);
if (!Stream_EnsureRemainingCapacity(s, inf))
return FALSE;
*flags = NO_BITMAP_COMPRESSION_HDR;
if ((*flags & NO_BITMAP_COMPRESSION_HDR) == 0)
bitmapLength += 8;
Stream_Write_UINT8(s, cache_bitmap->cacheId); /* cacheId (1 byte) */
Stream_Write_UINT8(s, 0); /* pad1Octet (1 byte) */
Stream_Write_UINT8(s, cache_bitmap->bitmapWidth); /* bitmapWidth (1 byte) */
Stream_Write_UINT8(s, cache_bitmap->bitmapHeight); /* bitmapHeight (1 byte) */
Stream_Write_UINT8(s, cache_bitmap->bitmapBpp); /* bitmapBpp (1 byte) */
Stream_Write_UINT16(s, bitmapLength); /* bitmapLength (2 bytes) */
Stream_Write_UINT16(s, cache_bitmap->cacheIndex); /* cacheIndex (2 bytes) */
if (compressed)
{
if ((*flags & NO_BITMAP_COMPRESSION_HDR) == 0)
{
BYTE* bitmapComprHdr = (BYTE*)&(cache_bitmap->bitmapComprHdr);
Stream_Write(s, bitmapComprHdr, 8); /* bitmapComprHdr (8 bytes) */
bitmapLength -= 8;
}
Stream_Write(s, cache_bitmap->bitmapDataStream, bitmapLength);
}
else
{
Stream_Write(s, cache_bitmap->bitmapDataStream, bitmapLength);
}
return TRUE;
}
static CACHE_BITMAP_V2_ORDER* update_read_cache_bitmap_v2_order(rdpUpdate* update, wStream* s,
BOOL compressed, UINT16 flags)
{
BYTE bitsPerPixelId;
CACHE_BITMAP_V2_ORDER* cache_bitmap_v2;
if (!update || !s)
return NULL;
cache_bitmap_v2 = calloc(1, sizeof(CACHE_BITMAP_V2_ORDER));
if (!cache_bitmap_v2)
goto fail;
cache_bitmap_v2->cacheId = flags & 0x0003;
cache_bitmap_v2->flags = (flags & 0xFF80) >> 7;
bitsPerPixelId = (flags & 0x0078) >> 3;
cache_bitmap_v2->bitmapBpp = CBR2_BPP[bitsPerPixelId];
if (cache_bitmap_v2->flags & CBR2_PERSISTENT_KEY_PRESENT)
{
if (Stream_GetRemainingLength(s) < 8)
goto fail;
Stream_Read_UINT32(s, cache_bitmap_v2->key1); /* key1 (4 bytes) */
Stream_Read_UINT32(s, cache_bitmap_v2->key2); /* key2 (4 bytes) */
}
if (cache_bitmap_v2->flags & CBR2_HEIGHT_SAME_AS_WIDTH)
{
if (!update_read_2byte_unsigned(s, &cache_bitmap_v2->bitmapWidth)) /* bitmapWidth */
goto fail;
cache_bitmap_v2->bitmapHeight = cache_bitmap_v2->bitmapWidth;
}
else
{
if (!update_read_2byte_unsigned(s, &cache_bitmap_v2->bitmapWidth) || /* bitmapWidth */
!update_read_2byte_unsigned(s, &cache_bitmap_v2->bitmapHeight)) /* bitmapHeight */
goto fail;
}
if (!update_read_4byte_unsigned(s, &cache_bitmap_v2->bitmapLength) || /* bitmapLength */
!update_read_2byte_unsigned(s, &cache_bitmap_v2->cacheIndex)) /* cacheIndex */
goto fail;
if (cache_bitmap_v2->flags & CBR2_DO_NOT_CACHE)
cache_bitmap_v2->cacheIndex = BITMAP_CACHE_WAITING_LIST_INDEX;
if (compressed)
{
if (!(cache_bitmap_v2->flags & CBR2_NO_BITMAP_COMPRESSION_HDR))
{
if (Stream_GetRemainingLength(s) < 8)
goto fail;
Stream_Read_UINT16(
s, cache_bitmap_v2->cbCompFirstRowSize); /* cbCompFirstRowSize (2 bytes) */
Stream_Read_UINT16(
s, cache_bitmap_v2->cbCompMainBodySize); /* cbCompMainBodySize (2 bytes) */
Stream_Read_UINT16(s, cache_bitmap_v2->cbScanWidth); /* cbScanWidth (2 bytes) */
Stream_Read_UINT16(
s, cache_bitmap_v2->cbUncompressedSize); /* cbUncompressedSize (2 bytes) */
cache_bitmap_v2->bitmapLength = cache_bitmap_v2->cbCompMainBodySize;
}
}
if (cache_bitmap_v2->bitmapLength == 0)
goto fail;
if (Stream_GetRemainingLength(s) < cache_bitmap_v2->bitmapLength)
goto fail;
if (cache_bitmap_v2->bitmapLength == 0)
goto fail;
cache_bitmap_v2->bitmapDataStream = malloc(cache_bitmap_v2->bitmapLength);
if (!cache_bitmap_v2->bitmapDataStream)
goto fail;
Stream_Read(s, cache_bitmap_v2->bitmapDataStream, cache_bitmap_v2->bitmapLength);
cache_bitmap_v2->compressed = compressed;
return cache_bitmap_v2;
fail:
free_cache_bitmap_v2_order(update->context, cache_bitmap_v2);
return NULL;
}
int update_approximate_cache_bitmap_v2_order(CACHE_BITMAP_V2_ORDER* cache_bitmap_v2,
BOOL compressed, UINT16* flags)
{
return 64 + cache_bitmap_v2->bitmapLength;
}
BOOL update_write_cache_bitmap_v2_order(wStream* s, CACHE_BITMAP_V2_ORDER* cache_bitmap_v2,
BOOL compressed, UINT16* flags)
{
BYTE bitsPerPixelId;
if (!Stream_EnsureRemainingCapacity(
s, update_approximate_cache_bitmap_v2_order(cache_bitmap_v2, compressed, flags)))
return FALSE;
bitsPerPixelId = BPP_CBR2[cache_bitmap_v2->bitmapBpp];
*flags = (cache_bitmap_v2->cacheId & 0x0003) | (bitsPerPixelId << 3) |
((cache_bitmap_v2->flags << 7) & 0xFF80);
if (cache_bitmap_v2->flags & CBR2_PERSISTENT_KEY_PRESENT)
{
Stream_Write_UINT32(s, cache_bitmap_v2->key1); /* key1 (4 bytes) */
Stream_Write_UINT32(s, cache_bitmap_v2->key2); /* key2 (4 bytes) */
}
if (cache_bitmap_v2->flags & CBR2_HEIGHT_SAME_AS_WIDTH)
{
if (!update_write_2byte_unsigned(s, cache_bitmap_v2->bitmapWidth)) /* bitmapWidth */
return FALSE;
}
else
{
if (!update_write_2byte_unsigned(s, cache_bitmap_v2->bitmapWidth) || /* bitmapWidth */
!update_write_2byte_unsigned(s, cache_bitmap_v2->bitmapHeight)) /* bitmapHeight */
return FALSE;
}
if (cache_bitmap_v2->flags & CBR2_DO_NOT_CACHE)
cache_bitmap_v2->cacheIndex = BITMAP_CACHE_WAITING_LIST_INDEX;
if (!update_write_4byte_unsigned(s, cache_bitmap_v2->bitmapLength) || /* bitmapLength */
!update_write_2byte_unsigned(s, cache_bitmap_v2->cacheIndex)) /* cacheIndex */
return FALSE;
if (compressed)
{
if (!(cache_bitmap_v2->flags & CBR2_NO_BITMAP_COMPRESSION_HDR))
{
Stream_Write_UINT16(
s, cache_bitmap_v2->cbCompFirstRowSize); /* cbCompFirstRowSize (2 bytes) */
Stream_Write_UINT16(
s, cache_bitmap_v2->cbCompMainBodySize); /* cbCompMainBodySize (2 bytes) */
Stream_Write_UINT16(s, cache_bitmap_v2->cbScanWidth); /* cbScanWidth (2 bytes) */
Stream_Write_UINT16(
s, cache_bitmap_v2->cbUncompressedSize); /* cbUncompressedSize (2 bytes) */
cache_bitmap_v2->bitmapLength = cache_bitmap_v2->cbCompMainBodySize;
}
if (!Stream_EnsureRemainingCapacity(s, cache_bitmap_v2->bitmapLength))
return FALSE;
Stream_Write(s, cache_bitmap_v2->bitmapDataStream, cache_bitmap_v2->bitmapLength);
}
else
{
if (!Stream_EnsureRemainingCapacity(s, cache_bitmap_v2->bitmapLength))
return FALSE;
Stream_Write(s, cache_bitmap_v2->bitmapDataStream, cache_bitmap_v2->bitmapLength);
}
cache_bitmap_v2->compressed = compressed;
return TRUE;
}
static CACHE_BITMAP_V3_ORDER* update_read_cache_bitmap_v3_order(rdpUpdate* update, wStream* s,
UINT16 flags)
{
BYTE bitsPerPixelId;
BITMAP_DATA_EX* bitmapData;
UINT32 new_len;
BYTE* new_data;
CACHE_BITMAP_V3_ORDER* cache_bitmap_v3;
if (!update || !s)
return NULL;
cache_bitmap_v3 = calloc(1, sizeof(CACHE_BITMAP_V3_ORDER));
if (!cache_bitmap_v3)
goto fail;
cache_bitmap_v3->cacheId = flags & 0x00000003;
cache_bitmap_v3->flags = (flags & 0x0000FF80) >> 7;
bitsPerPixelId = (flags & 0x00000078) >> 3;
cache_bitmap_v3->bpp = CBR23_BPP[bitsPerPixelId];
if (Stream_GetRemainingLength(s) < 21)
goto fail;
Stream_Read_UINT16(s, cache_bitmap_v3->cacheIndex); /* cacheIndex (2 bytes) */
Stream_Read_UINT32(s, cache_bitmap_v3->key1); /* key1 (4 bytes) */
Stream_Read_UINT32(s, cache_bitmap_v3->key2); /* key2 (4 bytes) */
bitmapData = &cache_bitmap_v3->bitmapData;
Stream_Read_UINT8(s, bitmapData->bpp);
if ((bitmapData->bpp < 1) || (bitmapData->bpp > 32))
{
WLog_Print(update->log, WLOG_ERROR, "invalid bpp value %" PRIu32 "", bitmapData->bpp);
goto fail;
}
Stream_Seek_UINT8(s); /* reserved1 (1 byte) */
Stream_Seek_UINT8(s); /* reserved2 (1 byte) */
Stream_Read_UINT8(s, bitmapData->codecID); /* codecID (1 byte) */
Stream_Read_UINT16(s, bitmapData->width); /* width (2 bytes) */
Stream_Read_UINT16(s, bitmapData->height); /* height (2 bytes) */
Stream_Read_UINT32(s, new_len); /* length (4 bytes) */
if ((new_len == 0) || (Stream_GetRemainingLength(s) < new_len))
goto fail;
new_data = (BYTE*)realloc(bitmapData->data, new_len);
if (!new_data)
goto fail;
bitmapData->data = new_data;
bitmapData->length = new_len;
Stream_Read(s, bitmapData->data, bitmapData->length);
return cache_bitmap_v3;
fail:
free_cache_bitmap_v3_order(update->context, cache_bitmap_v3);
return NULL;
}
int update_approximate_cache_bitmap_v3_order(CACHE_BITMAP_V3_ORDER* cache_bitmap_v3, UINT16* flags)
{
BITMAP_DATA_EX* bitmapData = &cache_bitmap_v3->bitmapData;
return 64 + bitmapData->length;
}
BOOL update_write_cache_bitmap_v3_order(wStream* s, CACHE_BITMAP_V3_ORDER* cache_bitmap_v3,
UINT16* flags)
{
BYTE bitsPerPixelId;
BITMAP_DATA_EX* bitmapData;
if (!Stream_EnsureRemainingCapacity(
s, update_approximate_cache_bitmap_v3_order(cache_bitmap_v3, flags)))
return FALSE;
bitmapData = &cache_bitmap_v3->bitmapData;
bitsPerPixelId = BPP_CBR23[cache_bitmap_v3->bpp];
*flags = (cache_bitmap_v3->cacheId & 0x00000003) |
((cache_bitmap_v3->flags << 7) & 0x0000FF80) | ((bitsPerPixelId << 3) & 0x00000078);
Stream_Write_UINT16(s, cache_bitmap_v3->cacheIndex); /* cacheIndex (2 bytes) */
Stream_Write_UINT32(s, cache_bitmap_v3->key1); /* key1 (4 bytes) */
Stream_Write_UINT32(s, cache_bitmap_v3->key2); /* key2 (4 bytes) */
Stream_Write_UINT8(s, bitmapData->bpp);
Stream_Write_UINT8(s, 0); /* reserved1 (1 byte) */
Stream_Write_UINT8(s, 0); /* reserved2 (1 byte) */
Stream_Write_UINT8(s, bitmapData->codecID); /* codecID (1 byte) */
Stream_Write_UINT16(s, bitmapData->width); /* width (2 bytes) */
Stream_Write_UINT16(s, bitmapData->height); /* height (2 bytes) */
Stream_Write_UINT32(s, bitmapData->length); /* length (4 bytes) */
Stream_Write(s, bitmapData->data, bitmapData->length);
return TRUE;
}
static CACHE_COLOR_TABLE_ORDER* update_read_cache_color_table_order(rdpUpdate* update, wStream* s,
UINT16 flags)
{
int i;
UINT32* colorTable;
CACHE_COLOR_TABLE_ORDER* cache_color_table = calloc(1, sizeof(CACHE_COLOR_TABLE_ORDER));
if (!cache_color_table)
goto fail;
if (Stream_GetRemainingLength(s) < 3)
goto fail;
Stream_Read_UINT8(s, cache_color_table->cacheIndex); /* cacheIndex (1 byte) */
Stream_Read_UINT16(s, cache_color_table->numberColors); /* numberColors (2 bytes) */
if (cache_color_table->numberColors != 256)
{
/* This field MUST be set to 256 */
goto fail;
}
if (Stream_GetRemainingLength(s) < cache_color_table->numberColors * 4)
goto fail;
colorTable = (UINT32*)&cache_color_table->colorTable;
for (i = 0; i < (int)cache_color_table->numberColors; i++)
update_read_color_quad(s, &colorTable[i]);
return cache_color_table;
fail:
free_cache_color_table_order(update->context, cache_color_table);
return NULL;
}
int update_approximate_cache_color_table_order(const CACHE_COLOR_TABLE_ORDER* cache_color_table,
UINT16* flags)
{
return 16 + (256 * 4);
}
BOOL update_write_cache_color_table_order(wStream* s,
const CACHE_COLOR_TABLE_ORDER* cache_color_table,
UINT16* flags)
{
int i, inf;
UINT32* colorTable;
if (cache_color_table->numberColors != 256)
return FALSE;
inf = update_approximate_cache_color_table_order(cache_color_table, flags);
if (!Stream_EnsureRemainingCapacity(s, inf))
return FALSE;
Stream_Write_UINT8(s, cache_color_table->cacheIndex); /* cacheIndex (1 byte) */
Stream_Write_UINT16(s, cache_color_table->numberColors); /* numberColors (2 bytes) */
colorTable = (UINT32*)&cache_color_table->colorTable;
for (i = 0; i < (int)cache_color_table->numberColors; i++)
{
update_write_color_quad(s, colorTable[i]);
}
return TRUE;
}
static CACHE_GLYPH_ORDER* update_read_cache_glyph_order(rdpUpdate* update, wStream* s, UINT16 flags)
{
UINT32 i;
CACHE_GLYPH_ORDER* cache_glyph_order = calloc(1, sizeof(CACHE_GLYPH_ORDER));
if (!cache_glyph_order || !update || !s)
goto fail;
if (Stream_GetRemainingLength(s) < 2)
goto fail;
Stream_Read_UINT8(s, cache_glyph_order->cacheId); /* cacheId (1 byte) */
Stream_Read_UINT8(s, cache_glyph_order->cGlyphs); /* cGlyphs (1 byte) */
for (i = 0; i < cache_glyph_order->cGlyphs; i++)
{
GLYPH_DATA* glyph = &cache_glyph_order->glyphData[i];
if (Stream_GetRemainingLength(s) < 10)
goto fail;
Stream_Read_UINT16(s, glyph->cacheIndex);
Stream_Read_INT16(s, glyph->x);
Stream_Read_INT16(s, glyph->y);
Stream_Read_UINT16(s, glyph->cx);
Stream_Read_UINT16(s, glyph->cy);
glyph->cb = ((glyph->cx + 7) / 8) * glyph->cy;
glyph->cb += ((glyph->cb % 4) > 0) ? 4 - (glyph->cb % 4) : 0;
if (Stream_GetRemainingLength(s) < glyph->cb)
goto fail;
glyph->aj = (BYTE*)malloc(glyph->cb);
if (!glyph->aj)
goto fail;
Stream_Read(s, glyph->aj, glyph->cb);
}
if ((flags & CG_GLYPH_UNICODE_PRESENT) && (cache_glyph_order->cGlyphs > 0))
{
cache_glyph_order->unicodeCharacters = calloc(cache_glyph_order->cGlyphs, sizeof(WCHAR));
if (!cache_glyph_order->unicodeCharacters)
goto fail;
if (Stream_GetRemainingLength(s) < sizeof(WCHAR) * cache_glyph_order->cGlyphs)
goto fail;
Stream_Read_UTF16_String(s, cache_glyph_order->unicodeCharacters,
cache_glyph_order->cGlyphs);
}
return cache_glyph_order;
fail:
free_cache_glyph_order(update->context, cache_glyph_order);
return NULL;
}
int update_approximate_cache_glyph_order(const CACHE_GLYPH_ORDER* cache_glyph, UINT16* flags)
{
return 2 + cache_glyph->cGlyphs * 32;
}
BOOL update_write_cache_glyph_order(wStream* s, const CACHE_GLYPH_ORDER* cache_glyph, UINT16* flags)
{
int i, inf;
INT16 lsi16;
const GLYPH_DATA* glyph;
inf = update_approximate_cache_glyph_order(cache_glyph, flags);
if (!Stream_EnsureRemainingCapacity(s, inf))
return FALSE;
Stream_Write_UINT8(s, cache_glyph->cacheId); /* cacheId (1 byte) */
Stream_Write_UINT8(s, cache_glyph->cGlyphs); /* cGlyphs (1 byte) */
for (i = 0; i < (int)cache_glyph->cGlyphs; i++)
{
UINT32 cb;
glyph = &cache_glyph->glyphData[i];
Stream_Write_UINT16(s, glyph->cacheIndex); /* cacheIndex (2 bytes) */
lsi16 = glyph->x;
Stream_Write_UINT16(s, lsi16); /* x (2 bytes) */
lsi16 = glyph->y;
Stream_Write_UINT16(s, lsi16); /* y (2 bytes) */
Stream_Write_UINT16(s, glyph->cx); /* cx (2 bytes) */
Stream_Write_UINT16(s, glyph->cy); /* cy (2 bytes) */
cb = ((glyph->cx + 7) / 8) * glyph->cy;
cb += ((cb % 4) > 0) ? 4 - (cb % 4) : 0;
Stream_Write(s, glyph->aj, cb);
}
if (*flags & CG_GLYPH_UNICODE_PRESENT)
{
Stream_Zero(s, cache_glyph->cGlyphs * 2);
}
return TRUE;
}
static CACHE_GLYPH_V2_ORDER* update_read_cache_glyph_v2_order(rdpUpdate* update, wStream* s,
UINT16 flags)
{
UINT32 i;
CACHE_GLYPH_V2_ORDER* cache_glyph_v2 = calloc(1, sizeof(CACHE_GLYPH_V2_ORDER));
if (!cache_glyph_v2)
goto fail;
cache_glyph_v2->cacheId = (flags & 0x000F);
cache_glyph_v2->flags = (flags & 0x00F0) >> 4;
cache_glyph_v2->cGlyphs = (flags & 0xFF00) >> 8;
for (i = 0; i < cache_glyph_v2->cGlyphs; i++)
{
GLYPH_DATA_V2* glyph = &cache_glyph_v2->glyphData[i];
if (Stream_GetRemainingLength(s) < 1)
goto fail;
Stream_Read_UINT8(s, glyph->cacheIndex);
if (!update_read_2byte_signed(s, &glyph->x) || !update_read_2byte_signed(s, &glyph->y) ||
!update_read_2byte_unsigned(s, &glyph->cx) ||
!update_read_2byte_unsigned(s, &glyph->cy))
{
goto fail;
}
glyph->cb = ((glyph->cx + 7) / 8) * glyph->cy;
glyph->cb += ((glyph->cb % 4) > 0) ? 4 - (glyph->cb % 4) : 0;
if (Stream_GetRemainingLength(s) < glyph->cb)
goto fail;
glyph->aj = (BYTE*)malloc(glyph->cb);
if (!glyph->aj)
goto fail;
Stream_Read(s, glyph->aj, glyph->cb);
}
if ((flags & CG_GLYPH_UNICODE_PRESENT) && (cache_glyph_v2->cGlyphs > 0))
{
cache_glyph_v2->unicodeCharacters = calloc(cache_glyph_v2->cGlyphs, sizeof(WCHAR));
if (!cache_glyph_v2->unicodeCharacters)
goto fail;
if (Stream_GetRemainingLength(s) < sizeof(WCHAR) * cache_glyph_v2->cGlyphs)
goto fail;
Stream_Read_UTF16_String(s, cache_glyph_v2->unicodeCharacters, cache_glyph_v2->cGlyphs);
}
return cache_glyph_v2;
fail:
free_cache_glyph_v2_order(update->context, cache_glyph_v2);
return NULL;
}
int update_approximate_cache_glyph_v2_order(const CACHE_GLYPH_V2_ORDER* cache_glyph_v2,
UINT16* flags)
{
return 8 + cache_glyph_v2->cGlyphs * 32;
}
BOOL update_write_cache_glyph_v2_order(wStream* s, const CACHE_GLYPH_V2_ORDER* cache_glyph_v2,
UINT16* flags)
{
UINT32 i, inf;
inf = update_approximate_cache_glyph_v2_order(cache_glyph_v2, flags);
if (!Stream_EnsureRemainingCapacity(s, inf))
return FALSE;
*flags = (cache_glyph_v2->cacheId & 0x000F) | ((cache_glyph_v2->flags & 0x000F) << 4) |
((cache_glyph_v2->cGlyphs & 0x00FF) << 8);
for (i = 0; i < cache_glyph_v2->cGlyphs; i++)
{
UINT32 cb;
const GLYPH_DATA_V2* glyph = &cache_glyph_v2->glyphData[i];
Stream_Write_UINT8(s, glyph->cacheIndex);
if (!update_write_2byte_signed(s, glyph->x) || !update_write_2byte_signed(s, glyph->y) ||
!update_write_2byte_unsigned(s, glyph->cx) ||
!update_write_2byte_unsigned(s, glyph->cy))
{
return FALSE;
}
cb = ((glyph->cx + 7) / 8) * glyph->cy;
cb += ((cb % 4) > 0) ? 4 - (cb % 4) : 0;
Stream_Write(s, glyph->aj, cb);
}
if (*flags & CG_GLYPH_UNICODE_PRESENT)
{
Stream_Zero(s, cache_glyph_v2->cGlyphs * 2);
}
return TRUE;
}
static BOOL update_decompress_brush(wStream* s, BYTE* output, size_t outSize, BYTE bpp)
{
INT32 x, y, k;
BYTE byte = 0;
const BYTE* palette = Stream_Pointer(s) + 16;
const INT32 bytesPerPixel = ((bpp + 1) / 8);
if (!Stream_SafeSeek(s, 16ULL + 7ULL * bytesPerPixel)) // 64 / 4
return FALSE;
for (y = 7; y >= 0; y--)
{
for (x = 0; x < 8; x++)
{
UINT32 index;
if ((x % 4) == 0)
Stream_Read_UINT8(s, byte);
index = ((byte >> ((3 - (x % 4)) * 2)) & 0x03);
for (k = 0; k < bytesPerPixel; k++)
{
const size_t dstIndex = ((y * 8 + x) * bytesPerPixel) + k;
const size_t srcIndex = (index * bytesPerPixel) + k;
if (dstIndex >= outSize)
return FALSE;
output[dstIndex] = palette[srcIndex];
}
}
}
return TRUE;
}
static BOOL update_compress_brush(wStream* s, const BYTE* input, BYTE bpp)
{
return FALSE;
}
static CACHE_BRUSH_ORDER* update_read_cache_brush_order(rdpUpdate* update, wStream* s, UINT16 flags)
{
int i;
BYTE iBitmapFormat;
BOOL compressed = FALSE;
CACHE_BRUSH_ORDER* cache_brush = calloc(1, sizeof(CACHE_BRUSH_ORDER));
if (!cache_brush)
goto fail;
if (Stream_GetRemainingLength(s) < 6)
goto fail;
Stream_Read_UINT8(s, cache_brush->index); /* cacheEntry (1 byte) */
Stream_Read_UINT8(s, iBitmapFormat); /* iBitmapFormat (1 byte) */
if (iBitmapFormat >= ARRAYSIZE(BMF_BPP))
goto fail;
cache_brush->bpp = BMF_BPP[iBitmapFormat];
Stream_Read_UINT8(s, cache_brush->cx); /* cx (1 byte) */
Stream_Read_UINT8(s, cache_brush->cy); /* cy (1 byte) */
Stream_Read_UINT8(s, cache_brush->style); /* style (1 byte) */
Stream_Read_UINT8(s, cache_brush->length); /* iBytes (1 byte) */
if ((cache_brush->cx == 8) && (cache_brush->cy == 8))
{
if (cache_brush->bpp == 1)
{
if (cache_brush->length != 8)
{
WLog_Print(update->log, WLOG_ERROR, "incompatible 1bpp brush of length:%" PRIu32 "",
cache_brush->length);
goto fail;
}
/* rows are encoded in reverse order */
if (Stream_GetRemainingLength(s) < 8)
goto fail;
for (i = 7; i >= 0; i--)
{
Stream_Read_UINT8(s, cache_brush->data[i]);
}
}
else
{
if ((iBitmapFormat == BMF_8BPP) && (cache_brush->length == 20))
compressed = TRUE;
else if ((iBitmapFormat == BMF_16BPP) && (cache_brush->length == 24))
compressed = TRUE;
else if ((iBitmapFormat == BMF_32BPP) && (cache_brush->length == 32))
compressed = TRUE;
if (compressed != FALSE)
{
/* compressed brush */
if (!update_decompress_brush(s, cache_brush->data, sizeof(cache_brush->data),
cache_brush->bpp))
goto fail;
}
else
{
/* uncompressed brush */
UINT32 scanline = (cache_brush->bpp / 8) * 8;
if (Stream_GetRemainingLength(s) < scanline * 8)
goto fail;
for (i = 7; i >= 0; i--)
{
Stream_Read(s, &cache_brush->data[i * scanline], scanline);
}
}
}
}
return cache_brush;
fail:
free_cache_brush_order(update->context, cache_brush);
return NULL;
}
int update_approximate_cache_brush_order(const CACHE_BRUSH_ORDER* cache_brush, UINT16* flags)
{
return 64;
}
BOOL update_write_cache_brush_order(wStream* s, const CACHE_BRUSH_ORDER* cache_brush, UINT16* flags)
{
int i;
BYTE iBitmapFormat;
BOOL compressed = FALSE;
if (!Stream_EnsureRemainingCapacity(s,
update_approximate_cache_brush_order(cache_brush, flags)))
return FALSE;
iBitmapFormat = BPP_BMF[cache_brush->bpp];
Stream_Write_UINT8(s, cache_brush->index); /* cacheEntry (1 byte) */
Stream_Write_UINT8(s, iBitmapFormat); /* iBitmapFormat (1 byte) */
Stream_Write_UINT8(s, cache_brush->cx); /* cx (1 byte) */
Stream_Write_UINT8(s, cache_brush->cy); /* cy (1 byte) */
Stream_Write_UINT8(s, cache_brush->style); /* style (1 byte) */
Stream_Write_UINT8(s, cache_brush->length); /* iBytes (1 byte) */
if ((cache_brush->cx == 8) && (cache_brush->cy == 8))
{
if (cache_brush->bpp == 1)
{
if (cache_brush->length != 8)
{
WLog_ERR(TAG, "incompatible 1bpp brush of length:%" PRIu32 "", cache_brush->length);
return FALSE;
}
for (i = 7; i >= 0; i--)
{
Stream_Write_UINT8(s, cache_brush->data[i]);
}
}
else
{
if ((iBitmapFormat == BMF_8BPP) && (cache_brush->length == 20))
compressed = TRUE;
else if ((iBitmapFormat == BMF_16BPP) && (cache_brush->length == 24))
compressed = TRUE;
else if ((iBitmapFormat == BMF_32BPP) && (cache_brush->length == 32))
compressed = TRUE;
if (compressed != FALSE)
{
/* compressed brush */
if (!update_compress_brush(s, cache_brush->data, cache_brush->bpp))
return FALSE;
}
else
{
/* uncompressed brush */
int scanline = (cache_brush->bpp / 8) * 8;
for (i = 7; i >= 0; i--)
{
Stream_Write(s, &cache_brush->data[i * scanline], scanline);
}
}
}
}
return TRUE;
}
/* Alternate Secondary Drawing Orders */
static BOOL
update_read_create_offscreen_bitmap_order(wStream* s,
CREATE_OFFSCREEN_BITMAP_ORDER* create_offscreen_bitmap)
{
UINT16 flags;
BOOL deleteListPresent;
OFFSCREEN_DELETE_LIST* deleteList;
if (Stream_GetRemainingLength(s) < 6)
return FALSE;
Stream_Read_UINT16(s, flags); /* flags (2 bytes) */
create_offscreen_bitmap->id = flags & 0x7FFF;
deleteListPresent = (flags & 0x8000) ? TRUE : FALSE;
Stream_Read_UINT16(s, create_offscreen_bitmap->cx); /* cx (2 bytes) */
Stream_Read_UINT16(s, create_offscreen_bitmap->cy); /* cy (2 bytes) */
deleteList = &(create_offscreen_bitmap->deleteList);
if (deleteListPresent)
{
UINT32 i;
if (Stream_GetRemainingLength(s) < 2)
return FALSE;
Stream_Read_UINT16(s, deleteList->cIndices);
if (deleteList->cIndices > deleteList->sIndices)
{
UINT16* new_indices;
new_indices = (UINT16*)realloc(deleteList->indices, deleteList->cIndices * 2);
if (!new_indices)
return FALSE;
deleteList->sIndices = deleteList->cIndices;
deleteList->indices = new_indices;
}
if (Stream_GetRemainingLength(s) < 2 * deleteList->cIndices)
return FALSE;
for (i = 0; i < deleteList->cIndices; i++)
{
Stream_Read_UINT16(s, deleteList->indices[i]);
}
}
else
{
deleteList->cIndices = 0;
}
return TRUE;
}
int update_approximate_create_offscreen_bitmap_order(
const CREATE_OFFSCREEN_BITMAP_ORDER* create_offscreen_bitmap)
{
const OFFSCREEN_DELETE_LIST* deleteList = &(create_offscreen_bitmap->deleteList);
return 32 + deleteList->cIndices * 2;
}
BOOL update_write_create_offscreen_bitmap_order(
wStream* s, const CREATE_OFFSCREEN_BITMAP_ORDER* create_offscreen_bitmap)
{
UINT16 flags;
BOOL deleteListPresent;
const OFFSCREEN_DELETE_LIST* deleteList;
if (!Stream_EnsureRemainingCapacity(
s, update_approximate_create_offscreen_bitmap_order(create_offscreen_bitmap)))
return FALSE;
deleteList = &(create_offscreen_bitmap->deleteList);
flags = create_offscreen_bitmap->id & 0x7FFF;
deleteListPresent = (deleteList->cIndices > 0) ? TRUE : FALSE;
if (deleteListPresent)
flags |= 0x8000;
Stream_Write_UINT16(s, flags); /* flags (2 bytes) */
Stream_Write_UINT16(s, create_offscreen_bitmap->cx); /* cx (2 bytes) */
Stream_Write_UINT16(s, create_offscreen_bitmap->cy); /* cy (2 bytes) */
if (deleteListPresent)
{
int i;
Stream_Write_UINT16(s, deleteList->cIndices);
for (i = 0; i < (int)deleteList->cIndices; i++)
{
Stream_Write_UINT16(s, deleteList->indices[i]);
}
}
return TRUE;
}
static BOOL update_read_switch_surface_order(wStream* s, SWITCH_SURFACE_ORDER* switch_surface)
{
if (Stream_GetRemainingLength(s) < 2)
return FALSE;
Stream_Read_UINT16(s, switch_surface->bitmapId); /* bitmapId (2 bytes) */
return TRUE;
}
int update_approximate_switch_surface_order(const SWITCH_SURFACE_ORDER* switch_surface)
{
return 2;
}
BOOL update_write_switch_surface_order(wStream* s, const SWITCH_SURFACE_ORDER* switch_surface)
{
int inf = update_approximate_switch_surface_order(switch_surface);
if (!Stream_EnsureRemainingCapacity(s, inf))
return FALSE;
Stream_Write_UINT16(s, switch_surface->bitmapId); /* bitmapId (2 bytes) */
return TRUE;
}
static BOOL
update_read_create_nine_grid_bitmap_order(wStream* s,
CREATE_NINE_GRID_BITMAP_ORDER* create_nine_grid_bitmap)
{
NINE_GRID_BITMAP_INFO* nineGridInfo;
if (Stream_GetRemainingLength(s) < 19)
return FALSE;
Stream_Read_UINT8(s, create_nine_grid_bitmap->bitmapBpp); /* bitmapBpp (1 byte) */
if ((create_nine_grid_bitmap->bitmapBpp < 1) || (create_nine_grid_bitmap->bitmapBpp > 32))
{
WLog_ERR(TAG, "invalid bpp value %" PRIu32 "", create_nine_grid_bitmap->bitmapBpp);
return FALSE;
}
Stream_Read_UINT16(s, create_nine_grid_bitmap->bitmapId); /* bitmapId (2 bytes) */
nineGridInfo = &(create_nine_grid_bitmap->nineGridInfo);
Stream_Read_UINT32(s, nineGridInfo->flFlags); /* flFlags (4 bytes) */
Stream_Read_UINT16(s, nineGridInfo->ulLeftWidth); /* ulLeftWidth (2 bytes) */
Stream_Read_UINT16(s, nineGridInfo->ulRightWidth); /* ulRightWidth (2 bytes) */
Stream_Read_UINT16(s, nineGridInfo->ulTopHeight); /* ulTopHeight (2 bytes) */
Stream_Read_UINT16(s, nineGridInfo->ulBottomHeight); /* ulBottomHeight (2 bytes) */
update_read_colorref(s, &nineGridInfo->crTransparent); /* crTransparent (4 bytes) */
return TRUE;
}
static BOOL update_read_frame_marker_order(wStream* s, FRAME_MARKER_ORDER* frame_marker)
{
if (Stream_GetRemainingLength(s) < 4)
return FALSE;
Stream_Read_UINT32(s, frame_marker->action); /* action (4 bytes) */
return TRUE;
}
static BOOL update_read_stream_bitmap_first_order(wStream* s,
STREAM_BITMAP_FIRST_ORDER* stream_bitmap_first)
{
if (Stream_GetRemainingLength(s) < 10) // 8 + 2 at least
return FALSE;
Stream_Read_UINT8(s, stream_bitmap_first->bitmapFlags); /* bitmapFlags (1 byte) */
Stream_Read_UINT8(s, stream_bitmap_first->bitmapBpp); /* bitmapBpp (1 byte) */
if ((stream_bitmap_first->bitmapBpp < 1) || (stream_bitmap_first->bitmapBpp > 32))
{
WLog_ERR(TAG, "invalid bpp value %" PRIu32 "", stream_bitmap_first->bitmapBpp);
return FALSE;
}
Stream_Read_UINT16(s, stream_bitmap_first->bitmapType); /* bitmapType (2 bytes) */
Stream_Read_UINT16(s, stream_bitmap_first->bitmapWidth); /* bitmapWidth (2 bytes) */
Stream_Read_UINT16(s, stream_bitmap_first->bitmapHeight); /* bitmapHeigth (2 bytes) */
if (stream_bitmap_first->bitmapFlags & STREAM_BITMAP_V2)
{
if (Stream_GetRemainingLength(s) < 4)
return FALSE;
Stream_Read_UINT32(s, stream_bitmap_first->bitmapSize); /* bitmapSize (4 bytes) */
}
else
{
if (Stream_GetRemainingLength(s) < 2)
return FALSE;
Stream_Read_UINT16(s, stream_bitmap_first->bitmapSize); /* bitmapSize (2 bytes) */
}
FIELD_SKIP_BUFFER16(
s, stream_bitmap_first->bitmapBlockSize); /* bitmapBlockSize(2 bytes) + bitmapBlock */
return TRUE;
}
static BOOL update_read_stream_bitmap_next_order(wStream* s,
STREAM_BITMAP_NEXT_ORDER* stream_bitmap_next)
{
if (Stream_GetRemainingLength(s) < 5)
return FALSE;
Stream_Read_UINT8(s, stream_bitmap_next->bitmapFlags); /* bitmapFlags (1 byte) */
Stream_Read_UINT16(s, stream_bitmap_next->bitmapType); /* bitmapType (2 bytes) */
FIELD_SKIP_BUFFER16(
s, stream_bitmap_next->bitmapBlockSize); /* bitmapBlockSize(2 bytes) + bitmapBlock */
return TRUE;
}
static BOOL update_read_draw_gdiplus_first_order(wStream* s,
DRAW_GDIPLUS_FIRST_ORDER* draw_gdiplus_first)
{
if (Stream_GetRemainingLength(s) < 11)
return FALSE;
Stream_Seek_UINT8(s); /* pad1Octet (1 byte) */
Stream_Read_UINT16(s, draw_gdiplus_first->cbSize); /* cbSize (2 bytes) */
Stream_Read_UINT32(s, draw_gdiplus_first->cbTotalSize); /* cbTotalSize (4 bytes) */
Stream_Read_UINT32(s, draw_gdiplus_first->cbTotalEmfSize); /* cbTotalEmfSize (4 bytes) */
return Stream_SafeSeek(s, draw_gdiplus_first->cbSize); /* emfRecords */
}
static BOOL update_read_draw_gdiplus_next_order(wStream* s,
DRAW_GDIPLUS_NEXT_ORDER* draw_gdiplus_next)
{
if (Stream_GetRemainingLength(s) < 3)
return FALSE;
Stream_Seek_UINT8(s); /* pad1Octet (1 byte) */
FIELD_SKIP_BUFFER16(s, draw_gdiplus_next->cbSize); /* cbSize(2 bytes) + emfRecords */
return TRUE;
}
static BOOL update_read_draw_gdiplus_end_order(wStream* s, DRAW_GDIPLUS_END_ORDER* draw_gdiplus_end)
{
if (Stream_GetRemainingLength(s) < 11)
return FALSE;
Stream_Seek_UINT8(s); /* pad1Octet (1 byte) */
Stream_Read_UINT16(s, draw_gdiplus_end->cbSize); /* cbSize (2 bytes) */
Stream_Read_UINT32(s, draw_gdiplus_end->cbTotalSize); /* cbTotalSize (4 bytes) */
Stream_Read_UINT32(s, draw_gdiplus_end->cbTotalEmfSize); /* cbTotalEmfSize (4 bytes) */
return Stream_SafeSeek(s, draw_gdiplus_end->cbSize); /* emfRecords */
}
static BOOL
update_read_draw_gdiplus_cache_first_order(wStream* s,
DRAW_GDIPLUS_CACHE_FIRST_ORDER* draw_gdiplus_cache_first)
{
if (Stream_GetRemainingLength(s) < 11)
return FALSE;
Stream_Read_UINT8(s, draw_gdiplus_cache_first->flags); /* flags (1 byte) */
Stream_Read_UINT16(s, draw_gdiplus_cache_first->cacheType); /* cacheType (2 bytes) */
Stream_Read_UINT16(s, draw_gdiplus_cache_first->cacheIndex); /* cacheIndex (2 bytes) */
Stream_Read_UINT16(s, draw_gdiplus_cache_first->cbSize); /* cbSize (2 bytes) */
Stream_Read_UINT32(s, draw_gdiplus_cache_first->cbTotalSize); /* cbTotalSize (4 bytes) */
return Stream_SafeSeek(s, draw_gdiplus_cache_first->cbSize); /* emfRecords */
}
static BOOL
update_read_draw_gdiplus_cache_next_order(wStream* s,
DRAW_GDIPLUS_CACHE_NEXT_ORDER* draw_gdiplus_cache_next)
{
if (Stream_GetRemainingLength(s) < 7)
return FALSE;
Stream_Read_UINT8(s, draw_gdiplus_cache_next->flags); /* flags (1 byte) */
Stream_Read_UINT16(s, draw_gdiplus_cache_next->cacheType); /* cacheType (2 bytes) */
Stream_Read_UINT16(s, draw_gdiplus_cache_next->cacheIndex); /* cacheIndex (2 bytes) */
FIELD_SKIP_BUFFER16(s, draw_gdiplus_cache_next->cbSize); /* cbSize(2 bytes) + emfRecords */
return TRUE;
}
static BOOL
update_read_draw_gdiplus_cache_end_order(wStream* s,
DRAW_GDIPLUS_CACHE_END_ORDER* draw_gdiplus_cache_end)
{
if (Stream_GetRemainingLength(s) < 11)
return FALSE;
Stream_Read_UINT8(s, draw_gdiplus_cache_end->flags); /* flags (1 byte) */
Stream_Read_UINT16(s, draw_gdiplus_cache_end->cacheType); /* cacheType (2 bytes) */
Stream_Read_UINT16(s, draw_gdiplus_cache_end->cacheIndex); /* cacheIndex (2 bytes) */
Stream_Read_UINT16(s, draw_gdiplus_cache_end->cbSize); /* cbSize (2 bytes) */
Stream_Read_UINT32(s, draw_gdiplus_cache_end->cbTotalSize); /* cbTotalSize (4 bytes) */
return Stream_SafeSeek(s, draw_gdiplus_cache_end->cbSize); /* emfRecords */
}
static BOOL update_read_field_flags(wStream* s, UINT32* fieldFlags, BYTE flags, BYTE fieldBytes)
{
int i;
BYTE byte;
if (flags & ORDER_ZERO_FIELD_BYTE_BIT0)
fieldBytes--;
if (flags & ORDER_ZERO_FIELD_BYTE_BIT1)
{
if (fieldBytes > 1)
fieldBytes -= 2;
else
fieldBytes = 0;
}
if (Stream_GetRemainingLength(s) < fieldBytes)
return FALSE;
*fieldFlags = 0;
for (i = 0; i < fieldBytes; i++)
{
Stream_Read_UINT8(s, byte);
*fieldFlags |= byte << (i * 8);
}
return TRUE;
}
BOOL update_write_field_flags(wStream* s, UINT32 fieldFlags, BYTE flags, BYTE fieldBytes)
{
BYTE byte;
if (fieldBytes == 1)
{
byte = fieldFlags & 0xFF;
Stream_Write_UINT8(s, byte);
}
else if (fieldBytes == 2)
{
byte = fieldFlags & 0xFF;
Stream_Write_UINT8(s, byte);
byte = (fieldFlags >> 8) & 0xFF;
Stream_Write_UINT8(s, byte);
}
else if (fieldBytes == 3)
{
byte = fieldFlags & 0xFF;
Stream_Write_UINT8(s, byte);
byte = (fieldFlags >> 8) & 0xFF;
Stream_Write_UINT8(s, byte);
byte = (fieldFlags >> 16) & 0xFF;
Stream_Write_UINT8(s, byte);
}
else
{
return FALSE;
}
return TRUE;
}
static BOOL update_read_bounds(wStream* s, rdpBounds* bounds)
{
BYTE flags;
if (Stream_GetRemainingLength(s) < 1)
return FALSE;
Stream_Read_UINT8(s, flags); /* field flags */
if (flags & BOUND_LEFT)
{
if (!update_read_coord(s, &bounds->left, FALSE))
return FALSE;
}
else if (flags & BOUND_DELTA_LEFT)
{
if (!update_read_coord(s, &bounds->left, TRUE))
return FALSE;
}
if (flags & BOUND_TOP)
{
if (!update_read_coord(s, &bounds->top, FALSE))
return FALSE;
}
else if (flags & BOUND_DELTA_TOP)
{
if (!update_read_coord(s, &bounds->top, TRUE))
return FALSE;
}
if (flags & BOUND_RIGHT)
{
if (!update_read_coord(s, &bounds->right, FALSE))
return FALSE;
}
else if (flags & BOUND_DELTA_RIGHT)
{
if (!update_read_coord(s, &bounds->right, TRUE))
return FALSE;
}
if (flags & BOUND_BOTTOM)
{
if (!update_read_coord(s, &bounds->bottom, FALSE))
return FALSE;
}
else if (flags & BOUND_DELTA_BOTTOM)
{
if (!update_read_coord(s, &bounds->bottom, TRUE))
return FALSE;
}
return TRUE;
}
BOOL update_write_bounds(wStream* s, ORDER_INFO* orderInfo)
{
if (!(orderInfo->controlFlags & ORDER_BOUNDS))
return TRUE;
if (orderInfo->controlFlags & ORDER_ZERO_BOUNDS_DELTAS)
return TRUE;
Stream_Write_UINT8(s, orderInfo->boundsFlags); /* field flags */
if (orderInfo->boundsFlags & BOUND_LEFT)
{
if (!update_write_coord(s, orderInfo->bounds.left))
return FALSE;
}
else if (orderInfo->boundsFlags & BOUND_DELTA_LEFT)
{
}
if (orderInfo->boundsFlags & BOUND_TOP)
{
if (!update_write_coord(s, orderInfo->bounds.top))
return FALSE;
}
else if (orderInfo->boundsFlags & BOUND_DELTA_TOP)
{
}
if (orderInfo->boundsFlags & BOUND_RIGHT)
{
if (!update_write_coord(s, orderInfo->bounds.right))
return FALSE;
}
else if (orderInfo->boundsFlags & BOUND_DELTA_RIGHT)
{
}
if (orderInfo->boundsFlags & BOUND_BOTTOM)
{
if (!update_write_coord(s, orderInfo->bounds.bottom))
return FALSE;
}
else if (orderInfo->boundsFlags & BOUND_DELTA_BOTTOM)
{
}
return TRUE;
}
static BOOL read_primary_order(wLog* log, const char* orderName, wStream* s,
const ORDER_INFO* orderInfo, rdpPrimaryUpdate* primary)
{
BOOL rc = FALSE;
if (!s || !orderInfo || !primary || !orderName)
return FALSE;
switch (orderInfo->orderType)
{
case ORDER_TYPE_DSTBLT:
rc = update_read_dstblt_order(s, orderInfo, &(primary->dstblt));
break;
case ORDER_TYPE_PATBLT:
rc = update_read_patblt_order(s, orderInfo, &(primary->patblt));
break;
case ORDER_TYPE_SCRBLT:
rc = update_read_scrblt_order(s, orderInfo, &(primary->scrblt));
break;
case ORDER_TYPE_OPAQUE_RECT:
rc = update_read_opaque_rect_order(s, orderInfo, &(primary->opaque_rect));
break;
case ORDER_TYPE_DRAW_NINE_GRID:
rc = update_read_draw_nine_grid_order(s, orderInfo, &(primary->draw_nine_grid));
break;
case ORDER_TYPE_MULTI_DSTBLT:
rc = update_read_multi_dstblt_order(s, orderInfo, &(primary->multi_dstblt));
break;
case ORDER_TYPE_MULTI_PATBLT:
rc = update_read_multi_patblt_order(s, orderInfo, &(primary->multi_patblt));
break;
case ORDER_TYPE_MULTI_SCRBLT:
rc = update_read_multi_scrblt_order(s, orderInfo, &(primary->multi_scrblt));
break;
case ORDER_TYPE_MULTI_OPAQUE_RECT:
rc = update_read_multi_opaque_rect_order(s, orderInfo, &(primary->multi_opaque_rect));
break;
case ORDER_TYPE_MULTI_DRAW_NINE_GRID:
rc = update_read_multi_draw_nine_grid_order(s, orderInfo,
&(primary->multi_draw_nine_grid));
break;
case ORDER_TYPE_LINE_TO:
rc = update_read_line_to_order(s, orderInfo, &(primary->line_to));
break;
case ORDER_TYPE_POLYLINE:
rc = update_read_polyline_order(s, orderInfo, &(primary->polyline));
break;
case ORDER_TYPE_MEMBLT:
rc = update_read_memblt_order(s, orderInfo, &(primary->memblt));
break;
case ORDER_TYPE_MEM3BLT:
rc = update_read_mem3blt_order(s, orderInfo, &(primary->mem3blt));
break;
case ORDER_TYPE_SAVE_BITMAP:
rc = update_read_save_bitmap_order(s, orderInfo, &(primary->save_bitmap));
break;
case ORDER_TYPE_GLYPH_INDEX:
rc = update_read_glyph_index_order(s, orderInfo, &(primary->glyph_index));
break;
case ORDER_TYPE_FAST_INDEX:
rc = update_read_fast_index_order(s, orderInfo, &(primary->fast_index));
break;
case ORDER_TYPE_FAST_GLYPH:
rc = update_read_fast_glyph_order(s, orderInfo, &(primary->fast_glyph));
break;
case ORDER_TYPE_POLYGON_SC:
rc = update_read_polygon_sc_order(s, orderInfo, &(primary->polygon_sc));
break;
case ORDER_TYPE_POLYGON_CB:
rc = update_read_polygon_cb_order(s, orderInfo, &(primary->polygon_cb));
break;
case ORDER_TYPE_ELLIPSE_SC:
rc = update_read_ellipse_sc_order(s, orderInfo, &(primary->ellipse_sc));
break;
case ORDER_TYPE_ELLIPSE_CB:
rc = update_read_ellipse_cb_order(s, orderInfo, &(primary->ellipse_cb));
break;
default:
WLog_Print(log, WLOG_WARN, "Primary Drawing Order %s not supported, ignoring",
orderName);
rc = TRUE;
break;
}
if (!rc)
{
WLog_Print(log, WLOG_ERROR, "%s - update_read_dstblt_order() failed", orderName);
return FALSE;
}
return TRUE;
}
static BOOL update_recv_primary_order(rdpUpdate* update, wStream* s, BYTE flags)
{
BYTE field;
BOOL rc = FALSE;
rdpContext* context = update->context;
rdpPrimaryUpdate* primary = update->primary;
ORDER_INFO* orderInfo = &(primary->order_info);
rdpSettings* settings = context->settings;
const char* orderName;
if (flags & ORDER_TYPE_CHANGE)
{
if (Stream_GetRemainingLength(s) < 1)
{
WLog_Print(update->log, WLOG_ERROR, "Stream_GetRemainingLength(s) < 1");
return FALSE;
}
Stream_Read_UINT8(s, orderInfo->orderType); /* orderType (1 byte) */
}
orderName = primary_order_string(orderInfo->orderType);
if (!check_primary_order_supported(update->log, settings, orderInfo->orderType, orderName))
return FALSE;
field = get_primary_drawing_order_field_bytes(orderInfo->orderType, &rc);
if (!rc)
return FALSE;
if (!update_read_field_flags(s, &(orderInfo->fieldFlags), flags, field))
{
WLog_Print(update->log, WLOG_ERROR, "update_read_field_flags() failed");
return FALSE;
}
if (flags & ORDER_BOUNDS)
{
if (!(flags & ORDER_ZERO_BOUNDS_DELTAS))
{
if (!update_read_bounds(s, &orderInfo->bounds))
{
WLog_Print(update->log, WLOG_ERROR, "update_read_bounds() failed");
return FALSE;
}
}
rc = IFCALLRESULT(FALSE, update->SetBounds, context, &orderInfo->bounds);
if (!rc)
return FALSE;
}
orderInfo->deltaCoordinates = (flags & ORDER_DELTA_COORDINATES) ? TRUE : FALSE;
if (!read_primary_order(update->log, orderName, s, orderInfo, primary))
return FALSE;
switch (orderInfo->orderType)
{
case ORDER_TYPE_DSTBLT:
{
WLog_Print(update->log, WLOG_DEBUG, "Primary Drawing Order %s rop=%s [0x%08" PRIx32 "]",
orderName, gdi_rop3_code_string(primary->dstblt.bRop),
gdi_rop3_code(primary->dstblt.bRop));
rc = IFCALLRESULT(FALSE, primary->DstBlt, context, &primary->dstblt);
}
break;
case ORDER_TYPE_PATBLT:
{
WLog_Print(update->log, WLOG_DEBUG, "Primary Drawing Order %s rop=%s [0x%08" PRIx32 "]",
orderName, gdi_rop3_code_string(primary->patblt.bRop),
gdi_rop3_code(primary->patblt.bRop));
rc = IFCALLRESULT(FALSE, primary->PatBlt, context, &primary->patblt);
}
break;
case ORDER_TYPE_SCRBLT:
{
WLog_Print(update->log, WLOG_DEBUG, "Primary Drawing Order %s rop=%s [0x%08" PRIx32 "]",
orderName, gdi_rop3_code_string(primary->scrblt.bRop),
gdi_rop3_code(primary->scrblt.bRop));
rc = IFCALLRESULT(FALSE, primary->ScrBlt, context, &primary->scrblt);
}
break;
case ORDER_TYPE_OPAQUE_RECT:
{
WLog_Print(update->log, WLOG_DEBUG, "Primary Drawing Order %s", orderName);
rc = IFCALLRESULT(FALSE, primary->OpaqueRect, context, &primary->opaque_rect);
}
break;
case ORDER_TYPE_DRAW_NINE_GRID:
{
WLog_Print(update->log, WLOG_DEBUG, "Primary Drawing Order %s", orderName);
rc = IFCALLRESULT(FALSE, primary->DrawNineGrid, context, &primary->draw_nine_grid);
}
break;
case ORDER_TYPE_MULTI_DSTBLT:
{
WLog_Print(update->log, WLOG_DEBUG, "Primary Drawing Order %s rop=%s [0x%08" PRIx32 "]",
orderName, gdi_rop3_code_string(primary->multi_dstblt.bRop),
gdi_rop3_code(primary->multi_dstblt.bRop));
rc = IFCALLRESULT(FALSE, primary->MultiDstBlt, context, &primary->multi_dstblt);
}
break;
case ORDER_TYPE_MULTI_PATBLT:
{
WLog_Print(update->log, WLOG_DEBUG, "Primary Drawing Order %s rop=%s [0x%08" PRIx32 "]",
orderName, gdi_rop3_code_string(primary->multi_patblt.bRop),
gdi_rop3_code(primary->multi_patblt.bRop));
rc = IFCALLRESULT(FALSE, primary->MultiPatBlt, context, &primary->multi_patblt);
}
break;
case ORDER_TYPE_MULTI_SCRBLT:
{
WLog_Print(update->log, WLOG_DEBUG, "Primary Drawing Order %s rop=%s [0x%08" PRIx32 "]",
orderName, gdi_rop3_code_string(primary->multi_scrblt.bRop),
gdi_rop3_code(primary->multi_scrblt.bRop));
rc = IFCALLRESULT(FALSE, primary->MultiScrBlt, context, &primary->multi_scrblt);
}
break;
case ORDER_TYPE_MULTI_OPAQUE_RECT:
{
WLog_Print(update->log, WLOG_DEBUG, "Primary Drawing Order %s", orderName);
rc =
IFCALLRESULT(FALSE, primary->MultiOpaqueRect, context, &primary->multi_opaque_rect);
}
break;
case ORDER_TYPE_MULTI_DRAW_NINE_GRID:
{
WLog_Print(update->log, WLOG_DEBUG, "Primary Drawing Order %s", orderName);
rc = IFCALLRESULT(FALSE, primary->MultiDrawNineGrid, context,
&primary->multi_draw_nine_grid);
}
break;
case ORDER_TYPE_LINE_TO:
{
WLog_Print(update->log, WLOG_DEBUG, "Primary Drawing Order %s", orderName);
rc = IFCALLRESULT(FALSE, primary->LineTo, context, &primary->line_to);
}
break;
case ORDER_TYPE_POLYLINE:
{
WLog_Print(update->log, WLOG_DEBUG, "Primary Drawing Order %s", orderName);
rc = IFCALLRESULT(FALSE, primary->Polyline, context, &primary->polyline);
}
break;
case ORDER_TYPE_MEMBLT:
{
WLog_Print(update->log, WLOG_DEBUG, "Primary Drawing Order %s rop=%s [0x%08" PRIx32 "]",
orderName, gdi_rop3_code_string(primary->memblt.bRop),
gdi_rop3_code(primary->memblt.bRop));
rc = IFCALLRESULT(FALSE, primary->MemBlt, context, &primary->memblt);
}
break;
case ORDER_TYPE_MEM3BLT:
{
WLog_Print(update->log, WLOG_DEBUG, "Primary Drawing Order %s rop=%s [0x%08" PRIx32 "]",
orderName, gdi_rop3_code_string(primary->mem3blt.bRop),
gdi_rop3_code(primary->mem3blt.bRop));
rc = IFCALLRESULT(FALSE, primary->Mem3Blt, context, &primary->mem3blt);
}
break;
case ORDER_TYPE_SAVE_BITMAP:
{
WLog_Print(update->log, WLOG_DEBUG, "Primary Drawing Order %s", orderName);
rc = IFCALLRESULT(FALSE, primary->SaveBitmap, context, &primary->save_bitmap);
}
break;
case ORDER_TYPE_GLYPH_INDEX:
{
WLog_Print(update->log, WLOG_DEBUG, "Primary Drawing Order %s", orderName);
rc = IFCALLRESULT(FALSE, primary->GlyphIndex, context, &primary->glyph_index);
}
break;
case ORDER_TYPE_FAST_INDEX:
{
WLog_Print(update->log, WLOG_DEBUG, "Primary Drawing Order %s", orderName);
rc = IFCALLRESULT(FALSE, primary->FastIndex, context, &primary->fast_index);
}
break;
case ORDER_TYPE_FAST_GLYPH:
{
WLog_Print(update->log, WLOG_DEBUG, "Primary Drawing Order %s", orderName);
rc = IFCALLRESULT(FALSE, primary->FastGlyph, context, &primary->fast_glyph);
}
break;
case ORDER_TYPE_POLYGON_SC:
{
WLog_Print(update->log, WLOG_DEBUG, "Primary Drawing Order %s", orderName);
rc = IFCALLRESULT(FALSE, primary->PolygonSC, context, &primary->polygon_sc);
}
break;
case ORDER_TYPE_POLYGON_CB:
{
WLog_Print(update->log, WLOG_DEBUG, "Primary Drawing Order %s", orderName);
rc = IFCALLRESULT(FALSE, primary->PolygonCB, context, &primary->polygon_cb);
}
break;
case ORDER_TYPE_ELLIPSE_SC:
{
WLog_Print(update->log, WLOG_DEBUG, "Primary Drawing Order %s", orderName);
rc = IFCALLRESULT(FALSE, primary->EllipseSC, context, &primary->ellipse_sc);
}
break;
case ORDER_TYPE_ELLIPSE_CB:
{
WLog_Print(update->log, WLOG_DEBUG, "Primary Drawing Order %s", orderName);
rc = IFCALLRESULT(FALSE, primary->EllipseCB, context, &primary->ellipse_cb);
}
break;
default:
WLog_Print(update->log, WLOG_WARN, "Primary Drawing Order %s not supported", orderName);
break;
}
if (!rc)
{
WLog_Print(update->log, WLOG_WARN, "Primary Drawing Order %s failed", orderName);
return FALSE;
}
if (flags & ORDER_BOUNDS)
{
rc = IFCALLRESULT(FALSE, update->SetBounds, context, NULL);
}
return rc;
}
static BOOL update_recv_secondary_order(rdpUpdate* update, wStream* s, BYTE flags)
{
BOOL rc = FALSE;
size_t start, end, diff;
BYTE orderType;
UINT16 extraFlags;
UINT16 orderLength;
rdpContext* context = update->context;
rdpSettings* settings = context->settings;
rdpSecondaryUpdate* secondary = update->secondary;
const char* name;
if (Stream_GetRemainingLength(s) < 5)
{
WLog_Print(update->log, WLOG_ERROR, "Stream_GetRemainingLength(s) < 5");
return FALSE;
}
Stream_Read_UINT16(s, orderLength); /* orderLength (2 bytes) */
Stream_Read_UINT16(s, extraFlags); /* extraFlags (2 bytes) */
Stream_Read_UINT8(s, orderType); /* orderType (1 byte) */
if (Stream_GetRemainingLength(s) < orderLength + 7U)
{
WLog_Print(update->log, WLOG_ERROR, "Stream_GetRemainingLength(s) %" PRIuz " < %" PRIu16,
Stream_GetRemainingLength(s), orderLength + 7);
return FALSE;
}
start = Stream_GetPosition(s);
name = secondary_order_string(orderType);
WLog_Print(update->log, WLOG_DEBUG, "Secondary Drawing Order %s", name);
if (!check_secondary_order_supported(update->log, settings, orderType, name))
return FALSE;
switch (orderType)
{
case ORDER_TYPE_BITMAP_UNCOMPRESSED:
case ORDER_TYPE_CACHE_BITMAP_COMPRESSED:
{
const BOOL compressed = (orderType == ORDER_TYPE_CACHE_BITMAP_COMPRESSED);
CACHE_BITMAP_ORDER* order =
update_read_cache_bitmap_order(update, s, compressed, extraFlags);
if (order)
{
rc = IFCALLRESULT(FALSE, secondary->CacheBitmap, context, order);
free_cache_bitmap_order(context, order);
}
}
break;
case ORDER_TYPE_BITMAP_UNCOMPRESSED_V2:
case ORDER_TYPE_BITMAP_COMPRESSED_V2:
{
const BOOL compressed = (orderType == ORDER_TYPE_BITMAP_COMPRESSED_V2);
CACHE_BITMAP_V2_ORDER* order =
update_read_cache_bitmap_v2_order(update, s, compressed, extraFlags);
if (order)
{
rc = IFCALLRESULT(FALSE, secondary->CacheBitmapV2, context, order);
free_cache_bitmap_v2_order(context, order);
}
}
break;
case ORDER_TYPE_BITMAP_COMPRESSED_V3:
{
CACHE_BITMAP_V3_ORDER* order = update_read_cache_bitmap_v3_order(update, s, extraFlags);
if (order)
{
rc = IFCALLRESULT(FALSE, secondary->CacheBitmapV3, context, order);
free_cache_bitmap_v3_order(context, order);
}
}
break;
case ORDER_TYPE_CACHE_COLOR_TABLE:
{
CACHE_COLOR_TABLE_ORDER* order =
update_read_cache_color_table_order(update, s, extraFlags);
if (order)
{
rc = IFCALLRESULT(FALSE, secondary->CacheColorTable, context, order);
free_cache_color_table_order(context, order);
}
}
break;
case ORDER_TYPE_CACHE_GLYPH:
{
switch (settings->GlyphSupportLevel)
{
case GLYPH_SUPPORT_PARTIAL:
case GLYPH_SUPPORT_FULL:
{
CACHE_GLYPH_ORDER* order = update_read_cache_glyph_order(update, s, extraFlags);
if (order)
{
rc = IFCALLRESULT(FALSE, secondary->CacheGlyph, context, order);
free_cache_glyph_order(context, order);
}
}
break;
case GLYPH_SUPPORT_ENCODE:
{
CACHE_GLYPH_V2_ORDER* order =
update_read_cache_glyph_v2_order(update, s, extraFlags);
if (order)
{
rc = IFCALLRESULT(FALSE, secondary->CacheGlyphV2, context, order);
free_cache_glyph_v2_order(context, order);
}
}
break;
case GLYPH_SUPPORT_NONE:
default:
break;
}
}
break;
case ORDER_TYPE_CACHE_BRUSH:
/* [MS-RDPEGDI] 2.2.2.2.1.2.7 Cache Brush (CACHE_BRUSH_ORDER) */
{
CACHE_BRUSH_ORDER* order = update_read_cache_brush_order(update, s, extraFlags);
if (order)
{
rc = IFCALLRESULT(FALSE, secondary->CacheBrush, context, order);
free_cache_brush_order(context, order);
}
}
break;
default:
WLog_Print(update->log, WLOG_WARN, "SECONDARY ORDER %s not supported", name);
break;
}
if (!rc)
{
WLog_Print(update->log, WLOG_ERROR, "SECONDARY ORDER %s failed", name);
}
start += orderLength + 7;
end = Stream_GetPosition(s);
if (start > end)
{
WLog_Print(update->log, WLOG_WARN, "SECONDARY_ORDER %s: read %" PRIuz "bytes too much",
name, end - start);
return FALSE;
}
diff = start - end;
if (diff > 0)
{
WLog_Print(update->log, WLOG_DEBUG,
"SECONDARY_ORDER %s: read %" PRIuz "bytes short, skipping", name, diff);
Stream_Seek(s, diff);
}
return rc;
}
static BOOL read_altsec_order(wStream* s, BYTE orderType, rdpAltSecUpdate* altsec)
{
BOOL rc = FALSE;
switch (orderType)
{
case ORDER_TYPE_CREATE_OFFSCREEN_BITMAP:
rc = update_read_create_offscreen_bitmap_order(s, &(altsec->create_offscreen_bitmap));
break;
case ORDER_TYPE_SWITCH_SURFACE:
rc = update_read_switch_surface_order(s, &(altsec->switch_surface));
break;
case ORDER_TYPE_CREATE_NINE_GRID_BITMAP:
rc = update_read_create_nine_grid_bitmap_order(s, &(altsec->create_nine_grid_bitmap));
break;
case ORDER_TYPE_FRAME_MARKER:
rc = update_read_frame_marker_order(s, &(altsec->frame_marker));
break;
case ORDER_TYPE_STREAM_BITMAP_FIRST:
rc = update_read_stream_bitmap_first_order(s, &(altsec->stream_bitmap_first));
break;
case ORDER_TYPE_STREAM_BITMAP_NEXT:
rc = update_read_stream_bitmap_next_order(s, &(altsec->stream_bitmap_next));
break;
case ORDER_TYPE_GDIPLUS_FIRST:
rc = update_read_draw_gdiplus_first_order(s, &(altsec->draw_gdiplus_first));
break;
case ORDER_TYPE_GDIPLUS_NEXT:
rc = update_read_draw_gdiplus_next_order(s, &(altsec->draw_gdiplus_next));
break;
case ORDER_TYPE_GDIPLUS_END:
rc = update_read_draw_gdiplus_end_order(s, &(altsec->draw_gdiplus_end));
break;
case ORDER_TYPE_GDIPLUS_CACHE_FIRST:
rc = update_read_draw_gdiplus_cache_first_order(s, &(altsec->draw_gdiplus_cache_first));
break;
case ORDER_TYPE_GDIPLUS_CACHE_NEXT:
rc = update_read_draw_gdiplus_cache_next_order(s, &(altsec->draw_gdiplus_cache_next));
break;
case ORDER_TYPE_GDIPLUS_CACHE_END:
rc = update_read_draw_gdiplus_cache_end_order(s, &(altsec->draw_gdiplus_cache_end));
break;
case ORDER_TYPE_WINDOW:
/* This order is handled elsewhere. */
rc = TRUE;
break;
case ORDER_TYPE_COMPDESK_FIRST:
rc = TRUE;
break;
default:
break;
}
return rc;
}
static BOOL update_recv_altsec_order(rdpUpdate* update, wStream* s, BYTE flags)
{
BYTE orderType = flags >>= 2; /* orderType is in higher 6 bits of flags field */
BOOL rc = FALSE;
rdpContext* context = update->context;
rdpSettings* settings = context->settings;
rdpAltSecUpdate* altsec = update->altsec;
const char* orderName = altsec_order_string(orderType);
WLog_Print(update->log, WLOG_DEBUG, "Alternate Secondary Drawing Order %s", orderName);
if (!check_alt_order_supported(update->log, settings, orderType, orderName))
return FALSE;
if (!read_altsec_order(s, orderType, altsec))
return FALSE;
switch (orderType)
{
case ORDER_TYPE_CREATE_OFFSCREEN_BITMAP:
IFCALLRET(altsec->CreateOffscreenBitmap, rc, context,
&(altsec->create_offscreen_bitmap));
break;
case ORDER_TYPE_SWITCH_SURFACE:
IFCALLRET(altsec->SwitchSurface, rc, context, &(altsec->switch_surface));
break;
case ORDER_TYPE_CREATE_NINE_GRID_BITMAP:
IFCALLRET(altsec->CreateNineGridBitmap, rc, context,
&(altsec->create_nine_grid_bitmap));
break;
case ORDER_TYPE_FRAME_MARKER:
IFCALLRET(altsec->FrameMarker, rc, context, &(altsec->frame_marker));
break;
case ORDER_TYPE_STREAM_BITMAP_FIRST:
IFCALLRET(altsec->StreamBitmapFirst, rc, context, &(altsec->stream_bitmap_first));
break;
case ORDER_TYPE_STREAM_BITMAP_NEXT:
IFCALLRET(altsec->StreamBitmapNext, rc, context, &(altsec->stream_bitmap_next));
break;
case ORDER_TYPE_GDIPLUS_FIRST:
IFCALLRET(altsec->DrawGdiPlusFirst, rc, context, &(altsec->draw_gdiplus_first));
break;
case ORDER_TYPE_GDIPLUS_NEXT:
IFCALLRET(altsec->DrawGdiPlusNext, rc, context, &(altsec->draw_gdiplus_next));
break;
case ORDER_TYPE_GDIPLUS_END:
IFCALLRET(altsec->DrawGdiPlusEnd, rc, context, &(altsec->draw_gdiplus_end));
break;
case ORDER_TYPE_GDIPLUS_CACHE_FIRST:
IFCALLRET(altsec->DrawGdiPlusCacheFirst, rc, context,
&(altsec->draw_gdiplus_cache_first));
break;
case ORDER_TYPE_GDIPLUS_CACHE_NEXT:
IFCALLRET(altsec->DrawGdiPlusCacheNext, rc, context,
&(altsec->draw_gdiplus_cache_next));
break;
case ORDER_TYPE_GDIPLUS_CACHE_END:
IFCALLRET(altsec->DrawGdiPlusCacheEnd, rc, context, &(altsec->draw_gdiplus_cache_end));
break;
case ORDER_TYPE_WINDOW:
rc = update_recv_altsec_window_order(update, s);
break;
case ORDER_TYPE_COMPDESK_FIRST:
rc = TRUE;
break;
default:
break;
}
if (!rc)
{
WLog_Print(update->log, WLOG_WARN, "Alternate Secondary Drawing Order %s failed",
orderName);
}
return rc;
}
BOOL update_recv_order(rdpUpdate* update, wStream* s)
{
BOOL rc;
BYTE controlFlags;
if (Stream_GetRemainingLength(s) < 1)
{
WLog_Print(update->log, WLOG_ERROR, "Stream_GetRemainingLength(s) < 1");
return FALSE;
}
Stream_Read_UINT8(s, controlFlags); /* controlFlags (1 byte) */
if (!(controlFlags & ORDER_STANDARD))
rc = update_recv_altsec_order(update, s, controlFlags);
else if (controlFlags & ORDER_SECONDARY)
rc = update_recv_secondary_order(update, s, controlFlags);
else
rc = update_recv_primary_order(update, s, controlFlags);
if (!rc)
WLog_Print(update->log, WLOG_ERROR, "order flags %02" PRIx8 " failed", controlFlags);
return rc;
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/good_3951_0 |
crossvul-cpp_data_good_543_0 | // SPDX-License-Identifier: (GPL-2.0 OR MIT)
/*
* SerDes PHY driver for Microsemi Ocelot
*
* Copyright (c) 2018 Microsemi
*
*/
#include <linux/err.h>
#include <linux/mfd/syscon.h>
#include <linux/module.h>
#include <linux/of.h>
#include <linux/of_platform.h>
#include <linux/phy/phy.h>
#include <linux/platform_device.h>
#include <linux/regmap.h>
#include <soc/mscc/ocelot_hsio.h>
#include <dt-bindings/phy/phy-ocelot-serdes.h>
struct serdes_ctrl {
struct regmap *regs;
struct device *dev;
struct phy *phys[SERDES_MAX];
};
struct serdes_macro {
u8 idx;
/* Not used when in QSGMII or PCIe mode */
int port;
struct serdes_ctrl *ctrl;
};
#define MCB_S1G_CFG_TIMEOUT 50
static int __serdes_write_mcb_s1g(struct regmap *regmap, u8 macro, u32 op)
{
unsigned int regval;
regmap_write(regmap, HSIO_MCB_S1G_ADDR_CFG, op |
HSIO_MCB_S1G_ADDR_CFG_SERDES1G_ADDR(BIT(macro)));
return regmap_read_poll_timeout(regmap, HSIO_MCB_S1G_ADDR_CFG, regval,
(regval & op) != op, 100,
MCB_S1G_CFG_TIMEOUT * 1000);
}
static int serdes_commit_mcb_s1g(struct regmap *regmap, u8 macro)
{
return __serdes_write_mcb_s1g(regmap, macro,
HSIO_MCB_S1G_ADDR_CFG_SERDES1G_WR_ONE_SHOT);
}
static int serdes_update_mcb_s1g(struct regmap *regmap, u8 macro)
{
return __serdes_write_mcb_s1g(regmap, macro,
HSIO_MCB_S1G_ADDR_CFG_SERDES1G_RD_ONE_SHOT);
}
static int serdes_init_s1g(struct regmap *regmap, u8 serdes)
{
int ret;
ret = serdes_update_mcb_s1g(regmap, serdes);
if (ret)
return ret;
regmap_update_bits(regmap, HSIO_S1G_COMMON_CFG,
HSIO_S1G_COMMON_CFG_SYS_RST |
HSIO_S1G_COMMON_CFG_ENA_LANE |
HSIO_S1G_COMMON_CFG_ENA_ELOOP |
HSIO_S1G_COMMON_CFG_ENA_FLOOP,
HSIO_S1G_COMMON_CFG_ENA_LANE);
regmap_update_bits(regmap, HSIO_S1G_PLL_CFG,
HSIO_S1G_PLL_CFG_PLL_FSM_ENA |
HSIO_S1G_PLL_CFG_PLL_FSM_CTRL_DATA_M,
HSIO_S1G_PLL_CFG_PLL_FSM_CTRL_DATA(200) |
HSIO_S1G_PLL_CFG_PLL_FSM_ENA);
regmap_update_bits(regmap, HSIO_S1G_MISC_CFG,
HSIO_S1G_MISC_CFG_DES_100FX_CPMD_ENA |
HSIO_S1G_MISC_CFG_LANE_RST,
HSIO_S1G_MISC_CFG_LANE_RST);
ret = serdes_commit_mcb_s1g(regmap, serdes);
if (ret)
return ret;
regmap_update_bits(regmap, HSIO_S1G_COMMON_CFG,
HSIO_S1G_COMMON_CFG_SYS_RST,
HSIO_S1G_COMMON_CFG_SYS_RST);
regmap_update_bits(regmap, HSIO_S1G_MISC_CFG,
HSIO_S1G_MISC_CFG_LANE_RST, 0);
ret = serdes_commit_mcb_s1g(regmap, serdes);
if (ret)
return ret;
return 0;
}
struct serdes_mux {
u8 idx;
u8 port;
enum phy_mode mode;
u32 mask;
u32 mux;
};
#define SERDES_MUX(_idx, _port, _mode, _mask, _mux) { \
.idx = _idx, \
.port = _port, \
.mode = _mode, \
.mask = _mask, \
.mux = _mux, \
}
#define SERDES_MUX_SGMII(i, p, m, c) SERDES_MUX(i, p, PHY_MODE_SGMII, m, c)
#define SERDES_MUX_QSGMII(i, p, m, c) SERDES_MUX(i, p, PHY_MODE_QSGMII, m, c)
static const struct serdes_mux ocelot_serdes_muxes[] = {
SERDES_MUX_SGMII(SERDES1G(0), 0, 0, 0),
SERDES_MUX_SGMII(SERDES1G(1), 1, HSIO_HW_CFG_DEV1G_5_MODE, 0),
SERDES_MUX_SGMII(SERDES1G(1), 5, HSIO_HW_CFG_QSGMII_ENA |
HSIO_HW_CFG_DEV1G_5_MODE, HSIO_HW_CFG_DEV1G_5_MODE),
SERDES_MUX_SGMII(SERDES1G(2), 2, HSIO_HW_CFG_DEV1G_4_MODE, 0),
SERDES_MUX_SGMII(SERDES1G(2), 4, HSIO_HW_CFG_QSGMII_ENA |
HSIO_HW_CFG_DEV1G_4_MODE, HSIO_HW_CFG_DEV1G_4_MODE),
SERDES_MUX_SGMII(SERDES1G(3), 3, HSIO_HW_CFG_DEV1G_6_MODE, 0),
SERDES_MUX_SGMII(SERDES1G(3), 6, HSIO_HW_CFG_QSGMII_ENA |
HSIO_HW_CFG_DEV1G_6_MODE, HSIO_HW_CFG_DEV1G_6_MODE),
SERDES_MUX_SGMII(SERDES1G(4), 4, HSIO_HW_CFG_QSGMII_ENA |
HSIO_HW_CFG_DEV1G_4_MODE | HSIO_HW_CFG_DEV1G_9_MODE,
0),
SERDES_MUX_SGMII(SERDES1G(4), 9, HSIO_HW_CFG_DEV1G_4_MODE |
HSIO_HW_CFG_DEV1G_9_MODE, HSIO_HW_CFG_DEV1G_4_MODE |
HSIO_HW_CFG_DEV1G_9_MODE),
SERDES_MUX_SGMII(SERDES1G(5), 5, HSIO_HW_CFG_QSGMII_ENA |
HSIO_HW_CFG_DEV1G_5_MODE | HSIO_HW_CFG_DEV2G5_10_MODE,
0),
SERDES_MUX_SGMII(SERDES1G(5), 10, HSIO_HW_CFG_PCIE_ENA |
HSIO_HW_CFG_DEV1G_5_MODE | HSIO_HW_CFG_DEV2G5_10_MODE,
HSIO_HW_CFG_DEV1G_5_MODE | HSIO_HW_CFG_DEV2G5_10_MODE),
SERDES_MUX_QSGMII(SERDES6G(0), 4, HSIO_HW_CFG_QSGMII_ENA,
HSIO_HW_CFG_QSGMII_ENA),
SERDES_MUX_QSGMII(SERDES6G(0), 5, HSIO_HW_CFG_QSGMII_ENA,
HSIO_HW_CFG_QSGMII_ENA),
SERDES_MUX_QSGMII(SERDES6G(0), 6, HSIO_HW_CFG_QSGMII_ENA,
HSIO_HW_CFG_QSGMII_ENA),
SERDES_MUX_SGMII(SERDES6G(0), 7, HSIO_HW_CFG_QSGMII_ENA, 0),
SERDES_MUX_QSGMII(SERDES6G(0), 7, HSIO_HW_CFG_QSGMII_ENA,
HSIO_HW_CFG_QSGMII_ENA),
SERDES_MUX_SGMII(SERDES6G(1), 8, 0, 0),
SERDES_MUX_SGMII(SERDES6G(2), 10, HSIO_HW_CFG_PCIE_ENA |
HSIO_HW_CFG_DEV2G5_10_MODE, 0),
SERDES_MUX(SERDES6G(2), 10, PHY_MODE_PCIE, HSIO_HW_CFG_PCIE_ENA,
HSIO_HW_CFG_PCIE_ENA),
};
static int serdes_set_mode(struct phy *phy, enum phy_mode mode)
{
struct serdes_macro *macro = phy_get_drvdata(phy);
unsigned int i;
int ret;
for (i = 0; i < ARRAY_SIZE(ocelot_serdes_muxes); i++) {
if (macro->idx != ocelot_serdes_muxes[i].idx ||
mode != ocelot_serdes_muxes[i].mode)
continue;
if (mode != PHY_MODE_QSGMII &&
macro->port != ocelot_serdes_muxes[i].port)
continue;
ret = regmap_update_bits(macro->ctrl->regs, HSIO_HW_CFG,
ocelot_serdes_muxes[i].mask,
ocelot_serdes_muxes[i].mux);
if (ret)
return ret;
if (macro->idx <= SERDES1G_MAX)
return serdes_init_s1g(macro->ctrl->regs, macro->idx);
/* SERDES6G and PCIe not supported yet */
return -EOPNOTSUPP;
}
return -EINVAL;
}
static const struct phy_ops serdes_ops = {
.set_mode = serdes_set_mode,
.owner = THIS_MODULE,
};
static struct phy *serdes_simple_xlate(struct device *dev,
struct of_phandle_args *args)
{
struct serdes_ctrl *ctrl = dev_get_drvdata(dev);
unsigned int port, idx, i;
if (args->args_count != 2)
return ERR_PTR(-EINVAL);
port = args->args[0];
idx = args->args[1];
for (i = 0; i < SERDES_MAX; i++) {
struct serdes_macro *macro = phy_get_drvdata(ctrl->phys[i]);
if (idx != macro->idx)
continue;
/* SERDES6G(0) is the only SerDes capable of QSGMII */
if (idx != SERDES6G(0) && macro->port >= 0)
return ERR_PTR(-EBUSY);
macro->port = port;
return ctrl->phys[i];
}
return ERR_PTR(-ENODEV);
}
static int serdes_phy_create(struct serdes_ctrl *ctrl, u8 idx, struct phy **phy)
{
struct serdes_macro *macro;
*phy = devm_phy_create(ctrl->dev, NULL, &serdes_ops);
if (IS_ERR(*phy))
return PTR_ERR(*phy);
macro = devm_kzalloc(ctrl->dev, sizeof(*macro), GFP_KERNEL);
if (!macro)
return -ENOMEM;
macro->idx = idx;
macro->ctrl = ctrl;
macro->port = -1;
phy_set_drvdata(*phy, macro);
return 0;
}
static int serdes_probe(struct platform_device *pdev)
{
struct phy_provider *provider;
struct serdes_ctrl *ctrl;
unsigned int i;
int ret;
ctrl = devm_kzalloc(&pdev->dev, sizeof(*ctrl), GFP_KERNEL);
if (!ctrl)
return -ENOMEM;
ctrl->dev = &pdev->dev;
ctrl->regs = syscon_node_to_regmap(pdev->dev.parent->of_node);
if (IS_ERR(ctrl->regs))
return PTR_ERR(ctrl->regs);
for (i = 0; i < SERDES_MAX; i++) {
ret = serdes_phy_create(ctrl, i, &ctrl->phys[i]);
if (ret)
return ret;
}
dev_set_drvdata(&pdev->dev, ctrl);
provider = devm_of_phy_provider_register(ctrl->dev,
serdes_simple_xlate);
return PTR_ERR_OR_ZERO(provider);
}
static const struct of_device_id serdes_ids[] = {
{ .compatible = "mscc,vsc7514-serdes", },
{},
};
MODULE_DEVICE_TABLE(of, serdes_ids);
static struct platform_driver mscc_ocelot_serdes = {
.probe = serdes_probe,
.driver = {
.name = "mscc,ocelot-serdes",
.of_match_table = of_match_ptr(serdes_ids),
},
};
module_platform_driver(mscc_ocelot_serdes);
MODULE_AUTHOR("Quentin Schulz <quentin.schulz@bootlin.com>");
MODULE_DESCRIPTION("SerDes driver for Microsemi Ocelot");
MODULE_LICENSE("Dual MIT/GPL");
| ./CrossVul/dataset_final_sorted/CWE-125/c/good_543_0 |
crossvul-cpp_data_bad_3955_0 | /**
* FreeRDP: A Remote Desktop Protocol Implementation
* RDP Licensing
*
* Copyright 2011-2013 Marc-Andre Moreau <marcandre.moreau@gmail.com>
* Copyright 2014 Norbert Federa <norbert.federa@thincast.com>
* Copyright 2018 David Fort <contact@hardening-consulting.com>
*
* 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 HAVE_CONFIG_H
#include "config.h"
#endif
#include <winpr/crt.h>
#include <winpr/crypto.h>
#include <winpr/shell.h>
#include <winpr/path.h>
#include <freerdp/log.h>
#include "redirection.h"
#include "certificate.h"
#include "license.h"
#define TAG FREERDP_TAG("core.license")
#if 0
#define LICENSE_NULL_CLIENT_RANDOM 1
#define LICENSE_NULL_PREMASTER_SECRET 1
#endif
static wStream* license_send_stream_init(rdpLicense* license);
static void license_generate_randoms(rdpLicense* license);
static BOOL license_generate_keys(rdpLicense* license);
static BOOL license_generate_hwid(rdpLicense* license);
static BOOL license_encrypt_premaster_secret(rdpLicense* license);
static LICENSE_PRODUCT_INFO* license_new_product_info(void);
static void license_free_product_info(LICENSE_PRODUCT_INFO* productInfo);
static BOOL license_read_product_info(wStream* s, LICENSE_PRODUCT_INFO* productInfo);
static LICENSE_BLOB* license_new_binary_blob(UINT16 type);
static void license_free_binary_blob(LICENSE_BLOB* blob);
static BOOL license_read_binary_blob(wStream* s, LICENSE_BLOB* blob);
static BOOL license_write_binary_blob(wStream* s, const LICENSE_BLOB* blob);
static SCOPE_LIST* license_new_scope_list(void);
static void license_free_scope_list(SCOPE_LIST* scopeList);
static BOOL license_read_scope_list(wStream* s, SCOPE_LIST* scopeList);
static BOOL license_read_license_request_packet(rdpLicense* license, wStream* s);
static BOOL license_read_platform_challenge_packet(rdpLicense* license, wStream* s);
static BOOL license_read_new_or_upgrade_license_packet(rdpLicense* license, wStream* s);
static BOOL license_read_error_alert_packet(rdpLicense* license, wStream* s);
static BOOL license_write_new_license_request_packet(rdpLicense* license, wStream* s);
static BOOL license_answer_license_request(rdpLicense* license);
static BOOL license_write_platform_challenge_response_packet(rdpLicense* license, wStream* s,
const BYTE* mac_data);
static BOOL license_send_platform_challenge_response_packet(rdpLicense* license);
static BOOL license_send_client_info(rdpLicense* license, const LICENSE_BLOB* calBlob,
BYTE* signature);
#define PLATFORMID (CLIENT_OS_ID_WINNT_POST_52 | CLIENT_IMAGE_ID_MICROSOFT)
#ifdef WITH_DEBUG_LICENSE
static const char* const LICENSE_MESSAGE_STRINGS[] = { "",
"License Request",
"Platform Challenge",
"New License",
"Upgrade License",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"License Info",
"New License Request",
"",
"Platform Challenge Response",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"Error Alert" };
static const char* const error_codes[] = { "ERR_UNKNOWN",
"ERR_INVALID_SERVER_CERTIFICATE",
"ERR_NO_LICENSE",
"ERR_INVALID_MAC",
"ERR_INVALID_SCOPE",
"ERR_UNKNOWN",
"ERR_NO_LICENSE_SERVER",
"STATUS_VALID_CLIENT",
"ERR_INVALID_CLIENT",
"ERR_UNKNOWN",
"ERR_UNKNOWN",
"ERR_INVALID_PRODUCT_ID",
"ERR_INVALID_MESSAGE_LENGTH" };
static const char* const state_transitions[] = { "ST_UNKNOWN", "ST_TOTAL_ABORT", "ST_NO_TRANSITION",
"ST_RESET_PHASE_TO_START",
"ST_RESEND_LAST_MESSAGE" };
static void license_print_product_info(const LICENSE_PRODUCT_INFO* productInfo)
{
char* CompanyName = NULL;
char* ProductId = NULL;
ConvertFromUnicode(CP_UTF8, 0, (WCHAR*)productInfo->pbCompanyName,
productInfo->cbCompanyName / 2, &CompanyName, 0, NULL, NULL);
ConvertFromUnicode(CP_UTF8, 0, (WCHAR*)productInfo->pbProductId, productInfo->cbProductId / 2,
&ProductId, 0, NULL, NULL);
WLog_INFO(TAG, "ProductInfo:");
WLog_INFO(TAG, "\tdwVersion: 0x%08" PRIX32 "", productInfo->dwVersion);
WLog_INFO(TAG, "\tCompanyName: %s", CompanyName);
WLog_INFO(TAG, "\tProductId: %s", ProductId);
free(CompanyName);
free(ProductId);
}
static void license_print_scope_list(const SCOPE_LIST* scopeList)
{
UINT32 index;
const LICENSE_BLOB* scope;
WLog_INFO(TAG, "ScopeList (%" PRIu32 "):", scopeList->count);
for (index = 0; index < scopeList->count; index++)
{
scope = &scopeList->array[index];
WLog_INFO(TAG, "\t%s", (const char*)scope->data);
}
}
#endif
static const char licenseStore[] = "licenses";
static BOOL computeCalHash(const char* hostname, char* hashStr)
{
WINPR_DIGEST_CTX* sha1 = NULL;
BOOL ret = FALSE;
BYTE hash[20];
size_t i;
if (!(sha1 = winpr_Digest_New()))
goto out;
if (!winpr_Digest_Init(sha1, WINPR_MD_SHA1))
goto out;
if (!winpr_Digest_Update(sha1, (const BYTE*)hostname, strlen(hostname)))
goto out;
if (!winpr_Digest_Final(sha1, hash, sizeof(hash)))
goto out;
for (i = 0; i < sizeof(hash); i++, hashStr += 2)
sprintf_s(hashStr, 3, "%.2x", hash[i]);
ret = TRUE;
out:
winpr_Digest_Free(sha1);
return ret;
}
static BOOL saveCal(rdpSettings* settings, const BYTE* data, int length, char* hostname)
{
char hash[41];
FILE* fp;
char* licenseStorePath = NULL;
char filename[MAX_PATH], filenameNew[MAX_PATH];
char *filepath = NULL, *filepathNew = NULL;
size_t written;
BOOL ret = FALSE;
if (!PathFileExistsA(settings->ConfigPath))
{
if (!PathMakePathA(settings->ConfigPath, 0))
{
WLog_ERR(TAG, "error creating directory '%s'", settings->ConfigPath);
goto out;
}
WLog_INFO(TAG, "creating directory %s", settings->ConfigPath);
}
if (!(licenseStorePath = GetCombinedPath(settings->ConfigPath, licenseStore)))
goto out;
if (!PathFileExistsA(licenseStorePath))
{
if (!PathMakePathA(licenseStorePath, 0))
{
WLog_ERR(TAG, "error creating directory '%s'", licenseStorePath);
goto out;
}
WLog_INFO(TAG, "creating directory %s", licenseStorePath);
}
if (!computeCalHash(hostname, hash))
goto out;
sprintf_s(filename, sizeof(filename) - 1, "%s.cal", hash);
sprintf_s(filenameNew, sizeof(filenameNew) - 1, "%s.cal.new", hash);
if (!(filepath = GetCombinedPath(licenseStorePath, filename)))
goto out;
if (!(filepathNew = GetCombinedPath(licenseStorePath, filenameNew)))
goto out;
fp = fopen(filepathNew, "wb");
if (!fp)
goto out;
written = fwrite(data, length, 1, fp);
fclose(fp);
if (written != 1)
{
DeleteFile(filepathNew);
goto out;
}
ret = MoveFileEx(filepathNew, filepath, MOVEFILE_REPLACE_EXISTING);
out:
free(filepathNew);
free(filepath);
free(licenseStorePath);
return ret;
}
static BYTE* loadCalFile(rdpSettings* settings, const char* hostname, int* dataLen)
{
char *licenseStorePath = NULL, *calPath = NULL;
char calFilename[MAX_PATH];
char hash[41];
int length, status;
FILE* fp;
BYTE* ret = NULL;
if (!computeCalHash(hostname, hash))
{
WLog_ERR(TAG, "loadCalFile: unable to compute hostname hash");
return NULL;
}
sprintf_s(calFilename, sizeof(calFilename) - 1, "%s.cal", hash);
if (!(licenseStorePath = GetCombinedPath(settings->ConfigPath, licenseStore)))
return NULL;
if (!(calPath = GetCombinedPath(licenseStorePath, calFilename)))
goto error_path;
fp = fopen(calPath, "rb");
if (!fp)
goto error_open;
_fseeki64(fp, 0, SEEK_END);
length = _ftelli64(fp);
_fseeki64(fp, 0, SEEK_SET);
ret = (BYTE*)malloc(length);
if (!ret)
goto error_malloc;
status = fread(ret, length, 1, fp);
if (status <= 0)
goto error_read;
*dataLen = length;
fclose(fp);
free(calPath);
free(licenseStorePath);
return ret;
error_read:
free(ret);
error_malloc:
fclose(fp);
error_open:
free(calPath);
error_path:
free(licenseStorePath);
return NULL;
}
/**
* Read a licensing preamble.\n
* @msdn{cc240480}
* @param s stream
* @param bMsgType license message type
* @param flags message flags
* @param wMsgSize message size
* @return if the operation completed successfully
*/
static BOOL license_read_preamble(wStream* s, BYTE* bMsgType, BYTE* flags, UINT16* wMsgSize)
{
/* preamble (4 bytes) */
if (Stream_GetRemainingLength(s) < 4)
return FALSE;
Stream_Read_UINT8(s, *bMsgType); /* bMsgType (1 byte) */
Stream_Read_UINT8(s, *flags); /* flags (1 byte) */
Stream_Read_UINT16(s, *wMsgSize); /* wMsgSize (2 bytes) */
return TRUE;
}
/**
* Write a licensing preamble.\n
* @msdn{cc240480}
* @param s stream
* @param bMsgType license message type
* @param flags message flags
* @param wMsgSize message size
*/
static BOOL license_write_preamble(wStream* s, BYTE bMsgType, BYTE flags, UINT16 wMsgSize)
{
if (!Stream_EnsureRemainingCapacity(s, 4))
return FALSE;
/* preamble (4 bytes) */
Stream_Write_UINT8(s, bMsgType); /* bMsgType (1 byte) */
Stream_Write_UINT8(s, flags); /* flags (1 byte) */
Stream_Write_UINT16(s, wMsgSize); /* wMsgSize (2 bytes) */
return TRUE;
}
/**
* Initialize a license packet stream.\n
* @param license license module
* @return stream
*/
wStream* license_send_stream_init(rdpLicense* license)
{
wStream* s;
BOOL do_crypt = license->rdp->do_crypt;
license->rdp->sec_flags = SEC_LICENSE_PKT;
/**
* Encryption of licensing packets is optional even if the rdp security
* layer is used. If the peer has not indicated that it is capable of
* processing encrypted licensing packets (rdp->do_crypt_license) we turn
* off encryption (via rdp->do_crypt) before initializing the rdp stream
* and reenable it afterwards.
*/
if (do_crypt)
{
license->rdp->sec_flags |= SEC_LICENSE_ENCRYPT_CS;
license->rdp->do_crypt = license->rdp->do_crypt_license;
}
s = rdp_send_stream_init(license->rdp);
if (!s)
return NULL;
license->rdp->do_crypt = do_crypt;
license->PacketHeaderLength = Stream_GetPosition(s);
if (!Stream_SafeSeek(s, LICENSE_PREAMBLE_LENGTH))
goto fail;
return s;
fail:
Stream_Release(s);
return NULL;
}
/**
* Send an RDP licensing packet.\n
* @msdn{cc240479}
* @param license license module
* @param s stream
*/
static BOOL license_send(rdpLicense* license, wStream* s, BYTE type)
{
size_t length;
BYTE flags;
UINT16 wMsgSize;
rdpRdp* rdp = license->rdp;
BOOL ret;
DEBUG_LICENSE("Sending %s Packet", LICENSE_MESSAGE_STRINGS[type & 0x1F]);
length = Stream_GetPosition(s);
wMsgSize = length - license->PacketHeaderLength;
Stream_SetPosition(s, license->PacketHeaderLength);
flags = PREAMBLE_VERSION_3_0;
/**
* Using EXTENDED_ERROR_MSG_SUPPORTED here would cause mstsc to crash when
* running in server mode! This flag seems to be incorrectly documented.
*/
if (!rdp->settings->ServerMode)
flags |= EXTENDED_ERROR_MSG_SUPPORTED;
if (!license_write_preamble(s, type, flags, wMsgSize))
return FALSE;
#ifdef WITH_DEBUG_LICENSE
WLog_DBG(TAG, "Sending %s Packet, length %" PRIu16 "", LICENSE_MESSAGE_STRINGS[type & 0x1F],
wMsgSize);
winpr_HexDump(TAG, WLOG_DEBUG, Stream_Pointer(s) - LICENSE_PREAMBLE_LENGTH, wMsgSize);
#endif
Stream_SetPosition(s, length);
ret = rdp_send(rdp, s, MCS_GLOBAL_CHANNEL_ID);
rdp->sec_flags = 0;
return ret;
}
/**
* Receive an RDP licensing packet.\n
* @msdn{cc240479}
* @param license license module
* @param s stream
* @return if the operation completed successfully
*/
int license_recv(rdpLicense* license, wStream* s)
{
BYTE flags;
BYTE bMsgType;
UINT16 wMsgSize;
UINT16 length;
UINT16 channelId;
UINT16 securityFlags = 0;
if (!rdp_read_header(license->rdp, s, &length, &channelId))
{
WLog_ERR(TAG, "Incorrect RDP header.");
return -1;
}
if (!rdp_read_security_header(s, &securityFlags, &length))
return -1;
if (securityFlags & SEC_ENCRYPT)
{
if (!rdp_decrypt(license->rdp, s, &length, securityFlags))
{
WLog_ERR(TAG, "rdp_decrypt failed");
return -1;
}
}
if (!(securityFlags & SEC_LICENSE_PKT))
{
int status;
if (!(securityFlags & SEC_ENCRYPT))
Stream_Rewind(s, RDP_SECURITY_HEADER_LENGTH);
status = rdp_recv_out_of_sequence_pdu(license->rdp, s);
if (status < 0)
{
WLog_ERR(TAG, "unexpected license packet.");
return status;
}
return 0;
}
if (!license_read_preamble(s, &bMsgType, &flags, &wMsgSize)) /* preamble (4 bytes) */
return -1;
DEBUG_LICENSE("Receiving %s Packet", LICENSE_MESSAGE_STRINGS[bMsgType & 0x1F]);
switch (bMsgType)
{
case LICENSE_REQUEST:
if (!license_read_license_request_packet(license, s))
return -1;
if (!license_answer_license_request(license))
return -1;
break;
case PLATFORM_CHALLENGE:
if (!license_read_platform_challenge_packet(license, s))
return -1;
if (!license_send_platform_challenge_response_packet(license))
return -1;
break;
case NEW_LICENSE:
case UPGRADE_LICENSE:
if (!license_read_new_or_upgrade_license_packet(license, s))
return -1;
break;
case ERROR_ALERT:
if (!license_read_error_alert_packet(license, s))
return -1;
break;
default:
WLog_ERR(TAG, "invalid bMsgType:%" PRIu8 "", bMsgType);
return -1;
}
if (!tpkt_ensure_stream_consumed(s, length))
return -1;
return 0;
}
void license_generate_randoms(rdpLicense* license)
{
#ifdef LICENSE_NULL_CLIENT_RANDOM
ZeroMemory(license->ClientRandom, CLIENT_RANDOM_LENGTH); /* ClientRandom */
#else
winpr_RAND(license->ClientRandom, CLIENT_RANDOM_LENGTH); /* ClientRandom */
#endif
#ifdef LICENSE_NULL_PREMASTER_SECRET
ZeroMemory(license->PremasterSecret, PREMASTER_SECRET_LENGTH); /* PremasterSecret */
#else
winpr_RAND(license->PremasterSecret, PREMASTER_SECRET_LENGTH); /* PremasterSecret */
#endif
}
/**
* Generate License Cryptographic Keys.
* @param license license module
*/
static BOOL license_generate_keys(rdpLicense* license)
{
BOOL ret;
if (
/* MasterSecret */
!security_master_secret(license->PremasterSecret, license->ClientRandom,
license->ServerRandom, license->MasterSecret) ||
/* SessionKeyBlob */
!security_session_key_blob(license->MasterSecret, license->ClientRandom,
license->ServerRandom, license->SessionKeyBlob))
{
return FALSE;
}
security_mac_salt_key(license->SessionKeyBlob, license->ClientRandom, license->ServerRandom,
license->MacSaltKey); /* MacSaltKey */
ret = security_licensing_encryption_key(
license->SessionKeyBlob, license->ClientRandom, license->ServerRandom,
license->LicensingEncryptionKey); /* LicensingEncryptionKey */
#ifdef WITH_DEBUG_LICENSE
WLog_DBG(TAG, "ClientRandom:");
winpr_HexDump(TAG, WLOG_DEBUG, license->ClientRandom, CLIENT_RANDOM_LENGTH);
WLog_DBG(TAG, "ServerRandom:");
winpr_HexDump(TAG, WLOG_DEBUG, license->ServerRandom, SERVER_RANDOM_LENGTH);
WLog_DBG(TAG, "PremasterSecret:");
winpr_HexDump(TAG, WLOG_DEBUG, license->PremasterSecret, PREMASTER_SECRET_LENGTH);
WLog_DBG(TAG, "MasterSecret:");
winpr_HexDump(TAG, WLOG_DEBUG, license->MasterSecret, MASTER_SECRET_LENGTH);
WLog_DBG(TAG, "SessionKeyBlob:");
winpr_HexDump(TAG, WLOG_DEBUG, license->SessionKeyBlob, SESSION_KEY_BLOB_LENGTH);
WLog_DBG(TAG, "MacSaltKey:");
winpr_HexDump(TAG, WLOG_DEBUG, license->MacSaltKey, MAC_SALT_KEY_LENGTH);
WLog_DBG(TAG, "LicensingEncryptionKey:");
winpr_HexDump(TAG, WLOG_DEBUG, license->LicensingEncryptionKey,
LICENSING_ENCRYPTION_KEY_LENGTH);
#endif
return ret;
}
/**
* Generate Unique Hardware Identifier (CLIENT_HARDWARE_ID).\n
* @param license license module
*/
BOOL license_generate_hwid(rdpLicense* license)
{
const BYTE* hashTarget;
size_t targetLen;
BYTE macAddress[6];
ZeroMemory(license->HardwareId, HWID_LENGTH);
if (license->rdp->settings->OldLicenseBehaviour)
{
ZeroMemory(macAddress, sizeof(macAddress));
hashTarget = macAddress;
targetLen = sizeof(macAddress);
}
else
{
wStream s;
const char* hostname = license->rdp->settings->ClientHostname;
Stream_StaticInit(&s, license->HardwareId, 4);
Stream_Write_UINT32(&s, PLATFORMID);
Stream_Free(&s, TRUE);
hashTarget = (const BYTE*)hostname;
targetLen = strlen(hostname);
}
/* Allow FIPS override for use of MD5 here, really this does not have to be MD5 as we are just
* taking a MD5 hash of the 6 bytes of 0's(macAddress) */
/* and filling in the Data1-Data4 fields of the CLIENT_HARDWARE_ID structure(from MS-RDPELE
* section 2.2.2.3.1). This is for RDP licensing packets */
/* which will already be encrypted under FIPS, so the use of MD5 here is not for sensitive data
* protection. */
return winpr_Digest_Allow_FIPS(WINPR_MD_MD5, hashTarget, targetLen,
&license->HardwareId[HWID_PLATFORM_ID_LENGTH],
WINPR_MD5_DIGEST_LENGTH);
}
static BOOL license_get_server_rsa_public_key(rdpLicense* license)
{
BYTE* Exponent;
BYTE* Modulus;
int ModulusLength;
rdpSettings* settings = license->rdp->settings;
if (license->ServerCertificate->length < 1)
{
if (!certificate_read_server_certificate(license->certificate, settings->ServerCertificate,
settings->ServerCertificateLength))
return FALSE;
}
Exponent = license->certificate->cert_info.exponent;
Modulus = license->certificate->cert_info.Modulus;
ModulusLength = license->certificate->cert_info.ModulusLength;
CopyMemory(license->Exponent, Exponent, 4);
license->ModulusLength = ModulusLength;
license->Modulus = (BYTE*)malloc(ModulusLength);
if (!license->Modulus)
return FALSE;
CopyMemory(license->Modulus, Modulus, ModulusLength);
return TRUE;
}
BOOL license_encrypt_premaster_secret(rdpLicense* license)
{
BYTE* EncryptedPremasterSecret;
if (!license_get_server_rsa_public_key(license))
return FALSE;
#ifdef WITH_DEBUG_LICENSE
WLog_DBG(TAG, "Modulus (%" PRIu32 " bits):", license->ModulusLength * 8);
winpr_HexDump(TAG, WLOG_DEBUG, license->Modulus, license->ModulusLength);
WLog_DBG(TAG, "Exponent:");
winpr_HexDump(TAG, WLOG_DEBUG, license->Exponent, 4);
#endif
EncryptedPremasterSecret = (BYTE*)calloc(1, license->ModulusLength);
if (!EncryptedPremasterSecret)
return FALSE;
license->EncryptedPremasterSecret->type = BB_RANDOM_BLOB;
license->EncryptedPremasterSecret->length = PREMASTER_SECRET_LENGTH;
#ifndef LICENSE_NULL_PREMASTER_SECRET
license->EncryptedPremasterSecret->length = crypto_rsa_public_encrypt(
license->PremasterSecret, PREMASTER_SECRET_LENGTH, license->ModulusLength, license->Modulus,
license->Exponent, EncryptedPremasterSecret);
#endif
license->EncryptedPremasterSecret->data = EncryptedPremasterSecret;
return TRUE;
}
static BOOL license_rc4_with_licenseKey(const rdpLicense* license, const BYTE* input, size_t len,
LICENSE_BLOB* target)
{
WINPR_RC4_CTX* rc4;
BYTE* buffer = NULL;
rc4 =
winpr_RC4_New_Allow_FIPS(license->LicensingEncryptionKey, LICENSING_ENCRYPTION_KEY_LENGTH);
if (!rc4)
return FALSE;
buffer = (BYTE*)realloc(target->data, len);
if (!buffer)
goto error_buffer;
target->data = buffer;
target->length = len;
if (!winpr_RC4_Update(rc4, len, input, buffer))
goto error_buffer;
winpr_RC4_Free(rc4);
return TRUE;
error_buffer:
winpr_RC4_Free(rc4);
return FALSE;
}
/**
* Encrypt the input using the license key and MAC the input for a signature
*
* @param license rdpLicense to get keys and salt from
* @param input the input data to encrypt and MAC
* @param len size of input
* @param target a target LICENSE_BLOB where the encrypted input will be stored
* @param mac the signature buffer (16 bytes)
* @return if the operation completed successfully
*/
static BOOL license_encrypt_and_MAC(rdpLicense* license, const BYTE* input, size_t len,
LICENSE_BLOB* target, BYTE* mac)
{
return license_rc4_with_licenseKey(license, input, len, target) &&
security_mac_data(license->MacSaltKey, input, len, mac);
}
/**
* Decrypt the input using the license key and check the MAC
*
* @param license rdpLicense to get keys and salt from
* @param input the input data to decrypt and MAC
* @param len size of input
* @param target a target LICENSE_BLOB where the decrypted input will be stored
* @param mac the signature buffer (16 bytes)
* @return if the operation completed successfully
*/
static BOOL license_decrypt_and_check_MAC(rdpLicense* license, const BYTE* input, size_t len,
LICENSE_BLOB* target, const BYTE* packetMac)
{
BYTE macData[16];
return license_rc4_with_licenseKey(license, input, len, target) &&
security_mac_data(license->MacSaltKey, target->data, len, macData) &&
(memcmp(packetMac, macData, sizeof(macData)) == 0);
}
/**
* Read Product Information (PRODUCT_INFO).\n
* @msdn{cc241915}
* @param s stream
* @param productInfo product information
*/
BOOL license_read_product_info(wStream* s, LICENSE_PRODUCT_INFO* productInfo)
{
if (Stream_GetRemainingLength(s) < 8)
return FALSE;
Stream_Read_UINT32(s, productInfo->dwVersion); /* dwVersion (4 bytes) */
Stream_Read_UINT32(s, productInfo->cbCompanyName); /* cbCompanyName (4 bytes) */
/* Name must be >0, but there is no upper limit defined, use UINT32_MAX */
if ((productInfo->cbCompanyName < 2) || (productInfo->cbCompanyName % 2 != 0))
return FALSE;
if (Stream_GetRemainingLength(s) < productInfo->cbCompanyName)
return FALSE;
productInfo->pbProductId = NULL;
productInfo->pbCompanyName = (BYTE*)malloc(productInfo->cbCompanyName);
if (!productInfo->pbCompanyName)
return FALSE;
Stream_Read(s, productInfo->pbCompanyName, productInfo->cbCompanyName);
if (Stream_GetRemainingLength(s) < 4)
goto out_fail;
Stream_Read_UINT32(s, productInfo->cbProductId); /* cbProductId (4 bytes) */
if ((productInfo->cbProductId < 2) || (productInfo->cbProductId % 2 != 0))
goto out_fail;
if (Stream_GetRemainingLength(s) < productInfo->cbProductId)
goto out_fail;
productInfo->pbProductId = (BYTE*)malloc(productInfo->cbProductId);
if (!productInfo->pbProductId)
goto out_fail;
Stream_Read(s, productInfo->pbProductId, productInfo->cbProductId);
return TRUE;
out_fail:
free(productInfo->pbCompanyName);
free(productInfo->pbProductId);
productInfo->pbCompanyName = NULL;
productInfo->pbProductId = NULL;
return FALSE;
}
/**
* Allocate New Product Information (LICENSE_PRODUCT_INFO).\n
* @msdn{cc241915}
* @return new product information
*/
LICENSE_PRODUCT_INFO* license_new_product_info()
{
LICENSE_PRODUCT_INFO* productInfo;
productInfo = (LICENSE_PRODUCT_INFO*)malloc(sizeof(LICENSE_PRODUCT_INFO));
if (!productInfo)
return NULL;
productInfo->dwVersion = 0;
productInfo->cbCompanyName = 0;
productInfo->pbCompanyName = NULL;
productInfo->cbProductId = 0;
productInfo->pbProductId = NULL;
return productInfo;
}
/**
* Free Product Information (LICENSE_PRODUCT_INFO).\n
* @msdn{cc241915}
* @param productInfo product information
*/
void license_free_product_info(LICENSE_PRODUCT_INFO* productInfo)
{
if (productInfo)
{
free(productInfo->pbCompanyName);
free(productInfo->pbProductId);
free(productInfo);
}
}
/**
* Read License Binary Blob (LICENSE_BINARY_BLOB).\n
* @msdn{cc240481}
* @param s stream
* @param blob license binary blob
*/
BOOL license_read_binary_blob(wStream* s, LICENSE_BLOB* blob)
{
UINT16 wBlobType;
if (Stream_GetRemainingLength(s) < 4)
return FALSE;
Stream_Read_UINT16(s, wBlobType); /* wBlobType (2 bytes) */
Stream_Read_UINT16(s, blob->length); /* wBlobLen (2 bytes) */
if (Stream_GetRemainingLength(s) < blob->length)
return FALSE;
/*
* Server can choose to not send data by setting length to 0.
* If so, it may not bother to set the type, so shortcut the warning
*/
if ((blob->type != BB_ANY_BLOB) && (blob->length == 0))
return TRUE;
if ((blob->type != wBlobType) && (blob->type != BB_ANY_BLOB))
{
WLog_ERR(TAG,
"license binary blob type (0x%" PRIx16 ") does not match expected type (0x%" PRIx16
").",
wBlobType, blob->type);
}
blob->type = wBlobType;
blob->data = (BYTE*)malloc(blob->length);
if (!blob->data)
return FALSE;
Stream_Read(s, blob->data, blob->length); /* blobData */
return TRUE;
}
/**
* Write License Binary Blob (LICENSE_BINARY_BLOB).\n
* @msdn{cc240481}
* @param s stream
* @param blob license binary blob
*/
BOOL license_write_binary_blob(wStream* s, const LICENSE_BLOB* blob)
{
if (!Stream_EnsureRemainingCapacity(s, blob->length + 4))
return FALSE;
Stream_Write_UINT16(s, blob->type); /* wBlobType (2 bytes) */
Stream_Write_UINT16(s, blob->length); /* wBlobLen (2 bytes) */
if (blob->length > 0)
Stream_Write(s, blob->data, blob->length); /* blobData */
return TRUE;
}
static BOOL license_write_encrypted_premaster_secret_blob(wStream* s, const LICENSE_BLOB* blob,
UINT32 ModulusLength)
{
UINT32 length;
length = ModulusLength + 8;
if (blob->length > ModulusLength)
{
WLog_ERR(TAG, "license_write_encrypted_premaster_secret_blob: invalid blob");
return FALSE;
}
if (!Stream_EnsureRemainingCapacity(s, length + 4))
return FALSE;
Stream_Write_UINT16(s, blob->type); /* wBlobType (2 bytes) */
Stream_Write_UINT16(s, length); /* wBlobLen (2 bytes) */
if (blob->length > 0)
Stream_Write(s, blob->data, blob->length); /* blobData */
Stream_Zero(s, length - blob->length);
return TRUE;
}
/**
* Allocate New License Binary Blob (LICENSE_BINARY_BLOB).\n
* @msdn{cc240481}
* @return new license binary blob
*/
LICENSE_BLOB* license_new_binary_blob(UINT16 type)
{
LICENSE_BLOB* blob;
blob = (LICENSE_BLOB*)calloc(1, sizeof(LICENSE_BLOB));
if (blob)
blob->type = type;
return blob;
}
/**
* Free License Binary Blob (LICENSE_BINARY_BLOB).\n
* @msdn{cc240481}
* @param blob license binary blob
*/
void license_free_binary_blob(LICENSE_BLOB* blob)
{
if (blob)
{
free(blob->data);
free(blob);
}
}
/**
* Read License Scope List (SCOPE_LIST).\n
* @msdn{cc241916}
* @param s stream
* @param scopeList scope list
*/
BOOL license_read_scope_list(wStream* s, SCOPE_LIST* scopeList)
{
UINT32 i;
UINT32 scopeCount;
if (Stream_GetRemainingLength(s) < 4)
return FALSE;
Stream_Read_UINT32(s, scopeCount); /* ScopeCount (4 bytes) */
if (scopeCount > Stream_GetRemainingLength(s) / 4) /* every blob is at least 4 bytes */
return FALSE;
scopeList->count = scopeCount;
scopeList->array = (LICENSE_BLOB*)calloc(scopeCount, sizeof(LICENSE_BLOB));
if (!scopeList->array)
return FALSE;
/* ScopeArray */
for (i = 0; i < scopeCount; i++)
{
scopeList->array[i].type = BB_SCOPE_BLOB;
if (!license_read_binary_blob(s, &scopeList->array[i]))
return FALSE;
}
return TRUE;
}
/**
* Allocate New License Scope List (SCOPE_LIST).\n
* @msdn{cc241916}
* @return new scope list
*/
SCOPE_LIST* license_new_scope_list()
{
return (SCOPE_LIST*)calloc(1, sizeof(SCOPE_LIST));
}
/**
* Free License Scope List (SCOPE_LIST).\n
* @msdn{cc241916}
* @param scopeList scope list
*/
void license_free_scope_list(SCOPE_LIST* scopeList)
{
UINT32 i;
if (!scopeList)
return;
/*
* We must NOT call license_free_binary_blob() on each scopelist->array[i] element,
* because scopelist->array was allocated at once, by a single call to malloc. The elements
* it contains cannot be deallocated separately then.
* To make things clean, we must deallocate each scopelist->array[].data,
* and finish by deallocating scopelist->array with a single call to free().
*/
for (i = 0; i < scopeList->count; i++)
{
free(scopeList->array[i].data);
}
free(scopeList->array);
free(scopeList);
}
BOOL license_send_client_info(rdpLicense* license, const LICENSE_BLOB* calBlob, BYTE* signature)
{
wStream* s;
/* Client License Information: */
UINT32 PlatformId = PLATFORMID;
UINT32 PreferredKeyExchangeAlg = KEY_EXCHANGE_ALG_RSA;
s = license_send_stream_init(license);
if (!s)
return FALSE;
Stream_Write_UINT32(s, PreferredKeyExchangeAlg); /* PreferredKeyExchangeAlg (4 bytes) */
Stream_Write_UINT32(s, PlatformId); /* PlatformId (4 bytes) */
/* ClientRandom (32 bytes) */
Stream_Write(s, license->ClientRandom, CLIENT_RANDOM_LENGTH);
/* Licensing Binary Blob with EncryptedPreMasterSecret: */
if (!license_write_encrypted_premaster_secret_blob(s, license->EncryptedPremasterSecret,
license->ModulusLength))
goto error;
/* Licensing Binary Blob with LicenseInfo: */
if (!license_write_binary_blob(s, calBlob))
goto error;
/* Licensing Binary Blob with EncryptedHWID */
if (!license_write_binary_blob(s, license->EncryptedHardwareId))
goto error;
/* MACData */
Stream_Write(s, signature, LICENSING_ENCRYPTION_KEY_LENGTH);
return license_send(license, s, LICENSE_INFO);
error:
Stream_Release(s);
return FALSE;
}
/**
* Read a LICENSE_REQUEST packet.\n
* @msdn{cc241914}
* @param license license module
* @param s stream
*/
BOOL license_read_license_request_packet(rdpLicense* license, wStream* s)
{
/* ServerRandom (32 bytes) */
if (Stream_GetRemainingLength(s) < 32)
return FALSE;
Stream_Read(s, license->ServerRandom, 32);
/* ProductInfo */
if (!license_read_product_info(s, license->ProductInfo))
return FALSE;
/* KeyExchangeList */
if (!license_read_binary_blob(s, license->KeyExchangeList))
return FALSE;
/* ServerCertificate */
if (!license_read_binary_blob(s, license->ServerCertificate))
return FALSE;
/* ScopeList */
if (!license_read_scope_list(s, license->ScopeList))
return FALSE;
/* Parse Server Certificate */
if (!certificate_read_server_certificate(license->certificate, license->ServerCertificate->data,
license->ServerCertificate->length))
return FALSE;
if (!license_generate_keys(license) || !license_generate_hwid(license) ||
!license_encrypt_premaster_secret(license))
return FALSE;
#ifdef WITH_DEBUG_LICENSE
WLog_DBG(TAG, "ServerRandom:");
winpr_HexDump(TAG, WLOG_DEBUG, license->ServerRandom, 32);
license_print_product_info(license->ProductInfo);
license_print_scope_list(license->ScopeList);
#endif
return TRUE;
}
/*
* Read a PLATFORM_CHALLENGE packet.\n
* @msdn{cc241921}
* @param license license module
* @param s stream
*/
BOOL license_read_platform_challenge_packet(rdpLicense* license, wStream* s)
{
BYTE macData[16];
UINT32 ConnectFlags = 0;
DEBUG_LICENSE("Receiving Platform Challenge Packet");
if (Stream_GetRemainingLength(s) < 4)
return FALSE;
Stream_Read_UINT32(s, ConnectFlags); /* ConnectFlags, Reserved (4 bytes) */
/* EncryptedPlatformChallenge */
license->EncryptedPlatformChallenge->type = BB_ANY_BLOB;
if (!license_read_binary_blob(s, license->EncryptedPlatformChallenge))
return FALSE;
license->EncryptedPlatformChallenge->type = BB_ENCRYPTED_DATA_BLOB;
/* MACData (16 bytes) */
if (Stream_GetRemainingLength(s) < 16)
return FALSE;
Stream_Read(s, macData, 16);
if (!license_decrypt_and_check_MAC(license, license->EncryptedPlatformChallenge->data,
license->EncryptedPlatformChallenge->length,
license->PlatformChallenge, macData))
return FALSE;
#ifdef WITH_DEBUG_LICENSE
WLog_DBG(TAG, "ConnectFlags: 0x%08" PRIX32 "", ConnectFlags);
WLog_DBG(TAG, "EncryptedPlatformChallenge:");
winpr_HexDump(TAG, WLOG_DEBUG, license->EncryptedPlatformChallenge->data,
license->EncryptedPlatformChallenge->length);
WLog_DBG(TAG, "PlatformChallenge:");
winpr_HexDump(TAG, WLOG_DEBUG, license->PlatformChallenge->data,
license->PlatformChallenge->length);
WLog_DBG(TAG, "MacData:");
winpr_HexDump(TAG, WLOG_DEBUG, macData, 16);
#endif
return TRUE;
}
static BOOL license_read_encrypted_blob(const rdpLicense* license, wStream* s, LICENSE_BLOB* target)
{
UINT16 wBlobType, wBlobLen;
BYTE* encryptedData;
if (Stream_GetRemainingLength(s) < 4)
return FALSE;
Stream_Read_UINT16(s, wBlobType);
if (wBlobType != BB_ENCRYPTED_DATA_BLOB)
{
WLog_DBG(
TAG,
"expecting BB_ENCRYPTED_DATA_BLOB blob, probably a windows 2003 server, continuing...");
}
Stream_Read_UINT16(s, wBlobLen);
if (Stream_GetRemainingLength(s) < wBlobLen)
return FALSE;
encryptedData = Stream_Pointer(s);
Stream_Seek(s, wBlobLen);
return license_rc4_with_licenseKey(license, encryptedData, wBlobLen, target);
}
/**
* Read a NEW_LICENSE packet.\n
* @msdn{cc241926}
* @param license license module
* @param s stream
*/
BOOL license_read_new_or_upgrade_license_packet(rdpLicense* license, wStream* s)
{
UINT32 os_major;
UINT32 os_minor;
UINT32 cbScope, cbCompanyName, cbProductId, cbLicenseInfo;
wStream* licenseStream = NULL;
BOOL ret = FALSE;
BYTE computedMac[16];
LICENSE_BLOB* calBlob;
DEBUG_LICENSE("Receiving Server New/Upgrade License Packet");
calBlob = license_new_binary_blob(BB_DATA_BLOB);
if (!calBlob)
return FALSE;
/* EncryptedLicenseInfo */
if (!license_read_encrypted_blob(license, s, calBlob))
goto out_free_blob;
/* compute MAC and check it */
if (Stream_GetRemainingLength(s) < 16)
goto out_free_blob;
if (!security_mac_data(license->MacSaltKey, calBlob->data, calBlob->length, computedMac))
goto out_free_blob;
if (memcmp(computedMac, Stream_Pointer(s), sizeof(computedMac)) != 0)
{
WLog_ERR(TAG, "new or upgrade license MAC mismatch");
goto out_free_blob;
}
if (!Stream_SafeSeek(s, 16))
goto out_free_blob;
licenseStream = Stream_New(calBlob->data, calBlob->length);
if (!licenseStream)
goto out_free_blob;
Stream_Read_UINT16(licenseStream, os_minor);
Stream_Read_UINT16(licenseStream, os_major);
/* Scope */
Stream_Read_UINT32(licenseStream, cbScope);
if (Stream_GetRemainingLength(licenseStream) < cbScope)
goto out_free_stream;
#ifdef WITH_DEBUG_LICENSE
WLog_DBG(TAG, "Scope:");
winpr_HexDump(TAG, WLOG_DEBUG, Stream_Pointer(licenseStream), cbScope);
#endif
Stream_Seek(licenseStream, cbScope);
/* CompanyName */
Stream_Read_UINT32(licenseStream, cbCompanyName);
if (Stream_GetRemainingLength(licenseStream) < cbCompanyName)
goto out_free_stream;
#ifdef WITH_DEBUG_LICENSE
WLog_DBG(TAG, "Company name:");
winpr_HexDump(TAG, WLOG_DEBUG, Stream_Pointer(licenseStream), cbCompanyName);
#endif
Stream_Seek(licenseStream, cbCompanyName);
/* productId */
Stream_Read_UINT32(licenseStream, cbProductId);
if (Stream_GetRemainingLength(licenseStream) < cbProductId)
goto out_free_stream;
#ifdef WITH_DEBUG_LICENSE
WLog_DBG(TAG, "Product id:");
winpr_HexDump(TAG, WLOG_DEBUG, Stream_Pointer(licenseStream), cbProductId);
#endif
Stream_Seek(licenseStream, cbProductId);
/* licenseInfo */
Stream_Read_UINT32(licenseStream, cbLicenseInfo);
if (Stream_GetRemainingLength(licenseStream) < cbLicenseInfo)
goto out_free_stream;
license->state = LICENSE_STATE_COMPLETED;
ret = TRUE;
if (!license->rdp->settings->OldLicenseBehaviour)
ret = saveCal(license->rdp->settings, Stream_Pointer(licenseStream), cbLicenseInfo,
license->rdp->settings->ClientHostname);
out_free_stream:
Stream_Free(licenseStream, FALSE);
out_free_blob:
license_free_binary_blob(calBlob);
return ret;
}
/**
* Read an ERROR_ALERT packet.\n
* @msdn{cc240482}
* @param license license module
* @param s stream
*/
BOOL license_read_error_alert_packet(rdpLicense* license, wStream* s)
{
UINT32 dwErrorCode;
UINT32 dwStateTransition;
if (Stream_GetRemainingLength(s) < 8)
return FALSE;
Stream_Read_UINT32(s, dwErrorCode); /* dwErrorCode (4 bytes) */
Stream_Read_UINT32(s, dwStateTransition); /* dwStateTransition (4 bytes) */
if (!license_read_binary_blob(s, license->ErrorInfo)) /* bbErrorInfo */
return FALSE;
#ifdef WITH_DEBUG_LICENSE
WLog_DBG(TAG, "dwErrorCode: %s, dwStateTransition: %s", error_codes[dwErrorCode],
state_transitions[dwStateTransition]);
#endif
if (dwErrorCode == STATUS_VALID_CLIENT)
{
license->state = LICENSE_STATE_COMPLETED;
return TRUE;
}
switch (dwStateTransition)
{
case ST_TOTAL_ABORT:
license->state = LICENSE_STATE_ABORTED;
break;
case ST_NO_TRANSITION:
license->state = LICENSE_STATE_COMPLETED;
break;
case ST_RESET_PHASE_TO_START:
license->state = LICENSE_STATE_AWAIT;
break;
case ST_RESEND_LAST_MESSAGE:
break;
default:
break;
}
return TRUE;
}
/**
* Write a NEW_LICENSE_REQUEST packet.\n
* @msdn{cc241918}
* @param license license module
* @param s stream
*/
BOOL license_write_new_license_request_packet(rdpLicense* license, wStream* s)
{
UINT32 PlatformId = PLATFORMID;
UINT32 PreferredKeyExchangeAlg = KEY_EXCHANGE_ALG_RSA;
Stream_Write_UINT32(s, PreferredKeyExchangeAlg); /* PreferredKeyExchangeAlg (4 bytes) */
Stream_Write_UINT32(s, PlatformId); /* PlatformId (4 bytes) */
Stream_Write(s, license->ClientRandom, 32); /* ClientRandom (32 bytes) */
if (/* EncryptedPremasterSecret */
!license_write_encrypted_premaster_secret_blob(s, license->EncryptedPremasterSecret,
license->ModulusLength) ||
/* ClientUserName */
!license_write_binary_blob(s, license->ClientUserName) ||
/* ClientMachineName */
!license_write_binary_blob(s, license->ClientMachineName))
{
return FALSE;
}
#ifdef WITH_DEBUG_LICENSE
WLog_DBG(TAG, "PreferredKeyExchangeAlg: 0x%08" PRIX32 "", PreferredKeyExchangeAlg);
WLog_DBG(TAG, "ClientRandom:");
winpr_HexDump(TAG, WLOG_DEBUG, license->ClientRandom, 32);
WLog_DBG(TAG, "EncryptedPremasterSecret");
winpr_HexDump(TAG, WLOG_DEBUG, license->EncryptedPremasterSecret->data,
license->EncryptedPremasterSecret->length);
WLog_DBG(TAG, "ClientUserName (%" PRIu16 "): %s", license->ClientUserName->length,
(char*)license->ClientUserName->data);
WLog_DBG(TAG, "ClientMachineName (%" PRIu16 "): %s", license->ClientMachineName->length,
(char*)license->ClientMachineName->data);
#endif
return TRUE;
}
/**
* Send a NEW_LICENSE_REQUEST packet.\n
* @msdn{cc241918}
* @param license license module
*/
BOOL license_answer_license_request(rdpLicense* license)
{
wStream* s;
BYTE* license_data = NULL;
int license_size = 0;
BOOL status;
char* username;
if (!license->rdp->settings->OldLicenseBehaviour)
license_data = loadCalFile(license->rdp->settings, license->rdp->settings->ClientHostname,
&license_size);
if (license_data)
{
LICENSE_BLOB* calBlob = NULL;
BYTE signature[LICENSING_ENCRYPTION_KEY_LENGTH];
DEBUG_LICENSE("Sending Saved License Packet");
license->EncryptedHardwareId->type = BB_ENCRYPTED_DATA_BLOB;
if (!license_encrypt_and_MAC(license, license->HardwareId, HWID_LENGTH,
license->EncryptedHardwareId, signature))
{
free(license_data);
return FALSE;
}
calBlob = license_new_binary_blob(BB_DATA_BLOB);
if (!calBlob)
{
free(license_data);
return FALSE;
}
calBlob->data = license_data;
calBlob->length = license_size;
status = license_send_client_info(license, calBlob, signature);
license_free_binary_blob(calBlob);
return status;
}
DEBUG_LICENSE("Sending New License Packet");
s = license_send_stream_init(license);
if (!s)
return FALSE;
if (license->rdp->settings->Username != NULL)
username = license->rdp->settings->Username;
else
username = "username";
license->ClientUserName->data = (BYTE*)username;
license->ClientUserName->length = strlen(username) + 1;
license->ClientMachineName->data = (BYTE*)license->rdp->settings->ClientHostname;
license->ClientMachineName->length = strlen(license->rdp->settings->ClientHostname) + 1;
status = license_write_new_license_request_packet(license, s);
license->ClientUserName->data = NULL;
license->ClientUserName->length = 0;
license->ClientMachineName->data = NULL;
license->ClientMachineName->length = 0;
if (!status)
{
Stream_Release(s);
return FALSE;
}
return license_send(license, s, NEW_LICENSE_REQUEST);
}
/**
* Write Client Challenge Response Packet.\n
* @msdn{cc241922}
* @param license license module
* @param s stream
* @param mac_data signature
*/
BOOL license_write_platform_challenge_response_packet(rdpLicense* license, wStream* s,
const BYTE* macData)
{
if (!license_write_binary_blob(
s,
license->EncryptedPlatformChallengeResponse) || /* EncryptedPlatformChallengeResponse */
!license_write_binary_blob(s, license->EncryptedHardwareId) || /* EncryptedHWID */
!Stream_EnsureRemainingCapacity(s, 16))
{
return FALSE;
}
Stream_Write(s, macData, 16); /* MACData */
return TRUE;
}
/**
* Send Client Challenge Response Packet.\n
* @msdn{cc241922}
* @param license license module
*/
BOOL license_send_platform_challenge_response_packet(rdpLicense* license)
{
wStream* s;
wStream* challengeRespData;
int length;
BYTE* buffer;
BYTE mac_data[16];
BOOL status;
DEBUG_LICENSE("Sending Platform Challenge Response Packet");
s = license_send_stream_init(license);
license->EncryptedPlatformChallenge->type = BB_DATA_BLOB;
/* prepare the PLATFORM_CHALLENGE_RESPONSE_DATA */
challengeRespData = Stream_New(NULL, 8 + license->PlatformChallenge->length);
if (!challengeRespData)
return FALSE;
Stream_Write_UINT16(challengeRespData, 0x0100); /* wVersion */
Stream_Write_UINT16(challengeRespData, OTHER_PLATFORM_CHALLENGE_TYPE); /* wClientType */
Stream_Write_UINT16(challengeRespData, LICENSE_DETAIL_DETAIL); /* wLicenseDetailLevel */
Stream_Write_UINT16(challengeRespData, license->PlatformChallenge->length); /* cbChallenge */
Stream_Write(challengeRespData, license->PlatformChallenge->data,
license->PlatformChallenge->length); /* pbChallenge */
Stream_SealLength(challengeRespData);
/* compute MAC of PLATFORM_CHALLENGE_RESPONSE_DATA + HWID */
length = Stream_Length(challengeRespData) + HWID_LENGTH;
buffer = (BYTE*)malloc(length);
if (!buffer)
{
Stream_Free(challengeRespData, TRUE);
return FALSE;
}
CopyMemory(buffer, Stream_Buffer(challengeRespData), Stream_Length(challengeRespData));
CopyMemory(&buffer[Stream_Length(challengeRespData)], license->HardwareId, HWID_LENGTH);
status = security_mac_data(license->MacSaltKey, buffer, length, mac_data);
free(buffer);
if (!status)
{
Stream_Free(challengeRespData, TRUE);
return FALSE;
}
license->EncryptedHardwareId->type = BB_ENCRYPTED_DATA_BLOB;
if (!license_rc4_with_licenseKey(license, license->HardwareId, HWID_LENGTH,
license->EncryptedHardwareId))
{
Stream_Free(challengeRespData, TRUE);
return FALSE;
}
status = license_rc4_with_licenseKey(license, Stream_Buffer(challengeRespData),
Stream_Length(challengeRespData),
license->EncryptedPlatformChallengeResponse);
Stream_Free(challengeRespData, TRUE);
if (!status)
return FALSE;
#ifdef WITH_DEBUG_LICENSE
WLog_DBG(TAG, "LicensingEncryptionKey:");
winpr_HexDump(TAG, WLOG_DEBUG, license->LicensingEncryptionKey, 16);
WLog_DBG(TAG, "HardwareId:");
winpr_HexDump(TAG, WLOG_DEBUG, license->HardwareId, HWID_LENGTH);
WLog_DBG(TAG, "EncryptedHardwareId:");
winpr_HexDump(TAG, WLOG_DEBUG, license->EncryptedHardwareId->data, HWID_LENGTH);
#endif
if (license_write_platform_challenge_response_packet(license, s, mac_data))
return license_send(license, s, PLATFORM_CHALLENGE_RESPONSE);
Stream_Release(s);
return FALSE;
}
/**
* Send Server License Error - Valid Client Packet.\n
* @msdn{cc241922}
* @param license license module
*/
BOOL license_send_valid_client_error_packet(rdpRdp* rdp)
{
rdpLicense* license = rdp->license;
wStream* s = license_send_stream_init(license);
if (!s)
return FALSE;
DEBUG_LICENSE("Sending Error Alert Packet");
Stream_Write_UINT32(s, STATUS_VALID_CLIENT); /* dwErrorCode */
Stream_Write_UINT32(s, ST_NO_TRANSITION); /* dwStateTransition */
if (license_write_binary_blob(s, license->ErrorInfo))
return license_send(license, s, ERROR_ALERT);
Stream_Release(s);
return FALSE;
}
/**
* Instantiate new license module.
* @param rdp RDP module
* @return new license module
*/
rdpLicense* license_new(rdpRdp* rdp)
{
rdpLicense* license;
license = (rdpLicense*)calloc(1, sizeof(rdpLicense));
if (!license)
return NULL;
license->rdp = rdp;
license->state = LICENSE_STATE_AWAIT;
if (!(license->certificate = certificate_new()))
goto out_error;
if (!(license->ProductInfo = license_new_product_info()))
goto out_error;
if (!(license->ErrorInfo = license_new_binary_blob(BB_ERROR_BLOB)))
goto out_error;
if (!(license->KeyExchangeList = license_new_binary_blob(BB_KEY_EXCHG_ALG_BLOB)))
goto out_error;
if (!(license->ServerCertificate = license_new_binary_blob(BB_CERTIFICATE_BLOB)))
goto out_error;
if (!(license->ClientUserName = license_new_binary_blob(BB_CLIENT_USER_NAME_BLOB)))
goto out_error;
if (!(license->ClientMachineName = license_new_binary_blob(BB_CLIENT_MACHINE_NAME_BLOB)))
goto out_error;
if (!(license->PlatformChallenge = license_new_binary_blob(BB_ANY_BLOB)))
goto out_error;
if (!(license->EncryptedPlatformChallenge = license_new_binary_blob(BB_ANY_BLOB)))
goto out_error;
if (!(license->EncryptedPlatformChallengeResponse =
license_new_binary_blob(BB_ENCRYPTED_DATA_BLOB)))
goto out_error;
if (!(license->EncryptedPremasterSecret = license_new_binary_blob(BB_ANY_BLOB)))
goto out_error;
if (!(license->EncryptedHardwareId = license_new_binary_blob(BB_ENCRYPTED_DATA_BLOB)))
goto out_error;
if (!(license->ScopeList = license_new_scope_list()))
goto out_error;
license_generate_randoms(license);
return license;
out_error:
license_free(license);
return NULL;
}
/**
* Free license module.
* @param license license module to be freed
*/
void license_free(rdpLicense* license)
{
if (license)
{
free(license->Modulus);
certificate_free(license->certificate);
license_free_product_info(license->ProductInfo);
license_free_binary_blob(license->ErrorInfo);
license_free_binary_blob(license->KeyExchangeList);
license_free_binary_blob(license->ServerCertificate);
license_free_binary_blob(license->ClientUserName);
license_free_binary_blob(license->ClientMachineName);
license_free_binary_blob(license->PlatformChallenge);
license_free_binary_blob(license->EncryptedPlatformChallenge);
license_free_binary_blob(license->EncryptedPlatformChallengeResponse);
license_free_binary_blob(license->EncryptedPremasterSecret);
license_free_binary_blob(license->EncryptedHardwareId);
license_free_scope_list(license->ScopeList);
free(license);
}
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_3955_0 |
crossvul-cpp_data_bad_5240_4 | 404: Not Found | ./CrossVul/dataset_final_sorted/CWE-125/c/bad_5240_4 |
crossvul-cpp_data_bad_1852_0 | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% 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,
height,
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_NONE:
break;
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) &&
((number_pixels*sun_info.depth) > (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");
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");
if (sun_info.type == RT_ENCODED)
(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+bytes_per_line % 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-125/c/bad_1852_0 |
crossvul-cpp_data_bad_5314_1 | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% QQQ U U AAA N N TTTTT U U M M %
% Q Q U U A A NN N T U U MM MM %
% Q Q U U AAAAA N N N T U U M M M %
% Q QQ U U A A N NN T U U M M %
% QQQQ UUU A A N N T UUU M M %
% %
% MagicCore Methods to Acquire / Destroy Quantum Pixels %
% %
% Software Design %
% Cristy %
% October 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. %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%
*/
/*
Include declarations.
*/
#include "MagickCore/studio.h"
#include "MagickCore/attribute.h"
#include "MagickCore/blob.h"
#include "MagickCore/blob-private.h"
#include "MagickCore/color-private.h"
#include "MagickCore/exception.h"
#include "MagickCore/exception-private.h"
#include "MagickCore/cache.h"
#include "MagickCore/cache-private.h"
#include "MagickCore/colorspace.h"
#include "MagickCore/colorspace-private.h"
#include "MagickCore/constitute.h"
#include "MagickCore/delegate.h"
#include "MagickCore/geometry.h"
#include "MagickCore/list.h"
#include "MagickCore/magick.h"
#include "MagickCore/memory_.h"
#include "MagickCore/monitor.h"
#include "MagickCore/option.h"
#include "MagickCore/pixel.h"
#include "MagickCore/pixel-accessor.h"
#include "MagickCore/property.h"
#include "MagickCore/quantum.h"
#include "MagickCore/quantum-private.h"
#include "MagickCore/resource_.h"
#include "MagickCore/semaphore.h"
#include "MagickCore/statistic.h"
#include "MagickCore/stream.h"
#include "MagickCore/string_.h"
#include "MagickCore/string-private.h"
#include "MagickCore/thread-private.h"
#include "MagickCore/utility.h"
/*
Define declarations.
*/
#define QuantumSignature 0xab
/*
Forward declarations.
*/
static void
DestroyQuantumPixels(QuantumInfo *);
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% A c q u i r e Q u a n t u m I n f o %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% AcquireQuantumInfo() allocates the QuantumInfo structure.
%
% The format of the AcquireQuantumInfo method is:
%
% QuantumInfo *AcquireQuantumInfo(const ImageInfo *image_info,Image *image)
%
% A description of each parameter follows:
%
% o image_info: the image info.
%
% o image: the image.
%
*/
MagickExport QuantumInfo *AcquireQuantumInfo(const ImageInfo *image_info,
Image *image)
{
MagickBooleanType
status;
QuantumInfo
*quantum_info;
quantum_info=(QuantumInfo *) AcquireMagickMemory(sizeof(*quantum_info));
if (quantum_info == (QuantumInfo *) NULL)
ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
quantum_info->signature=MagickCoreSignature;
GetQuantumInfo(image_info,quantum_info);
if (image == (const Image *) NULL)
return(quantum_info);
status=SetQuantumDepth(image,quantum_info,image->depth);
quantum_info->endian=image->endian;
if (status == MagickFalse)
quantum_info=DestroyQuantumInfo(quantum_info);
return(quantum_info);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ A c q u i r e Q u a n t u m P i x e l s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% AcquireQuantumPixels() allocates the pixel staging areas.
%
% The format of the AcquireQuantumPixels method is:
%
% MagickBooleanType AcquireQuantumPixels(QuantumInfo *quantum_info,
% const size_t extent)
%
% A description of each parameter follows:
%
% o quantum_info: the quantum info.
%
% o extent: the quantum info.
%
*/
static MagickBooleanType AcquireQuantumPixels(QuantumInfo *quantum_info,
const size_t extent)
{
register ssize_t
i;
assert(quantum_info != (QuantumInfo *) NULL);
assert(quantum_info->signature == MagickCoreSignature);
quantum_info->number_threads=(size_t) GetMagickResourceLimit(ThreadResource);
quantum_info->pixels=(unsigned char **) AcquireQuantumMemory(
quantum_info->number_threads,sizeof(*quantum_info->pixels));
if (quantum_info->pixels == (unsigned char **) NULL)
return(MagickFalse);
quantum_info->extent=extent;
(void) ResetMagickMemory(quantum_info->pixels,0,quantum_info->number_threads*
sizeof(*quantum_info->pixels));
for (i=0; i < (ssize_t) quantum_info->number_threads; i++)
{
quantum_info->pixels[i]=(unsigned char *) AcquireQuantumMemory(extent+1,
sizeof(**quantum_info->pixels));
if (quantum_info->pixels[i] == (unsigned char *) NULL)
{
while (--i >= 0)
quantum_info->pixels[i]=(unsigned char *) RelinquishMagickMemory(
quantum_info->pixels[i]);
return(MagickFalse);
}
(void) ResetMagickMemory(quantum_info->pixels[i],0,(extent+1)*
sizeof(**quantum_info->pixels));
quantum_info->pixels[i][extent]=QuantumSignature;
}
return(MagickTrue);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% D e s t r o y Q u a n t u m I n f o %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% DestroyQuantumInfo() deallocates memory associated with the QuantumInfo
% structure.
%
% The format of the DestroyQuantumInfo method is:
%
% QuantumInfo *DestroyQuantumInfo(QuantumInfo *quantum_info)
%
% A description of each parameter follows:
%
% o quantum_info: the quantum info.
%
*/
MagickExport QuantumInfo *DestroyQuantumInfo(QuantumInfo *quantum_info)
{
assert(quantum_info != (QuantumInfo *) NULL);
assert(quantum_info->signature == MagickCoreSignature);
if (quantum_info->pixels != (unsigned char **) NULL)
DestroyQuantumPixels(quantum_info);
if (quantum_info->semaphore != (SemaphoreInfo *) NULL)
RelinquishSemaphoreInfo(&quantum_info->semaphore);
quantum_info->signature=(~MagickCoreSignature);
quantum_info=(QuantumInfo *) RelinquishMagickMemory(quantum_info);
return(quantum_info);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ D e s t r o y Q u a n t u m P i x e l s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% DestroyQuantumPixels() destroys the quantum pixels.
%
% The format of the DestroyQuantumPixels() method is:
%
% void DestroyQuantumPixels(QuantumInfo *quantum_info)
%
% A description of each parameter follows:
%
% o quantum_info: the quantum info.
%
*/
static void DestroyQuantumPixels(QuantumInfo *quantum_info)
{
register ssize_t
i;
ssize_t
extent;
assert(quantum_info != (QuantumInfo *) NULL);
assert(quantum_info->signature == MagickCoreSignature);
assert(quantum_info->pixels != (unsigned char **) NULL);
extent=(ssize_t) quantum_info->extent;
for (i=0; i < (ssize_t) quantum_info->number_threads; i++)
if (quantum_info->pixels[i] != (unsigned char *) NULL)
{
/*
Did we overrun our quantum buffer?
*/
assert(quantum_info->pixels[i][extent] == QuantumSignature);
quantum_info->pixels[i]=(unsigned char *) RelinquishMagickMemory(
quantum_info->pixels[i]);
}
quantum_info->pixels=(unsigned char **) RelinquishMagickMemory(
quantum_info->pixels);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% G e t Q u a n t u m E x t e n t %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetQuantumExtent() returns the quantum pixel buffer extent.
%
% The format of the GetQuantumExtent method is:
%
% size_t GetQuantumExtent(Image *image,const QuantumInfo *quantum_info,
% const QuantumType quantum_type)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o quantum_info: the quantum info.
%
% o quantum_type: Declare which pixel components to transfer (red, green,
% blue, opacity, RGB, or RGBA).
%
*/
MagickExport size_t GetQuantumExtent(const Image *image,
const QuantumInfo *quantum_info,const QuantumType quantum_type)
{
size_t
extent,
packet_size;
assert(quantum_info != (QuantumInfo *) NULL);
assert(quantum_info->signature == MagickCoreSignature);
packet_size=1;
switch (quantum_type)
{
case GrayAlphaQuantum: packet_size=2; break;
case IndexAlphaQuantum: packet_size=2; break;
case RGBQuantum: packet_size=3; break;
case BGRQuantum: packet_size=3; break;
case RGBAQuantum: packet_size=4; break;
case RGBOQuantum: packet_size=4; break;
case BGRAQuantum: packet_size=4; break;
case CMYKQuantum: packet_size=4; break;
case CMYKAQuantum: packet_size=5; break;
default: break;
}
extent=MagickMax(image->columns,image->rows);
if (quantum_info->pack == MagickFalse)
return((size_t) (packet_size*extent*((quantum_info->depth+7)/8)));
return((size_t) ((packet_size*extent*quantum_info->depth+7)/8));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% G e t Q u a n t u m E n d i a n %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetQuantumEndian() returns the quantum endian of the image.
%
% The endian of the GetQuantumEndian method is:
%
% EndianType GetQuantumEndian(const QuantumInfo *quantum_info)
%
% A description of each parameter follows:
%
% o quantum_info: the quantum info.
%
*/
MagickExport EndianType GetQuantumEndian(const QuantumInfo *quantum_info)
{
assert(quantum_info != (QuantumInfo *) NULL);
assert(quantum_info->signature == MagickCoreSignature);
return(quantum_info->endian);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% G e t Q u a n t u m F o r m a t %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetQuantumFormat() returns the quantum format of the image.
%
% The format of the GetQuantumFormat method is:
%
% QuantumFormatType GetQuantumFormat(const QuantumInfo *quantum_info)
%
% A description of each parameter follows:
%
% o quantum_info: the quantum info.
%
*/
MagickExport QuantumFormatType GetQuantumFormat(const QuantumInfo *quantum_info)
{
assert(quantum_info != (QuantumInfo *) NULL);
assert(quantum_info->signature == MagickCoreSignature);
return(quantum_info->format);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% G e t Q u a n t u m I n f o %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetQuantumInfo() initializes the QuantumInfo structure to default values.
%
% The format of the GetQuantumInfo method is:
%
% GetQuantumInfo(const ImageInfo *image_info,QuantumInfo *quantum_info)
%
% A description of each parameter follows:
%
% o image_info: the image info.
%
% o quantum_info: the quantum info.
%
*/
MagickExport void GetQuantumInfo(const ImageInfo *image_info,
QuantumInfo *quantum_info)
{
const char
*option;
assert(quantum_info != (QuantumInfo *) NULL);
(void) ResetMagickMemory(quantum_info,0,sizeof(*quantum_info));
quantum_info->quantum=8;
quantum_info->maximum=1.0;
quantum_info->scale=QuantumRange;
quantum_info->pack=MagickTrue;
quantum_info->semaphore=AcquireSemaphoreInfo();
quantum_info->signature=MagickCoreSignature;
if (image_info == (const ImageInfo *) NULL)
return;
option=GetImageOption(image_info,"quantum:format");
if (option != (char *) NULL)
quantum_info->format=(QuantumFormatType) ParseCommandOption(
MagickQuantumFormatOptions,MagickFalse,option);
option=GetImageOption(image_info,"quantum:minimum");
if (option != (char *) NULL)
quantum_info->minimum=StringToDouble(option,(char **) NULL);
option=GetImageOption(image_info,"quantum:maximum");
if (option != (char *) NULL)
quantum_info->maximum=StringToDouble(option,(char **) NULL);
if ((quantum_info->minimum == 0.0) && (quantum_info->maximum == 0.0))
quantum_info->scale=0.0;
else
if (quantum_info->minimum == quantum_info->maximum)
{
quantum_info->scale=(double) QuantumRange/quantum_info->minimum;
quantum_info->minimum=0.0;
}
else
quantum_info->scale=(double) QuantumRange/(quantum_info->maximum-
quantum_info->minimum);
option=GetImageOption(image_info,"quantum:scale");
if (option != (char *) NULL)
quantum_info->scale=StringToDouble(option,(char **) NULL);
option=GetImageOption(image_info,"quantum:polarity");
if (option != (char *) NULL)
quantum_info->min_is_white=LocaleCompare(option,"min-is-white") == 0 ?
MagickTrue : MagickFalse;
quantum_info->endian=image_info->endian;
ResetQuantumState(quantum_info);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% G e t Q u a n t u m P i x e l s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetQuantumPixels() returns the quantum pixels.
%
% The format of the GetQuantumPixels method is:
%
% unsigned char *QuantumPixels GetQuantumPixels(
% const QuantumInfo *quantum_info)
%
% A description of each parameter follows:
%
% o image: the image.
%
*/
MagickExport unsigned char *GetQuantumPixels(const QuantumInfo *quantum_info)
{
const int
id = GetOpenMPThreadId();
assert(quantum_info != (QuantumInfo *) NULL);
assert(quantum_info->signature == MagickCoreSignature);
return(quantum_info->pixels[id]);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% G e t Q u a n t u m T y p e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetQuantumType() returns the quantum type of the image.
%
% The format of the GetQuantumType method is:
%
% QuantumType GetQuantumType(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 QuantumType GetQuantumType(Image *image,ExceptionInfo *exception)
{
QuantumType
quantum_type;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
(void) exception;
quantum_type=RGBQuantum;
if (image->alpha_trait != UndefinedPixelTrait)
quantum_type=RGBAQuantum;
if (image->colorspace == CMYKColorspace)
{
quantum_type=CMYKQuantum;
if (image->alpha_trait != UndefinedPixelTrait)
quantum_type=CMYKAQuantum;
}
if (IsGrayColorspace(image->colorspace) != MagickFalse)
{
quantum_type=GrayQuantum;
if (image->alpha_trait != UndefinedPixelTrait)
quantum_type=GrayAlphaQuantum;
}
if (image->storage_class == PseudoClass)
{
quantum_type=IndexQuantum;
if (image->alpha_trait != UndefinedPixelTrait)
quantum_type=IndexAlphaQuantum;
}
return(quantum_type);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ R e s e t Q u a n t u m S t a t e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ResetQuantumState() resets the quantum state.
%
% The format of the ResetQuantumState method is:
%
% void ResetQuantumState(QuantumInfo *quantum_info)
%
% A description of each parameter follows:
%
% o quantum_info: the quantum info.
%
*/
MagickPrivate void ResetQuantumState(QuantumInfo *quantum_info)
{
static const unsigned int mask[32] =
{
0x00000000U, 0x00000001U, 0x00000003U, 0x00000007U, 0x0000000fU,
0x0000001fU, 0x0000003fU, 0x0000007fU, 0x000000ffU, 0x000001ffU,
0x000003ffU, 0x000007ffU, 0x00000fffU, 0x00001fffU, 0x00003fffU,
0x00007fffU, 0x0000ffffU, 0x0001ffffU, 0x0003ffffU, 0x0007ffffU,
0x000fffffU, 0x001fffffU, 0x003fffffU, 0x007fffffU, 0x00ffffffU,
0x01ffffffU, 0x03ffffffU, 0x07ffffffU, 0x0fffffffU, 0x1fffffffU,
0x3fffffffU, 0x7fffffffU
};
assert(quantum_info != (QuantumInfo *) NULL);
assert(quantum_info->signature == MagickCoreSignature);
quantum_info->state.inverse_scale=1.0;
if (fabs(quantum_info->scale) >= MagickEpsilon)
quantum_info->state.inverse_scale/=quantum_info->scale;
quantum_info->state.pixel=0U;
quantum_info->state.bits=0U;
quantum_info->state.mask=mask;
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S e t Q u a n t u m F o r m a t %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% SetQuantumAlphaType() sets the quantum format.
%
% The format of the SetQuantumAlphaType method is:
%
% void SetQuantumAlphaType(QuantumInfo *quantum_info,
% const QuantumAlphaType type)
%
% A description of each parameter follows:
%
% o quantum_info: the quantum info.
%
% o type: the alpha type (e.g. associate).
%
*/
MagickExport void SetQuantumAlphaType(QuantumInfo *quantum_info,
const QuantumAlphaType type)
{
assert(quantum_info != (QuantumInfo *) NULL);
assert(quantum_info->signature == MagickCoreSignature);
quantum_info->alpha_type=type;
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S e t Q u a n t u m D e p t h %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% SetQuantumDepth() sets the quantum depth.
%
% The format of the SetQuantumDepth method is:
%
% MagickBooleanType SetQuantumDepth(const Image *image,
% QuantumInfo *quantum_info,const size_t depth)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o quantum_info: the quantum info.
%
% o depth: the quantum depth.
%
*/
MagickExport MagickBooleanType SetQuantumDepth(const Image *image,
QuantumInfo *quantum_info,const size_t depth)
{
size_t
extent,
quantum;
/*
Allocate the quantum pixel buffer.
*/
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(quantum_info != (QuantumInfo *) NULL);
assert(quantum_info->signature == MagickCoreSignature);
quantum_info->depth=depth;
if (quantum_info->format == FloatingPointQuantumFormat)
{
if (quantum_info->depth > 32)
quantum_info->depth=64;
else
if (quantum_info->depth > 16)
quantum_info->depth=32;
else
quantum_info->depth=16;
}
if (quantum_info->pixels != (unsigned char **) NULL)
DestroyQuantumPixels(quantum_info);
quantum=(quantum_info->pad+6)*(quantum_info->depth+7)/8;
extent=MagickMax(image->columns,image->rows)*quantum;
if ((MagickMax(image->columns,image->rows) != 0) &&
(quantum != (extent/MagickMax(image->columns,image->rows))))
return(MagickFalse);
return(AcquireQuantumPixels(quantum_info,extent));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S e t Q u a n t u m E n d i a n %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% SetQuantumEndian() sets the quantum endian.
%
% The endian of the SetQuantumEndian method is:
%
% MagickBooleanType SetQuantumEndian(const Image *image,
% QuantumInfo *quantum_info,const EndianType endian)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o quantum_info: the quantum info.
%
% o endian: the quantum endian.
%
*/
MagickExport MagickBooleanType SetQuantumEndian(const Image *image,
QuantumInfo *quantum_info,const EndianType endian)
{
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(quantum_info != (QuantumInfo *) NULL);
assert(quantum_info->signature == MagickCoreSignature);
quantum_info->endian=endian;
return(SetQuantumDepth(image,quantum_info,quantum_info->depth));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S e t Q u a n t u m F o r m a t %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% SetQuantumFormat() sets the quantum format.
%
% The format of the SetQuantumFormat method is:
%
% MagickBooleanType SetQuantumFormat(const Image *image,
% QuantumInfo *quantum_info,const QuantumFormatType format)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o quantum_info: the quantum info.
%
% o format: the quantum format.
%
*/
MagickExport MagickBooleanType SetQuantumFormat(const Image *image,
QuantumInfo *quantum_info,const QuantumFormatType format)
{
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(quantum_info != (QuantumInfo *) NULL);
assert(quantum_info->signature == MagickCoreSignature);
quantum_info->format=format;
return(SetQuantumDepth(image,quantum_info,quantum_info->depth));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S e t Q u a n t u m I m a g e T y p e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% SetQuantumImageType() sets the image type based on the quantum type.
%
% The format of the SetQuantumImageType method is:
%
% void ImageType SetQuantumImageType(Image *image,
% const QuantumType quantum_type)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o quantum_type: Declare which pixel components to transfer (red, green,
% blue, opacity, RGB, or RGBA).
%
*/
MagickExport void SetQuantumImageType(Image *image,
const QuantumType quantum_type)
{
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
switch (quantum_type)
{
case IndexQuantum:
case IndexAlphaQuantum:
{
image->type=PaletteType;
break;
}
case GrayQuantum:
case GrayAlphaQuantum:
{
image->type=GrayscaleType;
if (image->depth == 1)
image->type=BilevelType;
break;
}
case CyanQuantum:
case MagentaQuantum:
case YellowQuantum:
case BlackQuantum:
case CMYKQuantum:
case CMYKAQuantum:
{
image->type=ColorSeparationType;
break;
}
default:
{
image->type=TrueColorType;
break;
}
}
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S e t Q u a n t u m P a c k %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% SetQuantumPack() sets the quantum pack flag.
%
% The format of the SetQuantumPack method is:
%
% void SetQuantumPack(QuantumInfo *quantum_info,
% const MagickBooleanType pack)
%
% A description of each parameter follows:
%
% o quantum_info: the quantum info.
%
% o pack: the pack flag.
%
*/
MagickExport void SetQuantumPack(QuantumInfo *quantum_info,
const MagickBooleanType pack)
{
assert(quantum_info != (QuantumInfo *) NULL);
assert(quantum_info->signature == MagickCoreSignature);
quantum_info->pack=pack;
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S e t Q u a n t u m P a d %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% SetQuantumPad() sets the quantum pad.
%
% The format of the SetQuantumPad method is:
%
% MagickBooleanType SetQuantumPad(const Image *image,
% QuantumInfo *quantum_info,const size_t pad)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o quantum_info: the quantum info.
%
% o pad: the quantum pad.
%
*/
MagickExport MagickBooleanType SetQuantumPad(const Image *image,
QuantumInfo *quantum_info,const size_t pad)
{
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(quantum_info != (QuantumInfo *) NULL);
assert(quantum_info->signature == MagickCoreSignature);
quantum_info->pad=pad;
return(SetQuantumDepth(image,quantum_info,quantum_info->depth));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S e t Q u a n t u m M i n I s W h i t e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% SetQuantumMinIsWhite() sets the quantum min-is-white flag.
%
% The format of the SetQuantumMinIsWhite method is:
%
% void SetQuantumMinIsWhite(QuantumInfo *quantum_info,
% const MagickBooleanType min_is_white)
%
% A description of each parameter follows:
%
% o quantum_info: the quantum info.
%
% o min_is_white: the min-is-white flag.
%
*/
MagickExport void SetQuantumMinIsWhite(QuantumInfo *quantum_info,
const MagickBooleanType min_is_white)
{
assert(quantum_info != (QuantumInfo *) NULL);
assert(quantum_info->signature == MagickCoreSignature);
quantum_info->min_is_white=min_is_white;
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S e t Q u a n t u m Q u a n t u m %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% SetQuantumQuantum() sets the quantum quantum.
%
% The format of the SetQuantumQuantum method is:
%
% void SetQuantumQuantum(QuantumInfo *quantum_info,
% const size_t quantum)
%
% A description of each parameter follows:
%
% o quantum_info: the quantum info.
%
% o quantum: the quantum quantum.
%
*/
MagickExport void SetQuantumQuantum(QuantumInfo *quantum_info,
const size_t quantum)
{
assert(quantum_info != (QuantumInfo *) NULL);
assert(quantum_info->signature == MagickCoreSignature);
quantum_info->quantum=quantum;
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S e t Q u a n t u m S c a l e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% SetQuantumScale() sets the quantum scale.
%
% The format of the SetQuantumScale method is:
%
% void SetQuantumScale(QuantumInfo *quantum_info,const double scale)
%
% A description of each parameter follows:
%
% o quantum_info: the quantum info.
%
% o scale: the quantum scale.
%
*/
MagickExport void SetQuantumScale(QuantumInfo *quantum_info,const double scale)
{
assert(quantum_info != (QuantumInfo *) NULL);
assert(quantum_info->signature == MagickCoreSignature);
quantum_info->scale=scale;
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_5314_1 |
crossvul-cpp_data_good_5870_0 | /*
* Filtered Image Rescaling
* Based on Gems III
* - Schumacher general filtered image rescaling
* (pp. 414-424)
* by Dale Schumacher
*
* Additional changes by Ray Gardener, Daylon Graphics Ltd.
* December 4, 1999
*
* Ported to libgd by Pierre Joye. Support for multiple channels
* added (argb for now).
*
* Initial sources code is avaibable in the Gems Source Code Packages:
* http://www.acm.org/pubs/tog/GraphicsGems/GGemsIII.tar.gz
*/
/*
Summary:
- Horizontal filter contributions are calculated on the fly,
as each column is mapped from src to dst image. This lets
us omit having to allocate a temporary full horizontal stretch
of the src image.
- If none of the src pixels within a sampling region differ,
then the output pixel is forced to equal (any of) the source pixel.
This ensures that filters do not corrupt areas of constant color.
- Filter weight contribution results, after summing, are
rounded to the nearest pixel color value instead of
being casted to ILubyte (usually an int or char). Otherwise,
artifacting occurs.
*/
/*
Additional functions are available for simple rotation or up/downscaling.
downscaling using the fixed point implementations are usually much faster
than the existing gdImageCopyResampled while having a similar or better
quality.
For image rotations, the optimized versions have a lazy antialiasing for
the edges of the images. For a much better antialiased result, the affine
function is recommended.
*/
/*
TODO:
- Optimize pixel accesses and loops once we have continuous buffer
- Add scale support for a portion only of an image (equivalent of copyresized/resampled)
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <gd.h>
#include "gdhelpers.h"
#ifdef _MSC_VER
# pragma optimize("t", on)
# include <emmintrin.h>
#endif
#ifndef MIN
#define MIN(a,b) ((a)<(b)?(a):(b))
#endif
#define MIN3(a,b,c) ((a)<(b)?(MIN(a,c)):(MIN(b,c)))
#ifndef MAX
#define MAX(a,b) ((a)<(b)?(b):(a))
#endif
#define MAX3(a,b,c) ((a)<(b)?(MAX(b,c)):(MAX(a,c)))
#define CLAMP(x, low, high) (((x) > (high)) ? (high) : (((x) < (low)) ? (low) : (x)))
/* only used here, let do a generic fixed point integers later if required by other
part of GD */
typedef long gdFixed;
/* Integer to fixed point */
#define gd_itofx(x) ((x) << 8)
/* Float to fixed point */
#define gd_ftofx(x) (long)((x) * 256)
/* Double to fixed point */
#define gd_dtofx(x) (long)((x) * 256)
/* Fixed point to integer */
#define gd_fxtoi(x) ((x) >> 8)
/* Fixed point to float */
# define gd_fxtof(x) ((float)(x) / 256)
/* Fixed point to double */
#define gd_fxtod(x) ((double)(x) / 256)
/* Multiply a fixed by a fixed */
#define gd_mulfx(x,y) (((x) * (y)) >> 8)
/* Divide a fixed by a fixed */
#define gd_divfx(x,y) (((x) << 8) / (y))
typedef struct
{
double *Weights; /* Normalized weights of neighboring pixels */
int Left,Right; /* Bounds of source pixels window */
} ContributionType; /* Contirbution information for a single pixel */
typedef struct
{
ContributionType *ContribRow; /* Row (or column) of contribution weights */
unsigned int WindowSize, /* Filter window size (of affecting source pixels) */
LineLength; /* Length of line (no. or rows / cols) */
} LineContribType;
/* Each core filter has its own radius */
#define DEFAULT_FILTER_BICUBIC 3.0
#define DEFAULT_FILTER_BOX 0.5
#define DEFAULT_FILTER_GENERALIZED_CUBIC 0.5
#define DEFAULT_FILTER_RADIUS 1.0
#define DEFAULT_LANCZOS8_RADIUS 8.0
#define DEFAULT_LANCZOS3_RADIUS 3.0
#define DEFAULT_HERMITE_RADIUS 1.0
#define DEFAULT_BOX_RADIUS 0.5
#define DEFAULT_TRIANGLE_RADIUS 1.0
#define DEFAULT_BELL_RADIUS 1.5
#define DEFAULT_CUBICSPLINE_RADIUS 2.0
#define DEFAULT_MITCHELL_RADIUS 2.0
#define DEFAULT_COSINE_RADIUS 1.0
#define DEFAULT_CATMULLROM_RADIUS 2.0
#define DEFAULT_QUADRATIC_RADIUS 1.5
#define DEFAULT_QUADRATICBSPLINE_RADIUS 1.5
#define DEFAULT_CUBICCONVOLUTION_RADIUS 3.0
#define DEFAULT_GAUSSIAN_RADIUS 1.0
#define DEFAULT_HANNING_RADIUS 1.0
#define DEFAULT_HAMMING_RADIUS 1.0
#define DEFAULT_SINC_RADIUS 1.0
#define DEFAULT_WELSH_RADIUS 1.0
enum GD_RESIZE_FILTER_TYPE{
FILTER_DEFAULT = 0,
FILTER_BELL,
FILTER_BESSEL,
FILTER_BLACKMAN,
FILTER_BOX,
FILTER_BSPLINE,
FILTER_CATMULLROM,
FILTER_COSINE,
FILTER_CUBICCONVOLUTION,
FILTER_CUBICSPLINE,
FILTER_HERMITE,
FILTER_LANCZOS3,
FILTER_LANCZOS8,
FILTER_MITCHELL,
FILTER_QUADRATIC,
FILTER_QUADRATICBSPLINE,
FILTER_TRIANGLE,
FILTER_GAUSSIAN,
FILTER_HANNING,
FILTER_HAMMING,
FILTER_SINC,
FILTER_WELSH,
FILTER_CALLBACK = 999
};
typedef enum GD_RESIZE_FILTER_TYPE gdResizeFilterType;
static double KernelBessel_J1(const double x)
{
double p, q;
register long i;
static const double
Pone[] =
{
0.581199354001606143928050809e+21,
-0.6672106568924916298020941484e+20,
0.2316433580634002297931815435e+19,
-0.3588817569910106050743641413e+17,
0.2908795263834775409737601689e+15,
-0.1322983480332126453125473247e+13,
0.3413234182301700539091292655e+10,
-0.4695753530642995859767162166e+7,
0.270112271089232341485679099e+4
},
Qone[] =
{
0.11623987080032122878585294e+22,
0.1185770712190320999837113348e+20,
0.6092061398917521746105196863e+17,
0.2081661221307607351240184229e+15,
0.5243710262167649715406728642e+12,
0.1013863514358673989967045588e+10,
0.1501793594998585505921097578e+7,
0.1606931573481487801970916749e+4,
0.1e+1
};
p = Pone[8];
q = Qone[8];
for (i=7; i >= 0; i--)
{
p = p*x*x+Pone[i];
q = q*x*x+Qone[i];
}
return (double)(p/q);
}
static double KernelBessel_P1(const double x)
{
double p, q;
register long i;
static const double
Pone[] =
{
0.352246649133679798341724373e+5,
0.62758845247161281269005675e+5,
0.313539631109159574238669888e+5,
0.49854832060594338434500455e+4,
0.2111529182853962382105718e+3,
0.12571716929145341558495e+1
},
Qone[] =
{
0.352246649133679798068390431e+5,
0.626943469593560511888833731e+5,
0.312404063819041039923015703e+5,
0.4930396490181088979386097e+4,
0.2030775189134759322293574e+3,
0.1e+1
};
p = Pone[5];
q = Qone[5];
for (i=4; i >= 0; i--)
{
p = p*(8.0/x)*(8.0/x)+Pone[i];
q = q*(8.0/x)*(8.0/x)+Qone[i];
}
return (double)(p/q);
}
static double KernelBessel_Q1(const double x)
{
double p, q;
register long i;
static const double
Pone[] =
{
0.3511751914303552822533318e+3,
0.7210391804904475039280863e+3,
0.4259873011654442389886993e+3,
0.831898957673850827325226e+2,
0.45681716295512267064405e+1,
0.3532840052740123642735e-1
},
Qone[] =
{
0.74917374171809127714519505e+4,
0.154141773392650970499848051e+5,
0.91522317015169922705904727e+4,
0.18111867005523513506724158e+4,
0.1038187585462133728776636e+3,
0.1e+1
};
p = Pone[5];
q = Qone[5];
for (i=4; i >= 0; i--)
{
p = p*(8.0/x)*(8.0/x)+Pone[i];
q = q*(8.0/x)*(8.0/x)+Qone[i];
}
return (double)(p/q);
}
static double KernelBessel_Order1(double x)
{
double p, q;
if (x == 0.0)
return (0.0f);
p = x;
if (x < 0.0)
x=(-x);
if (x < 8.0)
return (p*KernelBessel_J1(x));
q = (double)sqrt(2.0f/(M_PI*x))*(double)(KernelBessel_P1(x)*(1.0f/sqrt(2.0f)*(sin(x)-cos(x)))-8.0f/x*KernelBessel_Q1(x)*
(-1.0f/sqrt(2.0f)*(sin(x)+cos(x))));
if (p < 0.0f)
q = (-q);
return (q);
}
static double filter_bessel(const double x)
{
if (x == 0.0f)
return (double)(M_PI/4.0f);
return (KernelBessel_Order1((double)M_PI*x)/(2.0f*x));
}
static double filter_blackman(const double x)
{
return (0.42f+0.5f*(double)cos(M_PI*x)+0.08f*(double)cos(2.0f*M_PI*x));
}
/**
* Bicubic interpolation kernel (a=-1):
\verbatim
/
| 1-2|t|**2+|t|**3 , if |t| < 1
h(t) = | 4-8|t|+5|t|**2-|t|**3 , if 1<=|t|<2
| 0 , otherwise
\
\endverbatim
* ***bd*** 2.2004
*/
static double filter_bicubic(const double t)
{
const double abs_t = (double)fabs(t);
const double abs_t_sq = abs_t * abs_t;
if (abs_t<1) return 1-2*abs_t_sq+abs_t_sq*abs_t;
if (abs_t<2) return 4 - 8*abs_t +5*abs_t_sq - abs_t_sq*abs_t;
return 0;
}
/**
* Generalized cubic kernel (for a=-1 it is the same as BicubicKernel):
\verbatim
/
| (a+2)|t|**3 - (a+3)|t|**2 + 1 , |t| <= 1
h(t) = | a|t|**3 - 5a|t|**2 + 8a|t| - 4a , 1 < |t| <= 2
| 0 , otherwise
\
\endverbatim
* Often used values for a are -1 and -1/2.
*/
static double filter_generalized_cubic(const double t)
{
const double a = -DEFAULT_FILTER_GENERALIZED_CUBIC;
double abs_t = (double)fabs(t);
double abs_t_sq = abs_t * abs_t;
if (abs_t < 1) return (a + 2) * abs_t_sq * abs_t - (a + 3) * abs_t_sq + 1;
if (abs_t < 2) return a * abs_t_sq * abs_t - 5 * a * abs_t_sq + 8 * a * abs_t - 4 * a;
return 0;
}
/* CubicSpline filter, default radius 2 */
static double filter_cubic_spline(const double x1)
{
const double x = x1 < 0.0 ? -x1 : x1;
if (x < 1.0 ) {
const double x2 = x*x;
return (0.5 * x2 * x - x2 + 2.0 / 3.0);
}
if (x < 2.0) {
return (pow(2.0 - x, 3.0)/6.0);
}
return 0;
}
/* CubicConvolution filter, default radius 3 */
static double filter_cubic_convolution(const double x1)
{
const double x = x1 < 0.0 ? -x1 : x1;
const double x2 = x1 * x1;
const double x2_x = x2 * x;
if (x <= 1.0) return ((4.0 / 3.0)* x2_x - (7.0 / 3.0) * x2 + 1.0);
if (x <= 2.0) return (- (7.0 / 12.0) * x2_x + 3 * x2 - (59.0 / 12.0) * x + 2.5);
if (x <= 3.0) return ( (1.0/12.0) * x2_x - (2.0 / 3.0) * x2 + 1.75 * x - 1.5);
return 0;
}
static double filter_box(double x) {
if (x < - DEFAULT_FILTER_BOX)
return 0.0f;
if (x < DEFAULT_FILTER_BOX)
return 1.0f;
return 0.0f;
}
static double filter_catmullrom(const double x)
{
if (x < -2.0)
return(0.0f);
if (x < -1.0)
return(0.5f*(4.0f+x*(8.0f+x*(5.0f+x))));
if (x < 0.0)
return(0.5f*(2.0f+x*x*(-5.0f-3.0f*x)));
if (x < 1.0)
return(0.5f*(2.0f+x*x*(-5.0f+3.0f*x)));
if (x < 2.0)
return(0.5f*(4.0f+x*(-8.0f+x*(5.0f-x))));
return(0.0f);
}
static double filter_filter(double t)
{
/* f(t) = 2|t|^3 - 3|t|^2 + 1, -1 <= t <= 1 */
if(t < 0.0) t = -t;
if(t < 1.0) return((2.0 * t - 3.0) * t * t + 1.0);
return(0.0);
}
/* Lanczos8 filter, default radius 8 */
static double filter_lanczos8(const double x1)
{
const double x = x1 < 0.0 ? -x1 : x1;
#define R DEFAULT_LANCZOS8_RADIUS
if ( x == 0.0) return 1;
if ( x < R) {
return R * sin(x*M_PI) * sin(x * M_PI/ R) / (x * M_PI * x * M_PI);
}
return 0.0;
#undef R
}
/* Lanczos3 filter, default radius 3 */
static double filter_lanczos3(const double x1)
{
const double x = x1 < 0.0 ? -x1 : x1;
#define R DEFAULT_LANCZOS3_RADIUS
if ( x == 0.0) return 1;
if ( x < R)
{
return R * sin(x*M_PI) * sin(x * M_PI / R) / (x * M_PI * x * M_PI);
}
return 0.0;
#undef R
}
/* Hermite filter, default radius 1 */
static double filter_hermite(const double x1)
{
const double x = x1 < 0.0 ? -x1 : x1;
if (x < 1.0) return ((2.0 * x - 3) * x * x + 1.0 );
return 0.0;
}
/* Trangle filter, default radius 1 */
static double filter_triangle(const double x1)
{
const double x = x1 < 0.0 ? -x1 : x1;
if (x < 1.0) return (1.0 - x);
return 0.0;
}
/* Bell filter, default radius 1.5 */
static double filter_bell(const double x1)
{
const double x = x1 < 0.0 ? -x1 : x1;
if (x < 0.5) return (0.75 - x*x);
if (x < 1.5) return (0.5 * pow(x - 1.5, 2.0));
return 0.0;
}
/* Mitchell filter, default radius 2.0 */
static double filter_mitchell(const double x)
{
#define KM_B (1.0f/3.0f)
#define KM_C (1.0f/3.0f)
#define KM_P0 (( 6.0f - 2.0f * KM_B ) / 6.0f)
#define KM_P2 ((-18.0f + 12.0f * KM_B + 6.0f * KM_C) / 6.0f)
#define KM_P3 (( 12.0f - 9.0f * KM_B - 6.0f * KM_C) / 6.0f)
#define KM_Q0 (( 8.0f * KM_B + 24.0f * KM_C) / 6.0f)
#define KM_Q1 ((-12.0f * KM_B - 48.0f * KM_C) / 6.0f)
#define KM_Q2 (( 6.0f * KM_B + 30.0f * KM_C) / 6.0f)
#define KM_Q3 (( -1.0f * KM_B - 6.0f * KM_C) / 6.0f)
if (x < -2.0)
return(0.0f);
if (x < -1.0)
return(KM_Q0-x*(KM_Q1-x*(KM_Q2-x*KM_Q3)));
if (x < 0.0f)
return(KM_P0+x*x*(KM_P2-x*KM_P3));
if (x < 1.0f)
return(KM_P0+x*x*(KM_P2+x*KM_P3));
if (x < 2.0f)
return(KM_Q0+x*(KM_Q1+x*(KM_Q2+x*KM_Q3)));
return(0.0f);
}
/* Cosine filter, default radius 1 */
static double filter_cosine(const double x)
{
if ((x >= -1.0) && (x <= 1.0)) return ((cos(x * M_PI) + 1.0)/2.0);
return 0;
}
/* Quadratic filter, default radius 1.5 */
static double filter_quadratic(const double x1)
{
const double x = x1 < 0.0 ? -x1 : x1;
if (x <= 0.5) return (- 2.0 * x * x + 1);
if (x <= 1.5) return (x * x - 2.5* x + 1.5);
return 0.0;
}
static double filter_bspline(const double x)
{
if (x>2.0f) {
return 0.0f;
} else {
double a, b, c, d;
/* Was calculated anyway cause the "if((x-1.0f) < 0)" */
const double xm1 = x - 1.0f;
const double xp1 = x + 1.0f;
const double xp2 = x + 2.0f;
if ((xp2) <= 0.0f) a = 0.0f; else a = xp2*xp2*xp2;
if ((xp1) <= 0.0f) b = 0.0f; else b = xp1*xp1*xp1;
if (x <= 0) c = 0.0f; else c = x*x*x;
if ((xm1) <= 0.0f) d = 0.0f; else d = xm1*xm1*xm1;
return (0.16666666666666666667f * (a - (4.0f * b) + (6.0f * c) - (4.0f * d)));
}
}
/* QuadraticBSpline filter, default radius 1.5 */
static double filter_quadratic_bspline(const double x1)
{
const double x = x1 < 0.0 ? -x1 : x1;
if (x <= 0.5) return (- x * x + 0.75);
if (x <= 1.5) return (0.5 * x * x - 1.5 * x + 1.125);
return 0.0;
}
static double filter_gaussian(const double x)
{
/* return(exp((double) (-2.0 * x * x)) * sqrt(2.0 / M_PI)); */
return (double)(exp(-2.0f * x * x) * 0.79788456080287f);
}
static double filter_hanning(const double x)
{
/* A Cosine windowing function */
return(0.5 + 0.5 * cos(M_PI * x));
}
static double filter_hamming(const double x)
{
/* should be
(0.54+0.46*cos(M_PI*(double) x));
but this approximation is sufficient */
if (x < -1.0f)
return 0.0f;
if (x < 0.0f)
return 0.92f*(-2.0f*x-3.0f)*x*x+1.0f;
if (x < 1.0f)
return 0.92f*(2.0f*x-3.0f)*x*x+1.0f;
return 0.0f;
}
static double filter_power(const double x)
{
const double a = 2.0f;
if (fabs(x)>1) return 0.0f;
return (1.0f - (double)fabs(pow(x,a)));
}
static double filter_sinc(const double x)
{
/* X-scaled Sinc(x) function. */
if (x == 0.0) return(1.0);
return (sin(M_PI * (double) x) / (M_PI * (double) x));
}
static double filter_welsh(const double x)
{
/* Welsh parabolic windowing filter */
if (x < 1.0)
return(1 - x*x);
return(0.0);
}
/* Copied from upstream's libgd */
static inline int _color_blend (const int dst, const int src)
{
const int src_alpha = gdTrueColorGetAlpha(src);
if( src_alpha == gdAlphaOpaque ) {
return src;
} else {
const int dst_alpha = gdTrueColorGetAlpha(dst);
if( src_alpha == gdAlphaTransparent ) return dst;
if( dst_alpha == gdAlphaTransparent ) {
return src;
} else {
register int alpha, red, green, blue;
const int src_weight = gdAlphaTransparent - src_alpha;
const int dst_weight = (gdAlphaTransparent - dst_alpha) * src_alpha / gdAlphaMax;
const int tot_weight = src_weight + dst_weight;
alpha = src_alpha * dst_alpha / gdAlphaMax;
red = (gdTrueColorGetRed(src) * src_weight
+ gdTrueColorGetRed(dst) * dst_weight) / tot_weight;
green = (gdTrueColorGetGreen(src) * src_weight
+ gdTrueColorGetGreen(dst) * dst_weight) / tot_weight;
blue = (gdTrueColorGetBlue(src) * src_weight
+ gdTrueColorGetBlue(dst) * dst_weight) / tot_weight;
return ((alpha << 24) + (red << 16) + (green << 8) + blue);
}
}
}
static inline int _setEdgePixel(const gdImagePtr src, unsigned int x, unsigned int y, gdFixed coverage, const int bgColor)
{
const gdFixed f_127 = gd_itofx(127);
register int c = src->tpixels[y][x];
c = c | (( (int) (gd_fxtof(gd_mulfx(coverage, f_127)) + 50.5f)) << 24);
return _color_blend(bgColor, c);
}
static inline int getPixelOverflowTC(gdImagePtr im, const int x, const int y, const int bgColor)
{
if (gdImageBoundsSafe(im, x, y)) {
const int c = im->tpixels[y][x];
if (c == im->transparent) {
return bgColor == -1 ? gdTrueColorAlpha(0, 0, 0, 127) : bgColor;
}
return c;
} else {
register int border = 0;
if (y < im->cy1) {
border = im->tpixels[0][im->cx1];
goto processborder;
}
if (y < im->cy1) {
border = im->tpixels[0][im->cx1];
goto processborder;
}
if (y > im->cy2) {
if (x >= im->cx1 && x <= im->cx1) {
border = im->tpixels[im->cy2][x];
goto processborder;
} else {
return gdTrueColorAlpha(0, 0, 0, 127);
}
}
/* y is bound safe at this point */
if (x < im->cx1) {
border = im->tpixels[y][im->cx1];
goto processborder;
}
if (x > im->cx2) {
border = im->tpixels[y][im->cx2];
}
processborder:
if (border == im->transparent) {
return gdTrueColorAlpha(0, 0, 0, 127);
} else{
return gdTrueColorAlpha(gdTrueColorGetRed(border), gdTrueColorGetGreen(border), gdTrueColorGetBlue(border), 127);
}
}
}
#define colorIndex2RGBA(c) gdTrueColorAlpha(im->red[(c)], im->green[(c)], im->blue[(c)], im->alpha[(c)])
#define colorIndex2RGBcustomA(c, a) gdTrueColorAlpha(im->red[(c)], im->green[(c)], im->blue[(c)], im->alpha[(a)])
static inline int getPixelOverflowPalette(gdImagePtr im, const int x, const int y, const int bgColor)
{
if (gdImageBoundsSafe(im, x, y)) {
const int c = im->pixels[y][x];
if (c == im->transparent) {
return bgColor == -1 ? gdTrueColorAlpha(0, 0, 0, 127) : bgColor;
}
return colorIndex2RGBA(c);
} else {
register int border = 0;
if (y < im->cy1) {
border = gdImageGetPixel(im, im->cx1, 0);
goto processborder;
}
if (y < im->cy1) {
border = gdImageGetPixel(im, im->cx1, 0);
goto processborder;
}
if (y > im->cy2) {
if (x >= im->cx1 && x <= im->cx1) {
border = gdImageGetPixel(im, x, im->cy2);
goto processborder;
} else {
return gdTrueColorAlpha(0, 0, 0, 127);
}
}
/* y is bound safe at this point */
if (x < im->cx1) {
border = gdImageGetPixel(im, im->cx1, y);
goto processborder;
}
if (x > im->cx2) {
border = gdImageGetPixel(im, im->cx2, y);
}
processborder:
if (border == im->transparent) {
return gdTrueColorAlpha(0, 0, 0, 127);
} else{
return colorIndex2RGBcustomA(border, 127);
}
}
}
static int getPixelInterpolateWeight(gdImagePtr im, const double x, const double y, const int bgColor)
{
/* Closest pixel <= (xf,yf) */
int sx = (int)(x);
int sy = (int)(y);
const double xf = x - (double)sx;
const double yf = y - (double)sy;
const double nxf = (double) 1.0 - xf;
const double nyf = (double) 1.0 - yf;
const double m1 = xf * yf;
const double m2 = nxf * yf;
const double m3 = xf * nyf;
const double m4 = nxf * nyf;
/* get color values of neighbouring pixels */
const int c1 = im->trueColor == 1 ? getPixelOverflowTC(im, sx, sy, bgColor) : getPixelOverflowPalette(im, sx, sy, bgColor);
const int c2 = im->trueColor == 1 ? getPixelOverflowTC(im, sx - 1, sy, bgColor) : getPixelOverflowPalette(im, sx - 1, sy, bgColor);
const int c3 = im->trueColor == 1 ? getPixelOverflowTC(im, sx, sy - 1, bgColor) : getPixelOverflowPalette(im, sx, sy - 1, bgColor);
const int c4 = im->trueColor == 1 ? getPixelOverflowTC(im, sx - 1, sy - 1, bgColor) : getPixelOverflowPalette(im, sx, sy - 1, bgColor);
int r, g, b, a;
if (x < 0) sx--;
if (y < 0) sy--;
/* component-wise summing-up of color values */
if (im->trueColor) {
r = (int)(m1*gdTrueColorGetRed(c1) + m2*gdTrueColorGetRed(c2) + m3*gdTrueColorGetRed(c3) + m4*gdTrueColorGetRed(c4));
g = (int)(m1*gdTrueColorGetGreen(c1) + m2*gdTrueColorGetGreen(c2) + m3*gdTrueColorGetGreen(c3) + m4*gdTrueColorGetGreen(c4));
b = (int)(m1*gdTrueColorGetBlue(c1) + m2*gdTrueColorGetBlue(c2) + m3*gdTrueColorGetBlue(c3) + m4*gdTrueColorGetBlue(c4));
a = (int)(m1*gdTrueColorGetAlpha(c1) + m2*gdTrueColorGetAlpha(c2) + m3*gdTrueColorGetAlpha(c3) + m4*gdTrueColorGetAlpha(c4));
} else {
r = (int)(m1*im->red[(c1)] + m2*im->red[(c2)] + m3*im->red[(c3)] + m4*im->red[(c4)]);
g = (int)(m1*im->green[(c1)] + m2*im->green[(c2)] + m3*im->green[(c3)] + m4*im->green[(c4)]);
b = (int)(m1*im->blue[(c1)] + m2*im->blue[(c2)] + m3*im->blue[(c3)] + m4*im->blue[(c4)]);
a = (int)(m1*im->alpha[(c1)] + m2*im->alpha[(c2)] + m3*im->alpha[(c3)] + m4*im->alpha[(c4)]);
}
r = CLAMP(r, 0, 255);
g = CLAMP(g, 0, 255);
b = CLAMP(b, 0, 255);
a = CLAMP(a, 0, gdAlphaMax);
return gdTrueColorAlpha(r, g, b, a);
}
/**
* Function: getPixelInterpolated
* Returns the interpolated color value using the default interpolation
* method. The returned color is always in the ARGB format (truecolor).
*
* Parameters:
* im - Image to set the default interpolation method
* y - X value of the ideal position
* y - Y value of the ideal position
* method - Interpolation method <gdInterpolationMethod>
*
* Returns:
* GD_TRUE if the affine is rectilinear or GD_FALSE
*
* See also:
* <gdSetInterpolationMethod>
*/
int getPixelInterpolated(gdImagePtr im, const double x, const double y, const int bgColor)
{
const int xi=(int)((x) < 0 ? x - 1: x);
const int yi=(int)((y) < 0 ? y - 1: y);
int yii;
int i;
double kernel, kernel_cache_y;
double kernel_x[12], kernel_y[4];
double new_r = 0.0f, new_g = 0.0f, new_b = 0.0f, new_a = 0.0f;
/* These methods use special implementations */
if (im->interpolation_id == GD_BILINEAR_FIXED || im->interpolation_id == GD_BICUBIC_FIXED || im->interpolation_id == GD_NEAREST_NEIGHBOUR) {
return -1;
}
/* Default to full alpha */
if (bgColor == -1) {
}
if (im->interpolation_id == GD_WEIGHTED4) {
return getPixelInterpolateWeight(im, x, y, bgColor);
}
if (im->interpolation_id == GD_NEAREST_NEIGHBOUR) {
if (im->trueColor == 1) {
return getPixelOverflowTC(im, xi, yi, bgColor);
} else {
return getPixelOverflowPalette(im, xi, yi, bgColor);
}
}
if (im->interpolation) {
for (i=0; i<4; i++) {
kernel_x[i] = (double) im->interpolation((double)(xi+i-1-x));
kernel_y[i] = (double) im->interpolation((double)(yi+i-1-y));
}
} else {
return -1;
}
/*
* TODO: use the known fast rgba multiplication implementation once
* the new formats are in place
*/
for (yii = yi-1; yii < yi+3; yii++) {
int xii;
kernel_cache_y = kernel_y[yii-(yi-1)];
if (im->trueColor) {
for (xii=xi-1; xii<xi+3; xii++) {
const int rgbs = getPixelOverflowTC(im, xii, yii, bgColor);
kernel = kernel_cache_y * kernel_x[xii-(xi-1)];
new_r += kernel * gdTrueColorGetRed(rgbs);
new_g += kernel * gdTrueColorGetGreen(rgbs);
new_b += kernel * gdTrueColorGetBlue(rgbs);
new_a += kernel * gdTrueColorGetAlpha(rgbs);
}
} else {
for (xii=xi-1; xii<xi+3; xii++) {
const int rgbs = getPixelOverflowPalette(im, xii, yii, bgColor);
kernel = kernel_cache_y * kernel_x[xii-(xi-1)];
new_r += kernel * gdTrueColorGetRed(rgbs);
new_g += kernel * gdTrueColorGetGreen(rgbs);
new_b += kernel * gdTrueColorGetBlue(rgbs);
new_a += kernel * gdTrueColorGetAlpha(rgbs);
}
}
}
new_r = CLAMP(new_r, 0, 255);
new_g = CLAMP(new_g, 0, 255);
new_b = CLAMP(new_b, 0, 255);
new_a = CLAMP(new_a, 0, gdAlphaMax);
return gdTrueColorAlpha(((int)new_r), ((int)new_g), ((int)new_b), ((int)new_a));
}
static inline LineContribType * _gdContributionsAlloc(unsigned int line_length, unsigned int windows_size)
{
unsigned int u = 0;
LineContribType *res;
res = (LineContribType *) gdMalloc(sizeof(LineContribType));
if (!res) {
return NULL;
}
res->WindowSize = windows_size;
res->LineLength = line_length;
res->ContribRow = (ContributionType *) gdMalloc(line_length * sizeof(ContributionType));
for (u = 0 ; u < line_length ; u++) {
res->ContribRow[u].Weights = (double *) gdMalloc(windows_size * sizeof(double));
}
return res;
}
static inline void _gdContributionsFree(LineContribType * p)
{
unsigned int u;
for (u = 0; u < p->LineLength; u++) {
gdFree(p->ContribRow[u].Weights);
}
gdFree(p->ContribRow);
gdFree(p);
}
static inline LineContribType *_gdContributionsCalc(unsigned int line_size, unsigned int src_size, double scale_d, const interpolation_method pFilter)
{
double width_d;
double scale_f_d = 1.0;
const double filter_width_d = DEFAULT_BOX_RADIUS;
int windows_size;
unsigned int u;
LineContribType *res;
if (scale_d < 1.0) {
width_d = filter_width_d / scale_d;
scale_f_d = scale_d;
} else {
width_d= filter_width_d;
}
windows_size = 2 * (int)ceil(width_d) + 1;
res = _gdContributionsAlloc(line_size, windows_size);
for (u = 0; u < line_size; u++) {
const double dCenter = (double)u / scale_d;
/* get the significant edge points affecting the pixel */
register int iLeft = MAX(0, (int)floor (dCenter - width_d));
int iRight = MIN((int)ceil(dCenter + width_d), (int)src_size - 1);
double dTotalWeight = 0.0;
int iSrc;
/* Cut edge points to fit in filter window in case of spill-off */
if (iRight - iLeft + 1 > windows_size) {
if (iLeft < ((int)src_size - 1 / 2)) {
iLeft++;
} else {
iRight--;
}
}
res->ContribRow[u].Left = iLeft;
res->ContribRow[u].Right = iRight;
for (iSrc = iLeft; iSrc <= iRight; iSrc++) {
dTotalWeight += (res->ContribRow[u].Weights[iSrc-iLeft] = scale_f_d * (*pFilter)(scale_f_d * (dCenter - (double)iSrc)));
}
if (dTotalWeight < 0.0) {
_gdContributionsFree(res);
return NULL;
}
if (dTotalWeight > 0.0) {
for (iSrc = iLeft; iSrc <= iRight; iSrc++) {
res->ContribRow[u].Weights[iSrc-iLeft] /= dTotalWeight;
}
}
}
return res;
}
static inline void _gdScaleRow(gdImagePtr pSrc, unsigned int src_width, gdImagePtr dst, unsigned int dst_width, unsigned int row, LineContribType *contrib)
{
int *p_src_row = pSrc->tpixels[row];
int *p_dst_row = dst->tpixels[row];
unsigned int x;
for (x = 0; x < dst_width - 1; x++) {
register unsigned char r = 0, g = 0, b = 0, a = 0;
const int left = contrib->ContribRow[x].Left;
const int right = contrib->ContribRow[x].Right;
int i;
/* Accumulate each channel */
for (i = left; i <= right; i++) {
const int left_channel = i - left;
r += (unsigned char)(contrib->ContribRow[x].Weights[left_channel] * (double)(gdTrueColorGetRed(p_src_row[i])));
g += (unsigned char)(contrib->ContribRow[x].Weights[left_channel] * (double)(gdTrueColorGetGreen(p_src_row[i])));
b += (unsigned char)(contrib->ContribRow[x].Weights[left_channel] * (double)(gdTrueColorGetBlue(p_src_row[i])));
a += (unsigned char)(contrib->ContribRow[x].Weights[left_channel] * (double)(gdTrueColorGetAlpha(p_src_row[i])));
}
p_dst_row[x] = gdTrueColorAlpha(r, g, b, a);
}
}
static inline void _gdScaleHoriz(gdImagePtr pSrc, unsigned int src_width, unsigned int src_height, gdImagePtr pDst, unsigned int dst_width, unsigned int dst_height)
{
unsigned int u;
LineContribType * contrib;
/* same width, just copy it */
if (dst_width == src_width) {
unsigned int y;
for (y = 0; y < src_height - 1; ++y) {
memcpy(pDst->tpixels[y], pSrc->tpixels[y], src_width);
}
}
contrib = _gdContributionsCalc(dst_width, src_width, (double)dst_width / (double)src_width, pSrc->interpolation);
if (contrib == NULL) {
return;
}
/* Scale each row */
for (u = 0; u < dst_height - 1; u++) {
_gdScaleRow(pSrc, src_width, pDst, dst_width, u, contrib);
}
_gdContributionsFree (contrib);
}
static inline void _gdScaleCol (gdImagePtr pSrc, unsigned int src_width, gdImagePtr pRes, unsigned int dst_width, unsigned int dst_height, unsigned int uCol, LineContribType *contrib)
{
unsigned int y;
for (y = 0; y < dst_height - 1; y++) {
register unsigned char r = 0, g = 0, b = 0, a = 0;
const int iLeft = contrib->ContribRow[y].Left;
const int iRight = contrib->ContribRow[y].Right;
int i;
int *row = pRes->tpixels[y];
/* Accumulate each channel */
for (i = iLeft; i <= iRight; i++) {
const int pCurSrc = pSrc->tpixels[i][uCol];
const int i_iLeft = i - iLeft;
r += (unsigned char)(contrib->ContribRow[y].Weights[i_iLeft] * (double)(gdTrueColorGetRed(pCurSrc)));
g += (unsigned char)(contrib->ContribRow[y].Weights[i_iLeft] * (double)(gdTrueColorGetGreen(pCurSrc)));
b += (unsigned char)(contrib->ContribRow[y].Weights[i_iLeft] * (double)(gdTrueColorGetBlue(pCurSrc)));
a += (unsigned char)(contrib->ContribRow[y].Weights[i_iLeft] * (double)(gdTrueColorGetAlpha(pCurSrc)));
}
pRes->tpixels[y][uCol] = gdTrueColorAlpha(r, g, b, a);
}
}
static inline void _gdScaleVert (const gdImagePtr pSrc, const unsigned int src_width, const unsigned int src_height, const gdImagePtr pDst, const unsigned int dst_width, const unsigned int dst_height)
{
unsigned int u;
LineContribType * contrib;
/* same height, copy it */
if (src_height == dst_height) {
unsigned int y;
for (y = 0; y < src_height - 1; ++y) {
memcpy(pDst->tpixels[y], pSrc->tpixels[y], src_width);
}
}
contrib = _gdContributionsCalc(dst_height, src_height, (double)(dst_height) / (double)(src_height), pSrc->interpolation);
/* scale each column */
for (u = 0; u < dst_width - 1; u++) {
_gdScaleCol(pSrc, src_width, pDst, dst_width, dst_height, u, contrib);
}
_gdContributionsFree(contrib);
}
gdImagePtr gdImageScaleTwoPass(const gdImagePtr src, const unsigned int src_width, const unsigned int src_height, const unsigned int new_width, const unsigned int new_height)
{
gdImagePtr tmp_im;
gdImagePtr dst;
tmp_im = gdImageCreateTrueColor(new_width, src_height);
if (tmp_im == NULL) {
return NULL;
}
gdImageSetInterpolationMethod(tmp_im, src->interpolation_id);
_gdScaleHoriz(src, src_width, src_height, tmp_im, new_width, src_height);
dst = gdImageCreateTrueColor(new_width, new_height);
if (dst == NULL) {
gdFree(tmp_im);
return NULL;
}
gdImageSetInterpolationMethod(dst, src->interpolation_id);
_gdScaleVert(tmp_im, new_width, src_height, dst, new_width, new_height);
gdFree(tmp_im);
return dst;
}
gdImagePtr Scale(const gdImagePtr src, const unsigned int src_width, const unsigned int src_height, const gdImagePtr dst, const unsigned int new_width, const unsigned int new_height)
{
gdImagePtr tmp_im;
tmp_im = gdImageCreateTrueColor(new_width, src_height);
if (tmp_im == NULL) {
return NULL;
}
gdImageSetInterpolationMethod(tmp_im, src->interpolation_id);
_gdScaleHoriz(src, src_width, src_height, tmp_im, new_width, src_height);
_gdScaleVert(tmp_im, new_width, src_height, dst, new_width, new_height);
gdFree(tmp_im);
return dst;
}
/*
BilinearFixed, BicubicFixed and nearest implementations are rewamped versions of the implementation in CBitmapEx
http://www.codeproject.com/Articles/29121/CBitmapEx-Free-C-Bitmap-Manipulation-Class
Integer only implementation, good to have for common usages like pre scale very large
images before using another interpolation methods for the last step.
*/
gdImagePtr gdImageScaleNearestNeighbour(gdImagePtr im, const unsigned int width, const unsigned int height)
{
const unsigned long new_width = MAX(1, width);
const unsigned long new_height = MAX(1, height);
const float dx = (float)im->sx / (float)new_width;
const float dy = (float)im->sy / (float)new_height;
const gdFixed f_dx = gd_ftofx(dx);
const gdFixed f_dy = gd_ftofx(dy);
gdImagePtr dst_img;
unsigned long dst_offset_x;
unsigned long dst_offset_y = 0;
unsigned int i;
dst_img = gdImageCreateTrueColor(new_width, new_height);
if (dst_img == NULL) {
return NULL;
}
for (i=0; i<new_height; i++) {
unsigned int j;
dst_offset_x = 0;
if (im->trueColor) {
for (j=0; j<new_width; j++) {
const gdFixed f_i = gd_itofx(i);
const gdFixed f_j = gd_itofx(j);
const gdFixed f_a = gd_mulfx(f_i, f_dy);
const gdFixed f_b = gd_mulfx(f_j, f_dx);
const long m = gd_fxtoi(f_a);
const long n = gd_fxtoi(f_b);
dst_img->tpixels[dst_offset_y][dst_offset_x++] = im->tpixels[m][n];
}
} else {
for (j=0; j<new_width; j++) {
const gdFixed f_i = gd_itofx(i);
const gdFixed f_j = gd_itofx(j);
const gdFixed f_a = gd_mulfx(f_i, f_dy);
const gdFixed f_b = gd_mulfx(f_j, f_dx);
const long m = gd_fxtoi(f_a);
const long n = gd_fxtoi(f_b);
dst_img->tpixels[dst_offset_y][dst_offset_x++] = colorIndex2RGBA(im->pixels[m][n]);
}
}
dst_offset_y++;
}
return dst_img;
}
static inline int getPixelOverflowColorTC(gdImagePtr im, const int x, const int y, const int color)
{
if (gdImageBoundsSafe(im, x, y)) {
const int c = im->tpixels[y][x];
if (c == im->transparent) {
return gdTrueColorAlpha(0, 0, 0, 127);
}
return c;
} else {
register int border = 0;
if (y < im->cy1) {
border = im->tpixels[0][im->cx1];
goto processborder;
}
if (y < im->cy1) {
border = im->tpixels[0][im->cx1];
goto processborder;
}
if (y > im->cy2) {
if (x >= im->cx1 && x <= im->cx1) {
border = im->tpixels[im->cy2][x];
goto processborder;
} else {
return gdTrueColorAlpha(0, 0, 0, 127);
}
}
/* y is bound safe at this point */
if (x < im->cx1) {
border = im->tpixels[y][im->cx1];
goto processborder;
}
if (x > im->cx2) {
border = im->tpixels[y][im->cx2];
}
processborder:
if (border == im->transparent) {
return gdTrueColorAlpha(0, 0, 0, 127);
} else{
return gdTrueColorAlpha(gdTrueColorGetRed(border), gdTrueColorGetGreen(border), gdTrueColorGetBlue(border), 127);
}
}
}
static gdImagePtr gdImageScaleBilinearPalette(gdImagePtr im, const unsigned int new_width, const unsigned int new_height)
{
long _width = MAX(1, new_width);
long _height = MAX(1, new_height);
float dx = (float)gdImageSX(im) / (float)_width;
float dy = (float)gdImageSY(im) / (float)_height;
gdFixed f_dx = gd_ftofx(dx);
gdFixed f_dy = gd_ftofx(dy);
gdFixed f_1 = gd_itofx(1);
int dst_offset_h;
int dst_offset_v = 0;
long i;
gdImagePtr new_img;
const int transparent = im->transparent;
new_img = gdImageCreateTrueColor(new_width, new_height);
if (new_img == NULL) {
return NULL;
}
new_img->transparent = gdTrueColorAlpha(im->red[transparent], im->green[transparent], im->blue[transparent], im->alpha[transparent]);
for (i=0; i < _height; i++) {
long j;
const gdFixed f_i = gd_itofx(i);
const gdFixed f_a = gd_mulfx(f_i, f_dy);
register long m = gd_fxtoi(f_a);
dst_offset_h = 0;
for (j=0; j < _width; j++) {
/* Update bitmap */
gdFixed f_j = gd_itofx(j);
gdFixed f_b = gd_mulfx(f_j, f_dx);
const long n = gd_fxtoi(f_b);
gdFixed f_f = f_a - gd_itofx(m);
gdFixed f_g = f_b - gd_itofx(n);
const gdFixed f_w1 = gd_mulfx(f_1-f_f, f_1-f_g);
const gdFixed f_w2 = gd_mulfx(f_1-f_f, f_g);
const gdFixed f_w3 = gd_mulfx(f_f, f_1-f_g);
const gdFixed f_w4 = gd_mulfx(f_f, f_g);
unsigned int pixel1;
unsigned int pixel2;
unsigned int pixel3;
unsigned int pixel4;
register gdFixed f_r1, f_r2, f_r3, f_r4,
f_g1, f_g2, f_g3, f_g4,
f_b1, f_b2, f_b3, f_b4,
f_a1, f_a2, f_a3, f_a4;
/* zero for the background color, nothig gets outside anyway */
pixel1 = getPixelOverflowPalette(im, n, m, 0);
pixel2 = getPixelOverflowPalette(im, n + 1, m, 0);
pixel3 = getPixelOverflowPalette(im, n, m + 1, 0);
pixel4 = getPixelOverflowPalette(im, n + 1, m + 1, 0);
f_r1 = gd_itofx(gdTrueColorGetRed(pixel1));
f_r2 = gd_itofx(gdTrueColorGetRed(pixel2));
f_r3 = gd_itofx(gdTrueColorGetRed(pixel3));
f_r4 = gd_itofx(gdTrueColorGetRed(pixel4));
f_g1 = gd_itofx(gdTrueColorGetGreen(pixel1));
f_g2 = gd_itofx(gdTrueColorGetGreen(pixel2));
f_g3 = gd_itofx(gdTrueColorGetGreen(pixel3));
f_g4 = gd_itofx(gdTrueColorGetGreen(pixel4));
f_b1 = gd_itofx(gdTrueColorGetBlue(pixel1));
f_b2 = gd_itofx(gdTrueColorGetBlue(pixel2));
f_b3 = gd_itofx(gdTrueColorGetBlue(pixel3));
f_b4 = gd_itofx(gdTrueColorGetBlue(pixel4));
f_a1 = gd_itofx(gdTrueColorGetAlpha(pixel1));
f_a2 = gd_itofx(gdTrueColorGetAlpha(pixel2));
f_a3 = gd_itofx(gdTrueColorGetAlpha(pixel3));
f_a4 = gd_itofx(gdTrueColorGetAlpha(pixel4));
{
const char red = (char) gd_fxtoi(gd_mulfx(f_w1, f_r1) + gd_mulfx(f_w2, f_r2) + gd_mulfx(f_w3, f_r3) + gd_mulfx(f_w4, f_r4));
const char green = (char) gd_fxtoi(gd_mulfx(f_w1, f_g1) + gd_mulfx(f_w2, f_g2) + gd_mulfx(f_w3, f_g3) + gd_mulfx(f_w4, f_g4));
const char blue = (char) gd_fxtoi(gd_mulfx(f_w1, f_b1) + gd_mulfx(f_w2, f_b2) + gd_mulfx(f_w3, f_b3) + gd_mulfx(f_w4, f_b4));
const char alpha = (char) gd_fxtoi(gd_mulfx(f_w1, f_a1) + gd_mulfx(f_w2, f_a2) + gd_mulfx(f_w3, f_a3) + gd_mulfx(f_w4, f_a4));
new_img->tpixels[dst_offset_v][dst_offset_h] = gdTrueColorAlpha(red, green, blue, alpha);
}
dst_offset_h++;
}
dst_offset_v++;
}
return new_img;
}
static gdImagePtr gdImageScaleBilinearTC(gdImagePtr im, const unsigned int new_width, const unsigned int new_height)
{
long dst_w = MAX(1, new_width);
long dst_h = MAX(1, new_height);
float dx = (float)gdImageSX(im) / (float)dst_w;
float dy = (float)gdImageSY(im) / (float)dst_h;
gdFixed f_dx = gd_ftofx(dx);
gdFixed f_dy = gd_ftofx(dy);
gdFixed f_1 = gd_itofx(1);
int dst_offset_h;
int dst_offset_v = 0;
int dwSrcTotalOffset;
long i;
gdImagePtr new_img;
new_img = gdImageCreateTrueColor(new_width, new_height);
if (!new_img){
return NULL;
}
for (i=0; i < dst_h; i++) {
long j;
dst_offset_h = 0;
for (j=0; j < dst_w; j++) {
/* Update bitmap */
gdFixed f_i = gd_itofx(i);
gdFixed f_j = gd_itofx(j);
gdFixed f_a = gd_mulfx(f_i, f_dy);
gdFixed f_b = gd_mulfx(f_j, f_dx);
const gdFixed m = gd_fxtoi(f_a);
const gdFixed n = gd_fxtoi(f_b);
gdFixed f_f = f_a - gd_itofx(m);
gdFixed f_g = f_b - gd_itofx(n);
const gdFixed f_w1 = gd_mulfx(f_1-f_f, f_1-f_g);
const gdFixed f_w2 = gd_mulfx(f_1-f_f, f_g);
const gdFixed f_w3 = gd_mulfx(f_f, f_1-f_g);
const gdFixed f_w4 = gd_mulfx(f_f, f_g);
unsigned int pixel1;
unsigned int pixel2;
unsigned int pixel3;
unsigned int pixel4;
register gdFixed f_r1, f_r2, f_r3, f_r4,
f_g1, f_g2, f_g3, f_g4,
f_b1, f_b2, f_b3, f_b4,
f_a1, f_a2, f_a3, f_a4;
dwSrcTotalOffset = m + n;
/* 0 for bgColor, nothing gets outside anyway */
pixel1 = getPixelOverflowTC(im, n, m, 0);
pixel2 = getPixelOverflowTC(im, n + 1, m, 0);
pixel3 = getPixelOverflowTC(im, n, m + 1, 0);
pixel4 = getPixelOverflowTC(im, n + 1, m + 1, 0);
f_r1 = gd_itofx(gdTrueColorGetRed(pixel1));
f_r2 = gd_itofx(gdTrueColorGetRed(pixel2));
f_r3 = gd_itofx(gdTrueColorGetRed(pixel3));
f_r4 = gd_itofx(gdTrueColorGetRed(pixel4));
f_g1 = gd_itofx(gdTrueColorGetGreen(pixel1));
f_g2 = gd_itofx(gdTrueColorGetGreen(pixel2));
f_g3 = gd_itofx(gdTrueColorGetGreen(pixel3));
f_g4 = gd_itofx(gdTrueColorGetGreen(pixel4));
f_b1 = gd_itofx(gdTrueColorGetBlue(pixel1));
f_b2 = gd_itofx(gdTrueColorGetBlue(pixel2));
f_b3 = gd_itofx(gdTrueColorGetBlue(pixel3));
f_b4 = gd_itofx(gdTrueColorGetBlue(pixel4));
f_a1 = gd_itofx(gdTrueColorGetAlpha(pixel1));
f_a2 = gd_itofx(gdTrueColorGetAlpha(pixel2));
f_a3 = gd_itofx(gdTrueColorGetAlpha(pixel3));
f_a4 = gd_itofx(gdTrueColorGetAlpha(pixel4));
{
const unsigned char red = (unsigned char) gd_fxtoi(gd_mulfx(f_w1, f_r1) + gd_mulfx(f_w2, f_r2) + gd_mulfx(f_w3, f_r3) + gd_mulfx(f_w4, f_r4));
const unsigned char green = (unsigned char) gd_fxtoi(gd_mulfx(f_w1, f_g1) + gd_mulfx(f_w2, f_g2) + gd_mulfx(f_w3, f_g3) + gd_mulfx(f_w4, f_g4));
const unsigned char blue = (unsigned char) gd_fxtoi(gd_mulfx(f_w1, f_b1) + gd_mulfx(f_w2, f_b2) + gd_mulfx(f_w3, f_b3) + gd_mulfx(f_w4, f_b4));
const unsigned char alpha = (unsigned char) gd_fxtoi(gd_mulfx(f_w1, f_a1) + gd_mulfx(f_w2, f_a2) + gd_mulfx(f_w3, f_a3) + gd_mulfx(f_w4, f_a4));
new_img->tpixels[dst_offset_v][dst_offset_h] = gdTrueColorAlpha(red, green, blue, alpha);
}
dst_offset_h++;
}
dst_offset_v++;
}
return new_img;
}
gdImagePtr gdImageScaleBilinear(gdImagePtr im, const unsigned int new_width, const unsigned int new_height)
{
if (im->trueColor) {
return gdImageScaleBilinearTC(im, new_width, new_height);
} else {
return gdImageScaleBilinearPalette(im, new_width, new_height);
}
}
gdImagePtr gdImageScaleBicubicFixed(gdImagePtr src, const unsigned int width, const unsigned int height)
{
const long new_width = MAX(1, width);
const long new_height = MAX(1, height);
const int src_w = gdImageSX(src);
const int src_h = gdImageSY(src);
const gdFixed f_dx = gd_ftofx((float)src_w / (float)new_width);
const gdFixed f_dy = gd_ftofx((float)src_h / (float)new_height);
const gdFixed f_1 = gd_itofx(1);
const gdFixed f_2 = gd_itofx(2);
const gdFixed f_4 = gd_itofx(4);
const gdFixed f_6 = gd_itofx(6);
const gdFixed f_gamma = gd_ftofx(1.04f);
gdImagePtr dst;
unsigned int dst_offset_x;
unsigned int dst_offset_y = 0;
long i;
/* impact perf a bit, but not that much. Implementation for palette
images can be done at a later point.
*/
if (src->trueColor == 0) {
gdImagePaletteToTrueColor(src);
}
dst = gdImageCreateTrueColor(new_width, new_height);
if (!dst) {
return NULL;
}
dst->saveAlphaFlag = 1;
for (i=0; i < new_height; i++) {
long j;
dst_offset_x = 0;
for (j=0; j < new_width; j++) {
const gdFixed f_a = gd_mulfx(gd_itofx(i), f_dy);
const gdFixed f_b = gd_mulfx(gd_itofx(j), f_dx);
const long m = gd_fxtoi(f_a);
const long n = gd_fxtoi(f_b);
const gdFixed f_f = f_a - gd_itofx(m);
const gdFixed f_g = f_b - gd_itofx(n);
unsigned int src_offset_x[16], src_offset_y[16];
long k;
register gdFixed f_red = 0, f_green = 0, f_blue = 0, f_alpha = 0;
unsigned char red, green, blue, alpha = 0;
int *dst_row = dst->tpixels[dst_offset_y];
if ((m < 1) || (n < 1)) {
src_offset_x[0] = n;
src_offset_y[0] = m;
} else {
src_offset_x[0] = n - 1;
src_offset_y[0] = m;
}
if (m < 1) {
src_offset_x[1] = n;
src_offset_y[1] = m;
} else {
src_offset_x[1] = n;
src_offset_y[1] = m;
}
if ((m < 1) || (n >= src_w - 1)) {
src_offset_x[2] = n;
src_offset_y[2] = m;
} else {
src_offset_x[2] = n + 1;
src_offset_y[2] = m;
}
if ((m < 1) || (n >= src_w - 2)) {
src_offset_x[3] = n;
src_offset_y[3] = m;
} else {
src_offset_x[3] = n + 1 + 1;
src_offset_y[3] = m;
}
if (n < 1) {
src_offset_x[4] = n;
src_offset_y[4] = m;
} else {
src_offset_x[4] = n - 1;
src_offset_y[4] = m;
}
src_offset_x[5] = n;
src_offset_y[5] = m;
if (n >= src_w-1) {
src_offset_x[6] = n;
src_offset_y[6] = m;
} else {
src_offset_x[6] = n + 1;
src_offset_y[6] = m;
}
if (n >= src_w - 2) {
src_offset_x[7] = n;
src_offset_y[7] = m;
} else {
src_offset_x[7] = n + 1 + 1;
src_offset_y[7] = m;
}
if ((m >= src_h - 1) || (n < 1)) {
src_offset_x[8] = n;
src_offset_y[8] = m;
} else {
src_offset_x[8] = n - 1;
src_offset_y[8] = m;
}
if (m >= src_h - 1) {
src_offset_x[8] = n;
src_offset_y[8] = m;
} else {
src_offset_x[9] = n;
src_offset_y[9] = m;
}
if ((m >= src_h-1) || (n >= src_w-1)) {
src_offset_x[10] = n;
src_offset_y[10] = m;
} else {
src_offset_x[10] = n + 1;
src_offset_y[10] = m;
}
if ((m >= src_h - 1) || (n >= src_w - 2)) {
src_offset_x[11] = n;
src_offset_y[11] = m;
} else {
src_offset_x[11] = n + 1 + 1;
src_offset_y[11] = m;
}
if ((m >= src_h - 2) || (n < 1)) {
src_offset_x[12] = n;
src_offset_y[12] = m;
} else {
src_offset_x[12] = n - 1;
src_offset_y[12] = m;
}
if (m >= src_h - 2) {
src_offset_x[13] = n;
src_offset_y[13] = m;
} else {
src_offset_x[13] = n;
src_offset_y[13] = m;
}
if ((m >= src_h - 2) || (n >= src_w - 1)) {
src_offset_x[14] = n;
src_offset_y[14] = m;
} else {
src_offset_x[14] = n + 1;
src_offset_y[14] = m;
}
if ((m >= src_h - 2) || (n >= src_w - 2)) {
src_offset_x[15] = n;
src_offset_y[15] = m;
} else {
src_offset_x[15] = n + 1 + 1;
src_offset_y[15] = m;
}
for (k = -1; k < 3; k++) {
const gdFixed f = gd_itofx(k)-f_f;
const gdFixed f_fm1 = f - f_1;
const gdFixed f_fp1 = f + f_1;
const gdFixed f_fp2 = f + f_2;
register gdFixed f_a = 0, f_b = 0, f_d = 0, f_c = 0;
register gdFixed f_RY;
int l;
if (f_fp2 > 0) f_a = gd_mulfx(f_fp2, gd_mulfx(f_fp2,f_fp2));
if (f_fp1 > 0) f_b = gd_mulfx(f_fp1, gd_mulfx(f_fp1,f_fp1));
if (f > 0) f_c = gd_mulfx(f, gd_mulfx(f,f));
if (f_fm1 > 0) f_d = gd_mulfx(f_fm1, gd_mulfx(f_fm1,f_fm1));
f_RY = gd_divfx((f_a - gd_mulfx(f_4,f_b) + gd_mulfx(f_6,f_c) - gd_mulfx(f_4,f_d)),f_6);
for (l = -1; l < 3; l++) {
const gdFixed f = gd_itofx(l) - f_g;
const gdFixed f_fm1 = f - f_1;
const gdFixed f_fp1 = f + f_1;
const gdFixed f_fp2 = f + f_2;
register gdFixed f_a = 0, f_b = 0, f_c = 0, f_d = 0;
register gdFixed f_RX, f_R, f_rs, f_gs, f_bs, f_ba;
register int c;
const int _k = ((k+1)*4) + (l+1);
if (f_fp2 > 0) f_a = gd_mulfx(f_fp2,gd_mulfx(f_fp2,f_fp2));
if (f_fp1 > 0) f_b = gd_mulfx(f_fp1,gd_mulfx(f_fp1,f_fp1));
if (f > 0) f_c = gd_mulfx(f,gd_mulfx(f,f));
if (f_fm1 > 0) f_d = gd_mulfx(f_fm1,gd_mulfx(f_fm1,f_fm1));
f_RX = gd_divfx((f_a-gd_mulfx(f_4,f_b)+gd_mulfx(f_6,f_c)-gd_mulfx(f_4,f_d)),f_6);
f_R = gd_mulfx(f_RY,f_RX);
c = src->tpixels[*(src_offset_y + _k)][*(src_offset_x + _k)];
f_rs = gd_itofx(gdTrueColorGetRed(c));
f_gs = gd_itofx(gdTrueColorGetGreen(c));
f_bs = gd_itofx(gdTrueColorGetBlue(c));
f_ba = gd_itofx(gdTrueColorGetAlpha(c));
f_red += gd_mulfx(f_rs,f_R);
f_green += gd_mulfx(f_gs,f_R);
f_blue += gd_mulfx(f_bs,f_R);
f_alpha += gd_mulfx(f_ba,f_R);
}
}
red = (unsigned char) CLAMP(gd_fxtoi(gd_mulfx(f_red, f_gamma)), 0, 255);
green = (unsigned char) CLAMP(gd_fxtoi(gd_mulfx(f_green, f_gamma)), 0, 255);
blue = (unsigned char) CLAMP(gd_fxtoi(gd_mulfx(f_blue, f_gamma)), 0, 255);
alpha = (unsigned char) CLAMP(gd_fxtoi(gd_mulfx(f_alpha, f_gamma)), 0, 127);
*(dst_row + dst_offset_x) = gdTrueColorAlpha(red, green, blue, alpha);
dst_offset_x++;
}
dst_offset_y++;
}
return dst;
}
gdImagePtr gdImageScale(const gdImagePtr src, const unsigned int new_width, const unsigned int new_height)
{
gdImagePtr im_scaled = NULL;
if (src == NULL || src->interpolation_id < 0 || src->interpolation_id > GD_METHOD_COUNT) {
return 0;
}
switch (src->interpolation_id) {
/*Special cases, optimized implementations */
case GD_NEAREST_NEIGHBOUR:
im_scaled = gdImageScaleNearestNeighbour(src, new_width, new_height);
break;
case GD_BILINEAR_FIXED:
im_scaled = gdImageScaleBilinear(src, new_width, new_height);
break;
case GD_BICUBIC_FIXED:
im_scaled = gdImageScaleBicubicFixed(src, new_width, new_height);
break;
/* generic */
default:
if (src->interpolation == NULL) {
return NULL;
}
im_scaled = gdImageScaleTwoPass(src, src->sx, src->sy, new_width, new_height);
break;
}
return im_scaled;
}
gdImagePtr gdImageRotateNearestNeighbour(gdImagePtr src, const float degrees, const int bgColor)
{
float _angle = ((float) (-degrees / 180.0f) * (float)M_PI);
const int src_w = gdImageSX(src);
const int src_h = gdImageSY(src);
const unsigned int new_width = (unsigned int)(abs((int)(src_w * cos(_angle))) + abs((int)(src_h * sin(_angle))) + 0.5f);
const unsigned int new_height = (unsigned int)(abs((int)(src_w * sin(_angle))) + abs((int)(src_h * cos(_angle))) + 0.5f);
const gdFixed f_0_5 = gd_ftofx(0.5f);
const gdFixed f_H = gd_itofx(src_h/2);
const gdFixed f_W = gd_itofx(src_w/2);
const gdFixed f_cos = gd_ftofx(cos(-_angle));
const gdFixed f_sin = gd_ftofx(sin(-_angle));
unsigned int dst_offset_x;
unsigned int dst_offset_y = 0;
unsigned int i;
gdImagePtr dst;
dst = gdImageCreateTrueColor(new_width, new_height);
if (!dst) {
return NULL;
}
dst->saveAlphaFlag = 1;
for (i = 0; i < new_height; i++) {
unsigned int j;
dst_offset_x = 0;
for (j = 0; j < new_width; j++) {
gdFixed f_i = gd_itofx((int)i - (int)new_height/2);
gdFixed f_j = gd_itofx((int)j - (int)new_width/2);
gdFixed f_m = gd_mulfx(f_j,f_sin) + gd_mulfx(f_i,f_cos) + f_0_5 + f_H;
gdFixed f_n = gd_mulfx(f_j,f_cos) - gd_mulfx(f_i,f_sin) + f_0_5 + f_W;
long m = gd_fxtoi(f_m);
long n = gd_fxtoi(f_n);
if ((m > 0) && (m < src_h-1) && (n > 0) && (n < src_w-1)) {
if (dst_offset_y < new_height) {
dst->tpixels[dst_offset_y][dst_offset_x++] = src->tpixels[m][n];
}
} else {
if (dst_offset_y < new_height) {
dst->tpixels[dst_offset_y][dst_offset_x++] = bgColor;
}
}
}
dst_offset_y++;
}
return dst;
}
gdImagePtr gdImageRotateGeneric(gdImagePtr src, const float degrees, const int bgColor)
{
float _angle = ((float) (-degrees / 180.0f) * (float)M_PI);
const int src_w = gdImageSX(src);
const int src_h = gdImageSY(src);
const unsigned int new_width = (unsigned int)(abs((int)(src_w * cos(_angle))) + abs((int)(src_h * sin(_angle))) + 0.5f);
const unsigned int new_height = (unsigned int)(abs((int)(src_w * sin(_angle))) + abs((int)(src_h * cos(_angle))) + 0.5f);
const gdFixed f_0_5 = gd_ftofx(0.5f);
const gdFixed f_H = gd_itofx(src_h/2);
const gdFixed f_W = gd_itofx(src_w/2);
const gdFixed f_cos = gd_ftofx(cos(-_angle));
const gdFixed f_sin = gd_ftofx(sin(-_angle));
unsigned int dst_offset_x;
unsigned int dst_offset_y = 0;
unsigned int i;
gdImagePtr dst;
const gdFixed f_slop_y = f_sin;
const gdFixed f_slop_x = f_cos;
const gdFixed f_slop = f_slop_x > 0 && f_slop_x > 0 ?
f_slop_x > f_slop_y ? gd_divfx(f_slop_y, f_slop_x) : gd_divfx(f_slop_x, f_slop_y)
: 0;
dst = gdImageCreateTrueColor(new_width, new_height);
if (!dst) {
return NULL;
}
dst->saveAlphaFlag = 1;
for (i = 0; i < new_height; i++) {
unsigned int j;
dst_offset_x = 0;
for (j = 0; j < new_width; j++) {
gdFixed f_i = gd_itofx((int)i - (int)new_height/ 2);
gdFixed f_j = gd_itofx((int)j - (int)new_width / 2);
gdFixed f_m = gd_mulfx(f_j,f_sin) + gd_mulfx(f_i,f_cos) + f_0_5 + f_H;
gdFixed f_n = gd_mulfx(f_j,f_cos) - gd_mulfx(f_i,f_sin) + f_0_5 + f_W;
long m = gd_fxtoi(f_m);
long n = gd_fxtoi(f_n);
if ((n <= 0) || (m <= 0) || (m >= src_h) || (n >= src_w)) {
dst->tpixels[dst_offset_y][dst_offset_x++] = bgColor;
} else if ((n <= 1) || (m <= 1) || (m >= src_h - 1) || (n >= src_w - 1)) {
gdFixed f_127 = gd_itofx(127);
register int c = getPixelInterpolated(src, n, m, bgColor);
c = c | (( gdTrueColorGetAlpha(c) + ((int)(127* gd_fxtof(f_slop)))) << 24);
dst->tpixels[dst_offset_y][dst_offset_x++] = _color_blend(bgColor, c);
} else {
dst->tpixels[dst_offset_y][dst_offset_x++] = getPixelInterpolated(src, n, m, bgColor);
}
}
dst_offset_y++;
}
return dst;
}
gdImagePtr gdImageRotateBilinear(gdImagePtr src, const float degrees, const int bgColor)
{
float _angle = (float)((- degrees / 180.0f) * M_PI);
const unsigned int src_w = gdImageSX(src);
const unsigned int src_h = gdImageSY(src);
unsigned int new_width = abs((int)(src_w*cos(_angle))) + abs((int)(src_h*sin(_angle) + 0.5f));
unsigned int new_height = abs((int)(src_w*sin(_angle))) + abs((int)(src_h*cos(_angle) + 0.5f));
const gdFixed f_0_5 = gd_ftofx(0.5f);
const gdFixed f_H = gd_itofx(src_h/2);
const gdFixed f_W = gd_itofx(src_w/2);
const gdFixed f_cos = gd_ftofx(cos(-_angle));
const gdFixed f_sin = gd_ftofx(sin(-_angle));
const gdFixed f_1 = gd_itofx(1);
unsigned int i;
unsigned int dst_offset_x;
unsigned int dst_offset_y = 0;
unsigned int src_offset_x, src_offset_y;
gdImagePtr dst;
dst = gdImageCreateTrueColor(new_width, new_height);
if (dst == NULL) {
return NULL;
}
dst->saveAlphaFlag = 1;
for (i = 0; i < new_height; i++) {
unsigned int j;
dst_offset_x = 0;
for (j=0; j < new_width; j++) {
const gdFixed f_i = gd_itofx((int)i - (int)new_height/2);
const gdFixed f_j = gd_itofx((int)j - (int)new_width/2);
const gdFixed f_m = gd_mulfx(f_j,f_sin) + gd_mulfx(f_i,f_cos) + f_0_5 + f_H;
const gdFixed f_n = gd_mulfx(f_j,f_cos) - gd_mulfx(f_i,f_sin) + f_0_5 + f_W;
const unsigned int m = gd_fxtoi(f_m);
const unsigned int n = gd_fxtoi(f_n);
if ((m > 0) && (m < src_h - 1) && (n > 0) && (n < src_w - 1)) {
const gdFixed f_f = f_m - gd_itofx(m);
const gdFixed f_g = f_n - gd_itofx(n);
const gdFixed f_w1 = gd_mulfx(f_1-f_f, f_1-f_g);
const gdFixed f_w2 = gd_mulfx(f_1-f_f, f_g);
const gdFixed f_w3 = gd_mulfx(f_f, f_1-f_g);
const gdFixed f_w4 = gd_mulfx(f_f, f_g);
if (n < src_w - 1) {
src_offset_x = n + 1;
src_offset_y = m;
}
if (m < src_h-1) {
src_offset_x = n;
src_offset_y = m + 1;
}
if (!((n >= src_w-1) || (m >= src_h-1))) {
src_offset_x = n + 1;
src_offset_y = m + 1;
}
{
const int pixel1 = src->tpixels[src_offset_y][src_offset_x];
register int pixel2, pixel3, pixel4;
if (src_offset_y + 1 >= src_h) {
pixel2 = bgColor;
pixel3 = bgColor;
pixel4 = bgColor;
} else if (src_offset_x + 1 >= src_w) {
pixel2 = bgColor;
pixel3 = bgColor;
pixel4 = bgColor;
} else {
pixel2 = src->tpixels[src_offset_y][src_offset_x + 1];
pixel3 = src->tpixels[src_offset_y + 1][src_offset_x];
pixel4 = src->tpixels[src_offset_y + 1][src_offset_x + 1];
}
{
const gdFixed f_r1 = gd_itofx(gdTrueColorGetRed(pixel1));
const gdFixed f_r2 = gd_itofx(gdTrueColorGetRed(pixel2));
const gdFixed f_r3 = gd_itofx(gdTrueColorGetRed(pixel3));
const gdFixed f_r4 = gd_itofx(gdTrueColorGetRed(pixel4));
const gdFixed f_g1 = gd_itofx(gdTrueColorGetGreen(pixel1));
const gdFixed f_g2 = gd_itofx(gdTrueColorGetGreen(pixel2));
const gdFixed f_g3 = gd_itofx(gdTrueColorGetGreen(pixel3));
const gdFixed f_g4 = gd_itofx(gdTrueColorGetGreen(pixel4));
const gdFixed f_b1 = gd_itofx(gdTrueColorGetBlue(pixel1));
const gdFixed f_b2 = gd_itofx(gdTrueColorGetBlue(pixel2));
const gdFixed f_b3 = gd_itofx(gdTrueColorGetBlue(pixel3));
const gdFixed f_b4 = gd_itofx(gdTrueColorGetBlue(pixel4));
const gdFixed f_a1 = gd_itofx(gdTrueColorGetAlpha(pixel1));
const gdFixed f_a2 = gd_itofx(gdTrueColorGetAlpha(pixel2));
const gdFixed f_a3 = gd_itofx(gdTrueColorGetAlpha(pixel3));
const gdFixed f_a4 = gd_itofx(gdTrueColorGetAlpha(pixel4));
const gdFixed f_red = gd_mulfx(f_w1, f_r1) + gd_mulfx(f_w2, f_r2) + gd_mulfx(f_w3, f_r3) + gd_mulfx(f_w4, f_r4);
const gdFixed f_green = gd_mulfx(f_w1, f_g1) + gd_mulfx(f_w2, f_g2) + gd_mulfx(f_w3, f_g3) + gd_mulfx(f_w4, f_g4);
const gdFixed f_blue = gd_mulfx(f_w1, f_b1) + gd_mulfx(f_w2, f_b2) + gd_mulfx(f_w3, f_b3) + gd_mulfx(f_w4, f_b4);
const gdFixed f_alpha = gd_mulfx(f_w1, f_a1) + gd_mulfx(f_w2, f_a2) + gd_mulfx(f_w3, f_a3) + gd_mulfx(f_w4, f_a4);
const unsigned char red = (unsigned char) CLAMP(gd_fxtoi(f_red), 0, 255);
const unsigned char green = (unsigned char) CLAMP(gd_fxtoi(f_green), 0, 255);
const unsigned char blue = (unsigned char) CLAMP(gd_fxtoi(f_blue), 0, 255);
const unsigned char alpha = (unsigned char) CLAMP(gd_fxtoi(f_alpha), 0, 127);
dst->tpixels[dst_offset_y][dst_offset_x++] = gdTrueColorAlpha(red, green, blue, alpha);
}
}
} else {
dst->tpixels[dst_offset_y][dst_offset_x++] = bgColor;
}
}
dst_offset_y++;
}
return dst;
}
gdImagePtr gdImageRotateBicubicFixed(gdImagePtr src, const float degrees, const int bgColor)
{
const float _angle = (float)((- degrees / 180.0f) * M_PI);
const int src_w = gdImageSX(src);
const int src_h = gdImageSY(src);
const unsigned int new_width = abs((int)(src_w*cos(_angle))) + abs((int)(src_h*sin(_angle) + 0.5f));
const unsigned int new_height = abs((int)(src_w*sin(_angle))) + abs((int)(src_h*cos(_angle) + 0.5f));
const gdFixed f_0_5 = gd_ftofx(0.5f);
const gdFixed f_H = gd_itofx(src_h/2);
const gdFixed f_W = gd_itofx(src_w/2);
const gdFixed f_cos = gd_ftofx(cos(-_angle));
const gdFixed f_sin = gd_ftofx(sin(-_angle));
const gdFixed f_1 = gd_itofx(1);
const gdFixed f_2 = gd_itofx(2);
const gdFixed f_4 = gd_itofx(4);
const gdFixed f_6 = gd_itofx(6);
const gdFixed f_gama = gd_ftofx(1.04f);
unsigned int dst_offset_x;
unsigned int dst_offset_y = 0;
unsigned int i;
gdImagePtr dst;
dst = gdImageCreateTrueColor(new_width, new_height);
if (dst == NULL) {
return NULL;
}
dst->saveAlphaFlag = 1;
for (i=0; i < new_height; i++) {
unsigned int j;
dst_offset_x = 0;
for (j=0; j < new_width; j++) {
const gdFixed f_i = gd_itofx((int)i - (int)new_height/2);
const gdFixed f_j = gd_itofx((int)j - (int)new_width/2);
const gdFixed f_m = gd_mulfx(f_j,f_sin) + gd_mulfx(f_i,f_cos) + f_0_5 + f_H;
const gdFixed f_n = gd_mulfx(f_j,f_cos) - gd_mulfx(f_i,f_sin) + f_0_5 + f_W;
const int m = gd_fxtoi(f_m);
const int n = gd_fxtoi(f_n);
if ((m > 0) && (m < src_h - 1) && (n > 0) && (n < src_w-1)) {
const gdFixed f_f = f_m - gd_itofx(m);
const gdFixed f_g = f_n - gd_itofx(n);
unsigned int src_offset_x[16], src_offset_y[16];
unsigned char red, green, blue, alpha;
gdFixed f_red=0, f_green=0, f_blue=0, f_alpha=0;
int k;
if ((m < 1) || (n < 1)) {
src_offset_x[0] = n;
src_offset_y[0] = m;
} else {
src_offset_x[0] = n - 1;
src_offset_y[0] = m;
}
if (m < 1) {
src_offset_x[1] = n;
src_offset_y[1] = m;
} else {
src_offset_x[1] = n;
src_offset_y[1] = m ;
}
if ((m < 1) || (n >= src_w-1)) {
src_offset_x[2] = - 1;
src_offset_y[2] = - 1;
} else {
src_offset_x[2] = n + 1;
src_offset_y[2] = m ;
}
if ((m < 1) || (n >= src_w-2)) {
src_offset_x[3] = - 1;
src_offset_y[3] = - 1;
} else {
src_offset_x[3] = n + 1 + 1;
src_offset_y[3] = m ;
}
if (n < 1) {
src_offset_x[4] = - 1;
src_offset_y[4] = - 1;
} else {
src_offset_x[4] = n - 1;
src_offset_y[4] = m;
}
src_offset_x[5] = n;
src_offset_y[5] = m;
if (n >= src_w-1) {
src_offset_x[6] = - 1;
src_offset_y[6] = - 1;
} else {
src_offset_x[6] = n + 1;
src_offset_y[6] = m;
}
if (n >= src_w-2) {
src_offset_x[7] = - 1;
src_offset_y[7] = - 1;
} else {
src_offset_x[7] = n + 1 + 1;
src_offset_y[7] = m;
}
if ((m >= src_h-1) || (n < 1)) {
src_offset_x[8] = - 1;
src_offset_y[8] = - 1;
} else {
src_offset_x[8] = n - 1;
src_offset_y[8] = m;
}
if (m >= src_h-1) {
src_offset_x[8] = - 1;
src_offset_y[8] = - 1;
} else {
src_offset_x[9] = n;
src_offset_y[9] = m;
}
if ((m >= src_h-1) || (n >= src_w-1)) {
src_offset_x[10] = - 1;
src_offset_y[10] = - 1;
} else {
src_offset_x[10] = n + 1;
src_offset_y[10] = m;
}
if ((m >= src_h-1) || (n >= src_w-2)) {
src_offset_x[11] = - 1;
src_offset_y[11] = - 1;
} else {
src_offset_x[11] = n + 1 + 1;
src_offset_y[11] = m;
}
if ((m >= src_h-2) || (n < 1)) {
src_offset_x[12] = - 1;
src_offset_y[12] = - 1;
} else {
src_offset_x[12] = n - 1;
src_offset_y[12] = m;
}
if (m >= src_h-2) {
src_offset_x[13] = - 1;
src_offset_y[13] = - 1;
} else {
src_offset_x[13] = n;
src_offset_y[13] = m;
}
if ((m >= src_h-2) || (n >= src_w - 1)) {
src_offset_x[14] = - 1;
src_offset_y[14] = - 1;
} else {
src_offset_x[14] = n + 1;
src_offset_y[14] = m;
}
if ((m >= src_h-2) || (n >= src_w-2)) {
src_offset_x[15] = - 1;
src_offset_y[15] = - 1;
} else {
src_offset_x[15] = n + 1 + 1;
src_offset_y[15] = m;
}
for (k=-1; k<3; k++) {
const gdFixed f = gd_itofx(k)-f_f;
const gdFixed f_fm1 = f - f_1;
const gdFixed f_fp1 = f + f_1;
const gdFixed f_fp2 = f + f_2;
gdFixed f_a = 0, f_b = 0,f_c = 0, f_d = 0;
gdFixed f_RY;
int l;
if (f_fp2 > 0) {
f_a = gd_mulfx(f_fp2,gd_mulfx(f_fp2,f_fp2));
}
if (f_fp1 > 0) {
f_b = gd_mulfx(f_fp1,gd_mulfx(f_fp1,f_fp1));
}
if (f > 0) {
f_c = gd_mulfx(f,gd_mulfx(f,f));
}
if (f_fm1 > 0) {
f_d = gd_mulfx(f_fm1,gd_mulfx(f_fm1,f_fm1));
}
f_RY = gd_divfx((f_a-gd_mulfx(f_4,f_b)+gd_mulfx(f_6,f_c)-gd_mulfx(f_4,f_d)),f_6);
for (l=-1; l< 3; l++) {
const gdFixed f = gd_itofx(l) - f_g;
const gdFixed f_fm1 = f - f_1;
const gdFixed f_fp1 = f + f_1;
const gdFixed f_fp2 = f + f_2;
gdFixed f_a = 0, f_b = 0, f_c = 0, f_d = 0;
gdFixed f_RX, f_R;
const int _k = ((k + 1) * 4) + (l + 1);
register gdFixed f_rs, f_gs, f_bs, f_as;
register int c;
if (f_fp2 > 0) {
f_a = gd_mulfx(f_fp2,gd_mulfx(f_fp2,f_fp2));
}
if (f_fp1 > 0) {
f_b = gd_mulfx(f_fp1,gd_mulfx(f_fp1,f_fp1));
}
if (f > 0) {
f_c = gd_mulfx(f,gd_mulfx(f,f));
}
if (f_fm1 > 0) {
f_d = gd_mulfx(f_fm1,gd_mulfx(f_fm1,f_fm1));
}
f_RX = gd_divfx((f_a - gd_mulfx(f_4, f_b) + gd_mulfx(f_6, f_c) - gd_mulfx(f_4, f_d)), f_6);
f_R = gd_mulfx(f_RY, f_RX);
if ((src_offset_x[_k] <= 0) || (src_offset_y[_k] <= 0) || (src_offset_y[_k] >= src_h) || (src_offset_x[_k] >= src_w)) {
c = bgColor;
} else if ((src_offset_x[_k] <= 1) || (src_offset_y[_k] <= 1) || (src_offset_y[_k] >= (int)src_h - 1) || (src_offset_x[_k] >= (int)src_w - 1)) {
gdFixed f_127 = gd_itofx(127);
c = src->tpixels[src_offset_y[_k]][src_offset_x[_k]];
c = c | (( (int) (gd_fxtof(gd_mulfx(f_R, f_127)) + 50.5f)) << 24);
c = _color_blend(bgColor, c);
} else {
c = src->tpixels[src_offset_y[_k]][src_offset_x[_k]];
}
f_rs = gd_itofx(gdTrueColorGetRed(c));
f_gs = gd_itofx(gdTrueColorGetGreen(c));
f_bs = gd_itofx(gdTrueColorGetBlue(c));
f_as = gd_itofx(gdTrueColorGetAlpha(c));
f_red += gd_mulfx(f_rs, f_R);
f_green += gd_mulfx(f_gs, f_R);
f_blue += gd_mulfx(f_bs, f_R);
f_alpha += gd_mulfx(f_as, f_R);
}
}
red = (unsigned char) CLAMP(gd_fxtoi(gd_mulfx(f_red, f_gama)), 0, 255);
green = (unsigned char) CLAMP(gd_fxtoi(gd_mulfx(f_green, f_gama)), 0, 255);
blue = (unsigned char) CLAMP(gd_fxtoi(gd_mulfx(f_blue, f_gama)), 0, 255);
alpha = (unsigned char) CLAMP(gd_fxtoi(gd_mulfx(f_alpha, f_gama)), 0, 127);
dst->tpixels[dst_offset_y][dst_offset_x] = gdTrueColorAlpha(red, green, blue, alpha);
} else {
dst->tpixels[dst_offset_y][dst_offset_x] = bgColor;
}
dst_offset_x++;
}
dst_offset_y++;
}
return dst;
}
gdImagePtr gdImageRotateInterpolated(const gdImagePtr src, const float angle, int bgcolor)
{
const int angle_rounded = (int)floor(angle * 100);
if (bgcolor < 0) {
return NULL;
}
/* impact perf a bit, but not that much. Implementation for palette
images can be done at a later point.
*/
if (src->trueColor == 0) {
if (bgcolor < gdMaxColors) {
bgcolor = gdTrueColorAlpha(src->red[bgcolor], src->green[bgcolor], src->blue[bgcolor], src->alpha[bgcolor]);
}
gdImagePaletteToTrueColor(src);
}
/* no interpolation needed here */
switch (angle_rounded) {
case 9000:
return gdImageRotate90(src, 0);
case 18000:
return gdImageRotate180(src, 0);
case 27000:
return gdImageRotate270(src, 0);
}
if (src == NULL || src->interpolation_id < 1 || src->interpolation_id > GD_METHOD_COUNT) {
return NULL;
}
switch (src->interpolation_id) {
case GD_NEAREST_NEIGHBOUR:
return gdImageRotateNearestNeighbour(src, angle, bgcolor);
break;
case GD_BILINEAR_FIXED:
return gdImageRotateBilinear(src, angle, bgcolor);
break;
case GD_BICUBIC_FIXED:
return gdImageRotateBicubicFixed(src, angle, bgcolor);
break;
default:
return gdImageRotateGeneric(src, angle, bgcolor);
}
return NULL;
}
/**
* Title: Affine transformation
**/
/**
* Group: Transform
**/
static void gdImageClipRectangle(gdImagePtr im, gdRectPtr r)
{
int c1x, c1y, c2x, c2y;
int x1,y1;
gdImageGetClip(im, &c1x, &c1y, &c2x, &c2y);
x1 = r->x + r->width - 1;
y1 = r->y + r->height - 1;
r->x = CLAMP(r->x, c1x, c2x);
r->y = CLAMP(r->y, c1y, c2y);
r->width = CLAMP(x1, c1x, c2x) - r->x + 1;
r->height = CLAMP(y1, c1y, c2y) - r->y + 1;
}
void gdDumpRect(const char *msg, gdRectPtr r)
{
printf("%s (%i, %i) (%i, %i)\n", msg, r->x, r->y, r->width, r->height);
}
/**
* Function: gdTransformAffineGetImage
* Applies an affine transformation to a region and return an image
* containing the complete transformation.
*
* Parameters:
* dst - Pointer to a gdImagePtr to store the created image, NULL when
* the creation or the transformation failed
* src - Source image
* src_area - rectangle defining the source region to transform
* dstY - Y position in the destination image
* affine - The desired affine transformation
*
* Returns:
* GD_TRUE if the affine is rectilinear or GD_FALSE
*/
int gdTransformAffineGetImage(gdImagePtr *dst,
const gdImagePtr src,
gdRectPtr src_area,
const double affine[6])
{
int res;
double m[6];
gdRect bbox;
gdRect area_full;
if (src_area == NULL) {
area_full.x = 0;
area_full.y = 0;
area_full.width = gdImageSX(src);
area_full.height = gdImageSY(src);
src_area = &area_full;
}
gdTransformAffineBoundingBox(src_area, affine, &bbox);
*dst = gdImageCreateTrueColor(bbox.width, bbox.height);
if (*dst == NULL) {
return GD_FALSE;
}
(*dst)->saveAlphaFlag = 1;
if (!src->trueColor) {
gdImagePaletteToTrueColor(src);
}
/* Translate to dst origin (0,0) */
gdAffineTranslate(m, -bbox.x, -bbox.y);
gdAffineConcat(m, affine, m);
gdImageAlphaBlending(*dst, 0);
res = gdTransformAffineCopy(*dst,
0,0,
src,
src_area,
m);
if (res != GD_TRUE) {
gdImageDestroy(*dst);
dst = NULL;
return GD_FALSE;
} else {
return GD_TRUE;
}
}
/**
* Function: gdTransformAffineCopy
* Applies an affine transformation to a region and copy the result
* in a destination to the given position.
*
* Parameters:
* dst - Image to draw the transformed image
* src - Source image
* dstX - X position in the destination image
* dstY - Y position in the destination image
* src_area - Rectangular region to rotate in the src image
*
* Returns:
* GD_TRUE if the affine is rectilinear or GD_FALSE
*/
int gdTransformAffineCopy(gdImagePtr dst,
int dst_x, int dst_y,
const gdImagePtr src,
gdRectPtr src_region,
const double affine[6])
{
int c1x,c1y,c2x,c2y;
int backclip = 0;
int backup_clipx1, backup_clipy1, backup_clipx2, backup_clipy2;
register int x, y, src_offset_x, src_offset_y;
double inv[6];
int *dst_p;
gdPointF pt, src_pt;
gdRect bbox;
int end_x, end_y;
gdInterpolationMethod interpolation_id_bak = GD_DEFAULT;
interpolation_method interpolation_bak;
/* These methods use special implementations */
if (src->interpolation_id == GD_BILINEAR_FIXED || src->interpolation_id == GD_BICUBIC_FIXED || src->interpolation_id == GD_NEAREST_NEIGHBOUR) {
interpolation_id_bak = src->interpolation_id;
interpolation_bak = src->interpolation;
gdImageSetInterpolationMethod(src, GD_BICUBIC);
}
gdImageClipRectangle(src, src_region);
if (src_region->x > 0 || src_region->y > 0
|| src_region->width < gdImageSX(src)
|| src_region->height < gdImageSY(src)) {
backclip = 1;
gdImageGetClip(src, &backup_clipx1, &backup_clipy1,
&backup_clipx2, &backup_clipy2);
gdImageSetClip(src, src_region->x, src_region->y,
src_region->x + src_region->width - 1,
src_region->y + src_region->height - 1);
}
if (!gdTransformAffineBoundingBox(src_region, affine, &bbox)) {
if (backclip) {
gdImageSetClip(src, backup_clipx1, backup_clipy1,
backup_clipx2, backup_clipy2);
}
gdImageSetInterpolationMethod(src, interpolation_id_bak);
return GD_FALSE;
}
gdImageGetClip(dst, &c1x, &c1y, &c2x, &c2y);
end_x = bbox.width + (int) fabs(bbox.x);
end_y = bbox.height + (int) fabs(bbox.y);
/* Get inverse affine to let us work with destination -> source */
gdAffineInvert(inv, affine);
src_offset_x = src_region->x;
src_offset_y = src_region->y;
if (dst->alphaBlendingFlag) {
for (y = bbox.y; y <= end_y; y++) {
pt.y = y + 0.5;
for (x = 0; x <= end_x; x++) {
pt.x = x + 0.5;
gdAffineApplyToPointF(&src_pt, &pt, inv);
gdImageSetPixel(dst, dst_x + x, dst_y + y, getPixelInterpolated(src, src_offset_x + src_pt.x, src_offset_y + src_pt.y, 0));
}
}
} else {
for (y = 0; y <= end_y; y++) {
pt.y = y + 0.5 + bbox.y;
if ((dst_y + y) < 0 || ((dst_y + y) > gdImageSY(dst) -1)) {
continue;
}
dst_p = dst->tpixels[dst_y + y] + dst_x;
for (x = 0; x <= end_x; x++) {
pt.x = x + 0.5 + bbox.x;
gdAffineApplyToPointF(&src_pt, &pt, inv);
if ((dst_x + x) < 0 || (dst_x + x) > (gdImageSX(dst) - 1)) {
break;
}
*(dst_p++) = getPixelInterpolated(src, src_offset_x + src_pt.x, src_offset_y + src_pt.y, -1);
}
}
}
/* Restore clip if required */
if (backclip) {
gdImageSetClip(src, backup_clipx1, backup_clipy1,
backup_clipx2, backup_clipy2);
}
gdImageSetInterpolationMethod(src, interpolation_id_bak);
return GD_TRUE;
}
/**
* Function: gdTransformAffineBoundingBox
* Returns the bounding box of an affine transformation applied to a
* rectangular area <gdRect>
*
* Parameters:
* src - Rectangular source area for the affine transformation
* affine - the affine transformation
* bbox - the resulting bounding box
*
* Returns:
* GD_TRUE if the affine is rectilinear or GD_FALSE
*/
int gdTransformAffineBoundingBox(gdRectPtr src, const double affine[6], gdRectPtr bbox)
{
gdPointF extent[4], min, max, point;
int i;
extent[0].x=0.0;
extent[0].y=0.0;
extent[1].x=(double) src->width;
extent[1].y=0.0;
extent[2].x=(double) src->width;
extent[2].y=(double) src->height;
extent[3].x=0.0;
extent[3].y=(double) src->height;
for (i=0; i < 4; i++) {
point=extent[i];
if (gdAffineApplyToPointF(&extent[i], &point, affine) != GD_TRUE) {
return GD_FALSE;
}
}
min=extent[0];
max=extent[0];
for (i=1; i < 4; i++) {
if (min.x > extent[i].x)
min.x=extent[i].x;
if (min.y > extent[i].y)
min.y=extent[i].y;
if (max.x < extent[i].x)
max.x=extent[i].x;
if (max.y < extent[i].y)
max.y=extent[i].y;
}
bbox->x = (int) min.x;
bbox->y = (int) min.y;
bbox->width = (int) floor(max.x - min.x) - 1;
bbox->height = (int) floor(max.y - min.y);
return GD_TRUE;
}
int gdImageSetInterpolationMethod(gdImagePtr im, gdInterpolationMethod id)
{
if (im == NULL || id < 0 || id > GD_METHOD_COUNT) {
return 0;
}
switch (id) {
case GD_DEFAULT:
id = GD_BILINEAR_FIXED;
/* Optimized versions */
case GD_BILINEAR_FIXED:
case GD_BICUBIC_FIXED:
case GD_NEAREST_NEIGHBOUR:
case GD_WEIGHTED4:
im->interpolation = NULL;
break;
/* generic versions*/
case GD_BELL:
im->interpolation = filter_bell;
break;
case GD_BESSEL:
im->interpolation = filter_bessel;
break;
case GD_BICUBIC:
im->interpolation = filter_bicubic;
break;
case GD_BLACKMAN:
im->interpolation = filter_blackman;
break;
case GD_BOX:
im->interpolation = filter_box;
break;
case GD_BSPLINE:
im->interpolation = filter_bspline;
break;
case GD_CATMULLROM:
im->interpolation = filter_catmullrom;
break;
case GD_GAUSSIAN:
im->interpolation = filter_gaussian;
break;
case GD_GENERALIZED_CUBIC:
im->interpolation = filter_generalized_cubic;
break;
case GD_HERMITE:
im->interpolation = filter_hermite;
break;
case GD_HAMMING:
im->interpolation = filter_hamming;
break;
case GD_HANNING:
im->interpolation = filter_hanning;
break;
case GD_MITCHELL:
im->interpolation = filter_mitchell;
break;
case GD_POWER:
im->interpolation = filter_power;
break;
case GD_QUADRATIC:
im->interpolation = filter_quadratic;
break;
case GD_SINC:
im->interpolation = filter_sinc;
break;
case GD_TRIANGLE:
im->interpolation = filter_triangle;
break;
default:
return 0;
break;
}
im->interpolation_id = id;
return 1;
}
#ifdef _MSC_VER
# pragma optimize("", on)
#endif
| ./CrossVul/dataset_final_sorted/CWE-125/c/good_5870_0 |
crossvul-cpp_data_good_463_0 | /*
* MMS protocol common definitions.
* Copyright (c) 2006,2007 Ryan Martell
* Copyright (c) 2007 Björn Axelsson
* Copyright (c) 2010 Zhentan Feng <spyfeng at gmail dot com>
*
* This file is part of FFmpeg.
*
* FFmpeg is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* FFmpeg is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with FFmpeg; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "mms.h"
#include "asf.h"
#include "libavutil/intreadwrite.h"
#define MMS_MAX_STREAMS 256 /**< arbitrary sanity check value */
int ff_mms_read_header(MMSContext *mms, uint8_t *buf, const int size)
{
char *pos;
int size_to_copy;
int remaining_size = mms->asf_header_size - mms->asf_header_read_size;
size_to_copy = FFMIN(size, remaining_size);
pos = mms->asf_header + mms->asf_header_read_size;
memcpy(buf, pos, size_to_copy);
if (mms->asf_header_read_size == mms->asf_header_size) {
av_freep(&mms->asf_header); // which contains asf header
}
mms->asf_header_read_size += size_to_copy;
return size_to_copy;
}
int ff_mms_read_data(MMSContext *mms, uint8_t *buf, const int size)
{
int read_size;
read_size = FFMIN(size, mms->remaining_in_len);
memcpy(buf, mms->read_in_ptr, read_size);
mms->remaining_in_len -= read_size;
mms->read_in_ptr += read_size;
return read_size;
}
int ff_mms_asf_header_parser(MMSContext *mms)
{
uint8_t *p = mms->asf_header;
uint8_t *end;
int flags, stream_id;
mms->stream_num = 0;
if (mms->asf_header_size < sizeof(ff_asf_guid) * 2 + 22 ||
memcmp(p, ff_asf_header, sizeof(ff_asf_guid))) {
av_log(NULL, AV_LOG_ERROR,
"Corrupt stream (invalid ASF header, size=%d)\n",
mms->asf_header_size);
return AVERROR_INVALIDDATA;
}
end = mms->asf_header + mms->asf_header_size;
p += sizeof(ff_asf_guid) + 14;
while(end - p >= sizeof(ff_asf_guid) + 8) {
uint64_t chunksize;
if (!memcmp(p, ff_asf_data_header, sizeof(ff_asf_guid))) {
chunksize = 50; // see Reference [2] section 5.1
} else {
chunksize = AV_RL64(p + sizeof(ff_asf_guid));
}
if (!chunksize || chunksize > end - p) {
av_log(NULL, AV_LOG_ERROR,
"Corrupt stream (header chunksize %"PRId64" is invalid)\n",
chunksize);
return AVERROR_INVALIDDATA;
}
if (!memcmp(p, ff_asf_file_header, sizeof(ff_asf_guid))) {
/* read packet size */
if (end - p > sizeof(ff_asf_guid) * 2 + 68) {
mms->asf_packet_len = AV_RL32(p + sizeof(ff_asf_guid) * 2 + 64);
if (mms->asf_packet_len <= 0 || mms->asf_packet_len > sizeof(mms->in_buffer)) {
av_log(NULL, AV_LOG_ERROR,
"Corrupt stream (too large pkt_len %d)\n",
mms->asf_packet_len);
return AVERROR_INVALIDDATA;
}
}
} else if (!memcmp(p, ff_asf_stream_header, sizeof(ff_asf_guid))) {
if (end - p >= (sizeof(ff_asf_guid) * 3 + 26)) {
flags = AV_RL16(p + sizeof(ff_asf_guid)*3 + 24);
stream_id = flags & 0x7F;
//The second condition is for checking CS_PKT_STREAM_ID_REQUEST packet size,
//we can calculate the packet size by stream_num.
//Please see function send_stream_selection_request().
if (mms->stream_num < MMS_MAX_STREAMS &&
46 + mms->stream_num * 6 < sizeof(mms->out_buffer)) {
mms->streams = av_fast_realloc(mms->streams,
&mms->nb_streams_allocated,
(mms->stream_num + 1) * sizeof(MMSStream));
if (!mms->streams)
return AVERROR(ENOMEM);
mms->streams[mms->stream_num].id = stream_id;
mms->stream_num++;
} else {
av_log(NULL, AV_LOG_ERROR,
"Corrupt stream (too many A/V streams)\n");
return AVERROR_INVALIDDATA;
}
}
} else if (!memcmp(p, ff_asf_ext_stream_header, sizeof(ff_asf_guid))) {
if (end - p >= 88) {
int stream_count = AV_RL16(p + 84), ext_len_count = AV_RL16(p + 86);
uint64_t skip_bytes = 88;
while (stream_count--) {
if (end - p < skip_bytes + 4) {
av_log(NULL, AV_LOG_ERROR,
"Corrupt stream (next stream name length is not in the buffer)\n");
return AVERROR_INVALIDDATA;
}
skip_bytes += 4 + AV_RL16(p + skip_bytes + 2);
}
while (ext_len_count--) {
if (end - p < skip_bytes + 22) {
av_log(NULL, AV_LOG_ERROR,
"Corrupt stream (next extension system info length is not in the buffer)\n");
return AVERROR_INVALIDDATA;
}
skip_bytes += 22 + AV_RL32(p + skip_bytes + 18);
}
if (end - p < skip_bytes) {
av_log(NULL, AV_LOG_ERROR,
"Corrupt stream (the last extension system info length is invalid)\n");
return AVERROR_INVALIDDATA;
}
if (chunksize - skip_bytes > 24)
chunksize = skip_bytes;
}
} else if (!memcmp(p, ff_asf_head1_guid, sizeof(ff_asf_guid))) {
chunksize = 46; // see references [2] section 3.4. This should be set 46.
if (chunksize > end - p) {
av_log(NULL, AV_LOG_ERROR,
"Corrupt stream (header chunksize %"PRId64" is invalid)\n",
chunksize);
return AVERROR_INVALIDDATA;
}
}
p += chunksize;
}
return 0;
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/good_463_0 |
crossvul-cpp_data_bad_949_1 | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% FFFFF OOO U U RRRR IIIII EEEEE RRRR %
% F O O U U R R I E R R %
% FFF O O U U RRRR I EEE RRRR %
% F O O U U R R I E R R %
% F OOO UUU R R IIIII EEEEE R R %
% %
% %
% MagickCore Discrete Fourier Transform Methods %
% %
% Software Design %
% Sean Burke %
% Fred Weinhaus %
% Cristy %
% July 2009 %
% %
% %
% 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/artifact.h"
#include "MagickCore/attribute.h"
#include "MagickCore/blob.h"
#include "MagickCore/cache.h"
#include "MagickCore/image.h"
#include "MagickCore/image-private.h"
#include "MagickCore/list.h"
#include "MagickCore/fourier.h"
#include "MagickCore/log.h"
#include "MagickCore/memory_.h"
#include "MagickCore/monitor.h"
#include "MagickCore/monitor-private.h"
#include "MagickCore/pixel-accessor.h"
#include "MagickCore/pixel-private.h"
#include "MagickCore/property.h"
#include "MagickCore/quantum-private.h"
#include "MagickCore/resource_.h"
#include "MagickCore/string-private.h"
#include "MagickCore/thread-private.h"
#if defined(MAGICKCORE_FFTW_DELEGATE)
#if defined(MAGICKCORE_HAVE_COMPLEX_H)
#include <complex.h>
#endif
#include <fftw3.h>
#if !defined(MAGICKCORE_HAVE_CABS)
#define cabs(z) (sqrt(z[0]*z[0]+z[1]*z[1]))
#endif
#if !defined(MAGICKCORE_HAVE_CARG)
#define carg(z) (atan2(cimag(z),creal(z)))
#endif
#if !defined(MAGICKCORE_HAVE_CIMAG)
#define cimag(z) (z[1])
#endif
#if !defined(MAGICKCORE_HAVE_CREAL)
#define creal(z) (z[0])
#endif
#endif
/*
Typedef declarations.
*/
typedef struct _FourierInfo
{
PixelChannel
channel;
MagickBooleanType
modulus;
size_t
width,
height;
ssize_t
center;
} FourierInfo;
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% C o m p l e x I m a g e s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ComplexImages() performs complex mathematics on an image sequence.
%
% The format of the ComplexImages method is:
%
% MagickBooleanType ComplexImages(Image *images,const ComplexOperator op,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o op: A complex operator.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *ComplexImages(const Image *images,const ComplexOperator op,
ExceptionInfo *exception)
{
#define ComplexImageTag "Complex/Image"
CacheView
*Ai_view,
*Ar_view,
*Bi_view,
*Br_view,
*Ci_view,
*Cr_view;
const char
*artifact;
const Image
*Ai_image,
*Ar_image,
*Bi_image,
*Br_image;
double
snr;
Image
*Ci_image,
*complex_images,
*Cr_image,
*image;
MagickBooleanType
status;
MagickOffsetType
progress;
ssize_t
y;
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);
if (images->next == (Image *) NULL)
{
(void) ThrowMagickException(exception,GetMagickModule(),ImageError,
"ImageSequenceRequired","`%s'",images->filename);
return((Image *) NULL);
}
image=CloneImage(images,0,0,MagickTrue,exception);
if (image == (Image *) NULL)
return((Image *) NULL);
if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse)
{
image=DestroyImageList(image);
return(image);
}
image->depth=32UL;
complex_images=NewImageList();
AppendImageToList(&complex_images,image);
image=CloneImage(images,0,0,MagickTrue,exception);
if (image == (Image *) NULL)
{
complex_images=DestroyImageList(complex_images);
return(complex_images);
}
AppendImageToList(&complex_images,image);
/*
Apply complex mathematics to image pixels.
*/
artifact=GetImageArtifact(image,"complex:snr");
snr=0.0;
if (artifact != (const char *) NULL)
snr=StringToDouble(artifact,(char **) NULL);
Ar_image=images;
Ai_image=images->next;
Br_image=images;
Bi_image=images->next;
if ((images->next->next != (Image *) NULL) &&
(images->next->next->next != (Image *) NULL))
{
Br_image=images->next->next;
Bi_image=images->next->next->next;
}
Cr_image=complex_images;
Ci_image=complex_images->next;
Ar_view=AcquireVirtualCacheView(Ar_image,exception);
Ai_view=AcquireVirtualCacheView(Ai_image,exception);
Br_view=AcquireVirtualCacheView(Br_image,exception);
Bi_view=AcquireVirtualCacheView(Bi_image,exception);
Cr_view=AcquireAuthenticCacheView(Cr_image,exception);
Ci_view=AcquireAuthenticCacheView(Ci_image,exception);
status=MagickTrue;
progress=0;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(images,complex_images,images->rows,1L)
#endif
for (y=0; y < (ssize_t) images->rows; y++)
{
register const Quantum
*magick_restrict Ai,
*magick_restrict Ar,
*magick_restrict Bi,
*magick_restrict Br;
register Quantum
*magick_restrict Ci,
*magick_restrict Cr;
register ssize_t
x;
if (status == MagickFalse)
continue;
Ar=GetCacheViewVirtualPixels(Ar_view,0,y,Ar_image->columns,1,exception);
Ai=GetCacheViewVirtualPixels(Ai_view,0,y,Ai_image->columns,1,exception);
Br=GetCacheViewVirtualPixels(Br_view,0,y,Br_image->columns,1,exception);
Bi=GetCacheViewVirtualPixels(Bi_view,0,y,Bi_image->columns,1,exception);
Cr=QueueCacheViewAuthenticPixels(Cr_view,0,y,Cr_image->columns,1,exception);
Ci=QueueCacheViewAuthenticPixels(Ci_view,0,y,Ci_image->columns,1,exception);
if ((Ar == (const Quantum *) NULL) || (Ai == (const Quantum *) NULL) ||
(Br == (const Quantum *) NULL) || (Bi == (const Quantum *) NULL) ||
(Cr == (Quantum *) NULL) || (Ci == (Quantum *) NULL))
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) images->columns; x++)
{
register ssize_t
i;
for (i=0; i < (ssize_t) GetPixelChannels(images); i++)
{
switch (op)
{
case AddComplexOperator:
{
Cr[i]=Ar[i]+Br[i];
Ci[i]=Ai[i]+Bi[i];
break;
}
case ConjugateComplexOperator:
default:
{
Cr[i]=Ar[i];
Ci[i]=(-Bi[i]);
break;
}
case DivideComplexOperator:
{
double
gamma;
gamma=PerceptibleReciprocal(Br[i]*Br[i]+Bi[i]*Bi[i]+snr);
Cr[i]=gamma*(Ar[i]*Br[i]+Ai[i]*Bi[i]);
Ci[i]=gamma*(Ai[i]*Br[i]-Ar[i]*Bi[i]);
break;
}
case MagnitudePhaseComplexOperator:
{
Cr[i]=sqrt(Ar[i]*Ar[i]+Ai[i]*Ai[i]);
Ci[i]=atan2(Ai[i],Ar[i])/(2.0*MagickPI)+0.5;
break;
}
case MultiplyComplexOperator:
{
Cr[i]=QuantumScale*(Ar[i]*Br[i]-Ai[i]*Bi[i]);
Ci[i]=QuantumScale*(Ai[i]*Br[i]+Ar[i]*Bi[i]);
break;
}
case RealImaginaryComplexOperator:
{
Cr[i]=Ar[i]*cos(2.0*MagickPI*(Ai[i]-0.5));
Ci[i]=Ar[i]*sin(2.0*MagickPI*(Ai[i]-0.5));
break;
}
case SubtractComplexOperator:
{
Cr[i]=Ar[i]-Br[i];
Ci[i]=Ai[i]-Bi[i];
break;
}
}
}
Ar+=GetPixelChannels(Ar_image);
Ai+=GetPixelChannels(Ai_image);
Br+=GetPixelChannels(Br_image);
Bi+=GetPixelChannels(Bi_image);
Cr+=GetPixelChannels(Cr_image);
Ci+=GetPixelChannels(Ci_image);
}
if (SyncCacheViewAuthenticPixels(Ci_view,exception) == MagickFalse)
status=MagickFalse;
if (SyncCacheViewAuthenticPixels(Cr_view,exception) == MagickFalse)
status=MagickFalse;
if (images->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp atomic
#endif
progress++;
proceed=SetImageProgress(images,ComplexImageTag,progress,images->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
Cr_view=DestroyCacheView(Cr_view);
Ci_view=DestroyCacheView(Ci_view);
Br_view=DestroyCacheView(Br_view);
Bi_view=DestroyCacheView(Bi_view);
Ar_view=DestroyCacheView(Ar_view);
Ai_view=DestroyCacheView(Ai_view);
if (status == MagickFalse)
complex_images=DestroyImageList(complex_images);
return(complex_images);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% F o r w a r d F o u r i e r T r a n s f o r m I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ForwardFourierTransformImage() implements the discrete Fourier transform
% (DFT) of the image either as a magnitude / phase or real / imaginary image
% pair.
%
% The format of the ForwadFourierTransformImage method is:
%
% Image *ForwardFourierTransformImage(const Image *image,
% const MagickBooleanType modulus,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o modulus: if true, return as transform as a magnitude / phase pair
% otherwise a real / imaginary image pair.
%
% o exception: return any errors or warnings in this structure.
%
*/
#if defined(MAGICKCORE_FFTW_DELEGATE)
static MagickBooleanType RollFourier(const size_t width,const size_t height,
const ssize_t x_offset,const ssize_t y_offset,double *roll_pixels)
{
double
*source_pixels;
MemoryInfo
*source_info;
register ssize_t
i,
x;
ssize_t
u,
v,
y;
/*
Move zero frequency (DC, average color) from (0,0) to (width/2,height/2).
*/
source_info=AcquireVirtualMemory(width,height*sizeof(*source_pixels));
if (source_info == (MemoryInfo *) NULL)
return(MagickFalse);
source_pixels=(double *) GetVirtualMemoryBlob(source_info);
i=0L;
for (y=0L; y < (ssize_t) height; y++)
{
if (y_offset < 0L)
v=((y+y_offset) < 0L) ? y+y_offset+(ssize_t) height : y+y_offset;
else
v=((y+y_offset) > ((ssize_t) height-1L)) ? y+y_offset-(ssize_t) height :
y+y_offset;
for (x=0L; x < (ssize_t) width; x++)
{
if (x_offset < 0L)
u=((x+x_offset) < 0L) ? x+x_offset+(ssize_t) width : x+x_offset;
else
u=((x+x_offset) > ((ssize_t) width-1L)) ? x+x_offset-(ssize_t) width :
x+x_offset;
source_pixels[v*width+u]=roll_pixels[i++];
}
}
(void) memcpy(roll_pixels,source_pixels,height*width*
sizeof(*source_pixels));
source_info=RelinquishVirtualMemory(source_info);
return(MagickTrue);
}
static MagickBooleanType ForwardQuadrantSwap(const size_t width,
const size_t height,double *source_pixels,double *forward_pixels)
{
MagickBooleanType
status;
register ssize_t
x;
ssize_t
center,
y;
/*
Swap quadrants.
*/
center=(ssize_t) (width/2L)+1L;
status=RollFourier((size_t) center,height,0L,(ssize_t) height/2L,
source_pixels);
if (status == MagickFalse)
return(MagickFalse);
for (y=0L; y < (ssize_t) height; y++)
for (x=0L; x < (ssize_t) (width/2L); x++)
forward_pixels[y*width+x+width/2L]=source_pixels[y*center+x];
for (y=1; y < (ssize_t) height; y++)
for (x=0L; x < (ssize_t) (width/2L); x++)
forward_pixels[(height-y)*width+width/2L-x-1L]=
source_pixels[y*center+x+1L];
for (x=0L; x < (ssize_t) (width/2L); x++)
forward_pixels[width/2L-x-1L]=source_pixels[x+1L];
return(MagickTrue);
}
static void CorrectPhaseLHS(const size_t width,const size_t height,
double *fourier_pixels)
{
register ssize_t
x;
ssize_t
y;
for (y=0L; y < (ssize_t) height; y++)
for (x=0L; x < (ssize_t) (width/2L); x++)
fourier_pixels[y*width+x]*=(-1.0);
}
static MagickBooleanType ForwardFourier(const FourierInfo *fourier_info,
Image *image,double *magnitude,double *phase,ExceptionInfo *exception)
{
CacheView
*magnitude_view,
*phase_view;
double
*magnitude_pixels,
*phase_pixels;
Image
*magnitude_image,
*phase_image;
MagickBooleanType
status;
MemoryInfo
*magnitude_info,
*phase_info;
register Quantum
*q;
register ssize_t
x;
ssize_t
i,
y;
magnitude_image=GetFirstImageInList(image);
phase_image=GetNextImageInList(image);
if (phase_image == (Image *) NULL)
{
(void) ThrowMagickException(exception,GetMagickModule(),ImageError,
"ImageSequenceRequired","`%s'",image->filename);
return(MagickFalse);
}
/*
Create "Fourier Transform" image from constituent arrays.
*/
magnitude_info=AcquireVirtualMemory((size_t) fourier_info->width,
fourier_info->height*sizeof(*magnitude_pixels));
phase_info=AcquireVirtualMemory((size_t) fourier_info->width,
fourier_info->height*sizeof(*phase_pixels));
if ((magnitude_info == (MemoryInfo *) NULL) ||
(phase_info == (MemoryInfo *) NULL))
{
if (phase_info != (MemoryInfo *) NULL)
phase_info=RelinquishVirtualMemory(phase_info);
if (magnitude_info != (MemoryInfo *) NULL)
magnitude_info=RelinquishVirtualMemory(magnitude_info);
(void) ThrowMagickException(exception,GetMagickModule(),
ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename);
return(MagickFalse);
}
magnitude_pixels=(double *) GetVirtualMemoryBlob(magnitude_info);
(void) memset(magnitude_pixels,0,fourier_info->width*
fourier_info->height*sizeof(*magnitude_pixels));
phase_pixels=(double *) GetVirtualMemoryBlob(phase_info);
(void) memset(phase_pixels,0,fourier_info->width*
fourier_info->height*sizeof(*phase_pixels));
status=ForwardQuadrantSwap(fourier_info->width,fourier_info->height,
magnitude,magnitude_pixels);
if (status != MagickFalse)
status=ForwardQuadrantSwap(fourier_info->width,fourier_info->height,phase,
phase_pixels);
CorrectPhaseLHS(fourier_info->width,fourier_info->height,phase_pixels);
if (fourier_info->modulus != MagickFalse)
{
i=0L;
for (y=0L; y < (ssize_t) fourier_info->height; y++)
for (x=0L; x < (ssize_t) fourier_info->width; x++)
{
phase_pixels[i]/=(2.0*MagickPI);
phase_pixels[i]+=0.5;
i++;
}
}
magnitude_view=AcquireAuthenticCacheView(magnitude_image,exception);
i=0L;
for (y=0L; y < (ssize_t) fourier_info->height; y++)
{
q=GetCacheViewAuthenticPixels(magnitude_view,0L,y,fourier_info->width,1UL,
exception);
if (q == (Quantum *) NULL)
break;
for (x=0L; x < (ssize_t) fourier_info->width; x++)
{
switch (fourier_info->channel)
{
case RedPixelChannel:
default:
{
SetPixelRed(magnitude_image,ClampToQuantum(QuantumRange*
magnitude_pixels[i]),q);
break;
}
case GreenPixelChannel:
{
SetPixelGreen(magnitude_image,ClampToQuantum(QuantumRange*
magnitude_pixels[i]),q);
break;
}
case BluePixelChannel:
{
SetPixelBlue(magnitude_image,ClampToQuantum(QuantumRange*
magnitude_pixels[i]),q);
break;
}
case BlackPixelChannel:
{
SetPixelBlack(magnitude_image,ClampToQuantum(QuantumRange*
magnitude_pixels[i]),q);
break;
}
case AlphaPixelChannel:
{
SetPixelAlpha(magnitude_image,ClampToQuantum(QuantumRange*
magnitude_pixels[i]),q);
break;
}
}
i++;
q+=GetPixelChannels(magnitude_image);
}
status=SyncCacheViewAuthenticPixels(magnitude_view,exception);
if (status == MagickFalse)
break;
}
magnitude_view=DestroyCacheView(magnitude_view);
i=0L;
phase_view=AcquireAuthenticCacheView(phase_image,exception);
for (y=0L; y < (ssize_t) fourier_info->height; y++)
{
q=GetCacheViewAuthenticPixels(phase_view,0L,y,fourier_info->width,1UL,
exception);
if (q == (Quantum *) NULL)
break;
for (x=0L; x < (ssize_t) fourier_info->width; x++)
{
switch (fourier_info->channel)
{
case RedPixelChannel:
default:
{
SetPixelRed(phase_image,ClampToQuantum(QuantumRange*
phase_pixels[i]),q);
break;
}
case GreenPixelChannel:
{
SetPixelGreen(phase_image,ClampToQuantum(QuantumRange*
phase_pixels[i]),q);
break;
}
case BluePixelChannel:
{
SetPixelBlue(phase_image,ClampToQuantum(QuantumRange*
phase_pixels[i]),q);
break;
}
case BlackPixelChannel:
{
SetPixelBlack(phase_image,ClampToQuantum(QuantumRange*
phase_pixels[i]),q);
break;
}
case AlphaPixelChannel:
{
SetPixelAlpha(phase_image,ClampToQuantum(QuantumRange*
phase_pixels[i]),q);
break;
}
}
i++;
q+=GetPixelChannels(phase_image);
}
status=SyncCacheViewAuthenticPixels(phase_view,exception);
if (status == MagickFalse)
break;
}
phase_view=DestroyCacheView(phase_view);
phase_info=RelinquishVirtualMemory(phase_info);
magnitude_info=RelinquishVirtualMemory(magnitude_info);
return(status);
}
static MagickBooleanType ForwardFourierTransform(FourierInfo *fourier_info,
const Image *image,double *magnitude_pixels,double *phase_pixels,
ExceptionInfo *exception)
{
CacheView
*image_view;
const char
*value;
double
*source_pixels;
fftw_complex
*forward_pixels;
fftw_plan
fftw_r2c_plan;
MemoryInfo
*forward_info,
*source_info;
register const Quantum
*p;
register ssize_t
i,
x;
ssize_t
y;
/*
Generate the forward Fourier transform.
*/
source_info=AcquireVirtualMemory((size_t) fourier_info->width,
fourier_info->height*sizeof(*source_pixels));
if (source_info == (MemoryInfo *) NULL)
{
(void) ThrowMagickException(exception,GetMagickModule(),
ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename);
return(MagickFalse);
}
source_pixels=(double *) GetVirtualMemoryBlob(source_info);
memset(source_pixels,0,fourier_info->width*fourier_info->height*
sizeof(*source_pixels));
i=0L;
image_view=AcquireVirtualCacheView(image,exception);
for (y=0L; y < (ssize_t) fourier_info->height; y++)
{
p=GetCacheViewVirtualPixels(image_view,0L,y,fourier_info->width,1UL,
exception);
if (p == (const Quantum *) NULL)
break;
for (x=0L; x < (ssize_t) fourier_info->width; x++)
{
switch (fourier_info->channel)
{
case RedPixelChannel:
default:
{
source_pixels[i]=QuantumScale*GetPixelRed(image,p);
break;
}
case GreenPixelChannel:
{
source_pixels[i]=QuantumScale*GetPixelGreen(image,p);
break;
}
case BluePixelChannel:
{
source_pixels[i]=QuantumScale*GetPixelBlue(image,p);
break;
}
case BlackPixelChannel:
{
source_pixels[i]=QuantumScale*GetPixelBlack(image,p);
break;
}
case AlphaPixelChannel:
{
source_pixels[i]=QuantumScale*GetPixelAlpha(image,p);
break;
}
}
i++;
p+=GetPixelChannels(image);
}
}
image_view=DestroyCacheView(image_view);
forward_info=AcquireVirtualMemory((size_t) fourier_info->width,
(fourier_info->height/2+1)*sizeof(*forward_pixels));
if (forward_info == (MemoryInfo *) NULL)
{
(void) ThrowMagickException(exception,GetMagickModule(),
ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename);
source_info=(MemoryInfo *) RelinquishVirtualMemory(source_info);
return(MagickFalse);
}
forward_pixels=(fftw_complex *) GetVirtualMemoryBlob(forward_info);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp critical (MagickCore_ForwardFourierTransform)
#endif
fftw_r2c_plan=fftw_plan_dft_r2c_2d(fourier_info->width,fourier_info->height,
source_pixels,forward_pixels,FFTW_ESTIMATE);
fftw_execute_dft_r2c(fftw_r2c_plan,source_pixels,forward_pixels);
fftw_destroy_plan(fftw_r2c_plan);
source_info=(MemoryInfo *) RelinquishVirtualMemory(source_info);
value=GetImageArtifact(image,"fourier:normalize");
if ((value == (const char *) NULL) || (LocaleCompare(value,"forward") == 0))
{
double
gamma;
/*
Normalize fourier transform.
*/
i=0L;
gamma=PerceptibleReciprocal((double) fourier_info->width*
fourier_info->height);
for (y=0L; y < (ssize_t) fourier_info->height; y++)
for (x=0L; x < (ssize_t) fourier_info->center; x++)
{
#if defined(MAGICKCORE_HAVE_COMPLEX_H)
forward_pixels[i]*=gamma;
#else
forward_pixels[i][0]*=gamma;
forward_pixels[i][1]*=gamma;
#endif
i++;
}
}
/*
Generate magnitude and phase (or real and imaginary).
*/
i=0L;
if (fourier_info->modulus != MagickFalse)
for (y=0L; y < (ssize_t) fourier_info->height; y++)
for (x=0L; x < (ssize_t) fourier_info->center; x++)
{
magnitude_pixels[i]=cabs(forward_pixels[i]);
phase_pixels[i]=carg(forward_pixels[i]);
i++;
}
else
for (y=0L; y < (ssize_t) fourier_info->height; y++)
for (x=0L; x < (ssize_t) fourier_info->center; x++)
{
magnitude_pixels[i]=creal(forward_pixels[i]);
phase_pixels[i]=cimag(forward_pixels[i]);
i++;
}
forward_info=(MemoryInfo *) RelinquishVirtualMemory(forward_info);
return(MagickTrue);
}
static MagickBooleanType ForwardFourierTransformChannel(const Image *image,
const PixelChannel channel,const MagickBooleanType modulus,
Image *fourier_image,ExceptionInfo *exception)
{
double
*magnitude_pixels,
*phase_pixels;
FourierInfo
fourier_info;
MagickBooleanType
status;
MemoryInfo
*magnitude_info,
*phase_info;
fourier_info.width=image->columns;
fourier_info.height=image->rows;
if ((image->columns != image->rows) || ((image->columns % 2) != 0) ||
((image->rows % 2) != 0))
{
size_t extent=image->columns < image->rows ? image->rows : image->columns;
fourier_info.width=(extent & 0x01) == 1 ? extent+1UL : extent;
}
fourier_info.height=fourier_info.width;
fourier_info.center=(ssize_t) (fourier_info.width/2L)+1L;
fourier_info.channel=channel;
fourier_info.modulus=modulus;
magnitude_info=AcquireVirtualMemory((size_t) fourier_info.width,
(fourier_info.height/2+1)*sizeof(*magnitude_pixels));
phase_info=AcquireVirtualMemory((size_t) fourier_info.width,
(fourier_info.height/2+1)*sizeof(*phase_pixels));
if ((magnitude_info == (MemoryInfo *) NULL) ||
(phase_info == (MemoryInfo *) NULL))
{
if (phase_info != (MemoryInfo *) NULL)
phase_info=RelinquishVirtualMemory(phase_info);
if (magnitude_info == (MemoryInfo *) NULL)
magnitude_info=RelinquishVirtualMemory(magnitude_info);
(void) ThrowMagickException(exception,GetMagickModule(),
ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename);
return(MagickFalse);
}
magnitude_pixels=(double *) GetVirtualMemoryBlob(magnitude_info);
phase_pixels=(double *) GetVirtualMemoryBlob(phase_info);
status=ForwardFourierTransform(&fourier_info,image,magnitude_pixels,
phase_pixels,exception);
if (status != MagickFalse)
status=ForwardFourier(&fourier_info,fourier_image,magnitude_pixels,
phase_pixels,exception);
phase_info=RelinquishVirtualMemory(phase_info);
magnitude_info=RelinquishVirtualMemory(magnitude_info);
return(status);
}
#endif
MagickExport Image *ForwardFourierTransformImage(const Image *image,
const MagickBooleanType modulus,ExceptionInfo *exception)
{
Image
*fourier_image;
fourier_image=NewImageList();
#if !defined(MAGICKCORE_FFTW_DELEGATE)
(void) modulus;
(void) ThrowMagickException(exception,GetMagickModule(),
MissingDelegateWarning,"DelegateLibrarySupportNotBuiltIn","`%s' (FFTW)",
image->filename);
#else
{
Image
*magnitude_image;
size_t
height,
width;
width=image->columns;
height=image->rows;
if ((image->columns != image->rows) || ((image->columns % 2) != 0) ||
((image->rows % 2) != 0))
{
size_t extent=image->columns < image->rows ? image->rows :
image->columns;
width=(extent & 0x01) == 1 ? extent+1UL : extent;
}
height=width;
magnitude_image=CloneImage(image,width,height,MagickTrue,exception);
if (magnitude_image != (Image *) NULL)
{
Image
*phase_image;
magnitude_image->storage_class=DirectClass;
magnitude_image->depth=32UL;
phase_image=CloneImage(image,width,height,MagickTrue,exception);
if (phase_image == (Image *) NULL)
magnitude_image=DestroyImage(magnitude_image);
else
{
MagickBooleanType
is_gray,
status;
phase_image->storage_class=DirectClass;
phase_image->depth=32UL;
AppendImageToList(&fourier_image,magnitude_image);
AppendImageToList(&fourier_image,phase_image);
status=MagickTrue;
is_gray=IsImageGray(image);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel sections
#endif
{
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp section
#endif
{
MagickBooleanType
thread_status;
if (is_gray != MagickFalse)
thread_status=ForwardFourierTransformChannel(image,
GrayPixelChannel,modulus,fourier_image,exception);
else
thread_status=ForwardFourierTransformChannel(image,
RedPixelChannel,modulus,fourier_image,exception);
if (thread_status == MagickFalse)
status=thread_status;
}
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp section
#endif
{
MagickBooleanType
thread_status;
thread_status=MagickTrue;
if (is_gray == MagickFalse)
thread_status=ForwardFourierTransformChannel(image,
GreenPixelChannel,modulus,fourier_image,exception);
if (thread_status == MagickFalse)
status=thread_status;
}
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp section
#endif
{
MagickBooleanType
thread_status;
thread_status=MagickTrue;
if (is_gray == MagickFalse)
thread_status=ForwardFourierTransformChannel(image,
BluePixelChannel,modulus,fourier_image,exception);
if (thread_status == MagickFalse)
status=thread_status;
}
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp section
#endif
{
MagickBooleanType
thread_status;
thread_status=MagickTrue;
if (image->colorspace == CMYKColorspace)
thread_status=ForwardFourierTransformChannel(image,
BlackPixelChannel,modulus,fourier_image,exception);
if (thread_status == MagickFalse)
status=thread_status;
}
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp section
#endif
{
MagickBooleanType
thread_status;
thread_status=MagickTrue;
if (image->alpha_trait != UndefinedPixelTrait)
thread_status=ForwardFourierTransformChannel(image,
AlphaPixelChannel,modulus,fourier_image,exception);
if (thread_status == MagickFalse)
status=thread_status;
}
}
if (status == MagickFalse)
fourier_image=DestroyImageList(fourier_image);
fftw_cleanup();
}
}
}
#endif
return(fourier_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% I n v e r s e F o u r i e r T r a n s f o r m I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% InverseFourierTransformImage() implements the inverse discrete Fourier
% transform (DFT) of the image either as a magnitude / phase or real /
% imaginary image pair.
%
% The format of the InverseFourierTransformImage method is:
%
% Image *InverseFourierTransformImage(const Image *magnitude_image,
% const Image *phase_image,const MagickBooleanType modulus,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o magnitude_image: the magnitude or real image.
%
% o phase_image: the phase or imaginary image.
%
% o modulus: if true, return transform as a magnitude / phase pair
% otherwise a real / imaginary image pair.
%
% o exception: return any errors or warnings in this structure.
%
*/
#if defined(MAGICKCORE_FFTW_DELEGATE)
static MagickBooleanType InverseQuadrantSwap(const size_t width,
const size_t height,const double *source,double *destination)
{
register ssize_t
x;
ssize_t
center,
y;
/*
Swap quadrants.
*/
center=(ssize_t) (width/2L)+1L;
for (y=1L; y < (ssize_t) height; y++)
for (x=0L; x < (ssize_t) (width/2L+1L); x++)
destination[(height-y)*center-x+width/2L]=source[y*width+x];
for (y=0L; y < (ssize_t) height; y++)
destination[y*center]=source[y*width+width/2L];
for (x=0L; x < center; x++)
destination[x]=source[center-x-1L];
return(RollFourier(center,height,0L,(ssize_t) height/-2L,destination));
}
static MagickBooleanType InverseFourier(FourierInfo *fourier_info,
const Image *magnitude_image,const Image *phase_image,
fftw_complex *fourier_pixels,ExceptionInfo *exception)
{
CacheView
*magnitude_view,
*phase_view;
double
*inverse_pixels,
*magnitude_pixels,
*phase_pixels;
MagickBooleanType
status;
MemoryInfo
*inverse_info,
*magnitude_info,
*phase_info;
register const Quantum
*p;
register ssize_t
i,
x;
ssize_t
y;
/*
Inverse fourier - read image and break down into a double array.
*/
magnitude_info=AcquireVirtualMemory((size_t) fourier_info->width,
fourier_info->height*sizeof(*magnitude_pixels));
phase_info=AcquireVirtualMemory((size_t) fourier_info->width,
fourier_info->height*sizeof(*phase_pixels));
inverse_info=AcquireVirtualMemory((size_t) fourier_info->width,
(fourier_info->height/2+1)*sizeof(*inverse_pixels));
if ((magnitude_info == (MemoryInfo *) NULL) ||
(phase_info == (MemoryInfo *) NULL) ||
(inverse_info == (MemoryInfo *) NULL))
{
if (magnitude_info != (MemoryInfo *) NULL)
magnitude_info=RelinquishVirtualMemory(magnitude_info);
if (phase_info != (MemoryInfo *) NULL)
phase_info=RelinquishVirtualMemory(phase_info);
if (inverse_info != (MemoryInfo *) NULL)
inverse_info=RelinquishVirtualMemory(inverse_info);
(void) ThrowMagickException(exception,GetMagickModule(),
ResourceLimitError,"MemoryAllocationFailed","`%s'",
magnitude_image->filename);
return(MagickFalse);
}
magnitude_pixels=(double *) GetVirtualMemoryBlob(magnitude_info);
phase_pixels=(double *) GetVirtualMemoryBlob(phase_info);
inverse_pixels=(double *) GetVirtualMemoryBlob(inverse_info);
i=0L;
magnitude_view=AcquireVirtualCacheView(magnitude_image,exception);
for (y=0L; y < (ssize_t) fourier_info->height; y++)
{
p=GetCacheViewVirtualPixels(magnitude_view,0L,y,fourier_info->width,1UL,
exception);
if (p == (const Quantum *) NULL)
break;
for (x=0L; x < (ssize_t) fourier_info->width; x++)
{
switch (fourier_info->channel)
{
case RedPixelChannel:
default:
{
magnitude_pixels[i]=QuantumScale*GetPixelRed(magnitude_image,p);
break;
}
case GreenPixelChannel:
{
magnitude_pixels[i]=QuantumScale*GetPixelGreen(magnitude_image,p);
break;
}
case BluePixelChannel:
{
magnitude_pixels[i]=QuantumScale*GetPixelBlue(magnitude_image,p);
break;
}
case BlackPixelChannel:
{
magnitude_pixels[i]=QuantumScale*GetPixelBlack(magnitude_image,p);
break;
}
case AlphaPixelChannel:
{
magnitude_pixels[i]=QuantumScale*GetPixelAlpha(magnitude_image,p);
break;
}
}
i++;
p+=GetPixelChannels(magnitude_image);
}
}
magnitude_view=DestroyCacheView(magnitude_view);
status=InverseQuadrantSwap(fourier_info->width,fourier_info->height,
magnitude_pixels,inverse_pixels);
(void) memcpy(magnitude_pixels,inverse_pixels,fourier_info->height*
fourier_info->center*sizeof(*magnitude_pixels));
i=0L;
phase_view=AcquireVirtualCacheView(phase_image,exception);
for (y=0L; y < (ssize_t) fourier_info->height; y++)
{
p=GetCacheViewVirtualPixels(phase_view,0,y,fourier_info->width,1,
exception);
if (p == (const Quantum *) NULL)
break;
for (x=0L; x < (ssize_t) fourier_info->width; x++)
{
switch (fourier_info->channel)
{
case RedPixelChannel:
default:
{
phase_pixels[i]=QuantumScale*GetPixelRed(phase_image,p);
break;
}
case GreenPixelChannel:
{
phase_pixels[i]=QuantumScale*GetPixelGreen(phase_image,p);
break;
}
case BluePixelChannel:
{
phase_pixels[i]=QuantumScale*GetPixelBlue(phase_image,p);
break;
}
case BlackPixelChannel:
{
phase_pixels[i]=QuantumScale*GetPixelBlack(phase_image,p);
break;
}
case AlphaPixelChannel:
{
phase_pixels[i]=QuantumScale*GetPixelAlpha(phase_image,p);
break;
}
}
i++;
p+=GetPixelChannels(phase_image);
}
}
if (fourier_info->modulus != MagickFalse)
{
i=0L;
for (y=0L; y < (ssize_t) fourier_info->height; y++)
for (x=0L; x < (ssize_t) fourier_info->width; x++)
{
phase_pixels[i]-=0.5;
phase_pixels[i]*=(2.0*MagickPI);
i++;
}
}
phase_view=DestroyCacheView(phase_view);
CorrectPhaseLHS(fourier_info->width,fourier_info->height,phase_pixels);
if (status != MagickFalse)
status=InverseQuadrantSwap(fourier_info->width,fourier_info->height,
phase_pixels,inverse_pixels);
(void) memcpy(phase_pixels,inverse_pixels,fourier_info->height*
fourier_info->center*sizeof(*phase_pixels));
inverse_info=RelinquishVirtualMemory(inverse_info);
/*
Merge two sets.
*/
i=0L;
if (fourier_info->modulus != MagickFalse)
for (y=0L; y < (ssize_t) fourier_info->height; y++)
for (x=0L; x < (ssize_t) fourier_info->center; x++)
{
#if defined(MAGICKCORE_HAVE_COMPLEX_H)
fourier_pixels[i]=magnitude_pixels[i]*cos(phase_pixels[i])+I*
magnitude_pixels[i]*sin(phase_pixels[i]);
#else
fourier_pixels[i][0]=magnitude_pixels[i]*cos(phase_pixels[i]);
fourier_pixels[i][1]=magnitude_pixels[i]*sin(phase_pixels[i]);
#endif
i++;
}
else
for (y=0L; y < (ssize_t) fourier_info->height; y++)
for (x=0L; x < (ssize_t) fourier_info->center; x++)
{
#if defined(MAGICKCORE_HAVE_COMPLEX_H)
fourier_pixels[i]=magnitude_pixels[i]+I*phase_pixels[i];
#else
fourier_pixels[i][0]=magnitude_pixels[i];
fourier_pixels[i][1]=phase_pixels[i];
#endif
i++;
}
magnitude_info=RelinquishVirtualMemory(magnitude_info);
phase_info=RelinquishVirtualMemory(phase_info);
return(status);
}
static MagickBooleanType InverseFourierTransform(FourierInfo *fourier_info,
fftw_complex *fourier_pixels,Image *image,ExceptionInfo *exception)
{
CacheView
*image_view;
const char
*value;
double
*source_pixels;
fftw_plan
fftw_c2r_plan;
MemoryInfo
*source_info;
register Quantum
*q;
register ssize_t
i,
x;
ssize_t
y;
source_info=AcquireVirtualMemory((size_t) fourier_info->width,
fourier_info->height*sizeof(*source_pixels));
if (source_info == (MemoryInfo *) NULL)
{
(void) ThrowMagickException(exception,GetMagickModule(),
ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename);
return(MagickFalse);
}
source_pixels=(double *) GetVirtualMemoryBlob(source_info);
value=GetImageArtifact(image,"fourier:normalize");
if (LocaleCompare(value,"inverse") == 0)
{
double
gamma;
/*
Normalize inverse transform.
*/
i=0L;
gamma=PerceptibleReciprocal((double) fourier_info->width*
fourier_info->height);
for (y=0L; y < (ssize_t) fourier_info->height; y++)
for (x=0L; x < (ssize_t) fourier_info->center; x++)
{
#if defined(MAGICKCORE_HAVE_COMPLEX_H)
fourier_pixels[i]*=gamma;
#else
fourier_pixels[i][0]*=gamma;
fourier_pixels[i][1]*=gamma;
#endif
i++;
}
}
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp critical (MagickCore_InverseFourierTransform)
#endif
fftw_c2r_plan=fftw_plan_dft_c2r_2d(fourier_info->width,fourier_info->height,
fourier_pixels,source_pixels,FFTW_ESTIMATE);
fftw_execute_dft_c2r(fftw_c2r_plan,fourier_pixels,source_pixels);
fftw_destroy_plan(fftw_c2r_plan);
i=0L;
image_view=AcquireAuthenticCacheView(image,exception);
for (y=0L; y < (ssize_t) fourier_info->height; y++)
{
if (y >= (ssize_t) image->rows)
break;
q=GetCacheViewAuthenticPixels(image_view,0L,y,fourier_info->width >
image->columns ? image->columns : fourier_info->width,1UL,exception);
if (q == (Quantum *) NULL)
break;
for (x=0L; x < (ssize_t) fourier_info->width; x++)
{
if (x < (ssize_t) image->columns)
switch (fourier_info->channel)
{
case RedPixelChannel:
default:
{
SetPixelRed(image,ClampToQuantum(QuantumRange*source_pixels[i]),q);
break;
}
case GreenPixelChannel:
{
SetPixelGreen(image,ClampToQuantum(QuantumRange*source_pixels[i]),
q);
break;
}
case BluePixelChannel:
{
SetPixelBlue(image,ClampToQuantum(QuantumRange*source_pixels[i]),
q);
break;
}
case BlackPixelChannel:
{
SetPixelBlack(image,ClampToQuantum(QuantumRange*source_pixels[i]),
q);
break;
}
case AlphaPixelChannel:
{
SetPixelAlpha(image,ClampToQuantum(QuantumRange*source_pixels[i]),
q);
break;
}
}
i++;
q+=GetPixelChannels(image);
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
break;
}
image_view=DestroyCacheView(image_view);
source_info=RelinquishVirtualMemory(source_info);
return(MagickTrue);
}
static MagickBooleanType InverseFourierTransformChannel(
const Image *magnitude_image,const Image *phase_image,
const PixelChannel channel,const MagickBooleanType modulus,
Image *fourier_image,ExceptionInfo *exception)
{
fftw_complex
*inverse_pixels;
FourierInfo
fourier_info;
MagickBooleanType
status;
MemoryInfo
*inverse_info;
fourier_info.width=magnitude_image->columns;
fourier_info.height=magnitude_image->rows;
if ((magnitude_image->columns != magnitude_image->rows) ||
((magnitude_image->columns % 2) != 0) ||
((magnitude_image->rows % 2) != 0))
{
size_t extent=magnitude_image->columns < magnitude_image->rows ?
magnitude_image->rows : magnitude_image->columns;
fourier_info.width=(extent & 0x01) == 1 ? extent+1UL : extent;
}
fourier_info.height=fourier_info.width;
fourier_info.center=(ssize_t) (fourier_info.width/2L)+1L;
fourier_info.channel=channel;
fourier_info.modulus=modulus;
inverse_info=AcquireVirtualMemory((size_t) fourier_info.width,
(fourier_info.height/2+1)*sizeof(*inverse_pixels));
if (inverse_info == (MemoryInfo *) NULL)
{
(void) ThrowMagickException(exception,GetMagickModule(),
ResourceLimitError,"MemoryAllocationFailed","`%s'",
magnitude_image->filename);
return(MagickFalse);
}
inverse_pixels=(fftw_complex *) GetVirtualMemoryBlob(inverse_info);
status=InverseFourier(&fourier_info,magnitude_image,phase_image,
inverse_pixels,exception);
if (status != MagickFalse)
status=InverseFourierTransform(&fourier_info,inverse_pixels,fourier_image,
exception);
inverse_info=RelinquishVirtualMemory(inverse_info);
return(status);
}
#endif
MagickExport Image *InverseFourierTransformImage(const Image *magnitude_image,
const Image *phase_image,const MagickBooleanType modulus,
ExceptionInfo *exception)
{
Image
*fourier_image;
assert(magnitude_image != (Image *) NULL);
assert(magnitude_image->signature == MagickCoreSignature);
if (magnitude_image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
magnitude_image->filename);
if (phase_image == (Image *) NULL)
{
(void) ThrowMagickException(exception,GetMagickModule(),ImageError,
"ImageSequenceRequired","`%s'",magnitude_image->filename);
return((Image *) NULL);
}
#if !defined(MAGICKCORE_FFTW_DELEGATE)
fourier_image=(Image *) NULL;
(void) modulus;
(void) ThrowMagickException(exception,GetMagickModule(),
MissingDelegateWarning,"DelegateLibrarySupportNotBuiltIn","`%s' (FFTW)",
magnitude_image->filename);
#else
{
fourier_image=CloneImage(magnitude_image,magnitude_image->columns,
magnitude_image->rows,MagickTrue,exception);
if (fourier_image != (Image *) NULL)
{
MagickBooleanType
is_gray,
status;
status=MagickTrue;
is_gray=IsImageGray(magnitude_image);
if (is_gray != MagickFalse)
is_gray=IsImageGray(phase_image);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel sections
#endif
{
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp section
#endif
{
MagickBooleanType
thread_status;
if (is_gray != MagickFalse)
thread_status=InverseFourierTransformChannel(magnitude_image,
phase_image,GrayPixelChannel,modulus,fourier_image,exception);
else
thread_status=InverseFourierTransformChannel(magnitude_image,
phase_image,RedPixelChannel,modulus,fourier_image,exception);
if (thread_status == MagickFalse)
status=thread_status;
}
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp section
#endif
{
MagickBooleanType
thread_status;
thread_status=MagickTrue;
if (is_gray == MagickFalse)
thread_status=InverseFourierTransformChannel(magnitude_image,
phase_image,GreenPixelChannel,modulus,fourier_image,exception);
if (thread_status == MagickFalse)
status=thread_status;
}
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp section
#endif
{
MagickBooleanType
thread_status;
thread_status=MagickTrue;
if (is_gray == MagickFalse)
thread_status=InverseFourierTransformChannel(magnitude_image,
phase_image,BluePixelChannel,modulus,fourier_image,exception);
if (thread_status == MagickFalse)
status=thread_status;
}
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp section
#endif
{
MagickBooleanType
thread_status;
thread_status=MagickTrue;
if (magnitude_image->colorspace == CMYKColorspace)
thread_status=InverseFourierTransformChannel(magnitude_image,
phase_image,BlackPixelChannel,modulus,fourier_image,exception);
if (thread_status == MagickFalse)
status=thread_status;
}
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp section
#endif
{
MagickBooleanType
thread_status;
thread_status=MagickTrue;
if (magnitude_image->alpha_trait != UndefinedPixelTrait)
thread_status=InverseFourierTransformChannel(magnitude_image,
phase_image,AlphaPixelChannel,modulus,fourier_image,exception);
if (thread_status == MagickFalse)
status=thread_status;
}
}
if (status == MagickFalse)
fourier_image=DestroyImage(fourier_image);
}
fftw_cleanup();
}
#endif
return(fourier_image);
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_949_1 |
crossvul-cpp_data_bad_2644_6 | /*
* Copyright (c) 1992, 1993, 1994, 1995, 1996
* The Regents of the University of California. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that: (1) source code distributions
* retain the above copyright notice and this paragraph in its entirety, (2)
* distributions including binary code include the above copyright notice and
* this paragraph in its entirety in the documentation or other materials
* provided with the distribution, and (3) all advertising materials mentioning
* features or use of this software display the following acknowledgement:
* ``This product includes software developed by the University of California,
* Lawrence Berkeley Laboratory and its contributors.'' Neither the name of
* the University nor the names of its contributors may be used to endorse
* or promote products derived from this software without specific prior
* written permission.
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*
* Original code by Matt Thomas, Digital Equipment Corporation
*
* Extensively modified by Hannes Gredler (hannes@gredler.at) for more
* complete IS-IS & CLNP support.
*/
/* \summary: ISO CLNS, ESIS, and ISIS printer */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <netdissect-stdinc.h>
#include <string.h>
#include "netdissect.h"
#include "addrtoname.h"
#include "ether.h"
#include "nlpid.h"
#include "extract.h"
#include "gmpls.h"
#include "oui.h"
#include "signature.h"
static const char tstr[] = " [|isis]";
/*
* IS-IS is defined in ISO 10589. Look there for protocol definitions.
*/
#define SYSTEM_ID_LEN ETHER_ADDR_LEN
#define NODE_ID_LEN SYSTEM_ID_LEN+1
#define LSP_ID_LEN SYSTEM_ID_LEN+2
#define ISIS_VERSION 1
#define ESIS_VERSION 1
#define CLNP_VERSION 1
#define ISIS_PDU_TYPE_MASK 0x1F
#define ESIS_PDU_TYPE_MASK 0x1F
#define CLNP_PDU_TYPE_MASK 0x1F
#define CLNP_FLAG_MASK 0xE0
#define ISIS_LAN_PRIORITY_MASK 0x7F
#define ISIS_PDU_L1_LAN_IIH 15
#define ISIS_PDU_L2_LAN_IIH 16
#define ISIS_PDU_PTP_IIH 17
#define ISIS_PDU_L1_LSP 18
#define ISIS_PDU_L2_LSP 20
#define ISIS_PDU_L1_CSNP 24
#define ISIS_PDU_L2_CSNP 25
#define ISIS_PDU_L1_PSNP 26
#define ISIS_PDU_L2_PSNP 27
static const struct tok isis_pdu_values[] = {
{ ISIS_PDU_L1_LAN_IIH, "L1 Lan IIH"},
{ ISIS_PDU_L2_LAN_IIH, "L2 Lan IIH"},
{ ISIS_PDU_PTP_IIH, "p2p IIH"},
{ ISIS_PDU_L1_LSP, "L1 LSP"},
{ ISIS_PDU_L2_LSP, "L2 LSP"},
{ ISIS_PDU_L1_CSNP, "L1 CSNP"},
{ ISIS_PDU_L2_CSNP, "L2 CSNP"},
{ ISIS_PDU_L1_PSNP, "L1 PSNP"},
{ ISIS_PDU_L2_PSNP, "L2 PSNP"},
{ 0, NULL}
};
/*
* A TLV is a tuple of a type, length and a value and is normally used for
* encoding information in all sorts of places. This is an enumeration of
* the well known types.
*
* list taken from rfc3359 plus some memory from veterans ;-)
*/
#define ISIS_TLV_AREA_ADDR 1 /* iso10589 */
#define ISIS_TLV_IS_REACH 2 /* iso10589 */
#define ISIS_TLV_ESNEIGH 3 /* iso10589 */
#define ISIS_TLV_PART_DIS 4 /* iso10589 */
#define ISIS_TLV_PREFIX_NEIGH 5 /* iso10589 */
#define ISIS_TLV_ISNEIGH 6 /* iso10589 */
#define ISIS_TLV_ISNEIGH_VARLEN 7 /* iso10589 */
#define ISIS_TLV_PADDING 8 /* iso10589 */
#define ISIS_TLV_LSP 9 /* iso10589 */
#define ISIS_TLV_AUTH 10 /* iso10589, rfc3567 */
#define ISIS_TLV_CHECKSUM 12 /* rfc3358 */
#define ISIS_TLV_CHECKSUM_MINLEN 2
#define ISIS_TLV_POI 13 /* rfc6232 */
#define ISIS_TLV_LSP_BUFFERSIZE 14 /* iso10589 rev2 */
#define ISIS_TLV_LSP_BUFFERSIZE_MINLEN 2
#define ISIS_TLV_EXT_IS_REACH 22 /* draft-ietf-isis-traffic-05 */
#define ISIS_TLV_IS_ALIAS_ID 24 /* draft-ietf-isis-ext-lsp-frags-02 */
#define ISIS_TLV_DECNET_PHASE4 42
#define ISIS_TLV_LUCENT_PRIVATE 66
#define ISIS_TLV_INT_IP_REACH 128 /* rfc1195, rfc2966 */
#define ISIS_TLV_PROTOCOLS 129 /* rfc1195 */
#define ISIS_TLV_EXT_IP_REACH 130 /* rfc1195, rfc2966 */
#define ISIS_TLV_IDRP_INFO 131 /* rfc1195 */
#define ISIS_TLV_IDRP_INFO_MINLEN 1
#define ISIS_TLV_IPADDR 132 /* rfc1195 */
#define ISIS_TLV_IPAUTH 133 /* rfc1195 */
#define ISIS_TLV_TE_ROUTER_ID 134 /* draft-ietf-isis-traffic-05 */
#define ISIS_TLV_EXTD_IP_REACH 135 /* draft-ietf-isis-traffic-05 */
#define ISIS_TLV_HOSTNAME 137 /* rfc2763 */
#define ISIS_TLV_SHARED_RISK_GROUP 138 /* draft-ietf-isis-gmpls-extensions */
#define ISIS_TLV_MT_PORT_CAP 143 /* rfc6165 */
#define ISIS_TLV_MT_CAPABILITY 144 /* rfc6329 */
#define ISIS_TLV_NORTEL_PRIVATE1 176
#define ISIS_TLV_NORTEL_PRIVATE2 177
#define ISIS_TLV_RESTART_SIGNALING 211 /* rfc3847 */
#define ISIS_TLV_RESTART_SIGNALING_FLAGLEN 1
#define ISIS_TLV_RESTART_SIGNALING_HOLDTIMELEN 2
#define ISIS_TLV_MT_IS_REACH 222 /* draft-ietf-isis-wg-multi-topology-05 */
#define ISIS_TLV_MT_SUPPORTED 229 /* draft-ietf-isis-wg-multi-topology-05 */
#define ISIS_TLV_MT_SUPPORTED_MINLEN 2
#define ISIS_TLV_IP6ADDR 232 /* draft-ietf-isis-ipv6-02 */
#define ISIS_TLV_MT_IP_REACH 235 /* draft-ietf-isis-wg-multi-topology-05 */
#define ISIS_TLV_IP6_REACH 236 /* draft-ietf-isis-ipv6-02 */
#define ISIS_TLV_MT_IP6_REACH 237 /* draft-ietf-isis-wg-multi-topology-05 */
#define ISIS_TLV_PTP_ADJ 240 /* rfc3373 */
#define ISIS_TLV_IIH_SEQNR 241 /* draft-shen-isis-iih-sequence-00 */
#define ISIS_TLV_IIH_SEQNR_MINLEN 4
#define ISIS_TLV_VENDOR_PRIVATE 250 /* draft-ietf-isis-experimental-tlv-01 */
#define ISIS_TLV_VENDOR_PRIVATE_MINLEN 3
static const struct tok isis_tlv_values[] = {
{ ISIS_TLV_AREA_ADDR, "Area address(es)"},
{ ISIS_TLV_IS_REACH, "IS Reachability"},
{ ISIS_TLV_ESNEIGH, "ES Neighbor(s)"},
{ ISIS_TLV_PART_DIS, "Partition DIS"},
{ ISIS_TLV_PREFIX_NEIGH, "Prefix Neighbors"},
{ ISIS_TLV_ISNEIGH, "IS Neighbor(s)"},
{ ISIS_TLV_ISNEIGH_VARLEN, "IS Neighbor(s) (variable length)"},
{ ISIS_TLV_PADDING, "Padding"},
{ ISIS_TLV_LSP, "LSP entries"},
{ ISIS_TLV_AUTH, "Authentication"},
{ ISIS_TLV_CHECKSUM, "Checksum"},
{ ISIS_TLV_POI, "Purge Originator Identifier"},
{ ISIS_TLV_LSP_BUFFERSIZE, "LSP Buffersize"},
{ ISIS_TLV_EXT_IS_REACH, "Extended IS Reachability"},
{ ISIS_TLV_IS_ALIAS_ID, "IS Alias ID"},
{ ISIS_TLV_DECNET_PHASE4, "DECnet Phase IV"},
{ ISIS_TLV_LUCENT_PRIVATE, "Lucent Proprietary"},
{ ISIS_TLV_INT_IP_REACH, "IPv4 Internal Reachability"},
{ ISIS_TLV_PROTOCOLS, "Protocols supported"},
{ ISIS_TLV_EXT_IP_REACH, "IPv4 External Reachability"},
{ ISIS_TLV_IDRP_INFO, "Inter-Domain Information Type"},
{ ISIS_TLV_IPADDR, "IPv4 Interface address(es)"},
{ ISIS_TLV_IPAUTH, "IPv4 authentication (deprecated)"},
{ ISIS_TLV_TE_ROUTER_ID, "Traffic Engineering Router ID"},
{ ISIS_TLV_EXTD_IP_REACH, "Extended IPv4 Reachability"},
{ ISIS_TLV_SHARED_RISK_GROUP, "Shared Risk Link Group"},
{ ISIS_TLV_MT_PORT_CAP, "Multi-Topology-Aware Port Capability"},
{ ISIS_TLV_MT_CAPABILITY, "Multi-Topology Capability"},
{ ISIS_TLV_NORTEL_PRIVATE1, "Nortel Proprietary"},
{ ISIS_TLV_NORTEL_PRIVATE2, "Nortel Proprietary"},
{ ISIS_TLV_HOSTNAME, "Hostname"},
{ ISIS_TLV_RESTART_SIGNALING, "Restart Signaling"},
{ ISIS_TLV_MT_IS_REACH, "Multi Topology IS Reachability"},
{ ISIS_TLV_MT_SUPPORTED, "Multi Topology"},
{ ISIS_TLV_IP6ADDR, "IPv6 Interface address(es)"},
{ ISIS_TLV_MT_IP_REACH, "Multi-Topology IPv4 Reachability"},
{ ISIS_TLV_IP6_REACH, "IPv6 reachability"},
{ ISIS_TLV_MT_IP6_REACH, "Multi-Topology IP6 Reachability"},
{ ISIS_TLV_PTP_ADJ, "Point-to-point Adjacency State"},
{ ISIS_TLV_IIH_SEQNR, "Hello PDU Sequence Number"},
{ ISIS_TLV_VENDOR_PRIVATE, "Vendor Private"},
{ 0, NULL }
};
#define ESIS_OPTION_PROTOCOLS 129
#define ESIS_OPTION_QOS_MAINTENANCE 195 /* iso9542 */
#define ESIS_OPTION_SECURITY 197 /* iso9542 */
#define ESIS_OPTION_ES_CONF_TIME 198 /* iso9542 */
#define ESIS_OPTION_PRIORITY 205 /* iso9542 */
#define ESIS_OPTION_ADDRESS_MASK 225 /* iso9542 */
#define ESIS_OPTION_SNPA_MASK 226 /* iso9542 */
static const struct tok esis_option_values[] = {
{ ESIS_OPTION_PROTOCOLS, "Protocols supported"},
{ ESIS_OPTION_QOS_MAINTENANCE, "QoS Maintenance" },
{ ESIS_OPTION_SECURITY, "Security" },
{ ESIS_OPTION_ES_CONF_TIME, "ES Configuration Time" },
{ ESIS_OPTION_PRIORITY, "Priority" },
{ ESIS_OPTION_ADDRESS_MASK, "Addressk Mask" },
{ ESIS_OPTION_SNPA_MASK, "SNPA Mask" },
{ 0, NULL }
};
#define CLNP_OPTION_DISCARD_REASON 193
#define CLNP_OPTION_QOS_MAINTENANCE 195 /* iso8473 */
#define CLNP_OPTION_SECURITY 197 /* iso8473 */
#define CLNP_OPTION_SOURCE_ROUTING 200 /* iso8473 */
#define CLNP_OPTION_ROUTE_RECORDING 203 /* iso8473 */
#define CLNP_OPTION_PADDING 204 /* iso8473 */
#define CLNP_OPTION_PRIORITY 205 /* iso8473 */
static const struct tok clnp_option_values[] = {
{ CLNP_OPTION_DISCARD_REASON, "Discard Reason"},
{ CLNP_OPTION_PRIORITY, "Priority"},
{ CLNP_OPTION_QOS_MAINTENANCE, "QoS Maintenance"},
{ CLNP_OPTION_SECURITY, "Security"},
{ CLNP_OPTION_SOURCE_ROUTING, "Source Routing"},
{ CLNP_OPTION_ROUTE_RECORDING, "Route Recording"},
{ CLNP_OPTION_PADDING, "Padding"},
{ 0, NULL }
};
static const struct tok clnp_option_rfd_class_values[] = {
{ 0x0, "General"},
{ 0x8, "Address"},
{ 0x9, "Source Routeing"},
{ 0xa, "Lifetime"},
{ 0xb, "PDU Discarded"},
{ 0xc, "Reassembly"},
{ 0, NULL }
};
static const struct tok clnp_option_rfd_general_values[] = {
{ 0x0, "Reason not specified"},
{ 0x1, "Protocol procedure error"},
{ 0x2, "Incorrect checksum"},
{ 0x3, "PDU discarded due to congestion"},
{ 0x4, "Header syntax error (cannot be parsed)"},
{ 0x5, "Segmentation needed but not permitted"},
{ 0x6, "Incomplete PDU received"},
{ 0x7, "Duplicate option"},
{ 0, NULL }
};
static const struct tok clnp_option_rfd_address_values[] = {
{ 0x0, "Destination address unreachable"},
{ 0x1, "Destination address unknown"},
{ 0, NULL }
};
static const struct tok clnp_option_rfd_source_routeing_values[] = {
{ 0x0, "Unspecified source routeing error"},
{ 0x1, "Syntax error in source routeing field"},
{ 0x2, "Unknown address in source routeing field"},
{ 0x3, "Path not acceptable"},
{ 0, NULL }
};
static const struct tok clnp_option_rfd_lifetime_values[] = {
{ 0x0, "Lifetime expired while data unit in transit"},
{ 0x1, "Lifetime expired during reassembly"},
{ 0, NULL }
};
static const struct tok clnp_option_rfd_pdu_discard_values[] = {
{ 0x0, "Unsupported option not specified"},
{ 0x1, "Unsupported protocol version"},
{ 0x2, "Unsupported security option"},
{ 0x3, "Unsupported source routeing option"},
{ 0x4, "Unsupported recording of route option"},
{ 0, NULL }
};
static const struct tok clnp_option_rfd_reassembly_values[] = {
{ 0x0, "Reassembly interference"},
{ 0, NULL }
};
/* array of 16 error-classes */
static const struct tok *clnp_option_rfd_error_class[] = {
clnp_option_rfd_general_values,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
clnp_option_rfd_address_values,
clnp_option_rfd_source_routeing_values,
clnp_option_rfd_lifetime_values,
clnp_option_rfd_pdu_discard_values,
clnp_option_rfd_reassembly_values,
NULL,
NULL,
NULL
};
#define CLNP_OPTION_OPTION_QOS_MASK 0x3f
#define CLNP_OPTION_SCOPE_MASK 0xc0
#define CLNP_OPTION_SCOPE_SA_SPEC 0x40
#define CLNP_OPTION_SCOPE_DA_SPEC 0x80
#define CLNP_OPTION_SCOPE_GLOBAL 0xc0
static const struct tok clnp_option_scope_values[] = {
{ CLNP_OPTION_SCOPE_SA_SPEC, "Source Address Specific"},
{ CLNP_OPTION_SCOPE_DA_SPEC, "Destination Address Specific"},
{ CLNP_OPTION_SCOPE_GLOBAL, "Globally unique"},
{ 0, NULL }
};
static const struct tok clnp_option_sr_rr_values[] = {
{ 0x0, "partial"},
{ 0x1, "complete"},
{ 0, NULL }
};
static const struct tok clnp_option_sr_rr_string_values[] = {
{ CLNP_OPTION_SOURCE_ROUTING, "source routing"},
{ CLNP_OPTION_ROUTE_RECORDING, "recording of route in progress"},
{ 0, NULL }
};
static const struct tok clnp_option_qos_global_values[] = {
{ 0x20, "reserved"},
{ 0x10, "sequencing vs. delay"},
{ 0x08, "congested"},
{ 0x04, "delay vs. cost"},
{ 0x02, "error vs. delay"},
{ 0x01, "error vs. cost"},
{ 0, NULL }
};
#define ISIS_SUBTLV_EXT_IS_REACH_ADMIN_GROUP 3 /* draft-ietf-isis-traffic-05 */
#define ISIS_SUBTLV_EXT_IS_REACH_LINK_LOCAL_REMOTE_ID 4 /* rfc4205 */
#define ISIS_SUBTLV_EXT_IS_REACH_LINK_REMOTE_ID 5 /* draft-ietf-isis-traffic-05 */
#define ISIS_SUBTLV_EXT_IS_REACH_IPV4_INTF_ADDR 6 /* draft-ietf-isis-traffic-05 */
#define ISIS_SUBTLV_EXT_IS_REACH_IPV4_NEIGHBOR_ADDR 8 /* draft-ietf-isis-traffic-05 */
#define ISIS_SUBTLV_EXT_IS_REACH_MAX_LINK_BW 9 /* draft-ietf-isis-traffic-05 */
#define ISIS_SUBTLV_EXT_IS_REACH_RESERVABLE_BW 10 /* draft-ietf-isis-traffic-05 */
#define ISIS_SUBTLV_EXT_IS_REACH_UNRESERVED_BW 11 /* rfc4124 */
#define ISIS_SUBTLV_EXT_IS_REACH_BW_CONSTRAINTS_OLD 12 /* draft-ietf-tewg-diff-te-proto-06 */
#define ISIS_SUBTLV_EXT_IS_REACH_TE_METRIC 18 /* draft-ietf-isis-traffic-05 */
#define ISIS_SUBTLV_EXT_IS_REACH_LINK_ATTRIBUTE 19 /* draft-ietf-isis-link-attr-01 */
#define ISIS_SUBTLV_EXT_IS_REACH_LINK_PROTECTION_TYPE 20 /* rfc4205 */
#define ISIS_SUBTLV_EXT_IS_REACH_INTF_SW_CAP_DESCR 21 /* rfc4205 */
#define ISIS_SUBTLV_EXT_IS_REACH_BW_CONSTRAINTS 22 /* rfc4124 */
#define ISIS_SUBTLV_SPB_METRIC 29 /* rfc6329 */
static const struct tok isis_ext_is_reach_subtlv_values[] = {
{ ISIS_SUBTLV_EXT_IS_REACH_ADMIN_GROUP, "Administrative groups" },
{ ISIS_SUBTLV_EXT_IS_REACH_LINK_LOCAL_REMOTE_ID, "Link Local/Remote Identifier" },
{ ISIS_SUBTLV_EXT_IS_REACH_LINK_REMOTE_ID, "Link Remote Identifier" },
{ ISIS_SUBTLV_EXT_IS_REACH_IPV4_INTF_ADDR, "IPv4 interface address" },
{ ISIS_SUBTLV_EXT_IS_REACH_IPV4_NEIGHBOR_ADDR, "IPv4 neighbor address" },
{ ISIS_SUBTLV_EXT_IS_REACH_MAX_LINK_BW, "Maximum link bandwidth" },
{ ISIS_SUBTLV_EXT_IS_REACH_RESERVABLE_BW, "Reservable link bandwidth" },
{ ISIS_SUBTLV_EXT_IS_REACH_UNRESERVED_BW, "Unreserved bandwidth" },
{ ISIS_SUBTLV_EXT_IS_REACH_TE_METRIC, "Traffic Engineering Metric" },
{ ISIS_SUBTLV_EXT_IS_REACH_LINK_ATTRIBUTE, "Link Attribute" },
{ ISIS_SUBTLV_EXT_IS_REACH_LINK_PROTECTION_TYPE, "Link Protection Type" },
{ ISIS_SUBTLV_EXT_IS_REACH_INTF_SW_CAP_DESCR, "Interface Switching Capability" },
{ ISIS_SUBTLV_EXT_IS_REACH_BW_CONSTRAINTS_OLD, "Bandwidth Constraints (old)" },
{ ISIS_SUBTLV_EXT_IS_REACH_BW_CONSTRAINTS, "Bandwidth Constraints" },
{ ISIS_SUBTLV_SPB_METRIC, "SPB Metric" },
{ 250, "Reserved for cisco specific extensions" },
{ 251, "Reserved for cisco specific extensions" },
{ 252, "Reserved for cisco specific extensions" },
{ 253, "Reserved for cisco specific extensions" },
{ 254, "Reserved for cisco specific extensions" },
{ 255, "Reserved for future expansion" },
{ 0, NULL }
};
#define ISIS_SUBTLV_EXTD_IP_REACH_ADMIN_TAG32 1 /* draft-ietf-isis-admin-tags-01 */
#define ISIS_SUBTLV_EXTD_IP_REACH_ADMIN_TAG64 2 /* draft-ietf-isis-admin-tags-01 */
#define ISIS_SUBTLV_EXTD_IP_REACH_MGMT_PREFIX_COLOR 117 /* draft-ietf-isis-wg-multi-topology-05 */
static const struct tok isis_ext_ip_reach_subtlv_values[] = {
{ ISIS_SUBTLV_EXTD_IP_REACH_ADMIN_TAG32, "32-Bit Administrative tag" },
{ ISIS_SUBTLV_EXTD_IP_REACH_ADMIN_TAG64, "64-Bit Administrative tag" },
{ ISIS_SUBTLV_EXTD_IP_REACH_MGMT_PREFIX_COLOR, "Management Prefix Color" },
{ 0, NULL }
};
static const struct tok isis_subtlv_link_attribute_values[] = {
{ 0x01, "Local Protection Available" },
{ 0x02, "Link excluded from local protection path" },
{ 0x04, "Local maintenance required"},
{ 0, NULL }
};
#define ISIS_SUBTLV_AUTH_SIMPLE 1
#define ISIS_SUBTLV_AUTH_GENERIC 3 /* rfc 5310 */
#define ISIS_SUBTLV_AUTH_MD5 54
#define ISIS_SUBTLV_AUTH_MD5_LEN 16
#define ISIS_SUBTLV_AUTH_PRIVATE 255
static const struct tok isis_subtlv_auth_values[] = {
{ ISIS_SUBTLV_AUTH_SIMPLE, "simple text password"},
{ ISIS_SUBTLV_AUTH_GENERIC, "Generic Crypto key-id"},
{ ISIS_SUBTLV_AUTH_MD5, "HMAC-MD5 password"},
{ ISIS_SUBTLV_AUTH_PRIVATE, "Routing Domain private password"},
{ 0, NULL }
};
#define ISIS_SUBTLV_IDRP_RES 0
#define ISIS_SUBTLV_IDRP_LOCAL 1
#define ISIS_SUBTLV_IDRP_ASN 2
static const struct tok isis_subtlv_idrp_values[] = {
{ ISIS_SUBTLV_IDRP_RES, "Reserved"},
{ ISIS_SUBTLV_IDRP_LOCAL, "Routing-Domain Specific"},
{ ISIS_SUBTLV_IDRP_ASN, "AS Number Tag"},
{ 0, NULL}
};
#define ISIS_SUBTLV_SPB_MCID 4
#define ISIS_SUBTLV_SPB_DIGEST 5
#define ISIS_SUBTLV_SPB_BVID 6
#define ISIS_SUBTLV_SPB_INSTANCE 1
#define ISIS_SUBTLV_SPBM_SI 3
#define ISIS_SPB_MCID_LEN 51
#define ISIS_SUBTLV_SPB_MCID_MIN_LEN 102
#define ISIS_SUBTLV_SPB_DIGEST_MIN_LEN 33
#define ISIS_SUBTLV_SPB_BVID_MIN_LEN 6
#define ISIS_SUBTLV_SPB_INSTANCE_MIN_LEN 19
#define ISIS_SUBTLV_SPB_INSTANCE_VLAN_TUPLE_LEN 8
static const struct tok isis_mt_port_cap_subtlv_values[] = {
{ ISIS_SUBTLV_SPB_MCID, "SPB MCID" },
{ ISIS_SUBTLV_SPB_DIGEST, "SPB Digest" },
{ ISIS_SUBTLV_SPB_BVID, "SPB BVID" },
{ 0, NULL }
};
static const struct tok isis_mt_capability_subtlv_values[] = {
{ ISIS_SUBTLV_SPB_INSTANCE, "SPB Instance" },
{ ISIS_SUBTLV_SPBM_SI, "SPBM Service Identifier and Unicast Address" },
{ 0, NULL }
};
struct isis_spb_mcid {
uint8_t format_id;
uint8_t name[32];
uint8_t revision_lvl[2];
uint8_t digest[16];
};
struct isis_subtlv_spb_mcid {
struct isis_spb_mcid mcid;
struct isis_spb_mcid aux_mcid;
};
struct isis_subtlv_spb_instance {
uint8_t cist_root_id[8];
uint8_t cist_external_root_path_cost[4];
uint8_t bridge_priority[2];
uint8_t spsourceid[4];
uint8_t no_of_trees;
};
#define CLNP_SEGMENT_PART 0x80
#define CLNP_MORE_SEGMENTS 0x40
#define CLNP_REQUEST_ER 0x20
static const struct tok clnp_flag_values[] = {
{ CLNP_SEGMENT_PART, "Segmentation permitted"},
{ CLNP_MORE_SEGMENTS, "more Segments"},
{ CLNP_REQUEST_ER, "request Error Report"},
{ 0, NULL}
};
#define ISIS_MASK_LSP_OL_BIT(x) ((x)&0x4)
#define ISIS_MASK_LSP_ISTYPE_BITS(x) ((x)&0x3)
#define ISIS_MASK_LSP_PARTITION_BIT(x) ((x)&0x80)
#define ISIS_MASK_LSP_ATT_BITS(x) ((x)&0x78)
#define ISIS_MASK_LSP_ATT_ERROR_BIT(x) ((x)&0x40)
#define ISIS_MASK_LSP_ATT_EXPENSE_BIT(x) ((x)&0x20)
#define ISIS_MASK_LSP_ATT_DELAY_BIT(x) ((x)&0x10)
#define ISIS_MASK_LSP_ATT_DEFAULT_BIT(x) ((x)&0x8)
#define ISIS_MASK_MTID(x) ((x)&0x0fff)
#define ISIS_MASK_MTFLAGS(x) ((x)&0xf000)
static const struct tok isis_mt_flag_values[] = {
{ 0x4000, "ATT bit set"},
{ 0x8000, "Overload bit set"},
{ 0, NULL}
};
#define ISIS_MASK_TLV_EXTD_IP_UPDOWN(x) ((x)&0x80)
#define ISIS_MASK_TLV_EXTD_IP_SUBTLV(x) ((x)&0x40)
#define ISIS_MASK_TLV_EXTD_IP6_IE(x) ((x)&0x40)
#define ISIS_MASK_TLV_EXTD_IP6_SUBTLV(x) ((x)&0x20)
#define ISIS_LSP_TLV_METRIC_SUPPORTED(x) ((x)&0x80)
#define ISIS_LSP_TLV_METRIC_IE(x) ((x)&0x40)
#define ISIS_LSP_TLV_METRIC_UPDOWN(x) ((x)&0x80)
#define ISIS_LSP_TLV_METRIC_VALUE(x) ((x)&0x3f)
#define ISIS_MASK_TLV_SHARED_RISK_GROUP(x) ((x)&0x1)
static const struct tok isis_mt_values[] = {
{ 0, "IPv4 unicast"},
{ 1, "In-Band Management"},
{ 2, "IPv6 unicast"},
{ 3, "Multicast"},
{ 4095, "Development, Experimental or Proprietary"},
{ 0, NULL }
};
static const struct tok isis_iih_circuit_type_values[] = {
{ 1, "Level 1 only"},
{ 2, "Level 2 only"},
{ 3, "Level 1, Level 2"},
{ 0, NULL}
};
#define ISIS_LSP_TYPE_UNUSED0 0
#define ISIS_LSP_TYPE_LEVEL_1 1
#define ISIS_LSP_TYPE_UNUSED2 2
#define ISIS_LSP_TYPE_LEVEL_2 3
static const struct tok isis_lsp_istype_values[] = {
{ ISIS_LSP_TYPE_UNUSED0, "Unused 0x0 (invalid)"},
{ ISIS_LSP_TYPE_LEVEL_1, "L1 IS"},
{ ISIS_LSP_TYPE_UNUSED2, "Unused 0x2 (invalid)"},
{ ISIS_LSP_TYPE_LEVEL_2, "L2 IS"},
{ 0, NULL }
};
/*
* Katz's point to point adjacency TLV uses codes to tell us the state of
* the remote adjacency. Enumerate them.
*/
#define ISIS_PTP_ADJ_UP 0
#define ISIS_PTP_ADJ_INIT 1
#define ISIS_PTP_ADJ_DOWN 2
static const struct tok isis_ptp_adjancey_values[] = {
{ ISIS_PTP_ADJ_UP, "Up" },
{ ISIS_PTP_ADJ_INIT, "Initializing" },
{ ISIS_PTP_ADJ_DOWN, "Down" },
{ 0, NULL}
};
struct isis_tlv_ptp_adj {
uint8_t adjacency_state;
uint8_t extd_local_circuit_id[4];
uint8_t neighbor_sysid[SYSTEM_ID_LEN];
uint8_t neighbor_extd_local_circuit_id[4];
};
static void osi_print_cksum(netdissect_options *, const uint8_t *pptr,
uint16_t checksum, int checksum_offset, u_int length);
static int clnp_print(netdissect_options *, const uint8_t *, u_int);
static void esis_print(netdissect_options *, const uint8_t *, u_int);
static int isis_print(netdissect_options *, const uint8_t *, u_int);
struct isis_metric_block {
uint8_t metric_default;
uint8_t metric_delay;
uint8_t metric_expense;
uint8_t metric_error;
};
struct isis_tlv_is_reach {
struct isis_metric_block isis_metric_block;
uint8_t neighbor_nodeid[NODE_ID_LEN];
};
struct isis_tlv_es_reach {
struct isis_metric_block isis_metric_block;
uint8_t neighbor_sysid[SYSTEM_ID_LEN];
};
struct isis_tlv_ip_reach {
struct isis_metric_block isis_metric_block;
uint8_t prefix[4];
uint8_t mask[4];
};
static const struct tok isis_is_reach_virtual_values[] = {
{ 0, "IsNotVirtual"},
{ 1, "IsVirtual"},
{ 0, NULL }
};
static const struct tok isis_restart_flag_values[] = {
{ 0x1, "Restart Request"},
{ 0x2, "Restart Acknowledgement"},
{ 0x4, "Suppress adjacency advertisement"},
{ 0, NULL }
};
struct isis_common_header {
uint8_t nlpid;
uint8_t fixed_len;
uint8_t version; /* Protocol version */
uint8_t id_length;
uint8_t pdu_type; /* 3 MSbits are reserved */
uint8_t pdu_version; /* Packet format version */
uint8_t reserved;
uint8_t max_area;
};
struct isis_iih_lan_header {
uint8_t circuit_type;
uint8_t source_id[SYSTEM_ID_LEN];
uint8_t holding_time[2];
uint8_t pdu_len[2];
uint8_t priority;
uint8_t lan_id[NODE_ID_LEN];
};
struct isis_iih_ptp_header {
uint8_t circuit_type;
uint8_t source_id[SYSTEM_ID_LEN];
uint8_t holding_time[2];
uint8_t pdu_len[2];
uint8_t circuit_id;
};
struct isis_lsp_header {
uint8_t pdu_len[2];
uint8_t remaining_lifetime[2];
uint8_t lsp_id[LSP_ID_LEN];
uint8_t sequence_number[4];
uint8_t checksum[2];
uint8_t typeblock;
};
struct isis_csnp_header {
uint8_t pdu_len[2];
uint8_t source_id[NODE_ID_LEN];
uint8_t start_lsp_id[LSP_ID_LEN];
uint8_t end_lsp_id[LSP_ID_LEN];
};
struct isis_psnp_header {
uint8_t pdu_len[2];
uint8_t source_id[NODE_ID_LEN];
};
struct isis_tlv_lsp {
uint8_t remaining_lifetime[2];
uint8_t lsp_id[LSP_ID_LEN];
uint8_t sequence_number[4];
uint8_t checksum[2];
};
#define ISIS_COMMON_HEADER_SIZE (sizeof(struct isis_common_header))
#define ISIS_IIH_LAN_HEADER_SIZE (sizeof(struct isis_iih_lan_header))
#define ISIS_IIH_PTP_HEADER_SIZE (sizeof(struct isis_iih_ptp_header))
#define ISIS_LSP_HEADER_SIZE (sizeof(struct isis_lsp_header))
#define ISIS_CSNP_HEADER_SIZE (sizeof(struct isis_csnp_header))
#define ISIS_PSNP_HEADER_SIZE (sizeof(struct isis_psnp_header))
void
isoclns_print(netdissect_options *ndo,
const uint8_t *p, u_int length, u_int caplen)
{
if (caplen <= 1) { /* enough bytes on the wire ? */
ND_PRINT((ndo, "|OSI"));
return;
}
if (ndo->ndo_eflag)
ND_PRINT((ndo, "OSI NLPID %s (0x%02x): ", tok2str(nlpid_values, "Unknown", *p), *p));
switch (*p) {
case NLPID_CLNP:
if (!clnp_print(ndo, p, length))
print_unknown_data(ndo, p, "\n\t", caplen);
break;
case NLPID_ESIS:
esis_print(ndo, p, length);
return;
case NLPID_ISIS:
if (!isis_print(ndo, p, length))
print_unknown_data(ndo, p, "\n\t", caplen);
break;
case NLPID_NULLNS:
ND_PRINT((ndo, "%slength: %u", ndo->ndo_eflag ? "" : ", ", length));
break;
case NLPID_Q933:
q933_print(ndo, p + 1, length - 1);
break;
case NLPID_IP:
ip_print(ndo, p + 1, length - 1);
break;
case NLPID_IP6:
ip6_print(ndo, p + 1, length - 1);
break;
case NLPID_PPP:
ppp_print(ndo, p + 1, length - 1);
break;
default:
if (!ndo->ndo_eflag)
ND_PRINT((ndo, "OSI NLPID 0x%02x unknown", *p));
ND_PRINT((ndo, "%slength: %u", ndo->ndo_eflag ? "" : ", ", length));
if (caplen > 1)
print_unknown_data(ndo, p, "\n\t", caplen);
break;
}
}
#define CLNP_PDU_ER 1
#define CLNP_PDU_DT 28
#define CLNP_PDU_MD 29
#define CLNP_PDU_ERQ 30
#define CLNP_PDU_ERP 31
static const struct tok clnp_pdu_values[] = {
{ CLNP_PDU_ER, "Error Report"},
{ CLNP_PDU_MD, "MD"},
{ CLNP_PDU_DT, "Data"},
{ CLNP_PDU_ERQ, "Echo Request"},
{ CLNP_PDU_ERP, "Echo Response"},
{ 0, NULL }
};
struct clnp_header_t {
uint8_t nlpid;
uint8_t length_indicator;
uint8_t version;
uint8_t lifetime; /* units of 500ms */
uint8_t type;
uint8_t segment_length[2];
uint8_t cksum[2];
};
struct clnp_segment_header_t {
uint8_t data_unit_id[2];
uint8_t segment_offset[2];
uint8_t total_length[2];
};
/*
* clnp_print
* Decode CLNP packets. Return 0 on error.
*/
static int
clnp_print(netdissect_options *ndo,
const uint8_t *pptr, u_int length)
{
const uint8_t *optr,*source_address,*dest_address;
u_int li,tlen,nsap_offset,source_address_length,dest_address_length, clnp_pdu_type, clnp_flags;
const struct clnp_header_t *clnp_header;
const struct clnp_segment_header_t *clnp_segment_header;
uint8_t rfd_error_major,rfd_error_minor;
clnp_header = (const struct clnp_header_t *) pptr;
ND_TCHECK(*clnp_header);
li = clnp_header->length_indicator;
optr = pptr;
if (!ndo->ndo_eflag)
ND_PRINT((ndo, "CLNP"));
/*
* Sanity checking of the header.
*/
if (clnp_header->version != CLNP_VERSION) {
ND_PRINT((ndo, "version %d packet not supported", clnp_header->version));
return (0);
}
if (li > length) {
ND_PRINT((ndo, " length indicator(%u) > PDU size (%u)!", li, length));
return (0);
}
if (li < sizeof(struct clnp_header_t)) {
ND_PRINT((ndo, " length indicator %u < min PDU size:", li));
while (pptr < ndo->ndo_snapend)
ND_PRINT((ndo, "%02X", *pptr++));
return (0);
}
/* FIXME further header sanity checking */
clnp_pdu_type = clnp_header->type & CLNP_PDU_TYPE_MASK;
clnp_flags = clnp_header->type & CLNP_FLAG_MASK;
pptr += sizeof(struct clnp_header_t);
li -= sizeof(struct clnp_header_t);
if (li < 1) {
ND_PRINT((ndo, "li < size of fixed part of CLNP header and addresses"));
return (0);
}
ND_TCHECK(*pptr);
dest_address_length = *pptr;
pptr += 1;
li -= 1;
if (li < dest_address_length) {
ND_PRINT((ndo, "li < size of fixed part of CLNP header and addresses"));
return (0);
}
ND_TCHECK2(*pptr, dest_address_length);
dest_address = pptr;
pptr += dest_address_length;
li -= dest_address_length;
if (li < 1) {
ND_PRINT((ndo, "li < size of fixed part of CLNP header and addresses"));
return (0);
}
ND_TCHECK(*pptr);
source_address_length = *pptr;
pptr += 1;
li -= 1;
if (li < source_address_length) {
ND_PRINT((ndo, "li < size of fixed part of CLNP header and addresses"));
return (0);
}
ND_TCHECK2(*pptr, source_address_length);
source_address = pptr;
pptr += source_address_length;
li -= source_address_length;
if (ndo->ndo_vflag < 1) {
ND_PRINT((ndo, "%s%s > %s, %s, length %u",
ndo->ndo_eflag ? "" : ", ",
isonsap_string(ndo, source_address, source_address_length),
isonsap_string(ndo, dest_address, dest_address_length),
tok2str(clnp_pdu_values,"unknown (%u)",clnp_pdu_type),
length));
return (1);
}
ND_PRINT((ndo, "%slength %u", ndo->ndo_eflag ? "" : ", ", length));
ND_PRINT((ndo, "\n\t%s PDU, hlen: %u, v: %u, lifetime: %u.%us, Segment PDU length: %u, checksum: 0x%04x",
tok2str(clnp_pdu_values, "unknown (%u)",clnp_pdu_type),
clnp_header->length_indicator,
clnp_header->version,
clnp_header->lifetime/2,
(clnp_header->lifetime%2)*5,
EXTRACT_16BITS(clnp_header->segment_length),
EXTRACT_16BITS(clnp_header->cksum)));
osi_print_cksum(ndo, optr, EXTRACT_16BITS(clnp_header->cksum), 7,
clnp_header->length_indicator);
ND_PRINT((ndo, "\n\tFlags [%s]",
bittok2str(clnp_flag_values, "none", clnp_flags)));
ND_PRINT((ndo, "\n\tsource address (length %u): %s\n\tdest address (length %u): %s",
source_address_length,
isonsap_string(ndo, source_address, source_address_length),
dest_address_length,
isonsap_string(ndo, dest_address, dest_address_length)));
if (clnp_flags & CLNP_SEGMENT_PART) {
if (li < sizeof(const struct clnp_segment_header_t)) {
ND_PRINT((ndo, "li < size of fixed part of CLNP header, addresses, and segment part"));
return (0);
}
clnp_segment_header = (const struct clnp_segment_header_t *) pptr;
ND_TCHECK(*clnp_segment_header);
ND_PRINT((ndo, "\n\tData Unit ID: 0x%04x, Segment Offset: %u, Total PDU Length: %u",
EXTRACT_16BITS(clnp_segment_header->data_unit_id),
EXTRACT_16BITS(clnp_segment_header->segment_offset),
EXTRACT_16BITS(clnp_segment_header->total_length)));
pptr+=sizeof(const struct clnp_segment_header_t);
li-=sizeof(const struct clnp_segment_header_t);
}
/* now walk the options */
while (li >= 2) {
u_int op, opli;
const uint8_t *tptr;
if (li < 2) {
ND_PRINT((ndo, ", bad opts/li"));
return (0);
}
ND_TCHECK2(*pptr, 2);
op = *pptr++;
opli = *pptr++;
li -= 2;
if (opli > li) {
ND_PRINT((ndo, ", opt (%d) too long", op));
return (0);
}
ND_TCHECK2(*pptr, opli);
li -= opli;
tptr = pptr;
tlen = opli;
ND_PRINT((ndo, "\n\t %s Option #%u, length %u, value: ",
tok2str(clnp_option_values,"Unknown",op),
op,
opli));
/*
* We've already checked that the entire option is present
* in the captured packet with the ND_TCHECK2() call.
* Therefore, we don't need to do ND_TCHECK()/ND_TCHECK2()
* checks.
* We do, however, need to check tlen, to make sure we
* don't run past the end of the option.
*/
switch (op) {
case CLNP_OPTION_ROUTE_RECORDING: /* those two options share the format */
case CLNP_OPTION_SOURCE_ROUTING:
if (tlen < 2) {
ND_PRINT((ndo, ", bad opt len"));
return (0);
}
ND_PRINT((ndo, "%s %s",
tok2str(clnp_option_sr_rr_values,"Unknown",*tptr),
tok2str(clnp_option_sr_rr_string_values, "Unknown Option %u", op)));
nsap_offset=*(tptr+1);
if (nsap_offset == 0) {
ND_PRINT((ndo, " Bad NSAP offset (0)"));
break;
}
nsap_offset-=1; /* offset to nsap list */
if (nsap_offset > tlen) {
ND_PRINT((ndo, " Bad NSAP offset (past end of option)"));
break;
}
tptr+=nsap_offset;
tlen-=nsap_offset;
while (tlen > 0) {
source_address_length=*tptr;
if (tlen < source_address_length+1) {
ND_PRINT((ndo, "\n\t NSAP address goes past end of option"));
break;
}
if (source_address_length > 0) {
source_address=(tptr+1);
ND_TCHECK2(*source_address, source_address_length);
ND_PRINT((ndo, "\n\t NSAP address (length %u): %s",
source_address_length,
isonsap_string(ndo, source_address, source_address_length)));
}
tlen-=source_address_length+1;
}
break;
case CLNP_OPTION_PRIORITY:
if (tlen < 1) {
ND_PRINT((ndo, ", bad opt len"));
return (0);
}
ND_PRINT((ndo, "0x%1x", *tptr&0x0f));
break;
case CLNP_OPTION_QOS_MAINTENANCE:
if (tlen < 1) {
ND_PRINT((ndo, ", bad opt len"));
return (0);
}
ND_PRINT((ndo, "\n\t Format Code: %s",
tok2str(clnp_option_scope_values, "Reserved", *tptr&CLNP_OPTION_SCOPE_MASK)));
if ((*tptr&CLNP_OPTION_SCOPE_MASK) == CLNP_OPTION_SCOPE_GLOBAL)
ND_PRINT((ndo, "\n\t QoS Flags [%s]",
bittok2str(clnp_option_qos_global_values,
"none",
*tptr&CLNP_OPTION_OPTION_QOS_MASK)));
break;
case CLNP_OPTION_SECURITY:
if (tlen < 2) {
ND_PRINT((ndo, ", bad opt len"));
return (0);
}
ND_PRINT((ndo, "\n\t Format Code: %s, Security-Level %u",
tok2str(clnp_option_scope_values,"Reserved",*tptr&CLNP_OPTION_SCOPE_MASK),
*(tptr+1)));
break;
case CLNP_OPTION_DISCARD_REASON:
if (tlen < 1) {
ND_PRINT((ndo, ", bad opt len"));
return (0);
}
rfd_error_major = (*tptr&0xf0) >> 4;
rfd_error_minor = *tptr&0x0f;
ND_PRINT((ndo, "\n\t Class: %s Error (0x%01x), %s (0x%01x)",
tok2str(clnp_option_rfd_class_values,"Unknown",rfd_error_major),
rfd_error_major,
tok2str(clnp_option_rfd_error_class[rfd_error_major],"Unknown",rfd_error_minor),
rfd_error_minor));
break;
case CLNP_OPTION_PADDING:
ND_PRINT((ndo, "padding data"));
break;
/*
* FIXME those are the defined Options that lack a decoder
* you are welcome to contribute code ;-)
*/
default:
print_unknown_data(ndo, tptr, "\n\t ", opli);
break;
}
if (ndo->ndo_vflag > 1)
print_unknown_data(ndo, pptr, "\n\t ", opli);
pptr += opli;
}
switch (clnp_pdu_type) {
case CLNP_PDU_ER: /* fall through */
case CLNP_PDU_ERP:
ND_TCHECK(*pptr);
if (*(pptr) == NLPID_CLNP) {
ND_PRINT((ndo, "\n\t-----original packet-----\n\t"));
/* FIXME recursion protection */
clnp_print(ndo, pptr, length - clnp_header->length_indicator);
break;
}
case CLNP_PDU_DT:
case CLNP_PDU_MD:
case CLNP_PDU_ERQ:
default:
/* dump the PDU specific data */
if (length-(pptr-optr) > 0) {
ND_PRINT((ndo, "\n\t undecoded non-header data, length %u", length-clnp_header->length_indicator));
print_unknown_data(ndo, pptr, "\n\t ", length - (pptr - optr));
}
}
return (1);
trunc:
ND_PRINT((ndo, "[|clnp]"));
return (1);
}
#define ESIS_PDU_REDIRECT 6
#define ESIS_PDU_ESH 2
#define ESIS_PDU_ISH 4
static const struct tok esis_pdu_values[] = {
{ ESIS_PDU_REDIRECT, "redirect"},
{ ESIS_PDU_ESH, "ESH"},
{ ESIS_PDU_ISH, "ISH"},
{ 0, NULL }
};
struct esis_header_t {
uint8_t nlpid;
uint8_t length_indicator;
uint8_t version;
uint8_t reserved;
uint8_t type;
uint8_t holdtime[2];
uint8_t cksum[2];
};
static void
esis_print(netdissect_options *ndo,
const uint8_t *pptr, u_int length)
{
const uint8_t *optr;
u_int li,esis_pdu_type,source_address_length, source_address_number;
const struct esis_header_t *esis_header;
if (!ndo->ndo_eflag)
ND_PRINT((ndo, "ES-IS"));
if (length <= 2) {
ND_PRINT((ndo, ndo->ndo_qflag ? "bad pkt!" : "no header at all!"));
return;
}
esis_header = (const struct esis_header_t *) pptr;
ND_TCHECK(*esis_header);
li = esis_header->length_indicator;
optr = pptr;
/*
* Sanity checking of the header.
*/
if (esis_header->nlpid != NLPID_ESIS) {
ND_PRINT((ndo, " nlpid 0x%02x packet not supported", esis_header->nlpid));
return;
}
if (esis_header->version != ESIS_VERSION) {
ND_PRINT((ndo, " version %d packet not supported", esis_header->version));
return;
}
if (li > length) {
ND_PRINT((ndo, " length indicator(%u) > PDU size (%u)!", li, length));
return;
}
if (li < sizeof(struct esis_header_t) + 2) {
ND_PRINT((ndo, " length indicator %u < min PDU size:", li));
while (pptr < ndo->ndo_snapend)
ND_PRINT((ndo, "%02X", *pptr++));
return;
}
esis_pdu_type = esis_header->type & ESIS_PDU_TYPE_MASK;
if (ndo->ndo_vflag < 1) {
ND_PRINT((ndo, "%s%s, length %u",
ndo->ndo_eflag ? "" : ", ",
tok2str(esis_pdu_values,"unknown type (%u)",esis_pdu_type),
length));
return;
} else
ND_PRINT((ndo, "%slength %u\n\t%s (%u)",
ndo->ndo_eflag ? "" : ", ",
length,
tok2str(esis_pdu_values,"unknown type: %u", esis_pdu_type),
esis_pdu_type));
ND_PRINT((ndo, ", v: %u%s", esis_header->version, esis_header->version == ESIS_VERSION ? "" : "unsupported" ));
ND_PRINT((ndo, ", checksum: 0x%04x", EXTRACT_16BITS(esis_header->cksum)));
osi_print_cksum(ndo, pptr, EXTRACT_16BITS(esis_header->cksum), 7, li);
ND_PRINT((ndo, ", holding time: %us, length indicator: %u",
EXTRACT_16BITS(esis_header->holdtime), li));
if (ndo->ndo_vflag > 1)
print_unknown_data(ndo, optr, "\n\t", sizeof(struct esis_header_t));
pptr += sizeof(struct esis_header_t);
li -= sizeof(struct esis_header_t);
switch (esis_pdu_type) {
case ESIS_PDU_REDIRECT: {
const uint8_t *dst, *snpa, *neta;
u_int dstl, snpal, netal;
ND_TCHECK(*pptr);
if (li < 1) {
ND_PRINT((ndo, ", bad redirect/li"));
return;
}
dstl = *pptr;
pptr++;
li--;
ND_TCHECK2(*pptr, dstl);
if (li < dstl) {
ND_PRINT((ndo, ", bad redirect/li"));
return;
}
dst = pptr;
pptr += dstl;
li -= dstl;
ND_PRINT((ndo, "\n\t %s", isonsap_string(ndo, dst, dstl)));
ND_TCHECK(*pptr);
if (li < 1) {
ND_PRINT((ndo, ", bad redirect/li"));
return;
}
snpal = *pptr;
pptr++;
li--;
ND_TCHECK2(*pptr, snpal);
if (li < snpal) {
ND_PRINT((ndo, ", bad redirect/li"));
return;
}
snpa = pptr;
pptr += snpal;
li -= snpal;
ND_TCHECK(*pptr);
if (li < 1) {
ND_PRINT((ndo, ", bad redirect/li"));
return;
}
netal = *pptr;
pptr++;
ND_TCHECK2(*pptr, netal);
if (li < netal) {
ND_PRINT((ndo, ", bad redirect/li"));
return;
}
neta = pptr;
pptr += netal;
li -= netal;
if (netal == 0)
ND_PRINT((ndo, "\n\t %s", etheraddr_string(ndo, snpa)));
else
ND_PRINT((ndo, "\n\t %s", isonsap_string(ndo, neta, netal)));
break;
}
case ESIS_PDU_ESH:
ND_TCHECK(*pptr);
if (li < 1) {
ND_PRINT((ndo, ", bad esh/li"));
return;
}
source_address_number = *pptr;
pptr++;
li--;
ND_PRINT((ndo, "\n\t Number of Source Addresses: %u", source_address_number));
while (source_address_number > 0) {
ND_TCHECK(*pptr);
if (li < 1) {
ND_PRINT((ndo, ", bad esh/li"));
return;
}
source_address_length = *pptr;
pptr++;
li--;
ND_TCHECK2(*pptr, source_address_length);
if (li < source_address_length) {
ND_PRINT((ndo, ", bad esh/li"));
return;
}
ND_PRINT((ndo, "\n\t NET (length: %u): %s",
source_address_length,
isonsap_string(ndo, pptr, source_address_length)));
pptr += source_address_length;
li -= source_address_length;
source_address_number--;
}
break;
case ESIS_PDU_ISH: {
ND_TCHECK(*pptr);
if (li < 1) {
ND_PRINT((ndo, ", bad ish/li"));
return;
}
source_address_length = *pptr;
pptr++;
li--;
ND_TCHECK2(*pptr, source_address_length);
if (li < source_address_length) {
ND_PRINT((ndo, ", bad ish/li"));
return;
}
ND_PRINT((ndo, "\n\t NET (length: %u): %s", source_address_length, isonsap_string(ndo, pptr, source_address_length)));
pptr += source_address_length;
li -= source_address_length;
break;
}
default:
if (ndo->ndo_vflag <= 1) {
if (pptr < ndo->ndo_snapend)
print_unknown_data(ndo, pptr, "\n\t ", ndo->ndo_snapend - pptr);
}
return;
}
/* now walk the options */
while (li != 0) {
u_int op, opli;
const uint8_t *tptr;
if (li < 2) {
ND_PRINT((ndo, ", bad opts/li"));
return;
}
ND_TCHECK2(*pptr, 2);
op = *pptr++;
opli = *pptr++;
li -= 2;
if (opli > li) {
ND_PRINT((ndo, ", opt (%d) too long", op));
return;
}
li -= opli;
tptr = pptr;
ND_PRINT((ndo, "\n\t %s Option #%u, length %u, value: ",
tok2str(esis_option_values,"Unknown",op),
op,
opli));
switch (op) {
case ESIS_OPTION_ES_CONF_TIME:
if (opli == 2) {
ND_TCHECK2(*pptr, 2);
ND_PRINT((ndo, "%us", EXTRACT_16BITS(tptr)));
} else
ND_PRINT((ndo, "(bad length)"));
break;
case ESIS_OPTION_PROTOCOLS:
while (opli>0) {
ND_TCHECK(*pptr);
ND_PRINT((ndo, "%s (0x%02x)",
tok2str(nlpid_values,
"unknown",
*tptr),
*tptr));
if (opli>1) /* further NPLIDs ? - put comma */
ND_PRINT((ndo, ", "));
tptr++;
opli--;
}
break;
/*
* FIXME those are the defined Options that lack a decoder
* you are welcome to contribute code ;-)
*/
case ESIS_OPTION_QOS_MAINTENANCE:
case ESIS_OPTION_SECURITY:
case ESIS_OPTION_PRIORITY:
case ESIS_OPTION_ADDRESS_MASK:
case ESIS_OPTION_SNPA_MASK:
default:
print_unknown_data(ndo, tptr, "\n\t ", opli);
break;
}
if (ndo->ndo_vflag > 1)
print_unknown_data(ndo, pptr, "\n\t ", opli);
pptr += opli;
}
trunc:
return;
}
static void
isis_print_mcid(netdissect_options *ndo,
const struct isis_spb_mcid *mcid)
{
int i;
ND_TCHECK(*mcid);
ND_PRINT((ndo, "ID: %d, Name: ", mcid->format_id));
if (fn_printzp(ndo, mcid->name, 32, ndo->ndo_snapend))
goto trunc;
ND_PRINT((ndo, "\n\t Lvl: %d", EXTRACT_16BITS(mcid->revision_lvl)));
ND_PRINT((ndo, ", Digest: "));
for(i=0;i<16;i++)
ND_PRINT((ndo, "%.2x ", mcid->digest[i]));
trunc:
ND_PRINT((ndo, "%s", tstr));
}
static int
isis_print_mt_port_cap_subtlv(netdissect_options *ndo,
const uint8_t *tptr, int len)
{
int stlv_type, stlv_len;
const struct isis_subtlv_spb_mcid *subtlv_spb_mcid;
int i;
while (len > 2)
{
stlv_type = *(tptr++);
stlv_len = *(tptr++);
/* first lets see if we know the subTLVs name*/
ND_PRINT((ndo, "\n\t %s subTLV #%u, length: %u",
tok2str(isis_mt_port_cap_subtlv_values, "unknown", stlv_type),
stlv_type,
stlv_len));
/*len -= TLV_TYPE_LEN_OFFSET;*/
len = len -2;
switch (stlv_type)
{
case ISIS_SUBTLV_SPB_MCID:
{
ND_TCHECK2(*(tptr), ISIS_SUBTLV_SPB_MCID_MIN_LEN);
subtlv_spb_mcid = (const struct isis_subtlv_spb_mcid *)tptr;
ND_PRINT((ndo, "\n\t MCID: "));
isis_print_mcid(ndo, &(subtlv_spb_mcid->mcid));
/*tptr += SPB_MCID_MIN_LEN;
len -= SPB_MCID_MIN_LEN; */
ND_PRINT((ndo, "\n\t AUX-MCID: "));
isis_print_mcid(ndo, &(subtlv_spb_mcid->aux_mcid));
/*tptr += SPB_MCID_MIN_LEN;
len -= SPB_MCID_MIN_LEN; */
tptr = tptr + sizeof(struct isis_subtlv_spb_mcid);
len = len - sizeof(struct isis_subtlv_spb_mcid);
break;
}
case ISIS_SUBTLV_SPB_DIGEST:
{
ND_TCHECK2(*(tptr), ISIS_SUBTLV_SPB_DIGEST_MIN_LEN);
ND_PRINT((ndo, "\n\t RES: %d V: %d A: %d D: %d",
(*(tptr) >> 5), (((*tptr)>> 4) & 0x01),
((*(tptr) >> 2) & 0x03), ((*tptr) & 0x03)));
tptr++;
ND_PRINT((ndo, "\n\t Digest: "));
for(i=1;i<=8; i++)
{
ND_PRINT((ndo, "%08x ", EXTRACT_32BITS(tptr)));
if (i%4 == 0 && i != 8)
ND_PRINT((ndo, "\n\t "));
tptr = tptr + 4;
}
len = len - ISIS_SUBTLV_SPB_DIGEST_MIN_LEN;
break;
}
case ISIS_SUBTLV_SPB_BVID:
{
ND_TCHECK2(*(tptr), stlv_len);
while (len >= ISIS_SUBTLV_SPB_BVID_MIN_LEN)
{
ND_TCHECK2(*(tptr), ISIS_SUBTLV_SPB_BVID_MIN_LEN);
ND_PRINT((ndo, "\n\t ECT: %08x",
EXTRACT_32BITS(tptr)));
tptr = tptr+4;
ND_PRINT((ndo, " BVID: %d, U:%01x M:%01x ",
(EXTRACT_16BITS (tptr) >> 4) ,
(EXTRACT_16BITS (tptr) >> 3) & 0x01,
(EXTRACT_16BITS (tptr) >> 2) & 0x01));
tptr = tptr + 2;
len = len - ISIS_SUBTLV_SPB_BVID_MIN_LEN;
}
break;
}
default:
break;
}
}
return 0;
trunc:
ND_PRINT((ndo, "\n\t\t"));
ND_PRINT((ndo, "%s", tstr));
return(1);
}
static int
isis_print_mt_capability_subtlv(netdissect_options *ndo,
const uint8_t *tptr, int len)
{
int stlv_type, stlv_len, tmp;
while (len > 2)
{
stlv_type = *(tptr++);
stlv_len = *(tptr++);
/* first lets see if we know the subTLVs name*/
ND_PRINT((ndo, "\n\t %s subTLV #%u, length: %u",
tok2str(isis_mt_capability_subtlv_values, "unknown", stlv_type),
stlv_type,
stlv_len));
len = len - 2;
switch (stlv_type)
{
case ISIS_SUBTLV_SPB_INSTANCE:
ND_TCHECK2(*tptr, ISIS_SUBTLV_SPB_INSTANCE_MIN_LEN);
ND_PRINT((ndo, "\n\t CIST Root-ID: %08x", EXTRACT_32BITS(tptr)));
tptr = tptr+4;
ND_PRINT((ndo, " %08x", EXTRACT_32BITS(tptr)));
tptr = tptr+4;
ND_PRINT((ndo, ", Path Cost: %08x", EXTRACT_32BITS(tptr)));
tptr = tptr+4;
ND_PRINT((ndo, ", Prio: %d", EXTRACT_16BITS(tptr)));
tptr = tptr + 2;
ND_PRINT((ndo, "\n\t RES: %d",
EXTRACT_16BITS(tptr) >> 5));
ND_PRINT((ndo, ", V: %d",
(EXTRACT_16BITS(tptr) >> 4) & 0x0001));
ND_PRINT((ndo, ", SPSource-ID: %d",
(EXTRACT_32BITS(tptr) & 0x000fffff)));
tptr = tptr+4;
ND_PRINT((ndo, ", No of Trees: %x", *(tptr)));
tmp = *(tptr++);
len = len - ISIS_SUBTLV_SPB_INSTANCE_MIN_LEN;
while (tmp)
{
ND_TCHECK2(*tptr, ISIS_SUBTLV_SPB_INSTANCE_VLAN_TUPLE_LEN);
ND_PRINT((ndo, "\n\t U:%d, M:%d, A:%d, RES:%d",
*(tptr) >> 7, (*(tptr) >> 6) & 0x01,
(*(tptr) >> 5) & 0x01, (*(tptr) & 0x1f)));
tptr++;
ND_PRINT((ndo, ", ECT: %08x", EXTRACT_32BITS(tptr)));
tptr = tptr + 4;
ND_PRINT((ndo, ", BVID: %d, SPVID: %d",
(EXTRACT_24BITS(tptr) >> 12) & 0x000fff,
EXTRACT_24BITS(tptr) & 0x000fff));
tptr = tptr + 3;
len = len - ISIS_SUBTLV_SPB_INSTANCE_VLAN_TUPLE_LEN;
tmp--;
}
break;
case ISIS_SUBTLV_SPBM_SI:
ND_TCHECK2(*tptr, 8);
ND_PRINT((ndo, "\n\t BMAC: %08x", EXTRACT_32BITS(tptr)));
tptr = tptr+4;
ND_PRINT((ndo, "%04x", EXTRACT_16BITS(tptr)));
tptr = tptr+2;
ND_PRINT((ndo, ", RES: %d, VID: %d", EXTRACT_16BITS(tptr) >> 12,
(EXTRACT_16BITS(tptr)) & 0x0fff));
tptr = tptr+2;
len = len - 8;
stlv_len = stlv_len - 8;
while (stlv_len >= 4) {
ND_TCHECK2(*tptr, 4);
ND_PRINT((ndo, "\n\t T: %d, R: %d, RES: %d, ISID: %d",
(EXTRACT_32BITS(tptr) >> 31),
(EXTRACT_32BITS(tptr) >> 30) & 0x01,
(EXTRACT_32BITS(tptr) >> 24) & 0x03f,
(EXTRACT_32BITS(tptr)) & 0x0ffffff));
tptr = tptr + 4;
len = len - 4;
stlv_len = stlv_len - 4;
}
break;
default:
break;
}
}
return 0;
trunc:
ND_PRINT((ndo, "\n\t\t"));
ND_PRINT((ndo, "%s", tstr));
return(1);
}
/* shared routine for printing system, node and lsp-ids */
static char *
isis_print_id(const uint8_t *cp, int id_len)
{
int i;
static char id[sizeof("xxxx.xxxx.xxxx.yy-zz")];
char *pos = id;
for (i = 1; i <= SYSTEM_ID_LEN; i++) {
snprintf(pos, sizeof(id) - (pos - id), "%02x", *cp++);
pos += strlen(pos);
if (i == 2 || i == 4)
*pos++ = '.';
}
if (id_len >= NODE_ID_LEN) {
snprintf(pos, sizeof(id) - (pos - id), ".%02x", *cp++);
pos += strlen(pos);
}
if (id_len == LSP_ID_LEN)
snprintf(pos, sizeof(id) - (pos - id), "-%02x", *cp);
return (id);
}
/* print the 4-byte metric block which is common found in the old-style TLVs */
static int
isis_print_metric_block(netdissect_options *ndo,
const struct isis_metric_block *isis_metric_block)
{
ND_PRINT((ndo, ", Default Metric: %d, %s",
ISIS_LSP_TLV_METRIC_VALUE(isis_metric_block->metric_default),
ISIS_LSP_TLV_METRIC_IE(isis_metric_block->metric_default) ? "External" : "Internal"));
if (!ISIS_LSP_TLV_METRIC_SUPPORTED(isis_metric_block->metric_delay))
ND_PRINT((ndo, "\n\t\t Delay Metric: %d, %s",
ISIS_LSP_TLV_METRIC_VALUE(isis_metric_block->metric_delay),
ISIS_LSP_TLV_METRIC_IE(isis_metric_block->metric_delay) ? "External" : "Internal"));
if (!ISIS_LSP_TLV_METRIC_SUPPORTED(isis_metric_block->metric_expense))
ND_PRINT((ndo, "\n\t\t Expense Metric: %d, %s",
ISIS_LSP_TLV_METRIC_VALUE(isis_metric_block->metric_expense),
ISIS_LSP_TLV_METRIC_IE(isis_metric_block->metric_expense) ? "External" : "Internal"));
if (!ISIS_LSP_TLV_METRIC_SUPPORTED(isis_metric_block->metric_error))
ND_PRINT((ndo, "\n\t\t Error Metric: %d, %s",
ISIS_LSP_TLV_METRIC_VALUE(isis_metric_block->metric_error),
ISIS_LSP_TLV_METRIC_IE(isis_metric_block->metric_error) ? "External" : "Internal"));
return(1); /* everything is ok */
}
static int
isis_print_tlv_ip_reach(netdissect_options *ndo,
const uint8_t *cp, const char *ident, int length)
{
int prefix_len;
const struct isis_tlv_ip_reach *tlv_ip_reach;
tlv_ip_reach = (const struct isis_tlv_ip_reach *)cp;
while (length > 0) {
if ((size_t)length < sizeof(*tlv_ip_reach)) {
ND_PRINT((ndo, "short IPv4 Reachability (%d vs %lu)",
length,
(unsigned long)sizeof(*tlv_ip_reach)));
return (0);
}
if (!ND_TTEST(*tlv_ip_reach))
return (0);
prefix_len = mask2plen(EXTRACT_32BITS(tlv_ip_reach->mask));
if (prefix_len == -1)
ND_PRINT((ndo, "%sIPv4 prefix: %s mask %s",
ident,
ipaddr_string(ndo, (tlv_ip_reach->prefix)),
ipaddr_string(ndo, (tlv_ip_reach->mask))));
else
ND_PRINT((ndo, "%sIPv4 prefix: %15s/%u",
ident,
ipaddr_string(ndo, (tlv_ip_reach->prefix)),
prefix_len));
ND_PRINT((ndo, ", Distribution: %s, Metric: %u, %s",
ISIS_LSP_TLV_METRIC_UPDOWN(tlv_ip_reach->isis_metric_block.metric_default) ? "down" : "up",
ISIS_LSP_TLV_METRIC_VALUE(tlv_ip_reach->isis_metric_block.metric_default),
ISIS_LSP_TLV_METRIC_IE(tlv_ip_reach->isis_metric_block.metric_default) ? "External" : "Internal"));
if (!ISIS_LSP_TLV_METRIC_SUPPORTED(tlv_ip_reach->isis_metric_block.metric_delay))
ND_PRINT((ndo, "%s Delay Metric: %u, %s",
ident,
ISIS_LSP_TLV_METRIC_VALUE(tlv_ip_reach->isis_metric_block.metric_delay),
ISIS_LSP_TLV_METRIC_IE(tlv_ip_reach->isis_metric_block.metric_delay) ? "External" : "Internal"));
if (!ISIS_LSP_TLV_METRIC_SUPPORTED(tlv_ip_reach->isis_metric_block.metric_expense))
ND_PRINT((ndo, "%s Expense Metric: %u, %s",
ident,
ISIS_LSP_TLV_METRIC_VALUE(tlv_ip_reach->isis_metric_block.metric_expense),
ISIS_LSP_TLV_METRIC_IE(tlv_ip_reach->isis_metric_block.metric_expense) ? "External" : "Internal"));
if (!ISIS_LSP_TLV_METRIC_SUPPORTED(tlv_ip_reach->isis_metric_block.metric_error))
ND_PRINT((ndo, "%s Error Metric: %u, %s",
ident,
ISIS_LSP_TLV_METRIC_VALUE(tlv_ip_reach->isis_metric_block.metric_error),
ISIS_LSP_TLV_METRIC_IE(tlv_ip_reach->isis_metric_block.metric_error) ? "External" : "Internal"));
length -= sizeof(struct isis_tlv_ip_reach);
tlv_ip_reach++;
}
return (1);
}
/*
* this is the common IP-REACH subTLV decoder it is called
* from various EXTD-IP REACH TLVs (135,235,236,237)
*/
static int
isis_print_ip_reach_subtlv(netdissect_options *ndo,
const uint8_t *tptr, int subt, int subl,
const char *ident)
{
/* first lets see if we know the subTLVs name*/
ND_PRINT((ndo, "%s%s subTLV #%u, length: %u",
ident, tok2str(isis_ext_ip_reach_subtlv_values, "unknown", subt),
subt, subl));
ND_TCHECK2(*tptr,subl);
switch(subt) {
case ISIS_SUBTLV_EXTD_IP_REACH_MGMT_PREFIX_COLOR: /* fall through */
case ISIS_SUBTLV_EXTD_IP_REACH_ADMIN_TAG32:
while (subl >= 4) {
ND_PRINT((ndo, ", 0x%08x (=%u)",
EXTRACT_32BITS(tptr),
EXTRACT_32BITS(tptr)));
tptr+=4;
subl-=4;
}
break;
case ISIS_SUBTLV_EXTD_IP_REACH_ADMIN_TAG64:
while (subl >= 8) {
ND_PRINT((ndo, ", 0x%08x%08x",
EXTRACT_32BITS(tptr),
EXTRACT_32BITS(tptr+4)));
tptr+=8;
subl-=8;
}
break;
default:
if (!print_unknown_data(ndo, tptr, "\n\t\t ", subl))
return(0);
break;
}
return(1);
trunc:
ND_PRINT((ndo, "%s", ident));
ND_PRINT((ndo, "%s", tstr));
return(0);
}
/*
* this is the common IS-REACH subTLV decoder it is called
* from isis_print_ext_is_reach()
*/
static int
isis_print_is_reach_subtlv(netdissect_options *ndo,
const uint8_t *tptr, u_int subt, u_int subl,
const char *ident)
{
u_int te_class,priority_level,gmpls_switch_cap;
union { /* int to float conversion buffer for several subTLVs */
float f;
uint32_t i;
} bw;
/* first lets see if we know the subTLVs name*/
ND_PRINT((ndo, "%s%s subTLV #%u, length: %u",
ident, tok2str(isis_ext_is_reach_subtlv_values, "unknown", subt),
subt, subl));
ND_TCHECK2(*tptr, subl);
switch(subt) {
case ISIS_SUBTLV_EXT_IS_REACH_ADMIN_GROUP:
case ISIS_SUBTLV_EXT_IS_REACH_LINK_LOCAL_REMOTE_ID:
case ISIS_SUBTLV_EXT_IS_REACH_LINK_REMOTE_ID:
if (subl >= 4) {
ND_PRINT((ndo, ", 0x%08x", EXTRACT_32BITS(tptr)));
if (subl == 8) /* rfc4205 */
ND_PRINT((ndo, ", 0x%08x", EXTRACT_32BITS(tptr+4)));
}
break;
case ISIS_SUBTLV_EXT_IS_REACH_IPV4_INTF_ADDR:
case ISIS_SUBTLV_EXT_IS_REACH_IPV4_NEIGHBOR_ADDR:
if (subl >= sizeof(struct in_addr))
ND_PRINT((ndo, ", %s", ipaddr_string(ndo, tptr)));
break;
case ISIS_SUBTLV_EXT_IS_REACH_MAX_LINK_BW :
case ISIS_SUBTLV_EXT_IS_REACH_RESERVABLE_BW:
if (subl >= 4) {
bw.i = EXTRACT_32BITS(tptr);
ND_PRINT((ndo, ", %.3f Mbps", bw.f * 8 / 1000000));
}
break;
case ISIS_SUBTLV_EXT_IS_REACH_UNRESERVED_BW :
if (subl >= 32) {
for (te_class = 0; te_class < 8; te_class++) {
bw.i = EXTRACT_32BITS(tptr);
ND_PRINT((ndo, "%s TE-Class %u: %.3f Mbps",
ident,
te_class,
bw.f * 8 / 1000000));
tptr+=4;
}
}
break;
case ISIS_SUBTLV_EXT_IS_REACH_BW_CONSTRAINTS: /* fall through */
case ISIS_SUBTLV_EXT_IS_REACH_BW_CONSTRAINTS_OLD:
ND_PRINT((ndo, "%sBandwidth Constraints Model ID: %s (%u)",
ident,
tok2str(diffserv_te_bc_values, "unknown", *tptr),
*tptr));
tptr++;
/* decode BCs until the subTLV ends */
for (te_class = 0; te_class < (subl-1)/4; te_class++) {
ND_TCHECK2(*tptr, 4);
bw.i = EXTRACT_32BITS(tptr);
ND_PRINT((ndo, "%s Bandwidth constraint CT%u: %.3f Mbps",
ident,
te_class,
bw.f * 8 / 1000000));
tptr+=4;
}
break;
case ISIS_SUBTLV_EXT_IS_REACH_TE_METRIC:
if (subl >= 3)
ND_PRINT((ndo, ", %u", EXTRACT_24BITS(tptr)));
break;
case ISIS_SUBTLV_EXT_IS_REACH_LINK_ATTRIBUTE:
if (subl == 2) {
ND_PRINT((ndo, ", [ %s ] (0x%04x)",
bittok2str(isis_subtlv_link_attribute_values,
"Unknown",
EXTRACT_16BITS(tptr)),
EXTRACT_16BITS(tptr)));
}
break;
case ISIS_SUBTLV_EXT_IS_REACH_LINK_PROTECTION_TYPE:
if (subl >= 2) {
ND_PRINT((ndo, ", %s, Priority %u",
bittok2str(gmpls_link_prot_values, "none", *tptr),
*(tptr+1)));
}
break;
case ISIS_SUBTLV_SPB_METRIC:
if (subl >= 6) {
ND_PRINT((ndo, ", LM: %u", EXTRACT_24BITS(tptr)));
tptr=tptr+3;
ND_PRINT((ndo, ", P: %u", *(tptr)));
tptr++;
ND_PRINT((ndo, ", P-ID: %u", EXTRACT_16BITS(tptr)));
}
break;
case ISIS_SUBTLV_EXT_IS_REACH_INTF_SW_CAP_DESCR:
if (subl >= 36) {
gmpls_switch_cap = *tptr;
ND_PRINT((ndo, "%s Interface Switching Capability:%s",
ident,
tok2str(gmpls_switch_cap_values, "Unknown", gmpls_switch_cap)));
ND_PRINT((ndo, ", LSP Encoding: %s",
tok2str(gmpls_encoding_values, "Unknown", *(tptr + 1))));
tptr+=4;
ND_PRINT((ndo, "%s Max LSP Bandwidth:", ident));
for (priority_level = 0; priority_level < 8; priority_level++) {
bw.i = EXTRACT_32BITS(tptr);
ND_PRINT((ndo, "%s priority level %d: %.3f Mbps",
ident,
priority_level,
bw.f * 8 / 1000000));
tptr+=4;
}
subl-=36;
switch (gmpls_switch_cap) {
case GMPLS_PSC1:
case GMPLS_PSC2:
case GMPLS_PSC3:
case GMPLS_PSC4:
ND_TCHECK2(*tptr, 6);
bw.i = EXTRACT_32BITS(tptr);
ND_PRINT((ndo, "%s Min LSP Bandwidth: %.3f Mbps", ident, bw.f * 8 / 1000000));
ND_PRINT((ndo, "%s Interface MTU: %u", ident, EXTRACT_16BITS(tptr + 4)));
break;
case GMPLS_TSC:
ND_TCHECK2(*tptr, 8);
bw.i = EXTRACT_32BITS(tptr);
ND_PRINT((ndo, "%s Min LSP Bandwidth: %.3f Mbps", ident, bw.f * 8 / 1000000));
ND_PRINT((ndo, "%s Indication %s", ident,
tok2str(gmpls_switch_cap_tsc_indication_values, "Unknown (%u)", *(tptr + 4))));
break;
default:
/* there is some optional stuff left to decode but this is as of yet
not specified so just lets hexdump what is left */
if(subl>0){
if (!print_unknown_data(ndo, tptr, "\n\t\t ", subl))
return(0);
}
}
}
break;
default:
if (!print_unknown_data(ndo, tptr, "\n\t\t ", subl))
return(0);
break;
}
return(1);
trunc:
return(0);
}
/*
* this is the common IS-REACH decoder it is called
* from various EXTD-IS REACH style TLVs (22,24,222)
*/
static int
isis_print_ext_is_reach(netdissect_options *ndo,
const uint8_t *tptr, const char *ident, int tlv_type)
{
char ident_buffer[20];
int subtlv_type,subtlv_len,subtlv_sum_len;
int proc_bytes = 0; /* how many bytes did we process ? */
if (!ND_TTEST2(*tptr, NODE_ID_LEN))
return(0);
ND_PRINT((ndo, "%sIS Neighbor: %s", ident, isis_print_id(tptr, NODE_ID_LEN)));
tptr+=(NODE_ID_LEN);
if (tlv_type != ISIS_TLV_IS_ALIAS_ID) { /* the Alias TLV Metric field is implicit 0 */
if (!ND_TTEST2(*tptr, 3)) /* and is therefore skipped */
return(0);
ND_PRINT((ndo, ", Metric: %d", EXTRACT_24BITS(tptr)));
tptr+=3;
}
if (!ND_TTEST2(*tptr, 1))
return(0);
subtlv_sum_len=*(tptr++); /* read out subTLV length */
proc_bytes=NODE_ID_LEN+3+1;
ND_PRINT((ndo, ", %ssub-TLVs present",subtlv_sum_len ? "" : "no "));
if (subtlv_sum_len) {
ND_PRINT((ndo, " (%u)", subtlv_sum_len));
while (subtlv_sum_len>0) {
if (!ND_TTEST2(*tptr,2))
return(0);
subtlv_type=*(tptr++);
subtlv_len=*(tptr++);
/* prepend the indent string */
snprintf(ident_buffer, sizeof(ident_buffer), "%s ",ident);
if (!isis_print_is_reach_subtlv(ndo, tptr, subtlv_type, subtlv_len, ident_buffer))
return(0);
tptr+=subtlv_len;
subtlv_sum_len-=(subtlv_len+2);
proc_bytes+=(subtlv_len+2);
}
}
return(proc_bytes);
}
/*
* this is the common Multi Topology ID decoder
* it is called from various MT-TLVs (222,229,235,237)
*/
static int
isis_print_mtid(netdissect_options *ndo,
const uint8_t *tptr, const char *ident)
{
if (!ND_TTEST2(*tptr, 2))
return(0);
ND_PRINT((ndo, "%s%s",
ident,
tok2str(isis_mt_values,
"Reserved for IETF Consensus",
ISIS_MASK_MTID(EXTRACT_16BITS(tptr)))));
ND_PRINT((ndo, " Topology (0x%03x), Flags: [%s]",
ISIS_MASK_MTID(EXTRACT_16BITS(tptr)),
bittok2str(isis_mt_flag_values, "none",ISIS_MASK_MTFLAGS(EXTRACT_16BITS(tptr)))));
return(2);
}
/*
* this is the common extended IP reach decoder
* it is called from TLVs (135,235,236,237)
* we process the TLV and optional subTLVs and return
* the amount of processed bytes
*/
static int
isis_print_extd_ip_reach(netdissect_options *ndo,
const uint8_t *tptr, const char *ident, uint16_t afi)
{
char ident_buffer[20];
uint8_t prefix[sizeof(struct in6_addr)]; /* shared copy buffer for IPv4 and IPv6 prefixes */
u_int metric, status_byte, bit_length, byte_length, sublen, processed, subtlvtype, subtlvlen;
if (!ND_TTEST2(*tptr, 4))
return (0);
metric = EXTRACT_32BITS(tptr);
processed=4;
tptr+=4;
if (afi == AF_INET) {
if (!ND_TTEST2(*tptr, 1)) /* fetch status byte */
return (0);
status_byte=*(tptr++);
bit_length = status_byte&0x3f;
if (bit_length > 32) {
ND_PRINT((ndo, "%sIPv4 prefix: bad bit length %u",
ident,
bit_length));
return (0);
}
processed++;
} else if (afi == AF_INET6) {
if (!ND_TTEST2(*tptr, 1)) /* fetch status & prefix_len byte */
return (0);
status_byte=*(tptr++);
bit_length=*(tptr++);
if (bit_length > 128) {
ND_PRINT((ndo, "%sIPv6 prefix: bad bit length %u",
ident,
bit_length));
return (0);
}
processed+=2;
} else
return (0); /* somebody is fooling us */
byte_length = (bit_length + 7) / 8; /* prefix has variable length encoding */
if (!ND_TTEST2(*tptr, byte_length))
return (0);
memset(prefix, 0, sizeof prefix); /* clear the copy buffer */
memcpy(prefix,tptr,byte_length); /* copy as much as is stored in the TLV */
tptr+=byte_length;
processed+=byte_length;
if (afi == AF_INET)
ND_PRINT((ndo, "%sIPv4 prefix: %15s/%u",
ident,
ipaddr_string(ndo, prefix),
bit_length));
else if (afi == AF_INET6)
ND_PRINT((ndo, "%sIPv6 prefix: %s/%u",
ident,
ip6addr_string(ndo, prefix),
bit_length));
ND_PRINT((ndo, ", Distribution: %s, Metric: %u",
ISIS_MASK_TLV_EXTD_IP_UPDOWN(status_byte) ? "down" : "up",
metric));
if (afi == AF_INET && ISIS_MASK_TLV_EXTD_IP_SUBTLV(status_byte))
ND_PRINT((ndo, ", sub-TLVs present"));
else if (afi == AF_INET6)
ND_PRINT((ndo, ", %s%s",
ISIS_MASK_TLV_EXTD_IP6_IE(status_byte) ? "External" : "Internal",
ISIS_MASK_TLV_EXTD_IP6_SUBTLV(status_byte) ? ", sub-TLVs present" : ""));
if ((afi == AF_INET && ISIS_MASK_TLV_EXTD_IP_SUBTLV(status_byte))
|| (afi == AF_INET6 && ISIS_MASK_TLV_EXTD_IP6_SUBTLV(status_byte))
) {
/* assume that one prefix can hold more
than one subTLV - therefore the first byte must reflect
the aggregate bytecount of the subTLVs for this prefix
*/
if (!ND_TTEST2(*tptr, 1))
return (0);
sublen=*(tptr++);
processed+=sublen+1;
ND_PRINT((ndo, " (%u)", sublen)); /* print out subTLV length */
while (sublen>0) {
if (!ND_TTEST2(*tptr,2))
return (0);
subtlvtype=*(tptr++);
subtlvlen=*(tptr++);
/* prepend the indent string */
snprintf(ident_buffer, sizeof(ident_buffer), "%s ",ident);
if (!isis_print_ip_reach_subtlv(ndo, tptr, subtlvtype, subtlvlen, ident_buffer))
return(0);
tptr+=subtlvlen;
sublen-=(subtlvlen+2);
}
}
return (processed);
}
/*
* Clear checksum and lifetime prior to signature verification.
*/
static void
isis_clear_checksum_lifetime(void *header)
{
struct isis_lsp_header *header_lsp = (struct isis_lsp_header *) header;
header_lsp->checksum[0] = 0;
header_lsp->checksum[1] = 0;
header_lsp->remaining_lifetime[0] = 0;
header_lsp->remaining_lifetime[1] = 0;
}
/*
* isis_print
* Decode IS-IS packets. Return 0 on error.
*/
static int
isis_print(netdissect_options *ndo,
const uint8_t *p, u_int length)
{
const struct isis_common_header *isis_header;
const struct isis_iih_lan_header *header_iih_lan;
const struct isis_iih_ptp_header *header_iih_ptp;
const struct isis_lsp_header *header_lsp;
const struct isis_csnp_header *header_csnp;
const struct isis_psnp_header *header_psnp;
const struct isis_tlv_lsp *tlv_lsp;
const struct isis_tlv_ptp_adj *tlv_ptp_adj;
const struct isis_tlv_is_reach *tlv_is_reach;
const struct isis_tlv_es_reach *tlv_es_reach;
uint8_t pdu_type, max_area, id_length, tlv_type, tlv_len, tmp, alen, lan_alen, prefix_len;
uint8_t ext_is_len, ext_ip_len, mt_len;
const uint8_t *optr, *pptr, *tptr;
u_short packet_len,pdu_len, key_id;
u_int i,vendor_id;
int sigcheck;
packet_len=length;
optr = p; /* initialize the _o_riginal pointer to the packet start -
need it for parsing the checksum TLV and authentication
TLV verification */
isis_header = (const struct isis_common_header *)p;
ND_TCHECK(*isis_header);
if (length < ISIS_COMMON_HEADER_SIZE)
goto trunc;
pptr = p+(ISIS_COMMON_HEADER_SIZE);
header_iih_lan = (const struct isis_iih_lan_header *)pptr;
header_iih_ptp = (const struct isis_iih_ptp_header *)pptr;
header_lsp = (const struct isis_lsp_header *)pptr;
header_csnp = (const struct isis_csnp_header *)pptr;
header_psnp = (const struct isis_psnp_header *)pptr;
if (!ndo->ndo_eflag)
ND_PRINT((ndo, "IS-IS"));
/*
* Sanity checking of the header.
*/
if (isis_header->version != ISIS_VERSION) {
ND_PRINT((ndo, "version %d packet not supported", isis_header->version));
return (0);
}
if ((isis_header->id_length != SYSTEM_ID_LEN) && (isis_header->id_length != 0)) {
ND_PRINT((ndo, "system ID length of %d is not supported",
isis_header->id_length));
return (0);
}
if (isis_header->pdu_version != ISIS_VERSION) {
ND_PRINT((ndo, "version %d packet not supported", isis_header->pdu_version));
return (0);
}
if (length < isis_header->fixed_len) {
ND_PRINT((ndo, "fixed header length %u > packet length %u", isis_header->fixed_len, length));
return (0);
}
if (isis_header->fixed_len < ISIS_COMMON_HEADER_SIZE) {
ND_PRINT((ndo, "fixed header length %u < minimum header size %u", isis_header->fixed_len, (u_int)ISIS_COMMON_HEADER_SIZE));
return (0);
}
max_area = isis_header->max_area;
switch(max_area) {
case 0:
max_area = 3; /* silly shit */
break;
case 255:
ND_PRINT((ndo, "bad packet -- 255 areas"));
return (0);
default:
break;
}
id_length = isis_header->id_length;
switch(id_length) {
case 0:
id_length = 6; /* silly shit again */
break;
case 1: /* 1-8 are valid sys-ID lenghts */
case 2:
case 3:
case 4:
case 5:
case 6:
case 7:
case 8:
break;
case 255:
id_length = 0; /* entirely useless */
break;
default:
break;
}
/* toss any non 6-byte sys-ID len PDUs */
if (id_length != 6 ) {
ND_PRINT((ndo, "bad packet -- illegal sys-ID length (%u)", id_length));
return (0);
}
pdu_type=isis_header->pdu_type;
/* in non-verbose mode print the basic PDU Type plus PDU specific brief information*/
if (ndo->ndo_vflag == 0) {
ND_PRINT((ndo, "%s%s",
ndo->ndo_eflag ? "" : ", ",
tok2str(isis_pdu_values, "unknown PDU-Type %u", pdu_type)));
} else {
/* ok they seem to want to know everything - lets fully decode it */
ND_PRINT((ndo, "%slength %u", ndo->ndo_eflag ? "" : ", ", length));
ND_PRINT((ndo, "\n\t%s, hlen: %u, v: %u, pdu-v: %u, sys-id-len: %u (%u), max-area: %u (%u)",
tok2str(isis_pdu_values,
"unknown, type %u",
pdu_type),
isis_header->fixed_len,
isis_header->version,
isis_header->pdu_version,
id_length,
isis_header->id_length,
max_area,
isis_header->max_area));
if (ndo->ndo_vflag > 1) {
if (!print_unknown_data(ndo, optr, "\n\t", 8)) /* provide the _o_riginal pointer */
return (0); /* for optionally debugging the common header */
}
}
switch (pdu_type) {
case ISIS_PDU_L1_LAN_IIH:
case ISIS_PDU_L2_LAN_IIH:
if (isis_header->fixed_len != (ISIS_COMMON_HEADER_SIZE+ISIS_IIH_LAN_HEADER_SIZE)) {
ND_PRINT((ndo, ", bogus fixed header length %u should be %lu",
isis_header->fixed_len, (unsigned long)(ISIS_COMMON_HEADER_SIZE+ISIS_IIH_LAN_HEADER_SIZE)));
return (0);
}
ND_TCHECK(*header_iih_lan);
if (length < ISIS_COMMON_HEADER_SIZE+ISIS_IIH_LAN_HEADER_SIZE)
goto trunc;
if (ndo->ndo_vflag == 0) {
ND_PRINT((ndo, ", src-id %s",
isis_print_id(header_iih_lan->source_id, SYSTEM_ID_LEN)));
ND_PRINT((ndo, ", lan-id %s, prio %u",
isis_print_id(header_iih_lan->lan_id,NODE_ID_LEN),
header_iih_lan->priority));
ND_PRINT((ndo, ", length %u", length));
return (1);
}
pdu_len=EXTRACT_16BITS(header_iih_lan->pdu_len);
if (packet_len>pdu_len) {
packet_len=pdu_len; /* do TLV decoding as long as it makes sense */
length=pdu_len;
}
ND_PRINT((ndo, "\n\t source-id: %s, holding time: %us, Flags: [%s]",
isis_print_id(header_iih_lan->source_id,SYSTEM_ID_LEN),
EXTRACT_16BITS(header_iih_lan->holding_time),
tok2str(isis_iih_circuit_type_values,
"unknown circuit type 0x%02x",
header_iih_lan->circuit_type)));
ND_PRINT((ndo, "\n\t lan-id: %s, Priority: %u, PDU length: %u",
isis_print_id(header_iih_lan->lan_id, NODE_ID_LEN),
(header_iih_lan->priority) & ISIS_LAN_PRIORITY_MASK,
pdu_len));
if (ndo->ndo_vflag > 1) {
if (!print_unknown_data(ndo, pptr, "\n\t ", ISIS_IIH_LAN_HEADER_SIZE))
return (0);
}
packet_len -= (ISIS_COMMON_HEADER_SIZE+ISIS_IIH_LAN_HEADER_SIZE);
pptr = p + (ISIS_COMMON_HEADER_SIZE+ISIS_IIH_LAN_HEADER_SIZE);
break;
case ISIS_PDU_PTP_IIH:
if (isis_header->fixed_len != (ISIS_COMMON_HEADER_SIZE+ISIS_IIH_PTP_HEADER_SIZE)) {
ND_PRINT((ndo, ", bogus fixed header length %u should be %lu",
isis_header->fixed_len, (unsigned long)(ISIS_COMMON_HEADER_SIZE+ISIS_IIH_PTP_HEADER_SIZE)));
return (0);
}
ND_TCHECK(*header_iih_ptp);
if (length < ISIS_COMMON_HEADER_SIZE+ISIS_IIH_PTP_HEADER_SIZE)
goto trunc;
if (ndo->ndo_vflag == 0) {
ND_PRINT((ndo, ", src-id %s", isis_print_id(header_iih_ptp->source_id, SYSTEM_ID_LEN)));
ND_PRINT((ndo, ", length %u", length));
return (1);
}
pdu_len=EXTRACT_16BITS(header_iih_ptp->pdu_len);
if (packet_len>pdu_len) {
packet_len=pdu_len; /* do TLV decoding as long as it makes sense */
length=pdu_len;
}
ND_PRINT((ndo, "\n\t source-id: %s, holding time: %us, Flags: [%s]",
isis_print_id(header_iih_ptp->source_id,SYSTEM_ID_LEN),
EXTRACT_16BITS(header_iih_ptp->holding_time),
tok2str(isis_iih_circuit_type_values,
"unknown circuit type 0x%02x",
header_iih_ptp->circuit_type)));
ND_PRINT((ndo, "\n\t circuit-id: 0x%02x, PDU length: %u",
header_iih_ptp->circuit_id,
pdu_len));
if (ndo->ndo_vflag > 1) {
if (!print_unknown_data(ndo, pptr, "\n\t ", ISIS_IIH_PTP_HEADER_SIZE))
return (0);
}
packet_len -= (ISIS_COMMON_HEADER_SIZE+ISIS_IIH_PTP_HEADER_SIZE);
pptr = p + (ISIS_COMMON_HEADER_SIZE+ISIS_IIH_PTP_HEADER_SIZE);
break;
case ISIS_PDU_L1_LSP:
case ISIS_PDU_L2_LSP:
if (isis_header->fixed_len != (ISIS_COMMON_HEADER_SIZE+ISIS_LSP_HEADER_SIZE)) {
ND_PRINT((ndo, ", bogus fixed header length %u should be %lu",
isis_header->fixed_len, (unsigned long)ISIS_LSP_HEADER_SIZE));
return (0);
}
ND_TCHECK(*header_lsp);
if (length < ISIS_COMMON_HEADER_SIZE+ISIS_LSP_HEADER_SIZE)
goto trunc;
if (ndo->ndo_vflag == 0) {
ND_PRINT((ndo, ", lsp-id %s, seq 0x%08x, lifetime %5us",
isis_print_id(header_lsp->lsp_id, LSP_ID_LEN),
EXTRACT_32BITS(header_lsp->sequence_number),
EXTRACT_16BITS(header_lsp->remaining_lifetime)));
ND_PRINT((ndo, ", length %u", length));
return (1);
}
pdu_len=EXTRACT_16BITS(header_lsp->pdu_len);
if (packet_len>pdu_len) {
packet_len=pdu_len; /* do TLV decoding as long as it makes sense */
length=pdu_len;
}
ND_PRINT((ndo, "\n\t lsp-id: %s, seq: 0x%08x, lifetime: %5us\n\t chksum: 0x%04x",
isis_print_id(header_lsp->lsp_id, LSP_ID_LEN),
EXTRACT_32BITS(header_lsp->sequence_number),
EXTRACT_16BITS(header_lsp->remaining_lifetime),
EXTRACT_16BITS(header_lsp->checksum)));
osi_print_cksum(ndo, (const uint8_t *)header_lsp->lsp_id,
EXTRACT_16BITS(header_lsp->checksum),
12, length-12);
ND_PRINT((ndo, ", PDU length: %u, Flags: [ %s",
pdu_len,
ISIS_MASK_LSP_OL_BIT(header_lsp->typeblock) ? "Overload bit set, " : ""));
if (ISIS_MASK_LSP_ATT_BITS(header_lsp->typeblock)) {
ND_PRINT((ndo, "%s", ISIS_MASK_LSP_ATT_DEFAULT_BIT(header_lsp->typeblock) ? "default " : ""));
ND_PRINT((ndo, "%s", ISIS_MASK_LSP_ATT_DELAY_BIT(header_lsp->typeblock) ? "delay " : ""));
ND_PRINT((ndo, "%s", ISIS_MASK_LSP_ATT_EXPENSE_BIT(header_lsp->typeblock) ? "expense " : ""));
ND_PRINT((ndo, "%s", ISIS_MASK_LSP_ATT_ERROR_BIT(header_lsp->typeblock) ? "error " : ""));
ND_PRINT((ndo, "ATT bit set, "));
}
ND_PRINT((ndo, "%s", ISIS_MASK_LSP_PARTITION_BIT(header_lsp->typeblock) ? "P bit set, " : ""));
ND_PRINT((ndo, "%s ]", tok2str(isis_lsp_istype_values, "Unknown(0x%x)",
ISIS_MASK_LSP_ISTYPE_BITS(header_lsp->typeblock))));
if (ndo->ndo_vflag > 1) {
if (!print_unknown_data(ndo, pptr, "\n\t ", ISIS_LSP_HEADER_SIZE))
return (0);
}
packet_len -= (ISIS_COMMON_HEADER_SIZE+ISIS_LSP_HEADER_SIZE);
pptr = p + (ISIS_COMMON_HEADER_SIZE+ISIS_LSP_HEADER_SIZE);
break;
case ISIS_PDU_L1_CSNP:
case ISIS_PDU_L2_CSNP:
if (isis_header->fixed_len != (ISIS_COMMON_HEADER_SIZE+ISIS_CSNP_HEADER_SIZE)) {
ND_PRINT((ndo, ", bogus fixed header length %u should be %lu",
isis_header->fixed_len, (unsigned long)(ISIS_COMMON_HEADER_SIZE+ISIS_CSNP_HEADER_SIZE)));
return (0);
}
ND_TCHECK(*header_csnp);
if (length < ISIS_COMMON_HEADER_SIZE+ISIS_CSNP_HEADER_SIZE)
goto trunc;
if (ndo->ndo_vflag == 0) {
ND_PRINT((ndo, ", src-id %s", isis_print_id(header_csnp->source_id, NODE_ID_LEN)));
ND_PRINT((ndo, ", length %u", length));
return (1);
}
pdu_len=EXTRACT_16BITS(header_csnp->pdu_len);
if (packet_len>pdu_len) {
packet_len=pdu_len; /* do TLV decoding as long as it makes sense */
length=pdu_len;
}
ND_PRINT((ndo, "\n\t source-id: %s, PDU length: %u",
isis_print_id(header_csnp->source_id, NODE_ID_LEN),
pdu_len));
ND_PRINT((ndo, "\n\t start lsp-id: %s",
isis_print_id(header_csnp->start_lsp_id, LSP_ID_LEN)));
ND_PRINT((ndo, "\n\t end lsp-id: %s",
isis_print_id(header_csnp->end_lsp_id, LSP_ID_LEN)));
if (ndo->ndo_vflag > 1) {
if (!print_unknown_data(ndo, pptr, "\n\t ", ISIS_CSNP_HEADER_SIZE))
return (0);
}
packet_len -= (ISIS_COMMON_HEADER_SIZE+ISIS_CSNP_HEADER_SIZE);
pptr = p + (ISIS_COMMON_HEADER_SIZE+ISIS_CSNP_HEADER_SIZE);
break;
case ISIS_PDU_L1_PSNP:
case ISIS_PDU_L2_PSNP:
if (isis_header->fixed_len != (ISIS_COMMON_HEADER_SIZE+ISIS_PSNP_HEADER_SIZE)) {
ND_PRINT((ndo, "- bogus fixed header length %u should be %lu",
isis_header->fixed_len, (unsigned long)(ISIS_COMMON_HEADER_SIZE+ISIS_PSNP_HEADER_SIZE)));
return (0);
}
ND_TCHECK(*header_psnp);
if (length < ISIS_COMMON_HEADER_SIZE+ISIS_PSNP_HEADER_SIZE)
goto trunc;
if (ndo->ndo_vflag == 0) {
ND_PRINT((ndo, ", src-id %s", isis_print_id(header_psnp->source_id, NODE_ID_LEN)));
ND_PRINT((ndo, ", length %u", length));
return (1);
}
pdu_len=EXTRACT_16BITS(header_psnp->pdu_len);
if (packet_len>pdu_len) {
packet_len=pdu_len; /* do TLV decoding as long as it makes sense */
length=pdu_len;
}
ND_PRINT((ndo, "\n\t source-id: %s, PDU length: %u",
isis_print_id(header_psnp->source_id, NODE_ID_LEN),
pdu_len));
if (ndo->ndo_vflag > 1) {
if (!print_unknown_data(ndo, pptr, "\n\t ", ISIS_PSNP_HEADER_SIZE))
return (0);
}
packet_len -= (ISIS_COMMON_HEADER_SIZE+ISIS_PSNP_HEADER_SIZE);
pptr = p + (ISIS_COMMON_HEADER_SIZE+ISIS_PSNP_HEADER_SIZE);
break;
default:
if (ndo->ndo_vflag == 0) {
ND_PRINT((ndo, ", length %u", length));
return (1);
}
(void)print_unknown_data(ndo, pptr, "\n\t ", length);
return (0);
}
/*
* Now print the TLV's.
*/
while (packet_len > 0) {
ND_TCHECK2(*pptr, 2);
if (packet_len < 2)
goto trunc;
tlv_type = *pptr++;
tlv_len = *pptr++;
tmp =tlv_len; /* copy temporary len & pointer to packet data */
tptr = pptr;
packet_len -= 2;
/* first lets see if we know the TLVs name*/
ND_PRINT((ndo, "\n\t %s TLV #%u, length: %u",
tok2str(isis_tlv_values,
"unknown",
tlv_type),
tlv_type,
tlv_len));
if (tlv_len == 0) /* something is invalid */
continue;
if (packet_len < tlv_len)
goto trunc;
/* now check if we have a decoder otherwise do a hexdump at the end*/
switch (tlv_type) {
case ISIS_TLV_AREA_ADDR:
ND_TCHECK2(*tptr, 1);
alen = *tptr++;
while (tmp && alen < tmp) {
ND_PRINT((ndo, "\n\t Area address (length: %u): %s",
alen,
isonsap_string(ndo, tptr, alen)));
tptr += alen;
tmp -= alen + 1;
if (tmp==0) /* if this is the last area address do not attemt a boundary check */
break;
ND_TCHECK2(*tptr, 1);
alen = *tptr++;
}
break;
case ISIS_TLV_ISNEIGH:
while (tmp >= ETHER_ADDR_LEN) {
ND_TCHECK2(*tptr, ETHER_ADDR_LEN);
ND_PRINT((ndo, "\n\t SNPA: %s", isis_print_id(tptr, ETHER_ADDR_LEN)));
tmp -= ETHER_ADDR_LEN;
tptr += ETHER_ADDR_LEN;
}
break;
case ISIS_TLV_ISNEIGH_VARLEN:
if (!ND_TTEST2(*tptr, 1) || tmp < 3) /* min. TLV length */
goto trunctlv;
lan_alen = *tptr++; /* LAN address length */
if (lan_alen == 0) {
ND_PRINT((ndo, "\n\t LAN address length 0 bytes (invalid)"));
break;
}
tmp --;
ND_PRINT((ndo, "\n\t LAN address length %u bytes ", lan_alen));
while (tmp >= lan_alen) {
ND_TCHECK2(*tptr, lan_alen);
ND_PRINT((ndo, "\n\t\tIS Neighbor: %s", isis_print_id(tptr, lan_alen)));
tmp -= lan_alen;
tptr +=lan_alen;
}
break;
case ISIS_TLV_PADDING:
break;
case ISIS_TLV_MT_IS_REACH:
mt_len = isis_print_mtid(ndo, tptr, "\n\t ");
if (mt_len == 0) /* did something go wrong ? */
goto trunctlv;
tptr+=mt_len;
tmp-=mt_len;
while (tmp >= 2+NODE_ID_LEN+3+1) {
ext_is_len = isis_print_ext_is_reach(ndo, tptr, "\n\t ", tlv_type);
if (ext_is_len == 0) /* did something go wrong ? */
goto trunctlv;
tmp-=ext_is_len;
tptr+=ext_is_len;
}
break;
case ISIS_TLV_IS_ALIAS_ID:
while (tmp >= NODE_ID_LEN+1) { /* is it worth attempting a decode ? */
ext_is_len = isis_print_ext_is_reach(ndo, tptr, "\n\t ", tlv_type);
if (ext_is_len == 0) /* did something go wrong ? */
goto trunctlv;
tmp-=ext_is_len;
tptr+=ext_is_len;
}
break;
case ISIS_TLV_EXT_IS_REACH:
while (tmp >= NODE_ID_LEN+3+1) { /* is it worth attempting a decode ? */
ext_is_len = isis_print_ext_is_reach(ndo, tptr, "\n\t ", tlv_type);
if (ext_is_len == 0) /* did something go wrong ? */
goto trunctlv;
tmp-=ext_is_len;
tptr+=ext_is_len;
}
break;
case ISIS_TLV_IS_REACH:
ND_TCHECK2(*tptr,1); /* check if there is one byte left to read out the virtual flag */
ND_PRINT((ndo, "\n\t %s",
tok2str(isis_is_reach_virtual_values,
"bogus virtual flag 0x%02x",
*tptr++)));
tlv_is_reach = (const struct isis_tlv_is_reach *)tptr;
while (tmp >= sizeof(struct isis_tlv_is_reach)) {
ND_TCHECK(*tlv_is_reach);
ND_PRINT((ndo, "\n\t IS Neighbor: %s",
isis_print_id(tlv_is_reach->neighbor_nodeid, NODE_ID_LEN)));
isis_print_metric_block(ndo, &tlv_is_reach->isis_metric_block);
tmp -= sizeof(struct isis_tlv_is_reach);
tlv_is_reach++;
}
break;
case ISIS_TLV_ESNEIGH:
tlv_es_reach = (const struct isis_tlv_es_reach *)tptr;
while (tmp >= sizeof(struct isis_tlv_es_reach)) {
ND_TCHECK(*tlv_es_reach);
ND_PRINT((ndo, "\n\t ES Neighbor: %s",
isis_print_id(tlv_es_reach->neighbor_sysid, SYSTEM_ID_LEN)));
isis_print_metric_block(ndo, &tlv_es_reach->isis_metric_block);
tmp -= sizeof(struct isis_tlv_es_reach);
tlv_es_reach++;
}
break;
/* those two TLVs share the same format */
case ISIS_TLV_INT_IP_REACH:
case ISIS_TLV_EXT_IP_REACH:
if (!isis_print_tlv_ip_reach(ndo, pptr, "\n\t ", tlv_len))
return (1);
break;
case ISIS_TLV_EXTD_IP_REACH:
while (tmp>0) {
ext_ip_len = isis_print_extd_ip_reach(ndo, tptr, "\n\t ", AF_INET);
if (ext_ip_len == 0) /* did something go wrong ? */
goto trunctlv;
tptr+=ext_ip_len;
tmp-=ext_ip_len;
}
break;
case ISIS_TLV_MT_IP_REACH:
mt_len = isis_print_mtid(ndo, tptr, "\n\t ");
if (mt_len == 0) { /* did something go wrong ? */
goto trunctlv;
}
tptr+=mt_len;
tmp-=mt_len;
while (tmp>0) {
ext_ip_len = isis_print_extd_ip_reach(ndo, tptr, "\n\t ", AF_INET);
if (ext_ip_len == 0) /* did something go wrong ? */
goto trunctlv;
tptr+=ext_ip_len;
tmp-=ext_ip_len;
}
break;
case ISIS_TLV_IP6_REACH:
while (tmp>0) {
ext_ip_len = isis_print_extd_ip_reach(ndo, tptr, "\n\t ", AF_INET6);
if (ext_ip_len == 0) /* did something go wrong ? */
goto trunctlv;
tptr+=ext_ip_len;
tmp-=ext_ip_len;
}
break;
case ISIS_TLV_MT_IP6_REACH:
mt_len = isis_print_mtid(ndo, tptr, "\n\t ");
if (mt_len == 0) { /* did something go wrong ? */
goto trunctlv;
}
tptr+=mt_len;
tmp-=mt_len;
while (tmp>0) {
ext_ip_len = isis_print_extd_ip_reach(ndo, tptr, "\n\t ", AF_INET6);
if (ext_ip_len == 0) /* did something go wrong ? */
goto trunctlv;
tptr+=ext_ip_len;
tmp-=ext_ip_len;
}
break;
case ISIS_TLV_IP6ADDR:
while (tmp>=sizeof(struct in6_addr)) {
ND_TCHECK2(*tptr, sizeof(struct in6_addr));
ND_PRINT((ndo, "\n\t IPv6 interface address: %s",
ip6addr_string(ndo, tptr)));
tptr += sizeof(struct in6_addr);
tmp -= sizeof(struct in6_addr);
}
break;
case ISIS_TLV_AUTH:
ND_TCHECK2(*tptr, 1);
ND_PRINT((ndo, "\n\t %s: ",
tok2str(isis_subtlv_auth_values,
"unknown Authentication type 0x%02x",
*tptr)));
switch (*tptr) {
case ISIS_SUBTLV_AUTH_SIMPLE:
if (fn_printzp(ndo, tptr + 1, tlv_len - 1, ndo->ndo_snapend))
goto trunctlv;
break;
case ISIS_SUBTLV_AUTH_MD5:
for(i=1;i<tlv_len;i++) {
ND_TCHECK2(*(tptr + i), 1);
ND_PRINT((ndo, "%02x", *(tptr + i)));
}
if (tlv_len != ISIS_SUBTLV_AUTH_MD5_LEN+1)
ND_PRINT((ndo, ", (invalid subTLV) "));
sigcheck = signature_verify(ndo, optr, length, tptr + 1,
isis_clear_checksum_lifetime,
header_lsp);
ND_PRINT((ndo, " (%s)", tok2str(signature_check_values, "Unknown", sigcheck)));
break;
case ISIS_SUBTLV_AUTH_GENERIC:
ND_TCHECK2(*(tptr + 1), 2);
key_id = EXTRACT_16BITS((tptr+1));
ND_PRINT((ndo, "%u, password: ", key_id));
for(i=1 + sizeof(uint16_t);i<tlv_len;i++) {
ND_TCHECK2(*(tptr + i), 1);
ND_PRINT((ndo, "%02x", *(tptr + i)));
}
break;
case ISIS_SUBTLV_AUTH_PRIVATE:
default:
if (!print_unknown_data(ndo, tptr + 1, "\n\t\t ", tlv_len - 1))
return(0);
break;
}
break;
case ISIS_TLV_PTP_ADJ:
tlv_ptp_adj = (const struct isis_tlv_ptp_adj *)tptr;
if(tmp>=1) {
ND_TCHECK2(*tptr, 1);
ND_PRINT((ndo, "\n\t Adjacency State: %s (%u)",
tok2str(isis_ptp_adjancey_values, "unknown", *tptr),
*tptr));
tmp--;
}
if(tmp>sizeof(tlv_ptp_adj->extd_local_circuit_id)) {
ND_TCHECK(tlv_ptp_adj->extd_local_circuit_id);
ND_PRINT((ndo, "\n\t Extended Local circuit-ID: 0x%08x",
EXTRACT_32BITS(tlv_ptp_adj->extd_local_circuit_id)));
tmp-=sizeof(tlv_ptp_adj->extd_local_circuit_id);
}
if(tmp>=SYSTEM_ID_LEN) {
ND_TCHECK2(tlv_ptp_adj->neighbor_sysid, SYSTEM_ID_LEN);
ND_PRINT((ndo, "\n\t Neighbor System-ID: %s",
isis_print_id(tlv_ptp_adj->neighbor_sysid, SYSTEM_ID_LEN)));
tmp-=SYSTEM_ID_LEN;
}
if(tmp>=sizeof(tlv_ptp_adj->neighbor_extd_local_circuit_id)) {
ND_TCHECK(tlv_ptp_adj->neighbor_extd_local_circuit_id);
ND_PRINT((ndo, "\n\t Neighbor Extended Local circuit-ID: 0x%08x",
EXTRACT_32BITS(tlv_ptp_adj->neighbor_extd_local_circuit_id)));
}
break;
case ISIS_TLV_PROTOCOLS:
ND_PRINT((ndo, "\n\t NLPID(s): "));
while (tmp>0) {
ND_TCHECK2(*(tptr), 1);
ND_PRINT((ndo, "%s (0x%02x)",
tok2str(nlpid_values,
"unknown",
*tptr),
*tptr));
if (tmp>1) /* further NPLIDs ? - put comma */
ND_PRINT((ndo, ", "));
tptr++;
tmp--;
}
break;
case ISIS_TLV_MT_PORT_CAP:
{
ND_TCHECK2(*(tptr), 2);
ND_PRINT((ndo, "\n\t RES: %d, MTID(s): %d",
(EXTRACT_16BITS (tptr) >> 12),
(EXTRACT_16BITS (tptr) & 0x0fff)));
tmp = tmp-2;
tptr = tptr+2;
if (tmp)
isis_print_mt_port_cap_subtlv(ndo, tptr, tmp);
break;
}
case ISIS_TLV_MT_CAPABILITY:
ND_TCHECK2(*(tptr), 2);
ND_PRINT((ndo, "\n\t O: %d, RES: %d, MTID(s): %d",
(EXTRACT_16BITS(tptr) >> 15) & 0x01,
(EXTRACT_16BITS(tptr) >> 12) & 0x07,
EXTRACT_16BITS(tptr) & 0x0fff));
tmp = tmp-2;
tptr = tptr+2;
if (tmp)
isis_print_mt_capability_subtlv(ndo, tptr, tmp);
break;
case ISIS_TLV_TE_ROUTER_ID:
ND_TCHECK2(*pptr, sizeof(struct in_addr));
ND_PRINT((ndo, "\n\t Traffic Engineering Router ID: %s", ipaddr_string(ndo, pptr)));
break;
case ISIS_TLV_IPADDR:
while (tmp>=sizeof(struct in_addr)) {
ND_TCHECK2(*tptr, sizeof(struct in_addr));
ND_PRINT((ndo, "\n\t IPv4 interface address: %s", ipaddr_string(ndo, tptr)));
tptr += sizeof(struct in_addr);
tmp -= sizeof(struct in_addr);
}
break;
case ISIS_TLV_HOSTNAME:
ND_PRINT((ndo, "\n\t Hostname: "));
if (fn_printzp(ndo, tptr, tmp, ndo->ndo_snapend))
goto trunctlv;
break;
case ISIS_TLV_SHARED_RISK_GROUP:
if (tmp < NODE_ID_LEN)
break;
ND_TCHECK2(*tptr, NODE_ID_LEN);
ND_PRINT((ndo, "\n\t IS Neighbor: %s", isis_print_id(tptr, NODE_ID_LEN)));
tptr+=(NODE_ID_LEN);
tmp-=(NODE_ID_LEN);
if (tmp < 1)
break;
ND_TCHECK2(*tptr, 1);
ND_PRINT((ndo, ", Flags: [%s]", ISIS_MASK_TLV_SHARED_RISK_GROUP(*tptr++) ? "numbered" : "unnumbered"));
tmp--;
if (tmp < sizeof(struct in_addr))
break;
ND_TCHECK2(*tptr, sizeof(struct in_addr));
ND_PRINT((ndo, "\n\t IPv4 interface address: %s", ipaddr_string(ndo, tptr)));
tptr+=sizeof(struct in_addr);
tmp-=sizeof(struct in_addr);
if (tmp < sizeof(struct in_addr))
break;
ND_TCHECK2(*tptr, sizeof(struct in_addr));
ND_PRINT((ndo, "\n\t IPv4 neighbor address: %s", ipaddr_string(ndo, tptr)));
tptr+=sizeof(struct in_addr);
tmp-=sizeof(struct in_addr);
while (tmp>=4) {
ND_TCHECK2(*tptr, 4);
ND_PRINT((ndo, "\n\t Link-ID: 0x%08x", EXTRACT_32BITS(tptr)));
tptr+=4;
tmp-=4;
}
break;
case ISIS_TLV_LSP:
tlv_lsp = (const struct isis_tlv_lsp *)tptr;
while(tmp>=sizeof(struct isis_tlv_lsp)) {
ND_TCHECK((tlv_lsp->lsp_id)[LSP_ID_LEN-1]);
ND_PRINT((ndo, "\n\t lsp-id: %s",
isis_print_id(tlv_lsp->lsp_id, LSP_ID_LEN)));
ND_TCHECK2(tlv_lsp->sequence_number, 4);
ND_PRINT((ndo, ", seq: 0x%08x", EXTRACT_32BITS(tlv_lsp->sequence_number)));
ND_TCHECK2(tlv_lsp->remaining_lifetime, 2);
ND_PRINT((ndo, ", lifetime: %5ds", EXTRACT_16BITS(tlv_lsp->remaining_lifetime)));
ND_TCHECK2(tlv_lsp->checksum, 2);
ND_PRINT((ndo, ", chksum: 0x%04x", EXTRACT_16BITS(tlv_lsp->checksum)));
tmp-=sizeof(struct isis_tlv_lsp);
tlv_lsp++;
}
break;
case ISIS_TLV_CHECKSUM:
if (tmp < ISIS_TLV_CHECKSUM_MINLEN)
break;
ND_TCHECK2(*tptr, ISIS_TLV_CHECKSUM_MINLEN);
ND_PRINT((ndo, "\n\t checksum: 0x%04x ", EXTRACT_16BITS(tptr)));
/* do not attempt to verify the checksum if it is zero
* most likely a HMAC-MD5 TLV is also present and
* to avoid conflicts the checksum TLV is zeroed.
* see rfc3358 for details
*/
osi_print_cksum(ndo, optr, EXTRACT_16BITS(tptr), tptr-optr,
length);
break;
case ISIS_TLV_POI:
if (tlv_len >= SYSTEM_ID_LEN + 1) {
ND_TCHECK2(*tptr, SYSTEM_ID_LEN + 1);
ND_PRINT((ndo, "\n\t Purge Originator System-ID: %s",
isis_print_id(tptr + 1, SYSTEM_ID_LEN)));
}
if (tlv_len == 2 * SYSTEM_ID_LEN + 1) {
ND_TCHECK2(*tptr, 2 * SYSTEM_ID_LEN + 1);
ND_PRINT((ndo, "\n\t Received from System-ID: %s",
isis_print_id(tptr + SYSTEM_ID_LEN + 1, SYSTEM_ID_LEN)));
}
break;
case ISIS_TLV_MT_SUPPORTED:
if (tmp < ISIS_TLV_MT_SUPPORTED_MINLEN)
break;
while (tmp>1) {
/* length can only be a multiple of 2, otherwise there is
something broken -> so decode down until length is 1 */
if (tmp!=1) {
mt_len = isis_print_mtid(ndo, tptr, "\n\t ");
if (mt_len == 0) /* did something go wrong ? */
goto trunctlv;
tptr+=mt_len;
tmp-=mt_len;
} else {
ND_PRINT((ndo, "\n\t invalid MT-ID"));
break;
}
}
break;
case ISIS_TLV_RESTART_SIGNALING:
/* first attempt to decode the flags */
if (tmp < ISIS_TLV_RESTART_SIGNALING_FLAGLEN)
break;
ND_TCHECK2(*tptr, ISIS_TLV_RESTART_SIGNALING_FLAGLEN);
ND_PRINT((ndo, "\n\t Flags [%s]",
bittok2str(isis_restart_flag_values, "none", *tptr)));
tptr+=ISIS_TLV_RESTART_SIGNALING_FLAGLEN;
tmp-=ISIS_TLV_RESTART_SIGNALING_FLAGLEN;
/* is there anything other than the flags field? */
if (tmp == 0)
break;
if (tmp < ISIS_TLV_RESTART_SIGNALING_HOLDTIMELEN)
break;
ND_TCHECK2(*tptr, ISIS_TLV_RESTART_SIGNALING_HOLDTIMELEN);
ND_PRINT((ndo, ", Remaining holding time %us", EXTRACT_16BITS(tptr)));
tptr+=ISIS_TLV_RESTART_SIGNALING_HOLDTIMELEN;
tmp-=ISIS_TLV_RESTART_SIGNALING_HOLDTIMELEN;
/* is there an additional sysid field present ?*/
if (tmp == SYSTEM_ID_LEN) {
ND_TCHECK2(*tptr, SYSTEM_ID_LEN);
ND_PRINT((ndo, ", for %s", isis_print_id(tptr,SYSTEM_ID_LEN)));
}
break;
case ISIS_TLV_IDRP_INFO:
if (tmp < ISIS_TLV_IDRP_INFO_MINLEN)
break;
ND_TCHECK2(*tptr, ISIS_TLV_IDRP_INFO_MINLEN);
ND_PRINT((ndo, "\n\t Inter-Domain Information Type: %s",
tok2str(isis_subtlv_idrp_values,
"Unknown (0x%02x)",
*tptr)));
switch (*tptr++) {
case ISIS_SUBTLV_IDRP_ASN:
ND_TCHECK2(*tptr, 2); /* fetch AS number */
ND_PRINT((ndo, "AS Number: %u", EXTRACT_16BITS(tptr)));
break;
case ISIS_SUBTLV_IDRP_LOCAL:
case ISIS_SUBTLV_IDRP_RES:
default:
if (!print_unknown_data(ndo, tptr, "\n\t ", tlv_len - 1))
return(0);
break;
}
break;
case ISIS_TLV_LSP_BUFFERSIZE:
if (tmp < ISIS_TLV_LSP_BUFFERSIZE_MINLEN)
break;
ND_TCHECK2(*tptr, ISIS_TLV_LSP_BUFFERSIZE_MINLEN);
ND_PRINT((ndo, "\n\t LSP Buffersize: %u", EXTRACT_16BITS(tptr)));
break;
case ISIS_TLV_PART_DIS:
while (tmp >= SYSTEM_ID_LEN) {
ND_TCHECK2(*tptr, SYSTEM_ID_LEN);
ND_PRINT((ndo, "\n\t %s", isis_print_id(tptr, SYSTEM_ID_LEN)));
tptr+=SYSTEM_ID_LEN;
tmp-=SYSTEM_ID_LEN;
}
break;
case ISIS_TLV_PREFIX_NEIGH:
if (tmp < sizeof(struct isis_metric_block))
break;
ND_TCHECK2(*tptr, sizeof(struct isis_metric_block));
ND_PRINT((ndo, "\n\t Metric Block"));
isis_print_metric_block(ndo, (const struct isis_metric_block *)tptr);
tptr+=sizeof(struct isis_metric_block);
tmp-=sizeof(struct isis_metric_block);
while(tmp>0) {
ND_TCHECK2(*tptr, 1);
prefix_len=*tptr++; /* read out prefix length in semioctets*/
if (prefix_len < 2) {
ND_PRINT((ndo, "\n\t\tAddress: prefix length %u < 2", prefix_len));
break;
}
tmp--;
if (tmp < prefix_len/2)
break;
ND_TCHECK2(*tptr, prefix_len / 2);
ND_PRINT((ndo, "\n\t\tAddress: %s/%u",
isonsap_string(ndo, tptr, prefix_len / 2), prefix_len * 4));
tptr+=prefix_len/2;
tmp-=prefix_len/2;
}
break;
case ISIS_TLV_IIH_SEQNR:
if (tmp < ISIS_TLV_IIH_SEQNR_MINLEN)
break;
ND_TCHECK2(*tptr, ISIS_TLV_IIH_SEQNR_MINLEN); /* check if four bytes are on the wire */
ND_PRINT((ndo, "\n\t Sequence number: %u", EXTRACT_32BITS(tptr)));
break;
case ISIS_TLV_VENDOR_PRIVATE:
if (tmp < ISIS_TLV_VENDOR_PRIVATE_MINLEN)
break;
ND_TCHECK2(*tptr, ISIS_TLV_VENDOR_PRIVATE_MINLEN); /* check if enough byte for a full oui */
vendor_id = EXTRACT_24BITS(tptr);
ND_PRINT((ndo, "\n\t Vendor: %s (%u)",
tok2str(oui_values, "Unknown", vendor_id),
vendor_id));
tptr+=3;
tmp-=3;
if (tmp > 0) /* hexdump the rest */
if (!print_unknown_data(ndo, tptr, "\n\t\t", tmp))
return(0);
break;
/*
* FIXME those are the defined TLVs that lack a decoder
* you are welcome to contribute code ;-)
*/
case ISIS_TLV_DECNET_PHASE4:
case ISIS_TLV_LUCENT_PRIVATE:
case ISIS_TLV_IPAUTH:
case ISIS_TLV_NORTEL_PRIVATE1:
case ISIS_TLV_NORTEL_PRIVATE2:
default:
if (ndo->ndo_vflag <= 1) {
if (!print_unknown_data(ndo, pptr, "\n\t\t", tlv_len))
return(0);
}
break;
}
/* do we want to see an additionally hexdump ? */
if (ndo->ndo_vflag> 1) {
if (!print_unknown_data(ndo, pptr, "\n\t ", tlv_len))
return(0);
}
pptr += tlv_len;
packet_len -= tlv_len;
}
if (packet_len != 0) {
ND_PRINT((ndo, "\n\t %u straggler bytes", packet_len));
}
return (1);
trunc:
ND_PRINT((ndo, "%s", tstr));
return (1);
trunctlv:
ND_PRINT((ndo, "\n\t\t"));
ND_PRINT((ndo, "%s", tstr));
return(1);
}
static void
osi_print_cksum(netdissect_options *ndo, const uint8_t *pptr,
uint16_t checksum, int checksum_offset, u_int length)
{
uint16_t calculated_checksum;
/* do not attempt to verify the checksum if it is zero,
* if the offset is nonsense,
* or the base pointer is not sane
*/
if (!checksum
|| checksum_offset < 0
|| !ND_TTEST2(*(pptr + checksum_offset), 2)
|| (u_int)checksum_offset > length
|| !ND_TTEST2(*pptr, length)) {
ND_PRINT((ndo, " (unverified)"));
} else {
#if 0
printf("\nosi_print_cksum: %p %u %u\n", pptr, checksum_offset, length);
#endif
calculated_checksum = create_osi_cksum(pptr, checksum_offset, length);
if (checksum == calculated_checksum) {
ND_PRINT((ndo, " (correct)"));
} else {
ND_PRINT((ndo, " (incorrect should be 0x%04x)", calculated_checksum));
}
}
}
/*
* Local Variables:
* c-style: whitesmith
* c-basic-offset: 8
* End:
*/
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_2644_6 |
crossvul-cpp_data_good_263_0 | /*
* Copyright (c) 1998-2007 The TCPDUMP project
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that: (1) source code
* distributions retain the above copyright notice and this paragraph
* in its entirety, and (2) distributions including binary code include
* the above copyright notice and this paragraph in its entirety in
* the documentation or other materials provided with the distribution.
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND
* WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, WITHOUT
* LIMITATION, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE.
*
* Original code by Hannes Gredler (hannes@gredler.at)
*/
/* \summary: Resource ReSerVation Protocol (RSVP) printer */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <netdissect-stdinc.h>
#include "netdissect.h"
#include "extract.h"
#include "addrtoname.h"
#include "ethertype.h"
#include "gmpls.h"
#include "af.h"
#include "signature.h"
static const char tstr[] = " [|rsvp]";
/*
* RFC 2205 common header
*
* 0 1 2 3
* +-------------+-------------+-------------+-------------+
* | Vers | Flags| Msg Type | RSVP Checksum |
* +-------------+-------------+-------------+-------------+
* | Send_TTL | (Reserved) | RSVP Length |
* +-------------+-------------+-------------+-------------+
*
*/
struct rsvp_common_header {
uint8_t version_flags;
uint8_t msg_type;
uint8_t checksum[2];
uint8_t ttl;
uint8_t reserved;
uint8_t length[2];
};
/*
* RFC2205 object header
*
*
* 0 1 2 3
* +-------------+-------------+-------------+-------------+
* | Length (bytes) | Class-Num | C-Type |
* +-------------+-------------+-------------+-------------+
* | |
* // (Object contents) //
* | |
* +-------------+-------------+-------------+-------------+
*/
struct rsvp_object_header {
uint8_t length[2];
uint8_t class_num;
uint8_t ctype;
};
#define RSVP_VERSION 1
#define RSVP_EXTRACT_VERSION(x) (((x)&0xf0)>>4)
#define RSVP_EXTRACT_FLAGS(x) ((x)&0x0f)
#define RSVP_MSGTYPE_PATH 1
#define RSVP_MSGTYPE_RESV 2
#define RSVP_MSGTYPE_PATHERR 3
#define RSVP_MSGTYPE_RESVERR 4
#define RSVP_MSGTYPE_PATHTEAR 5
#define RSVP_MSGTYPE_RESVTEAR 6
#define RSVP_MSGTYPE_RESVCONF 7
#define RSVP_MSGTYPE_BUNDLE 12
#define RSVP_MSGTYPE_ACK 13
#define RSVP_MSGTYPE_HELLO_OLD 14 /* ancient Hellos */
#define RSVP_MSGTYPE_SREFRESH 15
#define RSVP_MSGTYPE_HELLO 20
static const struct tok rsvp_msg_type_values[] = {
{ RSVP_MSGTYPE_PATH, "Path" },
{ RSVP_MSGTYPE_RESV, "Resv" },
{ RSVP_MSGTYPE_PATHERR, "PathErr" },
{ RSVP_MSGTYPE_RESVERR, "ResvErr" },
{ RSVP_MSGTYPE_PATHTEAR, "PathTear" },
{ RSVP_MSGTYPE_RESVTEAR, "ResvTear" },
{ RSVP_MSGTYPE_RESVCONF, "ResvConf" },
{ RSVP_MSGTYPE_BUNDLE, "Bundle" },
{ RSVP_MSGTYPE_ACK, "Acknowledgement" },
{ RSVP_MSGTYPE_HELLO_OLD, "Hello (Old)" },
{ RSVP_MSGTYPE_SREFRESH, "Refresh" },
{ RSVP_MSGTYPE_HELLO, "Hello" },
{ 0, NULL}
};
static const struct tok rsvp_header_flag_values[] = {
{ 0x01, "Refresh reduction capable" }, /* rfc2961 */
{ 0, NULL}
};
#define RSVP_OBJ_SESSION 1 /* rfc2205 */
#define RSVP_OBJ_RSVP_HOP 3 /* rfc2205, rfc3473 */
#define RSVP_OBJ_INTEGRITY 4 /* rfc2747 */
#define RSVP_OBJ_TIME_VALUES 5 /* rfc2205 */
#define RSVP_OBJ_ERROR_SPEC 6
#define RSVP_OBJ_SCOPE 7
#define RSVP_OBJ_STYLE 8 /* rfc2205 */
#define RSVP_OBJ_FLOWSPEC 9 /* rfc2215 */
#define RSVP_OBJ_FILTERSPEC 10 /* rfc2215 */
#define RSVP_OBJ_SENDER_TEMPLATE 11
#define RSVP_OBJ_SENDER_TSPEC 12 /* rfc2215 */
#define RSVP_OBJ_ADSPEC 13 /* rfc2215 */
#define RSVP_OBJ_POLICY_DATA 14
#define RSVP_OBJ_CONFIRM 15 /* rfc2205 */
#define RSVP_OBJ_LABEL 16 /* rfc3209 */
#define RSVP_OBJ_LABEL_REQ 19 /* rfc3209 */
#define RSVP_OBJ_ERO 20 /* rfc3209 */
#define RSVP_OBJ_RRO 21 /* rfc3209 */
#define RSVP_OBJ_HELLO 22 /* rfc3209 */
#define RSVP_OBJ_MESSAGE_ID 23 /* rfc2961 */
#define RSVP_OBJ_MESSAGE_ID_ACK 24 /* rfc2961 */
#define RSVP_OBJ_MESSAGE_ID_LIST 25 /* rfc2961 */
#define RSVP_OBJ_RECOVERY_LABEL 34 /* rfc3473 */
#define RSVP_OBJ_UPSTREAM_LABEL 35 /* rfc3473 */
#define RSVP_OBJ_LABEL_SET 36 /* rfc3473 */
#define RSVP_OBJ_PROTECTION 37 /* rfc3473 */
#define RSVP_OBJ_S2L 50 /* rfc4875 */
#define RSVP_OBJ_DETOUR 63 /* draft-ietf-mpls-rsvp-lsp-fastreroute-07 */
#define RSVP_OBJ_CLASSTYPE 66 /* rfc4124 */
#define RSVP_OBJ_CLASSTYPE_OLD 125 /* draft-ietf-tewg-diff-te-proto-07 */
#define RSVP_OBJ_SUGGESTED_LABEL 129 /* rfc3473 */
#define RSVP_OBJ_ACCEPT_LABEL_SET 130 /* rfc3473 */
#define RSVP_OBJ_RESTART_CAPABILITY 131 /* rfc3473 */
#define RSVP_OBJ_NOTIFY_REQ 195 /* rfc3473 */
#define RSVP_OBJ_ADMIN_STATUS 196 /* rfc3473 */
#define RSVP_OBJ_PROPERTIES 204 /* juniper proprietary */
#define RSVP_OBJ_FASTREROUTE 205 /* draft-ietf-mpls-rsvp-lsp-fastreroute-07 */
#define RSVP_OBJ_SESSION_ATTRIBUTE 207 /* rfc3209 */
#define RSVP_OBJ_GENERALIZED_UNI 229 /* OIF RSVP extensions UNI 1.0 Signaling, Rel. 2 */
#define RSVP_OBJ_CALL_ID 230 /* rfc3474 */
#define RSVP_OBJ_CALL_OPS 236 /* rfc3474 */
static const struct tok rsvp_obj_values[] = {
{ RSVP_OBJ_SESSION, "Session" },
{ RSVP_OBJ_RSVP_HOP, "RSVP Hop" },
{ RSVP_OBJ_INTEGRITY, "Integrity" },
{ RSVP_OBJ_TIME_VALUES, "Time Values" },
{ RSVP_OBJ_ERROR_SPEC, "Error Spec" },
{ RSVP_OBJ_SCOPE, "Scope" },
{ RSVP_OBJ_STYLE, "Style" },
{ RSVP_OBJ_FLOWSPEC, "Flowspec" },
{ RSVP_OBJ_FILTERSPEC, "FilterSpec" },
{ RSVP_OBJ_SENDER_TEMPLATE, "Sender Template" },
{ RSVP_OBJ_SENDER_TSPEC, "Sender TSpec" },
{ RSVP_OBJ_ADSPEC, "Adspec" },
{ RSVP_OBJ_POLICY_DATA, "Policy Data" },
{ RSVP_OBJ_CONFIRM, "Confirm" },
{ RSVP_OBJ_LABEL, "Label" },
{ RSVP_OBJ_LABEL_REQ, "Label Request" },
{ RSVP_OBJ_ERO, "ERO" },
{ RSVP_OBJ_RRO, "RRO" },
{ RSVP_OBJ_HELLO, "Hello" },
{ RSVP_OBJ_MESSAGE_ID, "Message ID" },
{ RSVP_OBJ_MESSAGE_ID_ACK, "Message ID Ack" },
{ RSVP_OBJ_MESSAGE_ID_LIST, "Message ID List" },
{ RSVP_OBJ_RECOVERY_LABEL, "Recovery Label" },
{ RSVP_OBJ_UPSTREAM_LABEL, "Upstream Label" },
{ RSVP_OBJ_LABEL_SET, "Label Set" },
{ RSVP_OBJ_ACCEPT_LABEL_SET, "Acceptable Label Set" },
{ RSVP_OBJ_DETOUR, "Detour" },
{ RSVP_OBJ_CLASSTYPE, "Class Type" },
{ RSVP_OBJ_CLASSTYPE_OLD, "Class Type (old)" },
{ RSVP_OBJ_SUGGESTED_LABEL, "Suggested Label" },
{ RSVP_OBJ_PROPERTIES, "Properties" },
{ RSVP_OBJ_FASTREROUTE, "Fast Re-Route" },
{ RSVP_OBJ_SESSION_ATTRIBUTE, "Session Attribute" },
{ RSVP_OBJ_GENERALIZED_UNI, "Generalized UNI" },
{ RSVP_OBJ_CALL_ID, "Call-ID" },
{ RSVP_OBJ_CALL_OPS, "Call Capability" },
{ RSVP_OBJ_RESTART_CAPABILITY, "Restart Capability" },
{ RSVP_OBJ_NOTIFY_REQ, "Notify Request" },
{ RSVP_OBJ_PROTECTION, "Protection" },
{ RSVP_OBJ_ADMIN_STATUS, "Administrative Status" },
{ RSVP_OBJ_S2L, "Sub-LSP to LSP" },
{ 0, NULL}
};
#define RSVP_CTYPE_IPV4 1
#define RSVP_CTYPE_IPV6 2
#define RSVP_CTYPE_TUNNEL_IPV4 7
#define RSVP_CTYPE_TUNNEL_IPV6 8
#define RSVP_CTYPE_UNI_IPV4 11 /* OIF RSVP extensions UNI 1.0 Signaling Rel. 2 */
#define RSVP_CTYPE_1 1
#define RSVP_CTYPE_2 2
#define RSVP_CTYPE_3 3
#define RSVP_CTYPE_4 4
#define RSVP_CTYPE_12 12
#define RSVP_CTYPE_13 13
#define RSVP_CTYPE_14 14
/*
* the ctypes are not globally unique so for
* translating it to strings we build a table based
* on objects offsetted by the ctype
*/
static const struct tok rsvp_ctype_values[] = {
{ 256*RSVP_OBJ_RSVP_HOP+RSVP_CTYPE_IPV4, "IPv4" },
{ 256*RSVP_OBJ_RSVP_HOP+RSVP_CTYPE_IPV6, "IPv6" },
{ 256*RSVP_OBJ_RSVP_HOP+RSVP_CTYPE_3, "IPv4 plus opt. TLVs" },
{ 256*RSVP_OBJ_RSVP_HOP+RSVP_CTYPE_4, "IPv6 plus opt. TLVs" },
{ 256*RSVP_OBJ_NOTIFY_REQ+RSVP_CTYPE_IPV4, "IPv4" },
{ 256*RSVP_OBJ_NOTIFY_REQ+RSVP_CTYPE_IPV6, "IPv6" },
{ 256*RSVP_OBJ_CONFIRM+RSVP_CTYPE_IPV4, "IPv4" },
{ 256*RSVP_OBJ_CONFIRM+RSVP_CTYPE_IPV6, "IPv6" },
{ 256*RSVP_OBJ_TIME_VALUES+RSVP_CTYPE_1, "1" },
{ 256*RSVP_OBJ_FLOWSPEC+RSVP_CTYPE_1, "obsolete" },
{ 256*RSVP_OBJ_FLOWSPEC+RSVP_CTYPE_2, "IntServ" },
{ 256*RSVP_OBJ_SENDER_TSPEC+RSVP_CTYPE_2, "IntServ" },
{ 256*RSVP_OBJ_ADSPEC+RSVP_CTYPE_2, "IntServ" },
{ 256*RSVP_OBJ_FILTERSPEC+RSVP_CTYPE_IPV4, "IPv4" },
{ 256*RSVP_OBJ_FILTERSPEC+RSVP_CTYPE_IPV6, "IPv6" },
{ 256*RSVP_OBJ_FILTERSPEC+RSVP_CTYPE_3, "IPv6 Flow-label" },
{ 256*RSVP_OBJ_FILTERSPEC+RSVP_CTYPE_TUNNEL_IPV4, "Tunnel IPv4" },
{ 256*RSVP_OBJ_FILTERSPEC+RSVP_CTYPE_12, "IPv4 P2MP LSP Tunnel" },
{ 256*RSVP_OBJ_FILTERSPEC+RSVP_CTYPE_13, "IPv6 P2MP LSP Tunnel" },
{ 256*RSVP_OBJ_SESSION+RSVP_CTYPE_IPV4, "IPv4" },
{ 256*RSVP_OBJ_SESSION+RSVP_CTYPE_IPV6, "IPv6" },
{ 256*RSVP_OBJ_SESSION+RSVP_CTYPE_TUNNEL_IPV4, "Tunnel IPv4" },
{ 256*RSVP_OBJ_SESSION+RSVP_CTYPE_UNI_IPV4, "UNI IPv4" },
{ 256*RSVP_OBJ_SESSION+RSVP_CTYPE_13, "IPv4 P2MP LSP Tunnel" },
{ 256*RSVP_OBJ_SESSION+RSVP_CTYPE_14, "IPv6 P2MP LSP Tunnel" },
{ 256*RSVP_OBJ_SENDER_TEMPLATE+RSVP_CTYPE_IPV4, "IPv4" },
{ 256*RSVP_OBJ_SENDER_TEMPLATE+RSVP_CTYPE_IPV6, "IPv6" },
{ 256*RSVP_OBJ_SENDER_TEMPLATE+RSVP_CTYPE_TUNNEL_IPV4, "Tunnel IPv4" },
{ 256*RSVP_OBJ_SENDER_TEMPLATE+RSVP_CTYPE_12, "IPv4 P2MP LSP Tunnel" },
{ 256*RSVP_OBJ_SENDER_TEMPLATE+RSVP_CTYPE_13, "IPv6 P2MP LSP Tunnel" },
{ 256*RSVP_OBJ_MESSAGE_ID+RSVP_CTYPE_1, "1" },
{ 256*RSVP_OBJ_MESSAGE_ID_ACK+RSVP_CTYPE_1, "Message id ack" },
{ 256*RSVP_OBJ_MESSAGE_ID_ACK+RSVP_CTYPE_2, "Message id nack" },
{ 256*RSVP_OBJ_MESSAGE_ID_LIST+RSVP_CTYPE_1, "1" },
{ 256*RSVP_OBJ_STYLE+RSVP_CTYPE_1, "1" },
{ 256*RSVP_OBJ_HELLO+RSVP_CTYPE_1, "Hello Request" },
{ 256*RSVP_OBJ_HELLO+RSVP_CTYPE_2, "Hello Ack" },
{ 256*RSVP_OBJ_LABEL_REQ+RSVP_CTYPE_1, "without label range" },
{ 256*RSVP_OBJ_LABEL_REQ+RSVP_CTYPE_2, "with ATM label range" },
{ 256*RSVP_OBJ_LABEL_REQ+RSVP_CTYPE_3, "with FR label range" },
{ 256*RSVP_OBJ_LABEL_REQ+RSVP_CTYPE_4, "Generalized Label" },
{ 256*RSVP_OBJ_LABEL+RSVP_CTYPE_1, "Label" },
{ 256*RSVP_OBJ_LABEL+RSVP_CTYPE_2, "Generalized Label" },
{ 256*RSVP_OBJ_LABEL+RSVP_CTYPE_3, "Waveband Switching" },
{ 256*RSVP_OBJ_SUGGESTED_LABEL+RSVP_CTYPE_1, "Label" },
{ 256*RSVP_OBJ_SUGGESTED_LABEL+RSVP_CTYPE_2, "Generalized Label" },
{ 256*RSVP_OBJ_SUGGESTED_LABEL+RSVP_CTYPE_3, "Waveband Switching" },
{ 256*RSVP_OBJ_UPSTREAM_LABEL+RSVP_CTYPE_1, "Label" },
{ 256*RSVP_OBJ_UPSTREAM_LABEL+RSVP_CTYPE_2, "Generalized Label" },
{ 256*RSVP_OBJ_UPSTREAM_LABEL+RSVP_CTYPE_3, "Waveband Switching" },
{ 256*RSVP_OBJ_RECOVERY_LABEL+RSVP_CTYPE_1, "Label" },
{ 256*RSVP_OBJ_RECOVERY_LABEL+RSVP_CTYPE_2, "Generalized Label" },
{ 256*RSVP_OBJ_RECOVERY_LABEL+RSVP_CTYPE_3, "Waveband Switching" },
{ 256*RSVP_OBJ_ERO+RSVP_CTYPE_IPV4, "IPv4" },
{ 256*RSVP_OBJ_RRO+RSVP_CTYPE_IPV4, "IPv4" },
{ 256*RSVP_OBJ_ERROR_SPEC+RSVP_CTYPE_IPV4, "IPv4" },
{ 256*RSVP_OBJ_ERROR_SPEC+RSVP_CTYPE_IPV6, "IPv6" },
{ 256*RSVP_OBJ_ERROR_SPEC+RSVP_CTYPE_3, "IPv4 plus opt. TLVs" },
{ 256*RSVP_OBJ_ERROR_SPEC+RSVP_CTYPE_4, "IPv6 plus opt. TLVs" },
{ 256*RSVP_OBJ_RESTART_CAPABILITY+RSVP_CTYPE_1, "IPv4" },
{ 256*RSVP_OBJ_SESSION_ATTRIBUTE+RSVP_CTYPE_TUNNEL_IPV4, "Tunnel IPv4" },
{ 256*RSVP_OBJ_FASTREROUTE+RSVP_CTYPE_TUNNEL_IPV4, "Tunnel IPv4" }, /* old style*/
{ 256*RSVP_OBJ_FASTREROUTE+RSVP_CTYPE_1, "1" }, /* new style */
{ 256*RSVP_OBJ_DETOUR+RSVP_CTYPE_TUNNEL_IPV4, "Tunnel IPv4" },
{ 256*RSVP_OBJ_PROPERTIES+RSVP_CTYPE_1, "1" },
{ 256*RSVP_OBJ_ADMIN_STATUS+RSVP_CTYPE_1, "1" },
{ 256*RSVP_OBJ_CLASSTYPE+RSVP_CTYPE_1, "1" },
{ 256*RSVP_OBJ_CLASSTYPE_OLD+RSVP_CTYPE_1, "1" },
{ 256*RSVP_OBJ_LABEL_SET+RSVP_CTYPE_1, "1" },
{ 256*RSVP_OBJ_GENERALIZED_UNI+RSVP_CTYPE_1, "1" },
{ 256*RSVP_OBJ_S2L+RSVP_CTYPE_IPV4, "IPv4 sub-LSP" },
{ 256*RSVP_OBJ_S2L+RSVP_CTYPE_IPV6, "IPv6 sub-LSP" },
{ 0, NULL}
};
struct rsvp_obj_integrity_t {
uint8_t flags;
uint8_t res;
uint8_t key_id[6];
uint8_t sequence[8];
uint8_t digest[16];
};
static const struct tok rsvp_obj_integrity_flag_values[] = {
{ 0x80, "Handshake" },
{ 0, NULL}
};
struct rsvp_obj_frr_t {
uint8_t setup_prio;
uint8_t hold_prio;
uint8_t hop_limit;
uint8_t flags;
uint8_t bandwidth[4];
uint8_t include_any[4];
uint8_t exclude_any[4];
uint8_t include_all[4];
};
#define RSVP_OBJ_XRO_MASK_SUBOBJ(x) ((x)&0x7f)
#define RSVP_OBJ_XRO_MASK_LOOSE(x) ((x)&0x80)
#define RSVP_OBJ_XRO_RES 0
#define RSVP_OBJ_XRO_IPV4 1
#define RSVP_OBJ_XRO_IPV6 2
#define RSVP_OBJ_XRO_LABEL 3
#define RSVP_OBJ_XRO_ASN 32
#define RSVP_OBJ_XRO_MPLS 64
static const struct tok rsvp_obj_xro_values[] = {
{ RSVP_OBJ_XRO_RES, "Reserved" },
{ RSVP_OBJ_XRO_IPV4, "IPv4 prefix" },
{ RSVP_OBJ_XRO_IPV6, "IPv6 prefix" },
{ RSVP_OBJ_XRO_LABEL, "Label" },
{ RSVP_OBJ_XRO_ASN, "Autonomous system number" },
{ RSVP_OBJ_XRO_MPLS, "MPLS label switched path termination" },
{ 0, NULL}
};
/* draft-ietf-mpls-rsvp-lsp-fastreroute-07.txt */
static const struct tok rsvp_obj_rro_flag_values[] = {
{ 0x01, "Local protection available" },
{ 0x02, "Local protection in use" },
{ 0x04, "Bandwidth protection" },
{ 0x08, "Node protection" },
{ 0, NULL}
};
/* RFC3209 */
static const struct tok rsvp_obj_rro_label_flag_values[] = {
{ 0x01, "Global" },
{ 0, NULL}
};
static const struct tok rsvp_resstyle_values[] = {
{ 17, "Wildcard Filter" },
{ 10, "Fixed Filter" },
{ 18, "Shared Explicit" },
{ 0, NULL}
};
#define RSVP_OBJ_INTSERV_GUARANTEED_SERV 2
#define RSVP_OBJ_INTSERV_CONTROLLED_LOAD 5
static const struct tok rsvp_intserv_service_type_values[] = {
{ 1, "Default/Global Information" },
{ RSVP_OBJ_INTSERV_GUARANTEED_SERV, "Guaranteed Service" },
{ RSVP_OBJ_INTSERV_CONTROLLED_LOAD, "Controlled Load" },
{ 0, NULL}
};
static const struct tok rsvp_intserv_parameter_id_values[] = {
{ 4, "IS hop cnt" },
{ 6, "Path b/w estimate" },
{ 8, "Minimum path latency" },
{ 10, "Composed MTU" },
{ 127, "Token Bucket TSpec" },
{ 130, "Guaranteed Service RSpec" },
{ 133, "End-to-end composed value for C" },
{ 134, "End-to-end composed value for D" },
{ 135, "Since-last-reshaping point composed C" },
{ 136, "Since-last-reshaping point composed D" },
{ 0, NULL}
};
static const struct tok rsvp_session_attribute_flag_values[] = {
{ 0x01, "Local Protection" },
{ 0x02, "Label Recording" },
{ 0x04, "SE Style" },
{ 0x08, "Bandwidth protection" }, /* RFC4090 */
{ 0x10, "Node protection" }, /* RFC4090 */
{ 0, NULL}
};
static const struct tok rsvp_obj_prop_tlv_values[] = {
{ 0x01, "Cos" },
{ 0x02, "Metric 1" },
{ 0x04, "Metric 2" },
{ 0x08, "CCC Status" },
{ 0x10, "Path Type" },
{ 0, NULL}
};
#define RSVP_OBJ_ERROR_SPEC_CODE_ROUTING 24
#define RSVP_OBJ_ERROR_SPEC_CODE_NOTIFY 25
#define RSVP_OBJ_ERROR_SPEC_CODE_DIFFSERV_TE 28
#define RSVP_OBJ_ERROR_SPEC_CODE_DIFFSERV_TE_OLD 125
static const struct tok rsvp_obj_error_code_values[] = {
{ RSVP_OBJ_ERROR_SPEC_CODE_ROUTING, "Routing Problem" },
{ RSVP_OBJ_ERROR_SPEC_CODE_NOTIFY, "Notify Error" },
{ RSVP_OBJ_ERROR_SPEC_CODE_DIFFSERV_TE, "Diffserv TE Error" },
{ RSVP_OBJ_ERROR_SPEC_CODE_DIFFSERV_TE_OLD, "Diffserv TE Error (Old)" },
{ 0, NULL}
};
static const struct tok rsvp_obj_error_code_routing_values[] = {
{ 1, "Bad EXPLICIT_ROUTE object" },
{ 2, "Bad strict node" },
{ 3, "Bad loose node" },
{ 4, "Bad initial subobject" },
{ 5, "No route available toward destination" },
{ 6, "Unacceptable label value" },
{ 7, "RRO indicated routing loops" },
{ 8, "non-RSVP-capable router in the path" },
{ 9, "MPLS label allocation failure" },
{ 10, "Unsupported L3PID" },
{ 0, NULL}
};
static const struct tok rsvp_obj_error_code_diffserv_te_values[] = {
{ 1, "Unexpected CT object" },
{ 2, "Unsupported CT" },
{ 3, "Invalid CT value" },
{ 4, "CT/setup priority do not form a configured TE-Class" },
{ 5, "CT/holding priority do not form a configured TE-Class" },
{ 6, "CT/setup priority and CT/holding priority do not form a configured TE-Class" },
{ 7, "Inconsistency between signaled PSC and signaled CT" },
{ 8, "Inconsistency between signaled PHBs and signaled CT" },
{ 0, NULL}
};
/* rfc3473 / rfc 3471 */
static const struct tok rsvp_obj_admin_status_flag_values[] = {
{ 0x80000000, "Reflect" },
{ 0x00000004, "Testing" },
{ 0x00000002, "Admin-down" },
{ 0x00000001, "Delete-in-progress" },
{ 0, NULL}
};
/* label set actions - rfc3471 */
#define LABEL_SET_INCLUSIVE_LIST 0
#define LABEL_SET_EXCLUSIVE_LIST 1
#define LABEL_SET_INCLUSIVE_RANGE 2
#define LABEL_SET_EXCLUSIVE_RANGE 3
static const struct tok rsvp_obj_label_set_action_values[] = {
{ LABEL_SET_INCLUSIVE_LIST, "Inclusive list" },
{ LABEL_SET_EXCLUSIVE_LIST, "Exclusive list" },
{ LABEL_SET_INCLUSIVE_RANGE, "Inclusive range" },
{ LABEL_SET_EXCLUSIVE_RANGE, "Exclusive range" },
{ 0, NULL}
};
/* OIF RSVP extensions UNI 1.0 Signaling, release 2 */
#define RSVP_GEN_UNI_SUBOBJ_SOURCE_TNA_ADDRESS 1
#define RSVP_GEN_UNI_SUBOBJ_DESTINATION_TNA_ADDRESS 2
#define RSVP_GEN_UNI_SUBOBJ_DIVERSITY 3
#define RSVP_GEN_UNI_SUBOBJ_EGRESS_LABEL 4
#define RSVP_GEN_UNI_SUBOBJ_SERVICE_LEVEL 5
static const struct tok rsvp_obj_generalized_uni_values[] = {
{ RSVP_GEN_UNI_SUBOBJ_SOURCE_TNA_ADDRESS, "Source TNA address" },
{ RSVP_GEN_UNI_SUBOBJ_DESTINATION_TNA_ADDRESS, "Destination TNA address" },
{ RSVP_GEN_UNI_SUBOBJ_DIVERSITY, "Diversity" },
{ RSVP_GEN_UNI_SUBOBJ_EGRESS_LABEL, "Egress label" },
{ RSVP_GEN_UNI_SUBOBJ_SERVICE_LEVEL, "Service level" },
{ 0, NULL}
};
/*
* this is a dissector for all the intserv defined
* specs as defined per rfc2215
* it is called from various rsvp objects;
* returns the amount of bytes being processed
*/
static int
rsvp_intserv_print(netdissect_options *ndo,
const u_char *tptr, u_short obj_tlen)
{
int parameter_id,parameter_length;
union {
float f;
uint32_t i;
} bw;
if (obj_tlen < 4)
return 0;
ND_TCHECK_8BITS(tptr);
parameter_id = *(tptr);
ND_TCHECK2(*(tptr + 2), 2);
parameter_length = EXTRACT_16BITS(tptr+2)<<2; /* convert wordcount to bytecount */
ND_PRINT((ndo, "\n\t Parameter ID: %s (%u), length: %u, Flags: [0x%02x]",
tok2str(rsvp_intserv_parameter_id_values,"unknown",parameter_id),
parameter_id,
parameter_length,
*(tptr + 1)));
if (obj_tlen < parameter_length+4)
return 0;
switch(parameter_id) { /* parameter_id */
case 4:
/*
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | 4 (e) | (f) | 1 (g) |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | IS hop cnt (32-bit unsigned integer) |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*/
if (parameter_length == 4) {
ND_TCHECK2(*(tptr + 4), 4);
ND_PRINT((ndo, "\n\t\tIS hop count: %u", EXTRACT_32BITS(tptr + 4)));
}
break;
case 6:
/*
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | 6 (h) | (i) | 1 (j) |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Path b/w estimate (32-bit IEEE floating point number) |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*/
if (parameter_length == 4) {
ND_TCHECK2(*(tptr + 4), 4);
bw.i = EXTRACT_32BITS(tptr+4);
ND_PRINT((ndo, "\n\t\tPath b/w estimate: %.10g Mbps", bw.f / 125000));
}
break;
case 8:
/*
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | 8 (k) | (l) | 1 (m) |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Minimum path latency (32-bit integer) |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*/
if (parameter_length == 4) {
ND_TCHECK2(*(tptr + 4), 4);
ND_PRINT((ndo, "\n\t\tMinimum path latency: "));
if (EXTRACT_32BITS(tptr+4) == 0xffffffff)
ND_PRINT((ndo, "don't care"));
else
ND_PRINT((ndo, "%u", EXTRACT_32BITS(tptr + 4)));
}
break;
case 10:
/*
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | 10 (n) | (o) | 1 (p) |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Composed MTU (32-bit unsigned integer) |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*/
if (parameter_length == 4) {
ND_TCHECK2(*(tptr + 4), 4);
ND_PRINT((ndo, "\n\t\tComposed MTU: %u bytes", EXTRACT_32BITS(tptr + 4)));
}
break;
case 127:
/*
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | 127 (e) | 0 (f) | 5 (g) |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Token Bucket Rate [r] (32-bit IEEE floating point number) |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Token Bucket Size [b] (32-bit IEEE floating point number) |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Peak Data Rate [p] (32-bit IEEE floating point number) |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Minimum Policed Unit [m] (32-bit integer) |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Maximum Packet Size [M] (32-bit integer) |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*/
if (parameter_length == 20) {
ND_TCHECK2(*(tptr + 4), 20);
bw.i = EXTRACT_32BITS(tptr+4);
ND_PRINT((ndo, "\n\t\tToken Bucket Rate: %.10g Mbps", bw.f / 125000));
bw.i = EXTRACT_32BITS(tptr+8);
ND_PRINT((ndo, "\n\t\tToken Bucket Size: %.10g bytes", bw.f));
bw.i = EXTRACT_32BITS(tptr+12);
ND_PRINT((ndo, "\n\t\tPeak Data Rate: %.10g Mbps", bw.f / 125000));
ND_PRINT((ndo, "\n\t\tMinimum Policed Unit: %u bytes", EXTRACT_32BITS(tptr + 16)));
ND_PRINT((ndo, "\n\t\tMaximum Packet Size: %u bytes", EXTRACT_32BITS(tptr + 20)));
}
break;
case 130:
/*
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | 130 (h) | 0 (i) | 2 (j) |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Rate [R] (32-bit IEEE floating point number) |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Slack Term [S] (32-bit integer) |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*/
if (parameter_length == 8) {
ND_TCHECK2(*(tptr + 4), 8);
bw.i = EXTRACT_32BITS(tptr+4);
ND_PRINT((ndo, "\n\t\tRate: %.10g Mbps", bw.f / 125000));
ND_PRINT((ndo, "\n\t\tSlack Term: %u", EXTRACT_32BITS(tptr + 8)));
}
break;
case 133:
case 134:
case 135:
case 136:
if (parameter_length == 4) {
ND_TCHECK2(*(tptr + 4), 4);
ND_PRINT((ndo, "\n\t\tValue: %u", EXTRACT_32BITS(tptr + 4)));
}
break;
default:
if (ndo->ndo_vflag <= 1)
print_unknown_data(ndo, tptr + 4, "\n\t\t", parameter_length);
}
return (parameter_length+4); /* header length 4 bytes */
trunc:
ND_PRINT((ndo, "%s", tstr));
return 0;
}
/*
* Clear checksum prior to signature verification.
*/
static void
rsvp_clear_checksum(void *header)
{
struct rsvp_common_header *rsvp_com_header = (struct rsvp_common_header *) header;
rsvp_com_header->checksum[0] = 0;
rsvp_com_header->checksum[1] = 0;
}
static int
rsvp_obj_print(netdissect_options *ndo,
const u_char *pptr, u_int plen, const u_char *tptr,
const char *ident, u_int tlen,
const struct rsvp_common_header *rsvp_com_header)
{
const struct rsvp_object_header *rsvp_obj_header;
const u_char *obj_tptr;
union {
const struct rsvp_obj_integrity_t *rsvp_obj_integrity;
const struct rsvp_obj_frr_t *rsvp_obj_frr;
} obj_ptr;
u_short rsvp_obj_len,rsvp_obj_ctype,obj_tlen,intserv_serv_tlen;
int hexdump,processed,padbytes,error_code,error_value,i,sigcheck;
union {
float f;
uint32_t i;
} bw;
uint8_t namelen;
u_int action, subchannel;
while(tlen>=sizeof(struct rsvp_object_header)) {
/* did we capture enough for fully decoding the object header ? */
ND_TCHECK2(*tptr, sizeof(struct rsvp_object_header));
rsvp_obj_header = (const struct rsvp_object_header *)tptr;
rsvp_obj_len=EXTRACT_16BITS(rsvp_obj_header->length);
rsvp_obj_ctype=rsvp_obj_header->ctype;
if(rsvp_obj_len % 4) {
ND_PRINT((ndo, "%sERROR: object header size %u not a multiple of 4", ident, rsvp_obj_len));
return -1;
}
if(rsvp_obj_len < sizeof(struct rsvp_object_header)) {
ND_PRINT((ndo, "%sERROR: object header too short %u < %lu", ident, rsvp_obj_len,
(unsigned long)sizeof(const struct rsvp_object_header)));
return -1;
}
ND_PRINT((ndo, "%s%s Object (%u) Flags: [%s",
ident,
tok2str(rsvp_obj_values,
"Unknown",
rsvp_obj_header->class_num),
rsvp_obj_header->class_num,
((rsvp_obj_header->class_num) & 0x80) ? "ignore" : "reject"));
if (rsvp_obj_header->class_num > 128)
ND_PRINT((ndo, " %s",
((rsvp_obj_header->class_num) & 0x40) ? "and forward" : "silently"));
ND_PRINT((ndo, " if unknown], Class-Type: %s (%u), length: %u",
tok2str(rsvp_ctype_values,
"Unknown",
((rsvp_obj_header->class_num)<<8)+rsvp_obj_ctype),
rsvp_obj_ctype,
rsvp_obj_len));
if(tlen < rsvp_obj_len) {
ND_PRINT((ndo, "%sERROR: object goes past end of objects TLV", ident));
return -1;
}
obj_tptr=tptr+sizeof(struct rsvp_object_header);
obj_tlen=rsvp_obj_len-sizeof(struct rsvp_object_header);
/* did we capture enough for fully decoding the object ? */
if (!ND_TTEST2(*tptr, rsvp_obj_len))
return -1;
hexdump=FALSE;
switch(rsvp_obj_header->class_num) {
case RSVP_OBJ_SESSION:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_IPV4:
if (obj_tlen < 8)
return -1;
ND_PRINT((ndo, "%s IPv4 DestAddress: %s, Protocol ID: 0x%02x",
ident,
ipaddr_string(ndo, obj_tptr),
*(obj_tptr + sizeof(struct in_addr))));
ND_PRINT((ndo, "%s Flags: [0x%02x], DestPort %u",
ident,
*(obj_tptr+5),
EXTRACT_16BITS(obj_tptr + 6)));
obj_tlen-=8;
obj_tptr+=8;
break;
case RSVP_CTYPE_IPV6:
if (obj_tlen < 20)
return -1;
ND_PRINT((ndo, "%s IPv6 DestAddress: %s, Protocol ID: 0x%02x",
ident,
ip6addr_string(ndo, obj_tptr),
*(obj_tptr + sizeof(struct in6_addr))));
ND_PRINT((ndo, "%s Flags: [0x%02x], DestPort %u",
ident,
*(obj_tptr+sizeof(struct in6_addr)+1),
EXTRACT_16BITS(obj_tptr + sizeof(struct in6_addr) + 2)));
obj_tlen-=20;
obj_tptr+=20;
break;
case RSVP_CTYPE_TUNNEL_IPV6:
if (obj_tlen < 36)
return -1;
ND_PRINT((ndo, "%s IPv6 Tunnel EndPoint: %s, Tunnel ID: 0x%04x, Extended Tunnel ID: %s",
ident,
ip6addr_string(ndo, obj_tptr),
EXTRACT_16BITS(obj_tptr+18),
ip6addr_string(ndo, obj_tptr + 20)));
obj_tlen-=36;
obj_tptr+=36;
break;
case RSVP_CTYPE_14: /* IPv6 p2mp LSP Tunnel */
if (obj_tlen < 26)
return -1;
ND_PRINT((ndo, "%s IPv6 P2MP LSP ID: 0x%08x, Tunnel ID: 0x%04x, Extended Tunnel ID: %s",
ident,
EXTRACT_32BITS(obj_tptr),
EXTRACT_16BITS(obj_tptr+6),
ip6addr_string(ndo, obj_tptr + 8)));
obj_tlen-=26;
obj_tptr+=26;
break;
case RSVP_CTYPE_13: /* IPv4 p2mp LSP Tunnel */
if (obj_tlen < 12)
return -1;
ND_PRINT((ndo, "%s IPv4 P2MP LSP ID: %s, Tunnel ID: 0x%04x, Extended Tunnel ID: %s",
ident,
ipaddr_string(ndo, obj_tptr),
EXTRACT_16BITS(obj_tptr+6),
ipaddr_string(ndo, obj_tptr + 8)));
obj_tlen-=12;
obj_tptr+=12;
break;
case RSVP_CTYPE_TUNNEL_IPV4:
case RSVP_CTYPE_UNI_IPV4:
if (obj_tlen < 12)
return -1;
ND_PRINT((ndo, "%s IPv4 Tunnel EndPoint: %s, Tunnel ID: 0x%04x, Extended Tunnel ID: %s",
ident,
ipaddr_string(ndo, obj_tptr),
EXTRACT_16BITS(obj_tptr+6),
ipaddr_string(ndo, obj_tptr + 8)));
obj_tlen-=12;
obj_tptr+=12;
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_CONFIRM:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_IPV4:
if (obj_tlen < sizeof(struct in_addr))
return -1;
ND_PRINT((ndo, "%s IPv4 Receiver Address: %s",
ident,
ipaddr_string(ndo, obj_tptr)));
obj_tlen-=sizeof(struct in_addr);
obj_tptr+=sizeof(struct in_addr);
break;
case RSVP_CTYPE_IPV6:
if (obj_tlen < sizeof(struct in6_addr))
return -1;
ND_PRINT((ndo, "%s IPv6 Receiver Address: %s",
ident,
ip6addr_string(ndo, obj_tptr)));
obj_tlen-=sizeof(struct in6_addr);
obj_tptr+=sizeof(struct in6_addr);
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_NOTIFY_REQ:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_IPV4:
if (obj_tlen < sizeof(struct in_addr))
return -1;
ND_PRINT((ndo, "%s IPv4 Notify Node Address: %s",
ident,
ipaddr_string(ndo, obj_tptr)));
obj_tlen-=sizeof(struct in_addr);
obj_tptr+=sizeof(struct in_addr);
break;
case RSVP_CTYPE_IPV6:
if (obj_tlen < sizeof(struct in6_addr))
return-1;
ND_PRINT((ndo, "%s IPv6 Notify Node Address: %s",
ident,
ip6addr_string(ndo, obj_tptr)));
obj_tlen-=sizeof(struct in6_addr);
obj_tptr+=sizeof(struct in6_addr);
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_SUGGESTED_LABEL: /* fall through */
case RSVP_OBJ_UPSTREAM_LABEL: /* fall through */
case RSVP_OBJ_RECOVERY_LABEL: /* fall through */
case RSVP_OBJ_LABEL:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_1:
while(obj_tlen >= 4 ) {
ND_PRINT((ndo, "%s Label: %u", ident, EXTRACT_32BITS(obj_tptr)));
obj_tlen-=4;
obj_tptr+=4;
}
break;
case RSVP_CTYPE_2:
if (obj_tlen < 4)
return-1;
ND_PRINT((ndo, "%s Generalized Label: %u",
ident,
EXTRACT_32BITS(obj_tptr)));
obj_tlen-=4;
obj_tptr+=4;
break;
case RSVP_CTYPE_3:
if (obj_tlen < 12)
return-1;
ND_PRINT((ndo, "%s Waveband ID: %u%s Start Label: %u, Stop Label: %u",
ident,
EXTRACT_32BITS(obj_tptr),
ident,
EXTRACT_32BITS(obj_tptr+4),
EXTRACT_32BITS(obj_tptr + 8)));
obj_tlen-=12;
obj_tptr+=12;
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_STYLE:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_1:
if (obj_tlen < 4)
return-1;
ND_PRINT((ndo, "%s Reservation Style: %s, Flags: [0x%02x]",
ident,
tok2str(rsvp_resstyle_values,
"Unknown",
EXTRACT_24BITS(obj_tptr+1)),
*(obj_tptr)));
obj_tlen-=4;
obj_tptr+=4;
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_SENDER_TEMPLATE:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_IPV4:
if (obj_tlen < 8)
return-1;
ND_PRINT((ndo, "%s Source Address: %s, Source Port: %u",
ident,
ipaddr_string(ndo, obj_tptr),
EXTRACT_16BITS(obj_tptr + 6)));
obj_tlen-=8;
obj_tptr+=8;
break;
case RSVP_CTYPE_IPV6:
if (obj_tlen < 20)
return-1;
ND_PRINT((ndo, "%s Source Address: %s, Source Port: %u",
ident,
ip6addr_string(ndo, obj_tptr),
EXTRACT_16BITS(obj_tptr + 18)));
obj_tlen-=20;
obj_tptr+=20;
break;
case RSVP_CTYPE_13: /* IPv6 p2mp LSP tunnel */
if (obj_tlen < 40)
return-1;
ND_PRINT((ndo, "%s IPv6 Tunnel Sender Address: %s, LSP ID: 0x%04x"
"%s Sub-Group Originator ID: %s, Sub-Group ID: 0x%04x",
ident,
ip6addr_string(ndo, obj_tptr),
EXTRACT_16BITS(obj_tptr+18),
ident,
ip6addr_string(ndo, obj_tptr+20),
EXTRACT_16BITS(obj_tptr + 38)));
obj_tlen-=40;
obj_tptr+=40;
break;
case RSVP_CTYPE_TUNNEL_IPV4:
if (obj_tlen < 8)
return-1;
ND_PRINT((ndo, "%s IPv4 Tunnel Sender Address: %s, LSP-ID: 0x%04x",
ident,
ipaddr_string(ndo, obj_tptr),
EXTRACT_16BITS(obj_tptr + 6)));
obj_tlen-=8;
obj_tptr+=8;
break;
case RSVP_CTYPE_12: /* IPv4 p2mp LSP tunnel */
if (obj_tlen < 16)
return-1;
ND_PRINT((ndo, "%s IPv4 Tunnel Sender Address: %s, LSP ID: 0x%04x"
"%s Sub-Group Originator ID: %s, Sub-Group ID: 0x%04x",
ident,
ipaddr_string(ndo, obj_tptr),
EXTRACT_16BITS(obj_tptr+6),
ident,
ipaddr_string(ndo, obj_tptr+8),
EXTRACT_16BITS(obj_tptr + 12)));
obj_tlen-=16;
obj_tptr+=16;
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_LABEL_REQ:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_1:
while(obj_tlen >= 4 ) {
ND_PRINT((ndo, "%s L3 Protocol ID: %s",
ident,
tok2str(ethertype_values,
"Unknown Protocol (0x%04x)",
EXTRACT_16BITS(obj_tptr + 2))));
obj_tlen-=4;
obj_tptr+=4;
}
break;
case RSVP_CTYPE_2:
if (obj_tlen < 12)
return-1;
ND_PRINT((ndo, "%s L3 Protocol ID: %s",
ident,
tok2str(ethertype_values,
"Unknown Protocol (0x%04x)",
EXTRACT_16BITS(obj_tptr + 2))));
ND_PRINT((ndo, ",%s merge capability",((*(obj_tptr + 4)) & 0x80) ? "no" : "" ));
ND_PRINT((ndo, "%s Minimum VPI/VCI: %u/%u",
ident,
(EXTRACT_16BITS(obj_tptr+4))&0xfff,
(EXTRACT_16BITS(obj_tptr + 6)) & 0xfff));
ND_PRINT((ndo, "%s Maximum VPI/VCI: %u/%u",
ident,
(EXTRACT_16BITS(obj_tptr+8))&0xfff,
(EXTRACT_16BITS(obj_tptr + 10)) & 0xfff));
obj_tlen-=12;
obj_tptr+=12;
break;
case RSVP_CTYPE_3:
if (obj_tlen < 12)
return-1;
ND_PRINT((ndo, "%s L3 Protocol ID: %s",
ident,
tok2str(ethertype_values,
"Unknown Protocol (0x%04x)",
EXTRACT_16BITS(obj_tptr + 2))));
ND_PRINT((ndo, "%s Minimum/Maximum DLCI: %u/%u, %s%s bit DLCI",
ident,
(EXTRACT_32BITS(obj_tptr+4))&0x7fffff,
(EXTRACT_32BITS(obj_tptr+8))&0x7fffff,
(((EXTRACT_16BITS(obj_tptr+4)>>7)&3) == 0 ) ? "10" : "",
(((EXTRACT_16BITS(obj_tptr + 4) >> 7) & 3) == 2 ) ? "23" : ""));
obj_tlen-=12;
obj_tptr+=12;
break;
case RSVP_CTYPE_4:
if (obj_tlen < 4)
return-1;
ND_PRINT((ndo, "%s LSP Encoding Type: %s (%u)",
ident,
tok2str(gmpls_encoding_values,
"Unknown",
*obj_tptr),
*obj_tptr));
ND_PRINT((ndo, "%s Switching Type: %s (%u), Payload ID: %s (0x%04x)",
ident,
tok2str(gmpls_switch_cap_values,
"Unknown",
*(obj_tptr+1)),
*(obj_tptr+1),
tok2str(gmpls_payload_values,
"Unknown",
EXTRACT_16BITS(obj_tptr+2)),
EXTRACT_16BITS(obj_tptr + 2)));
obj_tlen-=4;
obj_tptr+=4;
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_RRO:
case RSVP_OBJ_ERO:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_IPV4:
while(obj_tlen >= 4 ) {
u_char length;
ND_TCHECK2(*obj_tptr, 4);
length = *(obj_tptr + 1);
ND_PRINT((ndo, "%s Subobject Type: %s, length %u",
ident,
tok2str(rsvp_obj_xro_values,
"Unknown %u",
RSVP_OBJ_XRO_MASK_SUBOBJ(*obj_tptr)),
length));
if (length == 0) { /* prevent infinite loops */
ND_PRINT((ndo, "%s ERROR: zero length ERO subtype", ident));
break;
}
switch(RSVP_OBJ_XRO_MASK_SUBOBJ(*obj_tptr)) {
u_char prefix_length;
case RSVP_OBJ_XRO_IPV4:
if (length != 8) {
ND_PRINT((ndo, " ERROR: length != 8"));
goto invalid;
}
ND_TCHECK2(*obj_tptr, 8);
prefix_length = *(obj_tptr+6);
if (prefix_length != 32) {
ND_PRINT((ndo, " ERROR: Prefix length %u != 32",
prefix_length));
goto invalid;
}
ND_PRINT((ndo, ", %s, %s/%u, Flags: [%s]",
RSVP_OBJ_XRO_MASK_LOOSE(*obj_tptr) ? "Loose" : "Strict",
ipaddr_string(ndo, obj_tptr+2),
*(obj_tptr+6),
bittok2str(rsvp_obj_rro_flag_values,
"none",
*(obj_tptr + 7)))); /* rfc3209 says that this field is rsvd. */
break;
case RSVP_OBJ_XRO_LABEL:
if (length != 8) {
ND_PRINT((ndo, " ERROR: length != 8"));
goto invalid;
}
ND_TCHECK2(*obj_tptr, 8);
ND_PRINT((ndo, ", Flags: [%s] (%#x), Class-Type: %s (%u), %u",
bittok2str(rsvp_obj_rro_label_flag_values,
"none",
*(obj_tptr+2)),
*(obj_tptr+2),
tok2str(rsvp_ctype_values,
"Unknown",
*(obj_tptr+3) + 256*RSVP_OBJ_RRO),
*(obj_tptr+3),
EXTRACT_32BITS(obj_tptr + 4)));
}
obj_tlen-=*(obj_tptr+1);
obj_tptr+=*(obj_tptr+1);
}
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_HELLO:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_1:
case RSVP_CTYPE_2:
if (obj_tlen < 8)
return-1;
ND_PRINT((ndo, "%s Source Instance: 0x%08x, Destination Instance: 0x%08x",
ident,
EXTRACT_32BITS(obj_tptr),
EXTRACT_32BITS(obj_tptr + 4)));
obj_tlen-=8;
obj_tptr+=8;
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_RESTART_CAPABILITY:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_1:
if (obj_tlen < 8)
return-1;
ND_PRINT((ndo, "%s Restart Time: %ums, Recovery Time: %ums",
ident,
EXTRACT_32BITS(obj_tptr),
EXTRACT_32BITS(obj_tptr + 4)));
obj_tlen-=8;
obj_tptr+=8;
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_SESSION_ATTRIBUTE:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_TUNNEL_IPV4:
if (obj_tlen < 4)
return-1;
namelen = *(obj_tptr+3);
if (obj_tlen < 4+namelen)
return-1;
ND_PRINT((ndo, "%s Session Name: ", ident));
for (i = 0; i < namelen; i++)
safeputchar(ndo, *(obj_tptr + 4 + i));
ND_PRINT((ndo, "%s Setup Priority: %u, Holding Priority: %u, Flags: [%s] (%#x)",
ident,
(int)*obj_tptr,
(int)*(obj_tptr+1),
bittok2str(rsvp_session_attribute_flag_values,
"none",
*(obj_tptr+2)),
*(obj_tptr + 2)));
obj_tlen-=4+*(obj_tptr+3);
obj_tptr+=4+*(obj_tptr+3);
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_GENERALIZED_UNI:
switch(rsvp_obj_ctype) {
int subobj_type,af,subobj_len,total_subobj_len;
case RSVP_CTYPE_1:
if (obj_tlen < 4)
return-1;
/* read variable length subobjects */
total_subobj_len = obj_tlen;
while(total_subobj_len > 0) {
/* If RFC 3476 Section 3.1 defined that a sub-object of the
* GENERALIZED_UNI RSVP object must have the Length field as
* a multiple of 4, instead of the check below it would be
* better to test total_subobj_len only once before the loop.
* So long as it does not define it and this while loop does
* not implement such a requirement, let's accept that within
* each iteration subobj_len may happen to be a multiple of 1
* and test it and total_subobj_len respectively.
*/
if (total_subobj_len < 4)
goto invalid;
subobj_len = EXTRACT_16BITS(obj_tptr);
subobj_type = (EXTRACT_16BITS(obj_tptr+2))>>8;
af = (EXTRACT_16BITS(obj_tptr+2))&0x00FF;
ND_PRINT((ndo, "%s Subobject Type: %s (%u), AF: %s (%u), length: %u",
ident,
tok2str(rsvp_obj_generalized_uni_values, "Unknown", subobj_type),
subobj_type,
tok2str(af_values, "Unknown", af), af,
subobj_len));
/* In addition to what is explained above, the same spec does not
* explicitly say that the same Length field includes the 4-octet
* sub-object header, but as long as this while loop implements it
* as it does include, let's keep the check below consistent with
* the rest of the code.
*/
if(subobj_len < 4 || subobj_len > total_subobj_len)
goto invalid;
switch(subobj_type) {
case RSVP_GEN_UNI_SUBOBJ_SOURCE_TNA_ADDRESS:
case RSVP_GEN_UNI_SUBOBJ_DESTINATION_TNA_ADDRESS:
switch(af) {
case AFNUM_INET:
if (subobj_len < 8)
return -1;
ND_PRINT((ndo, "%s UNI IPv4 TNA address: %s",
ident, ipaddr_string(ndo, obj_tptr + 4)));
break;
case AFNUM_INET6:
if (subobj_len < 20)
return -1;
ND_PRINT((ndo, "%s UNI IPv6 TNA address: %s",
ident, ip6addr_string(ndo, obj_tptr + 4)));
break;
case AFNUM_NSAP:
if (subobj_len) {
/* unless we have a TLV parser lets just hexdump */
hexdump=TRUE;
}
break;
}
break;
case RSVP_GEN_UNI_SUBOBJ_DIVERSITY:
if (subobj_len) {
/* unless we have a TLV parser lets just hexdump */
hexdump=TRUE;
}
break;
case RSVP_GEN_UNI_SUBOBJ_EGRESS_LABEL:
if (subobj_len < 16) {
return -1;
}
ND_PRINT((ndo, "%s U-bit: %x, Label type: %u, Logical port id: %u, Label: %u",
ident,
((EXTRACT_32BITS(obj_tptr+4))>>31),
((EXTRACT_32BITS(obj_tptr+4))&0xFF),
EXTRACT_32BITS(obj_tptr+8),
EXTRACT_32BITS(obj_tptr + 12)));
break;
case RSVP_GEN_UNI_SUBOBJ_SERVICE_LEVEL:
if (subobj_len < 8) {
return -1;
}
ND_PRINT((ndo, "%s Service level: %u",
ident, (EXTRACT_32BITS(obj_tptr + 4)) >> 24));
break;
default:
hexdump=TRUE;
break;
}
total_subobj_len-=subobj_len;
obj_tptr+=subobj_len;
obj_tlen+=subobj_len;
}
if (total_subobj_len) {
/* unless we have a TLV parser lets just hexdump */
hexdump=TRUE;
}
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_RSVP_HOP:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_3: /* fall through - FIXME add TLV parser */
case RSVP_CTYPE_IPV4:
if (obj_tlen < 8)
return-1;
ND_PRINT((ndo, "%s Previous/Next Interface: %s, Logical Interface Handle: 0x%08x",
ident,
ipaddr_string(ndo, obj_tptr),
EXTRACT_32BITS(obj_tptr + 4)));
obj_tlen-=8;
obj_tptr+=8;
if (obj_tlen)
hexdump=TRUE; /* unless we have a TLV parser lets just hexdump */
break;
case RSVP_CTYPE_4: /* fall through - FIXME add TLV parser */
case RSVP_CTYPE_IPV6:
if (obj_tlen < 20)
return-1;
ND_PRINT((ndo, "%s Previous/Next Interface: %s, Logical Interface Handle: 0x%08x",
ident,
ip6addr_string(ndo, obj_tptr),
EXTRACT_32BITS(obj_tptr + 16)));
obj_tlen-=20;
obj_tptr+=20;
hexdump=TRUE; /* unless we have a TLV parser lets just hexdump */
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_TIME_VALUES:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_1:
if (obj_tlen < 4)
return-1;
ND_PRINT((ndo, "%s Refresh Period: %ums",
ident,
EXTRACT_32BITS(obj_tptr)));
obj_tlen-=4;
obj_tptr+=4;
break;
default:
hexdump=TRUE;
}
break;
/* those three objects do share the same semantics */
case RSVP_OBJ_SENDER_TSPEC:
case RSVP_OBJ_ADSPEC:
case RSVP_OBJ_FLOWSPEC:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_2:
if (obj_tlen < 4)
return-1;
ND_PRINT((ndo, "%s Msg-Version: %u, length: %u",
ident,
(*obj_tptr & 0xf0) >> 4,
EXTRACT_16BITS(obj_tptr + 2) << 2));
obj_tptr+=4; /* get to the start of the service header */
obj_tlen-=4;
while (obj_tlen >= 4) {
intserv_serv_tlen=EXTRACT_16BITS(obj_tptr+2)<<2;
ND_PRINT((ndo, "%s Service Type: %s (%u), break bit %s set, Service length: %u",
ident,
tok2str(rsvp_intserv_service_type_values,"unknown",*(obj_tptr)),
*(obj_tptr),
(*(obj_tptr+1)&0x80) ? "" : "not",
intserv_serv_tlen));
obj_tptr+=4; /* get to the start of the parameter list */
obj_tlen-=4;
while (intserv_serv_tlen>=4) {
processed = rsvp_intserv_print(ndo, obj_tptr, obj_tlen);
if (processed == 0)
break;
obj_tlen-=processed;
intserv_serv_tlen-=processed;
obj_tptr+=processed;
}
}
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_FILTERSPEC:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_IPV4:
if (obj_tlen < 8)
return-1;
ND_PRINT((ndo, "%s Source Address: %s, Source Port: %u",
ident,
ipaddr_string(ndo, obj_tptr),
EXTRACT_16BITS(obj_tptr + 6)));
obj_tlen-=8;
obj_tptr+=8;
break;
case RSVP_CTYPE_IPV6:
if (obj_tlen < 20)
return-1;
ND_PRINT((ndo, "%s Source Address: %s, Source Port: %u",
ident,
ip6addr_string(ndo, obj_tptr),
EXTRACT_16BITS(obj_tptr + 18)));
obj_tlen-=20;
obj_tptr+=20;
break;
case RSVP_CTYPE_3:
if (obj_tlen < 20)
return-1;
ND_PRINT((ndo, "%s Source Address: %s, Flow Label: %u",
ident,
ip6addr_string(ndo, obj_tptr),
EXTRACT_24BITS(obj_tptr + 17)));
obj_tlen-=20;
obj_tptr+=20;
break;
case RSVP_CTYPE_TUNNEL_IPV6:
if (obj_tlen < 20)
return-1;
ND_PRINT((ndo, "%s Source Address: %s, LSP-ID: 0x%04x",
ident,
ipaddr_string(ndo, obj_tptr),
EXTRACT_16BITS(obj_tptr + 18)));
obj_tlen-=20;
obj_tptr+=20;
break;
case RSVP_CTYPE_13: /* IPv6 p2mp LSP tunnel */
if (obj_tlen < 40)
return-1;
ND_PRINT((ndo, "%s IPv6 Tunnel Sender Address: %s, LSP ID: 0x%04x"
"%s Sub-Group Originator ID: %s, Sub-Group ID: 0x%04x",
ident,
ip6addr_string(ndo, obj_tptr),
EXTRACT_16BITS(obj_tptr+18),
ident,
ip6addr_string(ndo, obj_tptr+20),
EXTRACT_16BITS(obj_tptr + 38)));
obj_tlen-=40;
obj_tptr+=40;
break;
case RSVP_CTYPE_TUNNEL_IPV4:
if (obj_tlen < 8)
return-1;
ND_PRINT((ndo, "%s Source Address: %s, LSP-ID: 0x%04x",
ident,
ipaddr_string(ndo, obj_tptr),
EXTRACT_16BITS(obj_tptr + 6)));
obj_tlen-=8;
obj_tptr+=8;
break;
case RSVP_CTYPE_12: /* IPv4 p2mp LSP tunnel */
if (obj_tlen < 16)
return-1;
ND_PRINT((ndo, "%s IPv4 Tunnel Sender Address: %s, LSP ID: 0x%04x"
"%s Sub-Group Originator ID: %s, Sub-Group ID: 0x%04x",
ident,
ipaddr_string(ndo, obj_tptr),
EXTRACT_16BITS(obj_tptr+6),
ident,
ipaddr_string(ndo, obj_tptr+8),
EXTRACT_16BITS(obj_tptr + 12)));
obj_tlen-=16;
obj_tptr+=16;
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_FASTREROUTE:
/* the differences between c-type 1 and 7 are minor */
obj_ptr.rsvp_obj_frr = (const struct rsvp_obj_frr_t *)obj_tptr;
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_1: /* new style */
if (obj_tlen < sizeof(struct rsvp_obj_frr_t))
return-1;
bw.i = EXTRACT_32BITS(obj_ptr.rsvp_obj_frr->bandwidth);
ND_PRINT((ndo, "%s Setup Priority: %u, Holding Priority: %u, Hop-limit: %u, Bandwidth: %.10g Mbps",
ident,
(int)obj_ptr.rsvp_obj_frr->setup_prio,
(int)obj_ptr.rsvp_obj_frr->hold_prio,
(int)obj_ptr.rsvp_obj_frr->hop_limit,
bw.f * 8 / 1000000));
ND_PRINT((ndo, "%s Include-any: 0x%08x, Exclude-any: 0x%08x, Include-all: 0x%08x",
ident,
EXTRACT_32BITS(obj_ptr.rsvp_obj_frr->include_any),
EXTRACT_32BITS(obj_ptr.rsvp_obj_frr->exclude_any),
EXTRACT_32BITS(obj_ptr.rsvp_obj_frr->include_all)));
obj_tlen-=sizeof(struct rsvp_obj_frr_t);
obj_tptr+=sizeof(struct rsvp_obj_frr_t);
break;
case RSVP_CTYPE_TUNNEL_IPV4: /* old style */
if (obj_tlen < 16)
return-1;
bw.i = EXTRACT_32BITS(obj_ptr.rsvp_obj_frr->bandwidth);
ND_PRINT((ndo, "%s Setup Priority: %u, Holding Priority: %u, Hop-limit: %u, Bandwidth: %.10g Mbps",
ident,
(int)obj_ptr.rsvp_obj_frr->setup_prio,
(int)obj_ptr.rsvp_obj_frr->hold_prio,
(int)obj_ptr.rsvp_obj_frr->hop_limit,
bw.f * 8 / 1000000));
ND_PRINT((ndo, "%s Include Colors: 0x%08x, Exclude Colors: 0x%08x",
ident,
EXTRACT_32BITS(obj_ptr.rsvp_obj_frr->include_any),
EXTRACT_32BITS(obj_ptr.rsvp_obj_frr->exclude_any)));
obj_tlen-=16;
obj_tptr+=16;
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_DETOUR:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_TUNNEL_IPV4:
while(obj_tlen >= 8) {
ND_PRINT((ndo, "%s PLR-ID: %s, Avoid-Node-ID: %s",
ident,
ipaddr_string(ndo, obj_tptr),
ipaddr_string(ndo, obj_tptr + 4)));
obj_tlen-=8;
obj_tptr+=8;
}
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_CLASSTYPE:
case RSVP_OBJ_CLASSTYPE_OLD: /* fall through */
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_1:
ND_TCHECK_32BITS(obj_tptr);
ND_PRINT((ndo, "%s CT: %u",
ident,
EXTRACT_32BITS(obj_tptr) & 0x7));
obj_tlen-=4;
obj_tptr+=4;
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_ERROR_SPEC:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_3: /* fall through - FIXME add TLV parser */
case RSVP_CTYPE_IPV4:
if (obj_tlen < 8)
return-1;
error_code=*(obj_tptr+5);
error_value=EXTRACT_16BITS(obj_tptr+6);
ND_PRINT((ndo, "%s Error Node Address: %s, Flags: [0x%02x]%s Error Code: %s (%u)",
ident,
ipaddr_string(ndo, obj_tptr),
*(obj_tptr+4),
ident,
tok2str(rsvp_obj_error_code_values,"unknown",error_code),
error_code));
switch (error_code) {
case RSVP_OBJ_ERROR_SPEC_CODE_ROUTING:
ND_PRINT((ndo, ", Error Value: %s (%u)",
tok2str(rsvp_obj_error_code_routing_values,"unknown",error_value),
error_value));
break;
case RSVP_OBJ_ERROR_SPEC_CODE_DIFFSERV_TE: /* fall through */
case RSVP_OBJ_ERROR_SPEC_CODE_DIFFSERV_TE_OLD:
ND_PRINT((ndo, ", Error Value: %s (%u)",
tok2str(rsvp_obj_error_code_diffserv_te_values,"unknown",error_value),
error_value));
break;
default:
ND_PRINT((ndo, ", Unknown Error Value (%u)", error_value));
break;
}
obj_tlen-=8;
obj_tptr+=8;
break;
case RSVP_CTYPE_4: /* fall through - FIXME add TLV parser */
case RSVP_CTYPE_IPV6:
if (obj_tlen < 20)
return-1;
error_code=*(obj_tptr+17);
error_value=EXTRACT_16BITS(obj_tptr+18);
ND_PRINT((ndo, "%s Error Node Address: %s, Flags: [0x%02x]%s Error Code: %s (%u)",
ident,
ip6addr_string(ndo, obj_tptr),
*(obj_tptr+16),
ident,
tok2str(rsvp_obj_error_code_values,"unknown",error_code),
error_code));
switch (error_code) {
case RSVP_OBJ_ERROR_SPEC_CODE_ROUTING:
ND_PRINT((ndo, ", Error Value: %s (%u)",
tok2str(rsvp_obj_error_code_routing_values,"unknown",error_value),
error_value));
break;
default:
break;
}
obj_tlen-=20;
obj_tptr+=20;
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_PROPERTIES:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_1:
if (obj_tlen < 4)
return-1;
padbytes = EXTRACT_16BITS(obj_tptr+2);
ND_PRINT((ndo, "%s TLV count: %u, padding bytes: %u",
ident,
EXTRACT_16BITS(obj_tptr),
padbytes));
obj_tlen-=4;
obj_tptr+=4;
/* loop through as long there is anything longer than the TLV header (2) */
while(obj_tlen >= 2 + padbytes) {
ND_PRINT((ndo, "%s %s TLV (0x%02x), length: %u", /* length includes header */
ident,
tok2str(rsvp_obj_prop_tlv_values,"unknown",*obj_tptr),
*obj_tptr,
*(obj_tptr + 1)));
if (obj_tlen < *(obj_tptr+1))
return-1;
if (*(obj_tptr+1) < 2)
return -1;
print_unknown_data(ndo, obj_tptr + 2, "\n\t\t", *(obj_tptr + 1) - 2);
obj_tlen-=*(obj_tptr+1);
obj_tptr+=*(obj_tptr+1);
}
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_MESSAGE_ID: /* fall through */
case RSVP_OBJ_MESSAGE_ID_ACK: /* fall through */
case RSVP_OBJ_MESSAGE_ID_LIST:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_1:
case RSVP_CTYPE_2:
if (obj_tlen < 8)
return-1;
ND_PRINT((ndo, "%s Flags [0x%02x], epoch: %u",
ident,
*obj_tptr,
EXTRACT_24BITS(obj_tptr + 1)));
obj_tlen-=4;
obj_tptr+=4;
/* loop through as long there are no messages left */
while(obj_tlen >= 4) {
ND_PRINT((ndo, "%s Message-ID 0x%08x (%u)",
ident,
EXTRACT_32BITS(obj_tptr),
EXTRACT_32BITS(obj_tptr)));
obj_tlen-=4;
obj_tptr+=4;
}
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_INTEGRITY:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_1:
if (obj_tlen < sizeof(struct rsvp_obj_integrity_t))
return-1;
obj_ptr.rsvp_obj_integrity = (const struct rsvp_obj_integrity_t *)obj_tptr;
ND_PRINT((ndo, "%s Key-ID 0x%04x%08x, Sequence 0x%08x%08x, Flags [%s]",
ident,
EXTRACT_16BITS(obj_ptr.rsvp_obj_integrity->key_id),
EXTRACT_32BITS(obj_ptr.rsvp_obj_integrity->key_id+2),
EXTRACT_32BITS(obj_ptr.rsvp_obj_integrity->sequence),
EXTRACT_32BITS(obj_ptr.rsvp_obj_integrity->sequence+4),
bittok2str(rsvp_obj_integrity_flag_values,
"none",
obj_ptr.rsvp_obj_integrity->flags)));
ND_PRINT((ndo, "%s MD5-sum 0x%08x%08x%08x%08x ",
ident,
EXTRACT_32BITS(obj_ptr.rsvp_obj_integrity->digest),
EXTRACT_32BITS(obj_ptr.rsvp_obj_integrity->digest+4),
EXTRACT_32BITS(obj_ptr.rsvp_obj_integrity->digest+8),
EXTRACT_32BITS(obj_ptr.rsvp_obj_integrity->digest + 12)));
sigcheck = signature_verify(ndo, pptr, plen,
obj_ptr.rsvp_obj_integrity->digest,
rsvp_clear_checksum,
rsvp_com_header);
ND_PRINT((ndo, " (%s)", tok2str(signature_check_values, "Unknown", sigcheck)));
obj_tlen+=sizeof(struct rsvp_obj_integrity_t);
obj_tptr+=sizeof(struct rsvp_obj_integrity_t);
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_ADMIN_STATUS:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_1:
if (obj_tlen < 4)
return-1;
ND_PRINT((ndo, "%s Flags [%s]", ident,
bittok2str(rsvp_obj_admin_status_flag_values, "none",
EXTRACT_32BITS(obj_tptr))));
obj_tlen-=4;
obj_tptr+=4;
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_LABEL_SET:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_1:
if (obj_tlen < 4)
return-1;
action = (EXTRACT_16BITS(obj_tptr)>>8);
ND_PRINT((ndo, "%s Action: %s (%u), Label type: %u", ident,
tok2str(rsvp_obj_label_set_action_values, "Unknown", action),
action, ((EXTRACT_32BITS(obj_tptr) & 0x7F))));
switch (action) {
case LABEL_SET_INCLUSIVE_RANGE:
case LABEL_SET_EXCLUSIVE_RANGE: /* fall through */
/* only a couple of subchannels are expected */
if (obj_tlen < 12)
return -1;
ND_PRINT((ndo, "%s Start range: %u, End range: %u", ident,
EXTRACT_32BITS(obj_tptr+4),
EXTRACT_32BITS(obj_tptr + 8)));
obj_tlen-=12;
obj_tptr+=12;
break;
default:
obj_tlen-=4;
obj_tptr+=4;
subchannel = 1;
while(obj_tlen >= 4 ) {
ND_PRINT((ndo, "%s Subchannel #%u: %u", ident, subchannel,
EXTRACT_32BITS(obj_tptr)));
obj_tptr+=4;
obj_tlen-=4;
subchannel++;
}
break;
}
break;
default:
hexdump=TRUE;
}
case RSVP_OBJ_S2L:
switch (rsvp_obj_ctype) {
case RSVP_CTYPE_IPV4:
if (obj_tlen < 4)
return-1;
ND_PRINT((ndo, "%s Sub-LSP destination address: %s",
ident, ipaddr_string(ndo, obj_tptr)));
obj_tlen-=4;
obj_tptr+=4;
break;
case RSVP_CTYPE_IPV6:
if (obj_tlen < 16)
return-1;
ND_PRINT((ndo, "%s Sub-LSP destination address: %s",
ident, ip6addr_string(ndo, obj_tptr)));
obj_tlen-=16;
obj_tptr+=16;
break;
default:
hexdump=TRUE;
}
/*
* FIXME those are the defined objects that lack a decoder
* you are welcome to contribute code ;-)
*/
case RSVP_OBJ_SCOPE:
case RSVP_OBJ_POLICY_DATA:
case RSVP_OBJ_ACCEPT_LABEL_SET:
case RSVP_OBJ_PROTECTION:
default:
if (ndo->ndo_vflag <= 1)
print_unknown_data(ndo, obj_tptr, "\n\t ", obj_tlen); /* FIXME indentation */
break;
}
/* do we also want to see a hex dump ? */
if (ndo->ndo_vflag > 1 || hexdump == TRUE)
print_unknown_data(ndo, tptr + sizeof(struct rsvp_object_header), "\n\t ", /* FIXME indentation */
rsvp_obj_len - sizeof(struct rsvp_object_header));
tptr+=rsvp_obj_len;
tlen-=rsvp_obj_len;
}
return 0;
invalid:
ND_PRINT((ndo, "%s", istr));
return -1;
trunc:
ND_PRINT((ndo, "\n\t\t"));
ND_PRINT((ndo, "%s", tstr));
return -1;
}
void
rsvp_print(netdissect_options *ndo,
register const u_char *pptr, register u_int len)
{
const struct rsvp_common_header *rsvp_com_header;
const u_char *tptr;
u_short plen, tlen;
tptr=pptr;
rsvp_com_header = (const struct rsvp_common_header *)pptr;
ND_TCHECK(*rsvp_com_header);
/*
* Sanity checking of the header.
*/
if (RSVP_EXTRACT_VERSION(rsvp_com_header->version_flags) != RSVP_VERSION) {
ND_PRINT((ndo, "ERROR: RSVP version %u packet not supported",
RSVP_EXTRACT_VERSION(rsvp_com_header->version_flags)));
return;
}
/* in non-verbose mode just lets print the basic Message Type*/
if (ndo->ndo_vflag < 1) {
ND_PRINT((ndo, "RSVPv%u %s Message, length: %u",
RSVP_EXTRACT_VERSION(rsvp_com_header->version_flags),
tok2str(rsvp_msg_type_values, "unknown (%u)",rsvp_com_header->msg_type),
len));
return;
}
/* ok they seem to want to know everything - lets fully decode it */
plen = tlen = EXTRACT_16BITS(rsvp_com_header->length);
ND_PRINT((ndo, "\n\tRSVPv%u %s Message (%u), Flags: [%s], length: %u, ttl: %u, checksum: 0x%04x",
RSVP_EXTRACT_VERSION(rsvp_com_header->version_flags),
tok2str(rsvp_msg_type_values, "unknown, type: %u",rsvp_com_header->msg_type),
rsvp_com_header->msg_type,
bittok2str(rsvp_header_flag_values,"none",RSVP_EXTRACT_FLAGS(rsvp_com_header->version_flags)),
tlen,
rsvp_com_header->ttl,
EXTRACT_16BITS(rsvp_com_header->checksum)));
if (tlen < sizeof(const struct rsvp_common_header)) {
ND_PRINT((ndo, "ERROR: common header too short %u < %lu", tlen,
(unsigned long)sizeof(const struct rsvp_common_header)));
return;
}
tptr+=sizeof(const struct rsvp_common_header);
tlen-=sizeof(const struct rsvp_common_header);
switch(rsvp_com_header->msg_type) {
case RSVP_MSGTYPE_BUNDLE:
/*
* Process each submessage in the bundle message.
* Bundle messages may not contain bundle submessages, so we don't
* need to handle bundle submessages specially.
*/
while(tlen > 0) {
const u_char *subpptr=tptr, *subtptr;
u_short subplen, subtlen;
subtptr=subpptr;
rsvp_com_header = (const struct rsvp_common_header *)subpptr;
ND_TCHECK(*rsvp_com_header);
/*
* Sanity checking of the header.
*/
if (RSVP_EXTRACT_VERSION(rsvp_com_header->version_flags) != RSVP_VERSION) {
ND_PRINT((ndo, "ERROR: RSVP version %u packet not supported",
RSVP_EXTRACT_VERSION(rsvp_com_header->version_flags)));
return;
}
subplen = subtlen = EXTRACT_16BITS(rsvp_com_header->length);
ND_PRINT((ndo, "\n\t RSVPv%u %s Message (%u), Flags: [%s], length: %u, ttl: %u, checksum: 0x%04x",
RSVP_EXTRACT_VERSION(rsvp_com_header->version_flags),
tok2str(rsvp_msg_type_values, "unknown, type: %u",rsvp_com_header->msg_type),
rsvp_com_header->msg_type,
bittok2str(rsvp_header_flag_values,"none",RSVP_EXTRACT_FLAGS(rsvp_com_header->version_flags)),
subtlen,
rsvp_com_header->ttl,
EXTRACT_16BITS(rsvp_com_header->checksum)));
if (subtlen < sizeof(const struct rsvp_common_header)) {
ND_PRINT((ndo, "ERROR: common header too short %u < %lu", subtlen,
(unsigned long)sizeof(const struct rsvp_common_header)));
return;
}
if (tlen < subtlen) {
ND_PRINT((ndo, "ERROR: common header too large %u > %u", subtlen,
tlen));
return;
}
subtptr+=sizeof(const struct rsvp_common_header);
subtlen-=sizeof(const struct rsvp_common_header);
/*
* Print all objects in the submessage.
*/
if (rsvp_obj_print(ndo, subpptr, subplen, subtptr, "\n\t ", subtlen, rsvp_com_header) == -1)
return;
tptr+=subtlen+sizeof(const struct rsvp_common_header);
tlen-=subtlen+sizeof(const struct rsvp_common_header);
}
break;
case RSVP_MSGTYPE_PATH:
case RSVP_MSGTYPE_RESV:
case RSVP_MSGTYPE_PATHERR:
case RSVP_MSGTYPE_RESVERR:
case RSVP_MSGTYPE_PATHTEAR:
case RSVP_MSGTYPE_RESVTEAR:
case RSVP_MSGTYPE_RESVCONF:
case RSVP_MSGTYPE_HELLO_OLD:
case RSVP_MSGTYPE_HELLO:
case RSVP_MSGTYPE_ACK:
case RSVP_MSGTYPE_SREFRESH:
/*
* Print all objects in the message.
*/
if (rsvp_obj_print(ndo, pptr, plen, tptr, "\n\t ", tlen, rsvp_com_header) == -1)
return;
break;
default:
print_unknown_data(ndo, tptr, "\n\t ", tlen);
break;
}
return;
trunc:
ND_PRINT((ndo, "\n\t\t"));
ND_PRINT((ndo, "%s", tstr));
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/good_263_0 |
crossvul-cpp_data_bad_265_0 | /*
* Copyright (C) 1999 WIDE Project.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the project nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* Extensively modified by Hannes Gredler (hannes@gredler.at) for more
* complete BGP support.
*/
/* \summary: Border Gateway Protocol (BGP) printer */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <netdissect-stdinc.h>
#include <stdio.h>
#include <string.h>
#include "netdissect.h"
#include "addrtoname.h"
#include "extract.h"
#include "af.h"
#include "l2vpn.h"
struct bgp {
uint8_t bgp_marker[16];
uint16_t bgp_len;
uint8_t bgp_type;
};
#define BGP_SIZE 19 /* unaligned */
#define BGP_OPEN 1
#define BGP_UPDATE 2
#define BGP_NOTIFICATION 3
#define BGP_KEEPALIVE 4
#define BGP_ROUTE_REFRESH 5
static const struct tok bgp_msg_values[] = {
{ BGP_OPEN, "Open"},
{ BGP_UPDATE, "Update"},
{ BGP_NOTIFICATION, "Notification"},
{ BGP_KEEPALIVE, "Keepalive"},
{ BGP_ROUTE_REFRESH, "Route Refresh"},
{ 0, NULL}
};
struct bgp_open {
uint8_t bgpo_marker[16];
uint16_t bgpo_len;
uint8_t bgpo_type;
uint8_t bgpo_version;
uint16_t bgpo_myas;
uint16_t bgpo_holdtime;
uint32_t bgpo_id;
uint8_t bgpo_optlen;
/* options should follow */
};
#define BGP_OPEN_SIZE 29 /* unaligned */
struct bgp_opt {
uint8_t bgpopt_type;
uint8_t bgpopt_len;
/* variable length */
};
#define BGP_OPT_SIZE 2 /* some compilers may pad to 4 bytes */
#define BGP_CAP_HEADER_SIZE 2 /* some compilers may pad to 4 bytes */
struct bgp_notification {
uint8_t bgpn_marker[16];
uint16_t bgpn_len;
uint8_t bgpn_type;
uint8_t bgpn_major;
uint8_t bgpn_minor;
};
#define BGP_NOTIFICATION_SIZE 21 /* unaligned */
struct bgp_route_refresh {
uint8_t bgp_marker[16];
uint16_t len;
uint8_t type;
uint8_t afi[2]; /* the compiler messes this structure up */
uint8_t res; /* when doing misaligned sequences of int8 and int16 */
uint8_t safi; /* afi should be int16 - so we have to access it using */
}; /* EXTRACT_16BITS(&bgp_route_refresh->afi) (sigh) */
#define BGP_ROUTE_REFRESH_SIZE 23
#define bgp_attr_lenlen(flags, p) \
(((flags) & 0x10) ? 2 : 1)
#define bgp_attr_len(flags, p) \
(((flags) & 0x10) ? EXTRACT_16BITS(p) : *(p))
#define BGPTYPE_ORIGIN 1
#define BGPTYPE_AS_PATH 2
#define BGPTYPE_NEXT_HOP 3
#define BGPTYPE_MULTI_EXIT_DISC 4
#define BGPTYPE_LOCAL_PREF 5
#define BGPTYPE_ATOMIC_AGGREGATE 6
#define BGPTYPE_AGGREGATOR 7
#define BGPTYPE_COMMUNITIES 8 /* RFC1997 */
#define BGPTYPE_ORIGINATOR_ID 9 /* RFC4456 */
#define BGPTYPE_CLUSTER_LIST 10 /* RFC4456 */
#define BGPTYPE_DPA 11 /* deprecated, draft-ietf-idr-bgp-dpa */
#define BGPTYPE_ADVERTISERS 12 /* deprecated RFC1863 */
#define BGPTYPE_RCID_PATH 13 /* deprecated RFC1863 */
#define BGPTYPE_MP_REACH_NLRI 14 /* RFC4760 */
#define BGPTYPE_MP_UNREACH_NLRI 15 /* RFC4760 */
#define BGPTYPE_EXTD_COMMUNITIES 16 /* RFC4360 */
#define BGPTYPE_AS4_PATH 17 /* RFC6793 */
#define BGPTYPE_AGGREGATOR4 18 /* RFC6793 */
#define BGPTYPE_PMSI_TUNNEL 22 /* RFC6514 */
#define BGPTYPE_TUNNEL_ENCAP 23 /* RFC5512 */
#define BGPTYPE_TRAFFIC_ENG 24 /* RFC5543 */
#define BGPTYPE_IPV6_EXTD_COMMUNITIES 25 /* RFC5701 */
#define BGPTYPE_AIGP 26 /* RFC7311 */
#define BGPTYPE_PE_DISTINGUISHER_LABEL 27 /* RFC6514 */
#define BGPTYPE_ENTROPY_LABEL 28 /* RFC6790 */
#define BGPTYPE_LARGE_COMMUNITY 32 /* draft-ietf-idr-large-community-05 */
#define BGPTYPE_ATTR_SET 128 /* RFC6368 */
#define BGP_MP_NLRI_MINSIZE 3 /* End of RIB Marker detection */
static const struct tok bgp_attr_values[] = {
{ BGPTYPE_ORIGIN, "Origin"},
{ BGPTYPE_AS_PATH, "AS Path"},
{ BGPTYPE_AS4_PATH, "AS4 Path"},
{ BGPTYPE_NEXT_HOP, "Next Hop"},
{ BGPTYPE_MULTI_EXIT_DISC, "Multi Exit Discriminator"},
{ BGPTYPE_LOCAL_PREF, "Local Preference"},
{ BGPTYPE_ATOMIC_AGGREGATE, "Atomic Aggregate"},
{ BGPTYPE_AGGREGATOR, "Aggregator"},
{ BGPTYPE_AGGREGATOR4, "Aggregator4"},
{ BGPTYPE_COMMUNITIES, "Community"},
{ BGPTYPE_ORIGINATOR_ID, "Originator ID"},
{ BGPTYPE_CLUSTER_LIST, "Cluster List"},
{ BGPTYPE_DPA, "DPA"},
{ BGPTYPE_ADVERTISERS, "Advertisers"},
{ BGPTYPE_RCID_PATH, "RCID Path / Cluster ID"},
{ BGPTYPE_MP_REACH_NLRI, "Multi-Protocol Reach NLRI"},
{ BGPTYPE_MP_UNREACH_NLRI, "Multi-Protocol Unreach NLRI"},
{ BGPTYPE_EXTD_COMMUNITIES, "Extended Community"},
{ BGPTYPE_PMSI_TUNNEL, "PMSI Tunnel"},
{ BGPTYPE_TUNNEL_ENCAP, "Tunnel Encapsulation"},
{ BGPTYPE_TRAFFIC_ENG, "Traffic Engineering"},
{ BGPTYPE_IPV6_EXTD_COMMUNITIES, "IPv6 Extended Community"},
{ BGPTYPE_AIGP, "Accumulated IGP Metric"},
{ BGPTYPE_PE_DISTINGUISHER_LABEL, "PE Distinguisher Label"},
{ BGPTYPE_ENTROPY_LABEL, "Entropy Label"},
{ BGPTYPE_LARGE_COMMUNITY, "Large Community"},
{ BGPTYPE_ATTR_SET, "Attribute Set"},
{ 255, "Reserved for development"},
{ 0, NULL}
};
#define BGP_AS_SET 1
#define BGP_AS_SEQUENCE 2
#define BGP_CONFED_AS_SEQUENCE 3 /* draft-ietf-idr-rfc3065bis-01 */
#define BGP_CONFED_AS_SET 4 /* draft-ietf-idr-rfc3065bis-01 */
#define BGP_AS_SEG_TYPE_MIN BGP_AS_SET
#define BGP_AS_SEG_TYPE_MAX BGP_CONFED_AS_SET
static const struct tok bgp_as_path_segment_open_values[] = {
{ BGP_AS_SEQUENCE, ""},
{ BGP_AS_SET, "{ "},
{ BGP_CONFED_AS_SEQUENCE, "( "},
{ BGP_CONFED_AS_SET, "({ "},
{ 0, NULL}
};
static const struct tok bgp_as_path_segment_close_values[] = {
{ BGP_AS_SEQUENCE, ""},
{ BGP_AS_SET, "}"},
{ BGP_CONFED_AS_SEQUENCE, ")"},
{ BGP_CONFED_AS_SET, "})"},
{ 0, NULL}
};
#define BGP_OPT_AUTH 1
#define BGP_OPT_CAP 2
static const struct tok bgp_opt_values[] = {
{ BGP_OPT_AUTH, "Authentication Information"},
{ BGP_OPT_CAP, "Capabilities Advertisement"},
{ 0, NULL}
};
#define BGP_CAPCODE_MP 1 /* RFC2858 */
#define BGP_CAPCODE_RR 2 /* RFC2918 */
#define BGP_CAPCODE_ORF 3 /* RFC5291 */
#define BGP_CAPCODE_MR 4 /* RFC3107 */
#define BGP_CAPCODE_EXT_NH 5 /* RFC5549 */
#define BGP_CAPCODE_RESTART 64 /* RFC4724 */
#define BGP_CAPCODE_AS_NEW 65 /* RFC6793 */
#define BGP_CAPCODE_DYN_CAP 67 /* draft-ietf-idr-dynamic-cap */
#define BGP_CAPCODE_MULTISESS 68 /* draft-ietf-idr-bgp-multisession */
#define BGP_CAPCODE_ADD_PATH 69 /* RFC7911 */
#define BGP_CAPCODE_ENH_RR 70 /* draft-keyur-bgp-enhanced-route-refresh */
#define BGP_CAPCODE_RR_CISCO 128
static const struct tok bgp_capcode_values[] = {
{ BGP_CAPCODE_MP, "Multiprotocol Extensions"},
{ BGP_CAPCODE_RR, "Route Refresh"},
{ BGP_CAPCODE_ORF, "Cooperative Route Filtering"},
{ BGP_CAPCODE_MR, "Multiple Routes to a Destination"},
{ BGP_CAPCODE_EXT_NH, "Extended Next Hop Encoding"},
{ BGP_CAPCODE_RESTART, "Graceful Restart"},
{ BGP_CAPCODE_AS_NEW, "32-Bit AS Number"},
{ BGP_CAPCODE_DYN_CAP, "Dynamic Capability"},
{ BGP_CAPCODE_MULTISESS, "Multisession BGP"},
{ BGP_CAPCODE_ADD_PATH, "Multiple Paths"},
{ BGP_CAPCODE_ENH_RR, "Enhanced Route Refresh"},
{ BGP_CAPCODE_RR_CISCO, "Route Refresh (Cisco)"},
{ 0, NULL}
};
#define BGP_NOTIFY_MAJOR_MSG 1
#define BGP_NOTIFY_MAJOR_OPEN 2
#define BGP_NOTIFY_MAJOR_UPDATE 3
#define BGP_NOTIFY_MAJOR_HOLDTIME 4
#define BGP_NOTIFY_MAJOR_FSM 5
#define BGP_NOTIFY_MAJOR_CEASE 6
#define BGP_NOTIFY_MAJOR_CAP 7
static const struct tok bgp_notify_major_values[] = {
{ BGP_NOTIFY_MAJOR_MSG, "Message Header Error"},
{ BGP_NOTIFY_MAJOR_OPEN, "OPEN Message Error"},
{ BGP_NOTIFY_MAJOR_UPDATE, "UPDATE Message Error"},
{ BGP_NOTIFY_MAJOR_HOLDTIME,"Hold Timer Expired"},
{ BGP_NOTIFY_MAJOR_FSM, "Finite State Machine Error"},
{ BGP_NOTIFY_MAJOR_CEASE, "Cease"},
{ BGP_NOTIFY_MAJOR_CAP, "Capability Message Error"},
{ 0, NULL}
};
/* draft-ietf-idr-cease-subcode-02 */
#define BGP_NOTIFY_MINOR_CEASE_MAXPRFX 1
static const struct tok bgp_notify_minor_cease_values[] = {
{ BGP_NOTIFY_MINOR_CEASE_MAXPRFX, "Maximum Number of Prefixes Reached"},
{ 2, "Administratively Shutdown"},
{ 3, "Peer Unconfigured"},
{ 4, "Administratively Reset"},
{ 5, "Connection Rejected"},
{ 6, "Other Configuration Change"},
{ 7, "Connection Collision Resolution"},
{ 0, NULL}
};
static const struct tok bgp_notify_minor_msg_values[] = {
{ 1, "Connection Not Synchronized"},
{ 2, "Bad Message Length"},
{ 3, "Bad Message Type"},
{ 0, NULL}
};
static const struct tok bgp_notify_minor_open_values[] = {
{ 1, "Unsupported Version Number"},
{ 2, "Bad Peer AS"},
{ 3, "Bad BGP Identifier"},
{ 4, "Unsupported Optional Parameter"},
{ 5, "Authentication Failure"},
{ 6, "Unacceptable Hold Time"},
{ 7, "Capability Message Error"},
{ 0, NULL}
};
static const struct tok bgp_notify_minor_update_values[] = {
{ 1, "Malformed Attribute List"},
{ 2, "Unrecognized Well-known Attribute"},
{ 3, "Missing Well-known Attribute"},
{ 4, "Attribute Flags Error"},
{ 5, "Attribute Length Error"},
{ 6, "Invalid ORIGIN Attribute"},
{ 7, "AS Routing Loop"},
{ 8, "Invalid NEXT_HOP Attribute"},
{ 9, "Optional Attribute Error"},
{ 10, "Invalid Network Field"},
{ 11, "Malformed AS_PATH"},
{ 0, NULL}
};
static const struct tok bgp_notify_minor_fsm_values[] = {
{ 1, "In OpenSent State"},
{ 2, "In OpenConfirm State"},
{ 3, "In Established State"},
{ 0, NULL }
};
static const struct tok bgp_notify_minor_cap_values[] = {
{ 1, "Invalid Action Value" },
{ 2, "Invalid Capability Length" },
{ 3, "Malformed Capability Value" },
{ 4, "Unsupported Capability Code" },
{ 0, NULL }
};
static const struct tok bgp_origin_values[] = {
{ 0, "IGP"},
{ 1, "EGP"},
{ 2, "Incomplete"},
{ 0, NULL}
};
#define BGP_PMSI_TUNNEL_RSVP_P2MP 1
#define BGP_PMSI_TUNNEL_LDP_P2MP 2
#define BGP_PMSI_TUNNEL_PIM_SSM 3
#define BGP_PMSI_TUNNEL_PIM_SM 4
#define BGP_PMSI_TUNNEL_PIM_BIDIR 5
#define BGP_PMSI_TUNNEL_INGRESS 6
#define BGP_PMSI_TUNNEL_LDP_MP2MP 7
static const struct tok bgp_pmsi_tunnel_values[] = {
{ BGP_PMSI_TUNNEL_RSVP_P2MP, "RSVP-TE P2MP LSP"},
{ BGP_PMSI_TUNNEL_LDP_P2MP, "LDP P2MP LSP"},
{ BGP_PMSI_TUNNEL_PIM_SSM, "PIM-SSM Tree"},
{ BGP_PMSI_TUNNEL_PIM_SM, "PIM-SM Tree"},
{ BGP_PMSI_TUNNEL_PIM_BIDIR, "PIM-Bidir Tree"},
{ BGP_PMSI_TUNNEL_INGRESS, "Ingress Replication"},
{ BGP_PMSI_TUNNEL_LDP_MP2MP, "LDP MP2MP LSP"},
{ 0, NULL}
};
static const struct tok bgp_pmsi_flag_values[] = {
{ 0x01, "Leaf Information required"},
{ 0, NULL}
};
#define BGP_AIGP_TLV 1
static const struct tok bgp_aigp_values[] = {
{ BGP_AIGP_TLV, "AIGP"},
{ 0, NULL}
};
/* Subsequent address family identifier, RFC2283 section 7 */
#define SAFNUM_RES 0
#define SAFNUM_UNICAST 1
#define SAFNUM_MULTICAST 2
#define SAFNUM_UNIMULTICAST 3 /* deprecated now */
/* labeled BGP RFC3107 */
#define SAFNUM_LABUNICAST 4
/* RFC6514 */
#define SAFNUM_MULTICAST_VPN 5
/* draft-nalawade-kapoor-tunnel-safi */
#define SAFNUM_TUNNEL 64
/* RFC4761 */
#define SAFNUM_VPLS 65
/* RFC6037 */
#define SAFNUM_MDT 66
/* RFC4364 */
#define SAFNUM_VPNUNICAST 128
/* RFC6513 */
#define SAFNUM_VPNMULTICAST 129
#define SAFNUM_VPNUNIMULTICAST 130 /* deprecated now */
/* RFC4684 */
#define SAFNUM_RT_ROUTING_INFO 132
#define BGP_VPN_RD_LEN 8
static const struct tok bgp_safi_values[] = {
{ SAFNUM_RES, "Reserved"},
{ SAFNUM_UNICAST, "Unicast"},
{ SAFNUM_MULTICAST, "Multicast"},
{ SAFNUM_UNIMULTICAST, "Unicast+Multicast"},
{ SAFNUM_LABUNICAST, "labeled Unicast"},
{ SAFNUM_TUNNEL, "Tunnel"},
{ SAFNUM_VPLS, "VPLS"},
{ SAFNUM_MDT, "MDT"},
{ SAFNUM_VPNUNICAST, "labeled VPN Unicast"},
{ SAFNUM_VPNMULTICAST, "labeled VPN Multicast"},
{ SAFNUM_VPNUNIMULTICAST, "labeled VPN Unicast+Multicast"},
{ SAFNUM_RT_ROUTING_INFO, "Route Target Routing Information"},
{ SAFNUM_MULTICAST_VPN, "Multicast VPN"},
{ 0, NULL }
};
/* well-known community */
#define BGP_COMMUNITY_NO_EXPORT 0xffffff01
#define BGP_COMMUNITY_NO_ADVERT 0xffffff02
#define BGP_COMMUNITY_NO_EXPORT_SUBCONFED 0xffffff03
/* Extended community type - draft-ietf-idr-bgp-ext-communities-05 */
#define BGP_EXT_COM_RT_0 0x0002 /* Route Target,Format AS(2bytes):AN(4bytes) */
#define BGP_EXT_COM_RT_1 0x0102 /* Route Target,Format IP address:AN(2bytes) */
#define BGP_EXT_COM_RT_2 0x0202 /* Route Target,Format AN(4bytes):local(2bytes) */
#define BGP_EXT_COM_RO_0 0x0003 /* Route Origin,Format AS(2bytes):AN(4bytes) */
#define BGP_EXT_COM_RO_1 0x0103 /* Route Origin,Format IP address:AN(2bytes) */
#define BGP_EXT_COM_RO_2 0x0203 /* Route Origin,Format AN(4bytes):local(2bytes) */
#define BGP_EXT_COM_LINKBAND 0x4004 /* Link Bandwidth,Format AS(2B):Bandwidth(4B) */
/* rfc2547 bgp-mpls-vpns */
#define BGP_EXT_COM_VPN_ORIGIN 0x0005 /* OSPF Domain ID / VPN of Origin - draft-rosen-vpns-ospf-bgp-mpls */
#define BGP_EXT_COM_VPN_ORIGIN2 0x0105 /* duplicate - keep for backwards compatability */
#define BGP_EXT_COM_VPN_ORIGIN3 0x0205 /* duplicate - keep for backwards compatability */
#define BGP_EXT_COM_VPN_ORIGIN4 0x8005 /* duplicate - keep for backwards compatability */
#define BGP_EXT_COM_OSPF_RTYPE 0x0306 /* OSPF Route Type,Format Area(4B):RouteType(1B):Options(1B) */
#define BGP_EXT_COM_OSPF_RTYPE2 0x8000 /* duplicate - keep for backwards compatability */
#define BGP_EXT_COM_OSPF_RID 0x0107 /* OSPF Router ID,Format RouterID(4B):Unused(2B) */
#define BGP_EXT_COM_OSPF_RID2 0x8001 /* duplicate - keep for backwards compatability */
#define BGP_EXT_COM_L2INFO 0x800a /* draft-kompella-ppvpn-l2vpn */
#define BGP_EXT_COM_SOURCE_AS 0x0009 /* RFC-ietf-l3vpn-2547bis-mcast-bgp-08.txt */
#define BGP_EXT_COM_VRF_RT_IMP 0x010b /* RFC-ietf-l3vpn-2547bis-mcast-bgp-08.txt */
#define BGP_EXT_COM_L2VPN_RT_0 0x000a /* L2VPN Identifier,Format AS(2bytes):AN(4bytes) */
#define BGP_EXT_COM_L2VPN_RT_1 0xF10a /* L2VPN Identifier,Format IP address:AN(2bytes) */
/* http://www.cisco.com/en/US/tech/tk436/tk428/technologies_tech_note09186a00801eb09a.shtml */
#define BGP_EXT_COM_EIGRP_GEN 0x8800
#define BGP_EXT_COM_EIGRP_METRIC_AS_DELAY 0x8801
#define BGP_EXT_COM_EIGRP_METRIC_REL_NH_BW 0x8802
#define BGP_EXT_COM_EIGRP_METRIC_LOAD_MTU 0x8803
#define BGP_EXT_COM_EIGRP_EXT_REMAS_REMID 0x8804
#define BGP_EXT_COM_EIGRP_EXT_REMPROTO_REMMETRIC 0x8805
static const struct tok bgp_extd_comm_flag_values[] = {
{ 0x8000, "vendor-specific"},
{ 0x4000, "non-transitive"},
{ 0, NULL},
};
static const struct tok bgp_extd_comm_subtype_values[] = {
{ BGP_EXT_COM_RT_0, "target"},
{ BGP_EXT_COM_RT_1, "target"},
{ BGP_EXT_COM_RT_2, "target"},
{ BGP_EXT_COM_RO_0, "origin"},
{ BGP_EXT_COM_RO_1, "origin"},
{ BGP_EXT_COM_RO_2, "origin"},
{ BGP_EXT_COM_LINKBAND, "link-BW"},
{ BGP_EXT_COM_VPN_ORIGIN, "ospf-domain"},
{ BGP_EXT_COM_VPN_ORIGIN2, "ospf-domain"},
{ BGP_EXT_COM_VPN_ORIGIN3, "ospf-domain"},
{ BGP_EXT_COM_VPN_ORIGIN4, "ospf-domain"},
{ BGP_EXT_COM_OSPF_RTYPE, "ospf-route-type"},
{ BGP_EXT_COM_OSPF_RTYPE2, "ospf-route-type"},
{ BGP_EXT_COM_OSPF_RID, "ospf-router-id"},
{ BGP_EXT_COM_OSPF_RID2, "ospf-router-id"},
{ BGP_EXT_COM_L2INFO, "layer2-info"},
{ BGP_EXT_COM_EIGRP_GEN , "eigrp-general-route (flag, tag)" },
{ BGP_EXT_COM_EIGRP_METRIC_AS_DELAY , "eigrp-route-metric (AS, delay)" },
{ BGP_EXT_COM_EIGRP_METRIC_REL_NH_BW , "eigrp-route-metric (reliability, nexthop, bandwidth)" },
{ BGP_EXT_COM_EIGRP_METRIC_LOAD_MTU , "eigrp-route-metric (load, MTU)" },
{ BGP_EXT_COM_EIGRP_EXT_REMAS_REMID , "eigrp-external-route (remote-AS, remote-ID)" },
{ BGP_EXT_COM_EIGRP_EXT_REMPROTO_REMMETRIC , "eigrp-external-route (remote-proto, remote-metric)" },
{ BGP_EXT_COM_SOURCE_AS, "source-AS" },
{ BGP_EXT_COM_VRF_RT_IMP, "vrf-route-import"},
{ BGP_EXT_COM_L2VPN_RT_0, "l2vpn-id"},
{ BGP_EXT_COM_L2VPN_RT_1, "l2vpn-id"},
{ 0, NULL},
};
/* OSPF codes for BGP_EXT_COM_OSPF_RTYPE draft-rosen-vpns-ospf-bgp-mpls */
#define BGP_OSPF_RTYPE_RTR 1 /* OSPF Router LSA */
#define BGP_OSPF_RTYPE_NET 2 /* OSPF Network LSA */
#define BGP_OSPF_RTYPE_SUM 3 /* OSPF Summary LSA */
#define BGP_OSPF_RTYPE_EXT 5 /* OSPF External LSA, note that ASBR doesn't apply to MPLS-VPN */
#define BGP_OSPF_RTYPE_NSSA 7 /* OSPF NSSA External*/
#define BGP_OSPF_RTYPE_SHAM 129 /* OSPF-MPLS-VPN Sham link */
#define BGP_OSPF_RTYPE_METRIC_TYPE 0x1 /* LSB of RTYPE Options Field */
static const struct tok bgp_extd_comm_ospf_rtype_values[] = {
{ BGP_OSPF_RTYPE_RTR, "Router" },
{ BGP_OSPF_RTYPE_NET, "Network" },
{ BGP_OSPF_RTYPE_SUM, "Summary" },
{ BGP_OSPF_RTYPE_EXT, "External" },
{ BGP_OSPF_RTYPE_NSSA,"NSSA External" },
{ BGP_OSPF_RTYPE_SHAM,"MPLS-VPN Sham" },
{ 0, NULL },
};
/* ADD-PATH Send/Receive field values */
static const struct tok bgp_add_path_recvsend[] = {
{ 1, "Receive" },
{ 2, "Send" },
{ 3, "Both" },
{ 0, NULL },
};
static char astostr[20];
/*
* as_printf
*
* Convert an AS number into a string and return string pointer.
*
* Depending on bflag is set or not, AS number is converted into ASDOT notation
* or plain number notation.
*
*/
static char *
as_printf(netdissect_options *ndo,
char *str, int size, u_int asnum)
{
if (!ndo->ndo_bflag || asnum <= 0xFFFF) {
snprintf(str, size, "%u", asnum);
} else {
snprintf(str, size, "%u.%u", asnum >> 16, asnum & 0xFFFF);
}
return str;
}
#define ITEMCHECK(minlen) if (itemlen < minlen) goto badtlv;
int
decode_prefix4(netdissect_options *ndo,
const u_char *pptr, u_int itemlen, char *buf, u_int buflen)
{
struct in_addr addr;
u_int plen, plenbytes;
ND_TCHECK(pptr[0]);
ITEMCHECK(1);
plen = pptr[0];
if (32 < plen)
return -1;
itemlen -= 1;
memset(&addr, 0, sizeof(addr));
plenbytes = (plen + 7) / 8;
ND_TCHECK2(pptr[1], plenbytes);
ITEMCHECK(plenbytes);
memcpy(&addr, &pptr[1], plenbytes);
if (plen % 8) {
((u_char *)&addr)[plenbytes - 1] &=
((0xff00 >> (plen % 8)) & 0xff);
}
snprintf(buf, buflen, "%s/%d", ipaddr_string(ndo, &addr), plen);
return 1 + plenbytes;
trunc:
return -2;
badtlv:
return -3;
}
static int
decode_labeled_prefix4(netdissect_options *ndo,
const u_char *pptr, u_int itemlen, char *buf, u_int buflen)
{
struct in_addr addr;
u_int plen, plenbytes;
/* prefix length and label = 4 bytes */
ND_TCHECK2(pptr[0], 4);
ITEMCHECK(4);
plen = pptr[0]; /* get prefix length */
/* this is one of the weirdnesses of rfc3107
the label length (actually the label + COS bits)
is added to the prefix length;
we also do only read out just one label -
there is no real application for advertisement of
stacked labels in a single BGP message
*/
if (24 > plen)
return -1;
plen-=24; /* adjust prefixlen - labellength */
if (32 < plen)
return -1;
itemlen -= 4;
memset(&addr, 0, sizeof(addr));
plenbytes = (plen + 7) / 8;
ND_TCHECK2(pptr[4], plenbytes);
ITEMCHECK(plenbytes);
memcpy(&addr, &pptr[4], plenbytes);
if (plen % 8) {
((u_char *)&addr)[plenbytes - 1] &=
((0xff00 >> (plen % 8)) & 0xff);
}
/* the label may get offsetted by 4 bits so lets shift it right */
snprintf(buf, buflen, "%s/%d, label:%u %s",
ipaddr_string(ndo, &addr),
plen,
EXTRACT_24BITS(pptr+1)>>4,
((pptr[3]&1)==0) ? "(BOGUS: Bottom of Stack NOT set!)" : "(bottom)" );
return 4 + plenbytes;
trunc:
return -2;
badtlv:
return -3;
}
/*
* bgp_vpn_ip_print
*
* print an ipv4 or ipv6 address into a buffer dependend on address length.
*/
static char *
bgp_vpn_ip_print(netdissect_options *ndo,
const u_char *pptr, u_int addr_length)
{
/* worst case string is s fully formatted v6 address */
static char addr[sizeof("1234:5678:89ab:cdef:1234:5678:89ab:cdef")];
char *pos = addr;
switch(addr_length) {
case (sizeof(struct in_addr) << 3): /* 32 */
ND_TCHECK2(pptr[0], sizeof(struct in_addr));
snprintf(pos, sizeof(addr), "%s", ipaddr_string(ndo, pptr));
break;
case (sizeof(struct in6_addr) << 3): /* 128 */
ND_TCHECK2(pptr[0], sizeof(struct in6_addr));
snprintf(pos, sizeof(addr), "%s", ip6addr_string(ndo, pptr));
break;
default:
snprintf(pos, sizeof(addr), "bogus address length %u", addr_length);
break;
}
pos += strlen(pos);
trunc:
*(pos) = '\0';
return (addr);
}
/*
* bgp_vpn_sg_print
*
* print an multicast s,g entry into a buffer.
* the s,g entry is encoded like this.
*
* +-----------------------------------+
* | Multicast Source Length (1 octet) |
* +-----------------------------------+
* | Multicast Source (Variable) |
* +-----------------------------------+
* | Multicast Group Length (1 octet) |
* +-----------------------------------+
* | Multicast Group (Variable) |
* +-----------------------------------+
*
* return the number of bytes read from the wire.
*/
static int
bgp_vpn_sg_print(netdissect_options *ndo,
const u_char *pptr, char *buf, u_int buflen)
{
uint8_t addr_length;
u_int total_length, offset;
total_length = 0;
/* Source address length, encoded in bits */
ND_TCHECK2(pptr[0], 1);
addr_length = *pptr++;
/* Source address */
ND_TCHECK2(pptr[0], (addr_length >> 3));
total_length += (addr_length >> 3) + 1;
offset = strlen(buf);
if (addr_length) {
snprintf(buf + offset, buflen - offset, ", Source %s",
bgp_vpn_ip_print(ndo, pptr, addr_length));
pptr += (addr_length >> 3);
}
/* Group address length, encoded in bits */
ND_TCHECK2(pptr[0], 1);
addr_length = *pptr++;
/* Group address */
ND_TCHECK2(pptr[0], (addr_length >> 3));
total_length += (addr_length >> 3) + 1;
offset = strlen(buf);
if (addr_length) {
snprintf(buf + offset, buflen - offset, ", Group %s",
bgp_vpn_ip_print(ndo, pptr, addr_length));
pptr += (addr_length >> 3);
}
trunc:
return (total_length);
}
/* RDs and RTs share the same semantics
* we use bgp_vpn_rd_print for
* printing route targets inside a NLRI */
char *
bgp_vpn_rd_print(netdissect_options *ndo,
const u_char *pptr)
{
/* allocate space for the largest possible string */
static char rd[sizeof("xxxxxxxxxx:xxxxx (xxx.xxx.xxx.xxx:xxxxx)")];
char *pos = rd;
/* ok lets load the RD format */
switch (EXTRACT_16BITS(pptr)) {
/* 2-byte-AS:number fmt*/
case 0:
snprintf(pos, sizeof(rd) - (pos - rd), "%u:%u (= %u.%u.%u.%u)",
EXTRACT_16BITS(pptr+2),
EXTRACT_32BITS(pptr+4),
*(pptr+4), *(pptr+5), *(pptr+6), *(pptr+7));
break;
/* IP-address:AS fmt*/
case 1:
snprintf(pos, sizeof(rd) - (pos - rd), "%u.%u.%u.%u:%u",
*(pptr+2), *(pptr+3), *(pptr+4), *(pptr+5), EXTRACT_16BITS(pptr+6));
break;
/* 4-byte-AS:number fmt*/
case 2:
snprintf(pos, sizeof(rd) - (pos - rd), "%s:%u (%u.%u.%u.%u:%u)",
as_printf(ndo, astostr, sizeof(astostr), EXTRACT_32BITS(pptr+2)),
EXTRACT_16BITS(pptr+6), *(pptr+2), *(pptr+3), *(pptr+4),
*(pptr+5), EXTRACT_16BITS(pptr+6));
break;
default:
snprintf(pos, sizeof(rd) - (pos - rd), "unknown RD format");
break;
}
pos += strlen(pos);
*(pos) = '\0';
return (rd);
}
static int
decode_rt_routing_info(netdissect_options *ndo,
const u_char *pptr, char *buf, u_int buflen)
{
uint8_t route_target[8];
u_int plen;
char asbuf[sizeof(astostr)]; /* bgp_vpn_rd_print() overwrites astostr */
/* NLRI "prefix length" from RFC 2858 Section 4. */
ND_TCHECK(pptr[0]);
plen = pptr[0]; /* get prefix length */
/* NLRI "prefix" (ibid), valid lengths are { 0, 32, 33, ..., 96 } bits.
* RFC 4684 Section 4 defines the layout of "origin AS" and "route
* target" fields inside the "prefix" depending on its length.
*/
if (0 == plen) {
/* Without "origin AS", without "route target". */
snprintf(buf, buflen, "default route target");
return 1;
}
if (32 > plen)
return -1;
/* With at least "origin AS", possibly with "route target". */
ND_TCHECK_32BITS(pptr + 1);
as_printf(ndo, asbuf, sizeof(asbuf), EXTRACT_32BITS(pptr + 1));
plen-=32; /* adjust prefix length */
if (64 < plen)
return -1;
/* From now on (plen + 7) / 8 evaluates to { 0, 1, 2, ..., 8 }
* and gives the number of octets in the variable-length "route
* target" field inside this NLRI "prefix". Look for it.
*/
memset(&route_target, 0, sizeof(route_target));
ND_TCHECK2(pptr[5], (plen + 7) / 8);
memcpy(&route_target, &pptr[5], (plen + 7) / 8);
/* Which specification says to do this? */
if (plen % 8) {
((u_char *)&route_target)[(plen + 7) / 8 - 1] &=
((0xff00 >> (plen % 8)) & 0xff);
}
snprintf(buf, buflen, "origin AS: %s, route target %s",
asbuf,
bgp_vpn_rd_print(ndo, (u_char *)&route_target));
return 5 + (plen + 7) / 8;
trunc:
return -2;
}
static int
decode_labeled_vpn_prefix4(netdissect_options *ndo,
const u_char *pptr, char *buf, u_int buflen)
{
struct in_addr addr;
u_int plen;
ND_TCHECK(pptr[0]);
plen = pptr[0]; /* get prefix length */
if ((24+64) > plen)
return -1;
plen-=(24+64); /* adjust prefixlen - labellength - RD len*/
if (32 < plen)
return -1;
memset(&addr, 0, sizeof(addr));
ND_TCHECK2(pptr[12], (plen + 7) / 8);
memcpy(&addr, &pptr[12], (plen + 7) / 8);
if (plen % 8) {
((u_char *)&addr)[(plen + 7) / 8 - 1] &=
((0xff00 >> (plen % 8)) & 0xff);
}
/* the label may get offsetted by 4 bits so lets shift it right */
snprintf(buf, buflen, "RD: %s, %s/%d, label:%u %s",
bgp_vpn_rd_print(ndo, pptr+4),
ipaddr_string(ndo, &addr),
plen,
EXTRACT_24BITS(pptr+1)>>4,
((pptr[3]&1)==0) ? "(BOGUS: Bottom of Stack NOT set!)" : "(bottom)" );
return 12 + (plen + 7) / 8;
trunc:
return -2;
}
/*
* +-------------------------------+
* | |
* | RD:IPv4-address (12 octets) |
* | |
* +-------------------------------+
* | MDT Group-address (4 octets) |
* +-------------------------------+
*/
#define MDT_VPN_NLRI_LEN 16
static int
decode_mdt_vpn_nlri(netdissect_options *ndo,
const u_char *pptr, char *buf, u_int buflen)
{
const u_char *rd;
const u_char *vpn_ip;
ND_TCHECK(pptr[0]);
/* if the NLRI is not predefined length, quit.*/
if (*pptr != MDT_VPN_NLRI_LEN * 8)
return -1;
pptr++;
/* RD */
ND_TCHECK2(pptr[0], 8);
rd = pptr;
pptr+=8;
/* IPv4 address */
ND_TCHECK2(pptr[0], sizeof(struct in_addr));
vpn_ip = pptr;
pptr+=sizeof(struct in_addr);
/* MDT Group Address */
ND_TCHECK2(pptr[0], sizeof(struct in_addr));
snprintf(buf, buflen, "RD: %s, VPN IP Address: %s, MC Group Address: %s",
bgp_vpn_rd_print(ndo, rd), ipaddr_string(ndo, vpn_ip), ipaddr_string(ndo, pptr));
return MDT_VPN_NLRI_LEN + 1;
trunc:
return -2;
}
#define BGP_MULTICAST_VPN_ROUTE_TYPE_INTRA_AS_I_PMSI 1
#define BGP_MULTICAST_VPN_ROUTE_TYPE_INTER_AS_I_PMSI 2
#define BGP_MULTICAST_VPN_ROUTE_TYPE_S_PMSI 3
#define BGP_MULTICAST_VPN_ROUTE_TYPE_INTRA_AS_SEG_LEAF 4
#define BGP_MULTICAST_VPN_ROUTE_TYPE_SOURCE_ACTIVE 5
#define BGP_MULTICAST_VPN_ROUTE_TYPE_SHARED_TREE_JOIN 6
#define BGP_MULTICAST_VPN_ROUTE_TYPE_SOURCE_TREE_JOIN 7
static const struct tok bgp_multicast_vpn_route_type_values[] = {
{ BGP_MULTICAST_VPN_ROUTE_TYPE_INTRA_AS_I_PMSI, "Intra-AS I-PMSI"},
{ BGP_MULTICAST_VPN_ROUTE_TYPE_INTER_AS_I_PMSI, "Inter-AS I-PMSI"},
{ BGP_MULTICAST_VPN_ROUTE_TYPE_S_PMSI, "S-PMSI"},
{ BGP_MULTICAST_VPN_ROUTE_TYPE_INTRA_AS_SEG_LEAF, "Intra-AS Segment-Leaf"},
{ BGP_MULTICAST_VPN_ROUTE_TYPE_SOURCE_ACTIVE, "Source-Active"},
{ BGP_MULTICAST_VPN_ROUTE_TYPE_SHARED_TREE_JOIN, "Shared Tree Join"},
{ BGP_MULTICAST_VPN_ROUTE_TYPE_SOURCE_TREE_JOIN, "Source Tree Join"},
{ 0, NULL}
};
static int
decode_multicast_vpn(netdissect_options *ndo,
const u_char *pptr, char *buf, u_int buflen)
{
uint8_t route_type, route_length, addr_length, sg_length;
u_int offset;
ND_TCHECK2(pptr[0], 2);
route_type = *pptr++;
route_length = *pptr++;
snprintf(buf, buflen, "Route-Type: %s (%u), length: %u",
tok2str(bgp_multicast_vpn_route_type_values,
"Unknown", route_type),
route_type, route_length);
switch(route_type) {
case BGP_MULTICAST_VPN_ROUTE_TYPE_INTRA_AS_I_PMSI:
ND_TCHECK2(pptr[0], BGP_VPN_RD_LEN);
offset = strlen(buf);
snprintf(buf + offset, buflen - offset, ", RD: %s, Originator %s",
bgp_vpn_rd_print(ndo, pptr),
bgp_vpn_ip_print(ndo, pptr + BGP_VPN_RD_LEN,
(route_length - BGP_VPN_RD_LEN) << 3));
break;
case BGP_MULTICAST_VPN_ROUTE_TYPE_INTER_AS_I_PMSI:
ND_TCHECK2(pptr[0], BGP_VPN_RD_LEN + 4);
offset = strlen(buf);
snprintf(buf + offset, buflen - offset, ", RD: %s, Source-AS %s",
bgp_vpn_rd_print(ndo, pptr),
as_printf(ndo, astostr, sizeof(astostr),
EXTRACT_32BITS(pptr + BGP_VPN_RD_LEN)));
break;
case BGP_MULTICAST_VPN_ROUTE_TYPE_S_PMSI:
ND_TCHECK2(pptr[0], BGP_VPN_RD_LEN);
offset = strlen(buf);
snprintf(buf + offset, buflen - offset, ", RD: %s",
bgp_vpn_rd_print(ndo, pptr));
pptr += BGP_VPN_RD_LEN;
sg_length = bgp_vpn_sg_print(ndo, pptr, buf, buflen);
addr_length = route_length - sg_length;
ND_TCHECK2(pptr[0], addr_length);
offset = strlen(buf);
snprintf(buf + offset, buflen - offset, ", Originator %s",
bgp_vpn_ip_print(ndo, pptr, addr_length << 3));
break;
case BGP_MULTICAST_VPN_ROUTE_TYPE_SOURCE_ACTIVE:
ND_TCHECK2(pptr[0], BGP_VPN_RD_LEN);
offset = strlen(buf);
snprintf(buf + offset, buflen - offset, ", RD: %s",
bgp_vpn_rd_print(ndo, pptr));
pptr += BGP_VPN_RD_LEN;
bgp_vpn_sg_print(ndo, pptr, buf, buflen);
break;
case BGP_MULTICAST_VPN_ROUTE_TYPE_SHARED_TREE_JOIN: /* fall through */
case BGP_MULTICAST_VPN_ROUTE_TYPE_SOURCE_TREE_JOIN:
ND_TCHECK2(pptr[0], BGP_VPN_RD_LEN + 4);
offset = strlen(buf);
snprintf(buf + offset, buflen - offset, ", RD: %s, Source-AS %s",
bgp_vpn_rd_print(ndo, pptr),
as_printf(ndo, astostr, sizeof(astostr),
EXTRACT_32BITS(pptr + BGP_VPN_RD_LEN)));
pptr += BGP_VPN_RD_LEN + 4;
bgp_vpn_sg_print(ndo, pptr, buf, buflen);
break;
/*
* no per route-type printing yet.
*/
case BGP_MULTICAST_VPN_ROUTE_TYPE_INTRA_AS_SEG_LEAF:
default:
break;
}
return route_length + 2;
trunc:
return -2;
}
/*
* As I remember, some versions of systems have an snprintf() that
* returns -1 if the buffer would have overflowed. If the return
* value is negative, set buflen to 0, to indicate that we've filled
* the buffer up.
*
* If the return value is greater than buflen, that means that
* the buffer would have overflowed; again, set buflen to 0 in
* that case.
*/
#define UPDATE_BUF_BUFLEN(buf, buflen, stringlen) \
if (stringlen<0) \
buflen=0; \
else if ((u_int)stringlen>buflen) \
buflen=0; \
else { \
buflen-=stringlen; \
buf+=stringlen; \
}
static int
decode_labeled_vpn_l2(netdissect_options *ndo,
const u_char *pptr, char *buf, u_int buflen)
{
int plen,tlen,stringlen,tlv_type,tlv_len,ttlv_len;
ND_TCHECK2(pptr[0], 2);
plen=EXTRACT_16BITS(pptr);
tlen=plen;
pptr+=2;
/* Old and new L2VPN NLRI share AFI/SAFI
* -> Assume a 12 Byte-length NLRI is auto-discovery-only
* and > 17 as old format. Complain for the middle case
*/
if (plen==12) {
/* assume AD-only with RD, BGPNH */
ND_TCHECK2(pptr[0],12);
buf[0]='\0';
stringlen=snprintf(buf, buflen, "RD: %s, BGPNH: %s",
bgp_vpn_rd_print(ndo, pptr),
ipaddr_string(ndo, pptr+8)
);
UPDATE_BUF_BUFLEN(buf, buflen, stringlen);
pptr+=12;
tlen-=12;
return plen;
} else if (plen>17) {
/* assume old format */
/* RD, ID, LBLKOFF, LBLBASE */
ND_TCHECK2(pptr[0],15);
buf[0]='\0';
stringlen=snprintf(buf, buflen, "RD: %s, CE-ID: %u, Label-Block Offset: %u, Label Base %u",
bgp_vpn_rd_print(ndo, pptr),
EXTRACT_16BITS(pptr+8),
EXTRACT_16BITS(pptr+10),
EXTRACT_24BITS(pptr+12)>>4); /* the label is offsetted by 4 bits so lets shift it right */
UPDATE_BUF_BUFLEN(buf, buflen, stringlen);
pptr+=15;
tlen-=15;
/* ok now the variable part - lets read out TLVs*/
while (tlen>0) {
if (tlen < 3)
return -1;
ND_TCHECK2(pptr[0], 3);
tlv_type=*pptr++;
tlv_len=EXTRACT_16BITS(pptr);
ttlv_len=tlv_len;
pptr+=2;
switch(tlv_type) {
case 1:
if (buflen!=0) {
stringlen=snprintf(buf,buflen, "\n\t\tcircuit status vector (%u) length: %u: 0x",
tlv_type,
tlv_len);
UPDATE_BUF_BUFLEN(buf, buflen, stringlen);
}
ttlv_len=ttlv_len/8+1; /* how many bytes do we need to read ? */
while (ttlv_len>0) {
ND_TCHECK(pptr[0]);
if (buflen!=0) {
stringlen=snprintf(buf,buflen, "%02x",*pptr++);
UPDATE_BUF_BUFLEN(buf, buflen, stringlen);
}
ttlv_len--;
}
break;
default:
if (buflen!=0) {
stringlen=snprintf(buf,buflen, "\n\t\tunknown TLV #%u, length: %u",
tlv_type,
tlv_len);
UPDATE_BUF_BUFLEN(buf, buflen, stringlen);
}
break;
}
tlen-=(tlv_len<<3); /* the tlv-length is expressed in bits so lets shift it right */
}
return plen+2;
} else {
/* complain bitterly ? */
/* fall through */
goto trunc;
}
trunc:
return -2;
}
int
decode_prefix6(netdissect_options *ndo,
const u_char *pd, u_int itemlen, char *buf, u_int buflen)
{
struct in6_addr addr;
u_int plen, plenbytes;
ND_TCHECK(pd[0]);
ITEMCHECK(1);
plen = pd[0];
if (128 < plen)
return -1;
itemlen -= 1;
memset(&addr, 0, sizeof(addr));
plenbytes = (plen + 7) / 8;
ND_TCHECK2(pd[1], plenbytes);
ITEMCHECK(plenbytes);
memcpy(&addr, &pd[1], plenbytes);
if (plen % 8) {
addr.s6_addr[plenbytes - 1] &=
((0xff00 >> (plen % 8)) & 0xff);
}
snprintf(buf, buflen, "%s/%d", ip6addr_string(ndo, &addr), plen);
return 1 + plenbytes;
trunc:
return -2;
badtlv:
return -3;
}
static int
decode_labeled_prefix6(netdissect_options *ndo,
const u_char *pptr, u_int itemlen, char *buf, u_int buflen)
{
struct in6_addr addr;
u_int plen, plenbytes;
/* prefix length and label = 4 bytes */
ND_TCHECK2(pptr[0], 4);
ITEMCHECK(4);
plen = pptr[0]; /* get prefix length */
if (24 > plen)
return -1;
plen-=24; /* adjust prefixlen - labellength */
if (128 < plen)
return -1;
itemlen -= 4;
memset(&addr, 0, sizeof(addr));
plenbytes = (plen + 7) / 8;
ND_TCHECK2(pptr[4], plenbytes);
memcpy(&addr, &pptr[4], plenbytes);
if (plen % 8) {
addr.s6_addr[plenbytes - 1] &=
((0xff00 >> (plen % 8)) & 0xff);
}
/* the label may get offsetted by 4 bits so lets shift it right */
snprintf(buf, buflen, "%s/%d, label:%u %s",
ip6addr_string(ndo, &addr),
plen,
EXTRACT_24BITS(pptr+1)>>4,
((pptr[3]&1)==0) ? "(BOGUS: Bottom of Stack NOT set!)" : "(bottom)" );
return 4 + plenbytes;
trunc:
return -2;
badtlv:
return -3;
}
static int
decode_labeled_vpn_prefix6(netdissect_options *ndo,
const u_char *pptr, char *buf, u_int buflen)
{
struct in6_addr addr;
u_int plen;
ND_TCHECK(pptr[0]);
plen = pptr[0]; /* get prefix length */
if ((24+64) > plen)
return -1;
plen-=(24+64); /* adjust prefixlen - labellength - RD len*/
if (128 < plen)
return -1;
memset(&addr, 0, sizeof(addr));
ND_TCHECK2(pptr[12], (plen + 7) / 8);
memcpy(&addr, &pptr[12], (plen + 7) / 8);
if (plen % 8) {
addr.s6_addr[(plen + 7) / 8 - 1] &=
((0xff00 >> (plen % 8)) & 0xff);
}
/* the label may get offsetted by 4 bits so lets shift it right */
snprintf(buf, buflen, "RD: %s, %s/%d, label:%u %s",
bgp_vpn_rd_print(ndo, pptr+4),
ip6addr_string(ndo, &addr),
plen,
EXTRACT_24BITS(pptr+1)>>4,
((pptr[3]&1)==0) ? "(BOGUS: Bottom of Stack NOT set!)" : "(bottom)" );
return 12 + (plen + 7) / 8;
trunc:
return -2;
}
static int
decode_clnp_prefix(netdissect_options *ndo,
const u_char *pptr, char *buf, u_int buflen)
{
uint8_t addr[19];
u_int plen;
ND_TCHECK(pptr[0]);
plen = pptr[0]; /* get prefix length */
if (152 < plen)
return -1;
memset(&addr, 0, sizeof(addr));
ND_TCHECK2(pptr[4], (plen + 7) / 8);
memcpy(&addr, &pptr[4], (plen + 7) / 8);
if (plen % 8) {
addr[(plen + 7) / 8 - 1] &=
((0xff00 >> (plen % 8)) & 0xff);
}
snprintf(buf, buflen, "%s/%d",
isonsap_string(ndo, addr,(plen + 7) / 8),
plen);
return 1 + (plen + 7) / 8;
trunc:
return -2;
}
static int
decode_labeled_vpn_clnp_prefix(netdissect_options *ndo,
const u_char *pptr, char *buf, u_int buflen)
{
uint8_t addr[19];
u_int plen;
ND_TCHECK(pptr[0]);
plen = pptr[0]; /* get prefix length */
if ((24+64) > plen)
return -1;
plen-=(24+64); /* adjust prefixlen - labellength - RD len*/
if (152 < plen)
return -1;
memset(&addr, 0, sizeof(addr));
ND_TCHECK2(pptr[12], (plen + 7) / 8);
memcpy(&addr, &pptr[12], (plen + 7) / 8);
if (plen % 8) {
addr[(plen + 7) / 8 - 1] &=
((0xff00 >> (plen % 8)) & 0xff);
}
/* the label may get offsetted by 4 bits so lets shift it right */
snprintf(buf, buflen, "RD: %s, %s/%d, label:%u %s",
bgp_vpn_rd_print(ndo, pptr+4),
isonsap_string(ndo, addr,(plen + 7) / 8),
plen,
EXTRACT_24BITS(pptr+1)>>4,
((pptr[3]&1)==0) ? "(BOGUS: Bottom of Stack NOT set!)" : "(bottom)" );
return 12 + (plen + 7) / 8;
trunc:
return -2;
}
/*
* bgp_attr_get_as_size
*
* Try to find the size of the ASs encoded in an as-path. It is not obvious, as
* both Old speakers that do not support 4 byte AS, and the new speakers that do
* support, exchange AS-Path with the same path-attribute type value 0x02.
*/
static int
bgp_attr_get_as_size(netdissect_options *ndo,
uint8_t bgpa_type, const u_char *pptr, int len)
{
const u_char *tptr = pptr;
/*
* If the path attribute is the optional AS4 path type, then we already
* know, that ASs must be encoded in 4 byte format.
*/
if (bgpa_type == BGPTYPE_AS4_PATH) {
return 4;
}
/*
* Let us assume that ASs are of 2 bytes in size, and check if the AS-Path
* TLV is good. If not, ask the caller to try with AS encoded as 4 bytes
* each.
*/
while (tptr < pptr + len) {
ND_TCHECK(tptr[0]);
/*
* If we do not find a valid segment type, our guess might be wrong.
*/
if (tptr[0] < BGP_AS_SEG_TYPE_MIN || tptr[0] > BGP_AS_SEG_TYPE_MAX) {
goto trunc;
}
ND_TCHECK(tptr[1]);
tptr += 2 + tptr[1] * 2;
}
/*
* If we correctly reached end of the AS path attribute data content,
* then most likely ASs were indeed encoded as 2 bytes.
*/
if (tptr == pptr + len) {
return 2;
}
trunc:
/*
* We can come here, either we did not have enough data, or if we
* try to decode 4 byte ASs in 2 byte format. Either way, return 4,
* so that calller can try to decode each AS as of 4 bytes. If indeed
* there was not enough data, it will crib and end the parse anyways.
*/
return 4;
}
static int
bgp_attr_print(netdissect_options *ndo,
u_int atype, const u_char *pptr, u_int len)
{
int i;
uint16_t af;
uint8_t safi, snpa, nhlen;
union { /* copy buffer for bandwidth values */
float f;
uint32_t i;
} bw;
int advance;
u_int tlen;
const u_char *tptr;
char buf[MAXHOSTNAMELEN + 100];
int as_size;
tptr = pptr;
tlen=len;
switch (atype) {
case BGPTYPE_ORIGIN:
if (len != 1)
ND_PRINT((ndo, "invalid len"));
else {
ND_TCHECK(*tptr);
ND_PRINT((ndo, "%s", tok2str(bgp_origin_values,
"Unknown Origin Typecode",
tptr[0])));
}
break;
/*
* Process AS4 byte path and AS2 byte path attributes here.
*/
case BGPTYPE_AS4_PATH:
case BGPTYPE_AS_PATH:
if (len % 2) {
ND_PRINT((ndo, "invalid len"));
break;
}
if (!len) {
ND_PRINT((ndo, "empty"));
break;
}
/*
* BGP updates exchanged between New speakers that support 4
* byte AS, ASs are always encoded in 4 bytes. There is no
* definitive way to find this, just by the packet's
* contents. So, check for packet's TLV's sanity assuming
* 2 bytes first, and it does not pass, assume that ASs are
* encoded in 4 bytes format and move on.
*/
as_size = bgp_attr_get_as_size(ndo, atype, pptr, len);
while (tptr < pptr + len) {
ND_TCHECK(tptr[0]);
ND_PRINT((ndo, "%s", tok2str(bgp_as_path_segment_open_values,
"?", tptr[0])));
ND_TCHECK(tptr[1]);
for (i = 0; i < tptr[1] * as_size; i += as_size) {
ND_TCHECK2(tptr[2 + i], as_size);
ND_PRINT((ndo, "%s ",
as_printf(ndo, astostr, sizeof(astostr),
as_size == 2 ?
EXTRACT_16BITS(&tptr[2 + i]) :
EXTRACT_32BITS(&tptr[2 + i]))));
}
ND_TCHECK(tptr[0]);
ND_PRINT((ndo, "%s", tok2str(bgp_as_path_segment_close_values,
"?", tptr[0])));
ND_TCHECK(tptr[1]);
tptr += 2 + tptr[1] * as_size;
}
break;
case BGPTYPE_NEXT_HOP:
if (len != 4)
ND_PRINT((ndo, "invalid len"));
else {
ND_TCHECK2(tptr[0], 4);
ND_PRINT((ndo, "%s", ipaddr_string(ndo, tptr)));
}
break;
case BGPTYPE_MULTI_EXIT_DISC:
case BGPTYPE_LOCAL_PREF:
if (len != 4)
ND_PRINT((ndo, "invalid len"));
else {
ND_TCHECK2(tptr[0], 4);
ND_PRINT((ndo, "%u", EXTRACT_32BITS(tptr)));
}
break;
case BGPTYPE_ATOMIC_AGGREGATE:
if (len != 0)
ND_PRINT((ndo, "invalid len"));
break;
case BGPTYPE_AGGREGATOR:
/*
* Depending on the AS encoded is of 2 bytes or of 4 bytes,
* the length of this PA can be either 6 bytes or 8 bytes.
*/
if (len != 6 && len != 8) {
ND_PRINT((ndo, "invalid len"));
break;
}
ND_TCHECK2(tptr[0], len);
if (len == 6) {
ND_PRINT((ndo, " AS #%s, origin %s",
as_printf(ndo, astostr, sizeof(astostr), EXTRACT_16BITS(tptr)),
ipaddr_string(ndo, tptr + 2)));
} else {
ND_PRINT((ndo, " AS #%s, origin %s",
as_printf(ndo, astostr, sizeof(astostr),
EXTRACT_32BITS(tptr)), ipaddr_string(ndo, tptr + 4)));
}
break;
case BGPTYPE_AGGREGATOR4:
if (len != 8) {
ND_PRINT((ndo, "invalid len"));
break;
}
ND_TCHECK2(tptr[0], 8);
ND_PRINT((ndo, " AS #%s, origin %s",
as_printf(ndo, astostr, sizeof(astostr), EXTRACT_32BITS(tptr)),
ipaddr_string(ndo, tptr + 4)));
break;
case BGPTYPE_COMMUNITIES:
if (len % 4) {
ND_PRINT((ndo, "invalid len"));
break;
}
while (tlen>0) {
uint32_t comm;
ND_TCHECK2(tptr[0], 4);
comm = EXTRACT_32BITS(tptr);
switch (comm) {
case BGP_COMMUNITY_NO_EXPORT:
ND_PRINT((ndo, " NO_EXPORT"));
break;
case BGP_COMMUNITY_NO_ADVERT:
ND_PRINT((ndo, " NO_ADVERTISE"));
break;
case BGP_COMMUNITY_NO_EXPORT_SUBCONFED:
ND_PRINT((ndo, " NO_EXPORT_SUBCONFED"));
break;
default:
ND_PRINT((ndo, "%u:%u%s",
(comm >> 16) & 0xffff,
comm & 0xffff,
(tlen>4) ? ", " : ""));
break;
}
tlen -=4;
tptr +=4;
}
break;
case BGPTYPE_ORIGINATOR_ID:
if (len != 4) {
ND_PRINT((ndo, "invalid len"));
break;
}
ND_TCHECK2(tptr[0], 4);
ND_PRINT((ndo, "%s",ipaddr_string(ndo, tptr)));
break;
case BGPTYPE_CLUSTER_LIST:
if (len % 4) {
ND_PRINT((ndo, "invalid len"));
break;
}
while (tlen>0) {
ND_TCHECK2(tptr[0], 4);
ND_PRINT((ndo, "%s%s",
ipaddr_string(ndo, tptr),
(tlen>4) ? ", " : ""));
tlen -=4;
tptr +=4;
}
break;
case BGPTYPE_MP_REACH_NLRI:
ND_TCHECK2(tptr[0], 3);
af = EXTRACT_16BITS(tptr);
safi = tptr[2];
ND_PRINT((ndo, "\n\t AFI: %s (%u), %sSAFI: %s (%u)",
tok2str(af_values, "Unknown AFI", af),
af,
(safi>128) ? "vendor specific " : "", /* 128 is meanwhile wellknown */
tok2str(bgp_safi_values, "Unknown SAFI", safi),
safi));
switch(af<<8 | safi) {
case (AFNUM_INET<<8 | SAFNUM_UNICAST):
case (AFNUM_INET<<8 | SAFNUM_MULTICAST):
case (AFNUM_INET<<8 | SAFNUM_UNIMULTICAST):
case (AFNUM_INET<<8 | SAFNUM_LABUNICAST):
case (AFNUM_INET<<8 | SAFNUM_RT_ROUTING_INFO):
case (AFNUM_INET<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_INET<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_INET<<8 | SAFNUM_VPNUNIMULTICAST):
case (AFNUM_INET<<8 | SAFNUM_MULTICAST_VPN):
case (AFNUM_INET<<8 | SAFNUM_MDT):
case (AFNUM_INET6<<8 | SAFNUM_UNICAST):
case (AFNUM_INET6<<8 | SAFNUM_MULTICAST):
case (AFNUM_INET6<<8 | SAFNUM_UNIMULTICAST):
case (AFNUM_INET6<<8 | SAFNUM_LABUNICAST):
case (AFNUM_INET6<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_INET6<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_INET6<<8 | SAFNUM_VPNUNIMULTICAST):
case (AFNUM_NSAP<<8 | SAFNUM_UNICAST):
case (AFNUM_NSAP<<8 | SAFNUM_MULTICAST):
case (AFNUM_NSAP<<8 | SAFNUM_UNIMULTICAST):
case (AFNUM_NSAP<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_NSAP<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_NSAP<<8 | SAFNUM_VPNUNIMULTICAST):
case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_L2VPN<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNIMULTICAST):
case (AFNUM_VPLS<<8 | SAFNUM_VPLS):
break;
default:
ND_TCHECK2(tptr[0], tlen);
ND_PRINT((ndo, "\n\t no AFI %u / SAFI %u decoder", af, safi));
if (ndo->ndo_vflag <= 1)
print_unknown_data(ndo, tptr, "\n\t ", tlen);
goto done;
break;
}
tptr +=3;
ND_TCHECK(tptr[0]);
nhlen = tptr[0];
tlen = nhlen;
tptr++;
if (tlen) {
int nnh = 0;
ND_PRINT((ndo, "\n\t nexthop: "));
while (tlen > 0) {
if ( nnh++ > 0 ) {
ND_PRINT((ndo, ", " ));
}
switch(af<<8 | safi) {
case (AFNUM_INET<<8 | SAFNUM_UNICAST):
case (AFNUM_INET<<8 | SAFNUM_MULTICAST):
case (AFNUM_INET<<8 | SAFNUM_UNIMULTICAST):
case (AFNUM_INET<<8 | SAFNUM_LABUNICAST):
case (AFNUM_INET<<8 | SAFNUM_RT_ROUTING_INFO):
case (AFNUM_INET<<8 | SAFNUM_MULTICAST_VPN):
case (AFNUM_INET<<8 | SAFNUM_MDT):
if (tlen < (int)sizeof(struct in_addr)) {
ND_PRINT((ndo, "invalid len"));
tlen = 0;
} else {
ND_TCHECK2(tptr[0], sizeof(struct in_addr));
ND_PRINT((ndo, "%s",ipaddr_string(ndo, tptr)));
tlen -= sizeof(struct in_addr);
tptr += sizeof(struct in_addr);
}
break;
case (AFNUM_INET<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_INET<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_INET<<8 | SAFNUM_VPNUNIMULTICAST):
if (tlen < (int)(sizeof(struct in_addr)+BGP_VPN_RD_LEN)) {
ND_PRINT((ndo, "invalid len"));
tlen = 0;
} else {
ND_TCHECK2(tptr[0], sizeof(struct in_addr)+BGP_VPN_RD_LEN);
ND_PRINT((ndo, "RD: %s, %s",
bgp_vpn_rd_print(ndo, tptr),
ipaddr_string(ndo, tptr+BGP_VPN_RD_LEN)));
tlen -= (sizeof(struct in_addr)+BGP_VPN_RD_LEN);
tptr += (sizeof(struct in_addr)+BGP_VPN_RD_LEN);
}
break;
case (AFNUM_INET6<<8 | SAFNUM_UNICAST):
case (AFNUM_INET6<<8 | SAFNUM_MULTICAST):
case (AFNUM_INET6<<8 | SAFNUM_UNIMULTICAST):
case (AFNUM_INET6<<8 | SAFNUM_LABUNICAST):
if (tlen < (int)sizeof(struct in6_addr)) {
ND_PRINT((ndo, "invalid len"));
tlen = 0;
} else {
ND_TCHECK2(tptr[0], sizeof(struct in6_addr));
ND_PRINT((ndo, "%s", ip6addr_string(ndo, tptr)));
tlen -= sizeof(struct in6_addr);
tptr += sizeof(struct in6_addr);
}
break;
case (AFNUM_INET6<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_INET6<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_INET6<<8 | SAFNUM_VPNUNIMULTICAST):
if (tlen < (int)(sizeof(struct in6_addr)+BGP_VPN_RD_LEN)) {
ND_PRINT((ndo, "invalid len"));
tlen = 0;
} else {
ND_TCHECK2(tptr[0], sizeof(struct in6_addr)+BGP_VPN_RD_LEN);
ND_PRINT((ndo, "RD: %s, %s",
bgp_vpn_rd_print(ndo, tptr),
ip6addr_string(ndo, tptr+BGP_VPN_RD_LEN)));
tlen -= (sizeof(struct in6_addr)+BGP_VPN_RD_LEN);
tptr += (sizeof(struct in6_addr)+BGP_VPN_RD_LEN);
}
break;
case (AFNUM_VPLS<<8 | SAFNUM_VPLS):
case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_L2VPN<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNIMULTICAST):
if (tlen < (int)sizeof(struct in_addr)) {
ND_PRINT((ndo, "invalid len"));
tlen = 0;
} else {
ND_TCHECK2(tptr[0], sizeof(struct in_addr));
ND_PRINT((ndo, "%s", ipaddr_string(ndo, tptr)));
tlen -= (sizeof(struct in_addr));
tptr += (sizeof(struct in_addr));
}
break;
case (AFNUM_NSAP<<8 | SAFNUM_UNICAST):
case (AFNUM_NSAP<<8 | SAFNUM_MULTICAST):
case (AFNUM_NSAP<<8 | SAFNUM_UNIMULTICAST):
ND_TCHECK2(tptr[0], tlen);
ND_PRINT((ndo, "%s", isonsap_string(ndo, tptr, tlen)));
tptr += tlen;
tlen = 0;
break;
case (AFNUM_NSAP<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_NSAP<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_NSAP<<8 | SAFNUM_VPNUNIMULTICAST):
if (tlen < BGP_VPN_RD_LEN+1) {
ND_PRINT((ndo, "invalid len"));
tlen = 0;
} else {
ND_TCHECK2(tptr[0], tlen);
ND_PRINT((ndo, "RD: %s, %s",
bgp_vpn_rd_print(ndo, tptr),
isonsap_string(ndo, tptr+BGP_VPN_RD_LEN,tlen-BGP_VPN_RD_LEN)));
/* rfc986 mapped IPv4 address ? */
if (EXTRACT_32BITS(tptr+BGP_VPN_RD_LEN) == 0x47000601)
ND_PRINT((ndo, " = %s", ipaddr_string(ndo, tptr+BGP_VPN_RD_LEN+4)));
/* rfc1888 mapped IPv6 address ? */
else if (EXTRACT_24BITS(tptr+BGP_VPN_RD_LEN) == 0x350000)
ND_PRINT((ndo, " = %s", ip6addr_string(ndo, tptr+BGP_VPN_RD_LEN+3)));
tptr += tlen;
tlen = 0;
}
break;
default:
ND_TCHECK2(tptr[0], tlen);
ND_PRINT((ndo, "no AFI %u/SAFI %u decoder", af, safi));
if (ndo->ndo_vflag <= 1)
print_unknown_data(ndo, tptr, "\n\t ", tlen);
tptr += tlen;
tlen = 0;
goto done;
break;
}
}
}
ND_PRINT((ndo, ", nh-length: %u", nhlen));
tptr += tlen;
ND_TCHECK(tptr[0]);
snpa = tptr[0];
tptr++;
if (snpa) {
ND_PRINT((ndo, "\n\t %u SNPA", snpa));
for (/*nothing*/; snpa > 0; snpa--) {
ND_TCHECK(tptr[0]);
ND_PRINT((ndo, "\n\t %d bytes", tptr[0]));
tptr += tptr[0] + 1;
}
} else {
ND_PRINT((ndo, ", no SNPA"));
}
while (tptr < pptr + len) {
switch (af<<8 | safi) {
case (AFNUM_INET<<8 | SAFNUM_UNICAST):
case (AFNUM_INET<<8 | SAFNUM_MULTICAST):
case (AFNUM_INET<<8 | SAFNUM_UNIMULTICAST):
advance = decode_prefix4(ndo, tptr, len, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else if (advance == -3)
break; /* bytes left, but not enough */
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET<<8 | SAFNUM_LABUNICAST):
advance = decode_labeled_prefix4(ndo, tptr, len, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else if (advance == -3)
break; /* bytes left, but not enough */
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_INET<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_INET<<8 | SAFNUM_VPNUNIMULTICAST):
advance = decode_labeled_vpn_prefix4(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET<<8 | SAFNUM_RT_ROUTING_INFO):
advance = decode_rt_routing_info(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET<<8 | SAFNUM_MULTICAST_VPN): /* fall through */
case (AFNUM_INET6<<8 | SAFNUM_MULTICAST_VPN):
advance = decode_multicast_vpn(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET<<8 | SAFNUM_MDT):
advance = decode_mdt_vpn_nlri(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET6<<8 | SAFNUM_UNICAST):
case (AFNUM_INET6<<8 | SAFNUM_MULTICAST):
case (AFNUM_INET6<<8 | SAFNUM_UNIMULTICAST):
advance = decode_prefix6(ndo, tptr, len, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else if (advance == -3)
break; /* bytes left, but not enough */
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET6<<8 | SAFNUM_LABUNICAST):
advance = decode_labeled_prefix6(ndo, tptr, len, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else if (advance == -3)
break; /* bytes left, but not enough */
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET6<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_INET6<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_INET6<<8 | SAFNUM_VPNUNIMULTICAST):
advance = decode_labeled_vpn_prefix6(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_VPLS<<8 | SAFNUM_VPLS):
case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_L2VPN<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNIMULTICAST):
advance = decode_labeled_vpn_l2(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_NSAP<<8 | SAFNUM_UNICAST):
case (AFNUM_NSAP<<8 | SAFNUM_MULTICAST):
case (AFNUM_NSAP<<8 | SAFNUM_UNIMULTICAST):
advance = decode_clnp_prefix(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_NSAP<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_NSAP<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_NSAP<<8 | SAFNUM_VPNUNIMULTICAST):
advance = decode_labeled_vpn_clnp_prefix(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
default:
ND_TCHECK2(*tptr,tlen);
ND_PRINT((ndo, "\n\t no AFI %u / SAFI %u decoder", af, safi));
if (ndo->ndo_vflag <= 1)
print_unknown_data(ndo, tptr, "\n\t ", tlen);
advance = 0;
tptr = pptr + len;
break;
}
if (advance < 0)
break;
tptr += advance;
}
done:
break;
case BGPTYPE_MP_UNREACH_NLRI:
ND_TCHECK2(tptr[0], BGP_MP_NLRI_MINSIZE);
af = EXTRACT_16BITS(tptr);
safi = tptr[2];
ND_PRINT((ndo, "\n\t AFI: %s (%u), %sSAFI: %s (%u)",
tok2str(af_values, "Unknown AFI", af),
af,
(safi>128) ? "vendor specific " : "", /* 128 is meanwhile wellknown */
tok2str(bgp_safi_values, "Unknown SAFI", safi),
safi));
if (len == BGP_MP_NLRI_MINSIZE)
ND_PRINT((ndo, "\n\t End-of-Rib Marker (empty NLRI)"));
tptr += 3;
while (tptr < pptr + len) {
switch (af<<8 | safi) {
case (AFNUM_INET<<8 | SAFNUM_UNICAST):
case (AFNUM_INET<<8 | SAFNUM_MULTICAST):
case (AFNUM_INET<<8 | SAFNUM_UNIMULTICAST):
advance = decode_prefix4(ndo, tptr, len, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else if (advance == -3)
break; /* bytes left, but not enough */
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET<<8 | SAFNUM_LABUNICAST):
advance = decode_labeled_prefix4(ndo, tptr, len, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else if (advance == -3)
break; /* bytes left, but not enough */
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_INET<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_INET<<8 | SAFNUM_VPNUNIMULTICAST):
advance = decode_labeled_vpn_prefix4(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET6<<8 | SAFNUM_UNICAST):
case (AFNUM_INET6<<8 | SAFNUM_MULTICAST):
case (AFNUM_INET6<<8 | SAFNUM_UNIMULTICAST):
advance = decode_prefix6(ndo, tptr, len, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else if (advance == -3)
break; /* bytes left, but not enough */
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET6<<8 | SAFNUM_LABUNICAST):
advance = decode_labeled_prefix6(ndo, tptr, len, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else if (advance == -3)
break; /* bytes left, but not enough */
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET6<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_INET6<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_INET6<<8 | SAFNUM_VPNUNIMULTICAST):
advance = decode_labeled_vpn_prefix6(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_VPLS<<8 | SAFNUM_VPLS):
case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_L2VPN<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNIMULTICAST):
advance = decode_labeled_vpn_l2(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_NSAP<<8 | SAFNUM_UNICAST):
case (AFNUM_NSAP<<8 | SAFNUM_MULTICAST):
case (AFNUM_NSAP<<8 | SAFNUM_UNIMULTICAST):
advance = decode_clnp_prefix(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_NSAP<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_NSAP<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_NSAP<<8 | SAFNUM_VPNUNIMULTICAST):
advance = decode_labeled_vpn_clnp_prefix(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET<<8 | SAFNUM_MDT):
advance = decode_mdt_vpn_nlri(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET<<8 | SAFNUM_MULTICAST_VPN): /* fall through */
case (AFNUM_INET6<<8 | SAFNUM_MULTICAST_VPN):
advance = decode_multicast_vpn(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
default:
ND_TCHECK2(*(tptr-3),tlen);
ND_PRINT((ndo, "no AFI %u / SAFI %u decoder", af, safi));
if (ndo->ndo_vflag <= 1)
print_unknown_data(ndo, tptr-3, "\n\t ", tlen);
advance = 0;
tptr = pptr + len;
break;
}
if (advance < 0)
break;
tptr += advance;
}
break;
case BGPTYPE_EXTD_COMMUNITIES:
if (len % 8) {
ND_PRINT((ndo, "invalid len"));
break;
}
while (tlen>0) {
uint16_t extd_comm;
ND_TCHECK2(tptr[0], 2);
extd_comm=EXTRACT_16BITS(tptr);
ND_PRINT((ndo, "\n\t %s (0x%04x), Flags [%s]",
tok2str(bgp_extd_comm_subtype_values,
"unknown extd community typecode",
extd_comm),
extd_comm,
bittok2str(bgp_extd_comm_flag_values, "none", extd_comm)));
ND_TCHECK2(*(tptr+2), 6);
switch(extd_comm) {
case BGP_EXT_COM_RT_0:
case BGP_EXT_COM_RO_0:
case BGP_EXT_COM_L2VPN_RT_0:
ND_PRINT((ndo, ": %u:%u (= %s)",
EXTRACT_16BITS(tptr+2),
EXTRACT_32BITS(tptr+4),
ipaddr_string(ndo, tptr+4)));
break;
case BGP_EXT_COM_RT_1:
case BGP_EXT_COM_RO_1:
case BGP_EXT_COM_L2VPN_RT_1:
case BGP_EXT_COM_VRF_RT_IMP:
ND_PRINT((ndo, ": %s:%u",
ipaddr_string(ndo, tptr+2),
EXTRACT_16BITS(tptr+6)));
break;
case BGP_EXT_COM_RT_2:
case BGP_EXT_COM_RO_2:
ND_PRINT((ndo, ": %s:%u",
as_printf(ndo, astostr, sizeof(astostr),
EXTRACT_32BITS(tptr+2)), EXTRACT_16BITS(tptr+6)));
break;
case BGP_EXT_COM_LINKBAND:
bw.i = EXTRACT_32BITS(tptr+2);
ND_PRINT((ndo, ": bandwidth: %.3f Mbps",
bw.f*8/1000000));
break;
case BGP_EXT_COM_VPN_ORIGIN:
case BGP_EXT_COM_VPN_ORIGIN2:
case BGP_EXT_COM_VPN_ORIGIN3:
case BGP_EXT_COM_VPN_ORIGIN4:
case BGP_EXT_COM_OSPF_RID:
case BGP_EXT_COM_OSPF_RID2:
ND_PRINT((ndo, "%s", ipaddr_string(ndo, tptr+2)));
break;
case BGP_EXT_COM_OSPF_RTYPE:
case BGP_EXT_COM_OSPF_RTYPE2:
ND_PRINT((ndo, ": area:%s, router-type:%s, metric-type:%s%s",
ipaddr_string(ndo, tptr+2),
tok2str(bgp_extd_comm_ospf_rtype_values,
"unknown (0x%02x)",
*(tptr+6)),
(*(tptr+7) & BGP_OSPF_RTYPE_METRIC_TYPE) ? "E2" : "",
((*(tptr+6) == BGP_OSPF_RTYPE_EXT) || (*(tptr+6) == BGP_OSPF_RTYPE_NSSA)) ? "E1" : ""));
break;
case BGP_EXT_COM_L2INFO:
ND_PRINT((ndo, ": %s Control Flags [0x%02x]:MTU %u",
tok2str(l2vpn_encaps_values,
"unknown encaps",
*(tptr+2)),
*(tptr+3),
EXTRACT_16BITS(tptr+4)));
break;
case BGP_EXT_COM_SOURCE_AS:
ND_PRINT((ndo, ": AS %u", EXTRACT_16BITS(tptr+2)));
break;
default:
ND_TCHECK2(*tptr,8);
print_unknown_data(ndo, tptr, "\n\t ", 8);
break;
}
tlen -=8;
tptr +=8;
}
break;
case BGPTYPE_PMSI_TUNNEL:
{
uint8_t tunnel_type, flags;
ND_TCHECK2(tptr[0], 5);
tunnel_type = *(tptr+1);
flags = *tptr;
tlen = len;
ND_PRINT((ndo, "\n\t Tunnel-type %s (%u), Flags [%s], MPLS Label %u",
tok2str(bgp_pmsi_tunnel_values, "Unknown", tunnel_type),
tunnel_type,
bittok2str(bgp_pmsi_flag_values, "none", flags),
EXTRACT_24BITS(tptr+2)>>4));
tptr +=5;
tlen -= 5;
switch (tunnel_type) {
case BGP_PMSI_TUNNEL_PIM_SM: /* fall through */
case BGP_PMSI_TUNNEL_PIM_BIDIR:
ND_TCHECK2(tptr[0], 8);
ND_PRINT((ndo, "\n\t Sender %s, P-Group %s",
ipaddr_string(ndo, tptr),
ipaddr_string(ndo, tptr+4)));
break;
case BGP_PMSI_TUNNEL_PIM_SSM:
ND_TCHECK2(tptr[0], 8);
ND_PRINT((ndo, "\n\t Root-Node %s, P-Group %s",
ipaddr_string(ndo, tptr),
ipaddr_string(ndo, tptr+4)));
break;
case BGP_PMSI_TUNNEL_INGRESS:
ND_TCHECK2(tptr[0], 4);
ND_PRINT((ndo, "\n\t Tunnel-Endpoint %s",
ipaddr_string(ndo, tptr)));
break;
case BGP_PMSI_TUNNEL_LDP_P2MP: /* fall through */
case BGP_PMSI_TUNNEL_LDP_MP2MP:
ND_TCHECK2(tptr[0], 8);
ND_PRINT((ndo, "\n\t Root-Node %s, LSP-ID 0x%08x",
ipaddr_string(ndo, tptr),
EXTRACT_32BITS(tptr+4)));
break;
case BGP_PMSI_TUNNEL_RSVP_P2MP:
ND_TCHECK2(tptr[0], 8);
ND_PRINT((ndo, "\n\t Extended-Tunnel-ID %s, P2MP-ID 0x%08x",
ipaddr_string(ndo, tptr),
EXTRACT_32BITS(tptr+4)));
break;
default:
if (ndo->ndo_vflag <= 1) {
print_unknown_data(ndo, tptr, "\n\t ", tlen);
}
}
break;
}
case BGPTYPE_AIGP:
{
uint8_t type;
uint16_t length;
tlen = len;
while (tlen >= 3) {
ND_TCHECK2(tptr[0], 3);
type = *tptr;
length = EXTRACT_16BITS(tptr+1);
tptr += 3;
tlen -= 3;
ND_PRINT((ndo, "\n\t %s TLV (%u), length %u",
tok2str(bgp_aigp_values, "Unknown", type),
type, length));
if (length < 3)
goto trunc;
length -= 3;
/*
* Check if we can read the TLV data.
*/
ND_TCHECK2(tptr[3], length);
switch (type) {
case BGP_AIGP_TLV:
if (length < 8)
goto trunc;
ND_PRINT((ndo, ", metric %" PRIu64,
EXTRACT_64BITS(tptr)));
break;
default:
if (ndo->ndo_vflag <= 1) {
print_unknown_data(ndo, tptr,"\n\t ", length);
}
}
tptr += length;
tlen -= length;
}
break;
}
case BGPTYPE_ATTR_SET:
ND_TCHECK2(tptr[0], 4);
if (len < 4)
goto trunc;
ND_PRINT((ndo, "\n\t Origin AS: %s",
as_printf(ndo, astostr, sizeof(astostr), EXTRACT_32BITS(tptr))));
tptr+=4;
len -=4;
while (len) {
u_int aflags, alenlen, alen;
ND_TCHECK2(tptr[0], 2);
if (len < 2)
goto trunc;
aflags = *tptr;
atype = *(tptr + 1);
tptr += 2;
len -= 2;
alenlen = bgp_attr_lenlen(aflags, tptr);
ND_TCHECK2(tptr[0], alenlen);
if (len < alenlen)
goto trunc;
alen = bgp_attr_len(aflags, tptr);
tptr += alenlen;
len -= alenlen;
ND_PRINT((ndo, "\n\t %s (%u), length: %u",
tok2str(bgp_attr_values,
"Unknown Attribute", atype),
atype,
alen));
if (aflags) {
ND_PRINT((ndo, ", Flags [%s%s%s%s",
aflags & 0x80 ? "O" : "",
aflags & 0x40 ? "T" : "",
aflags & 0x20 ? "P" : "",
aflags & 0x10 ? "E" : ""));
if (aflags & 0xf)
ND_PRINT((ndo, "+%x", aflags & 0xf));
ND_PRINT((ndo, "]: "));
}
/* FIXME check for recursion */
if (!bgp_attr_print(ndo, atype, tptr, alen))
return 0;
tptr += alen;
len -= alen;
}
break;
case BGPTYPE_LARGE_COMMUNITY:
if (len == 0 || len % 12) {
ND_PRINT((ndo, "invalid len"));
break;
}
ND_PRINT((ndo, "\n\t "));
while (len > 0) {
ND_TCHECK2(*tptr, 12);
ND_PRINT((ndo, "%u:%u:%u%s",
EXTRACT_32BITS(tptr),
EXTRACT_32BITS(tptr + 4),
EXTRACT_32BITS(tptr + 8),
(len > 12) ? ", " : ""));
tptr += 12;
len -= 12;
}
break;
default:
ND_TCHECK2(*pptr,len);
ND_PRINT((ndo, "\n\t no Attribute %u decoder", atype)); /* we have no decoder for the attribute */
if (ndo->ndo_vflag <= 1)
print_unknown_data(ndo, pptr, "\n\t ", len);
break;
}
if (ndo->ndo_vflag > 1 && len) { /* omit zero length attributes*/
ND_TCHECK2(*pptr,len);
print_unknown_data(ndo, pptr, "\n\t ", len);
}
return 1;
trunc:
return 0;
}
static void
bgp_capabilities_print(netdissect_options *ndo,
const u_char *opt, int caps_len)
{
int cap_type, cap_len, tcap_len, cap_offset;
int i = 0;
while (i < caps_len) {
ND_TCHECK2(opt[i], BGP_CAP_HEADER_SIZE);
cap_type=opt[i];
cap_len=opt[i+1];
tcap_len=cap_len;
ND_PRINT((ndo, "\n\t %s (%u), length: %u",
tok2str(bgp_capcode_values, "Unknown",
cap_type),
cap_type,
cap_len));
ND_TCHECK2(opt[i+2], cap_len);
switch (cap_type) {
case BGP_CAPCODE_MP:
ND_PRINT((ndo, "\n\t\tAFI %s (%u), SAFI %s (%u)",
tok2str(af_values, "Unknown",
EXTRACT_16BITS(opt+i+2)),
EXTRACT_16BITS(opt+i+2),
tok2str(bgp_safi_values, "Unknown",
opt[i+5]),
opt[i+5]));
break;
case BGP_CAPCODE_RESTART:
/* Restart Flags (4 bits), Restart Time in seconds (12 bits) */
ND_TCHECK_16BITS(opt + i + 2);
ND_PRINT((ndo, "\n\t\tRestart Flags: [%s], Restart Time %us",
((opt[i+2])&0x80) ? "R" : "none",
EXTRACT_16BITS(opt+i+2)&0xfff));
tcap_len-=2;
cap_offset=4;
while(tcap_len>=4) {
ND_PRINT((ndo, "\n\t\t AFI %s (%u), SAFI %s (%u), Forwarding state preserved: %s",
tok2str(af_values,"Unknown",
EXTRACT_16BITS(opt+i+cap_offset)),
EXTRACT_16BITS(opt+i+cap_offset),
tok2str(bgp_safi_values,"Unknown",
opt[i+cap_offset+2]),
opt[i+cap_offset+2],
((opt[i+cap_offset+3])&0x80) ? "yes" : "no" ));
tcap_len-=4;
cap_offset+=4;
}
break;
case BGP_CAPCODE_RR:
case BGP_CAPCODE_RR_CISCO:
break;
case BGP_CAPCODE_AS_NEW:
/*
* Extract the 4 byte AS number encoded.
*/
if (cap_len == 4) {
ND_PRINT((ndo, "\n\t\t 4 Byte AS %s",
as_printf(ndo, astostr, sizeof(astostr),
EXTRACT_32BITS(opt + i + 2))));
}
break;
case BGP_CAPCODE_ADD_PATH:
cap_offset=2;
if (tcap_len == 0) {
ND_PRINT((ndo, " (bogus)")); /* length */
break;
}
while (tcap_len > 0) {
if (tcap_len < 4) {
ND_PRINT((ndo, "\n\t\t(invalid)"));
break;
}
ND_PRINT((ndo, "\n\t\tAFI %s (%u), SAFI %s (%u), Send/Receive: %s",
tok2str(af_values,"Unknown",EXTRACT_16BITS(opt+i+cap_offset)),
EXTRACT_16BITS(opt+i+cap_offset),
tok2str(bgp_safi_values,"Unknown",opt[i+cap_offset+2]),
opt[i+cap_offset+2],
tok2str(bgp_add_path_recvsend,"Bogus (0x%02x)",opt[i+cap_offset+3])
));
tcap_len-=4;
cap_offset+=4;
}
break;
default:
ND_PRINT((ndo, "\n\t\tno decoder for Capability %u",
cap_type));
if (ndo->ndo_vflag <= 1)
print_unknown_data(ndo, &opt[i+2], "\n\t\t", cap_len);
break;
}
if (ndo->ndo_vflag > 1 && cap_len > 0) {
print_unknown_data(ndo, &opt[i+2], "\n\t\t", cap_len);
}
i += BGP_CAP_HEADER_SIZE + cap_len;
}
return;
trunc:
ND_PRINT((ndo, "[|BGP]"));
}
static void
bgp_open_print(netdissect_options *ndo,
const u_char *dat, int length)
{
struct bgp_open bgpo;
struct bgp_opt bgpopt;
const u_char *opt;
int i;
ND_TCHECK2(dat[0], BGP_OPEN_SIZE);
memcpy(&bgpo, dat, BGP_OPEN_SIZE);
ND_PRINT((ndo, "\n\t Version %d, ", bgpo.bgpo_version));
ND_PRINT((ndo, "my AS %s, ",
as_printf(ndo, astostr, sizeof(astostr), ntohs(bgpo.bgpo_myas))));
ND_PRINT((ndo, "Holdtime %us, ", ntohs(bgpo.bgpo_holdtime)));
ND_PRINT((ndo, "ID %s", ipaddr_string(ndo, &bgpo.bgpo_id)));
ND_PRINT((ndo, "\n\t Optional parameters, length: %u", bgpo.bgpo_optlen));
/* some little sanity checking */
if (length < bgpo.bgpo_optlen+BGP_OPEN_SIZE)
return;
/* ugly! */
opt = &((const struct bgp_open *)dat)->bgpo_optlen;
opt++;
i = 0;
while (i < bgpo.bgpo_optlen) {
ND_TCHECK2(opt[i], BGP_OPT_SIZE);
memcpy(&bgpopt, &opt[i], BGP_OPT_SIZE);
if (i + 2 + bgpopt.bgpopt_len > bgpo.bgpo_optlen) {
ND_PRINT((ndo, "\n\t Option %d, length: %u", bgpopt.bgpopt_type, bgpopt.bgpopt_len));
break;
}
ND_PRINT((ndo, "\n\t Option %s (%u), length: %u",
tok2str(bgp_opt_values,"Unknown",
bgpopt.bgpopt_type),
bgpopt.bgpopt_type,
bgpopt.bgpopt_len));
/* now let's decode the options we know*/
switch(bgpopt.bgpopt_type) {
case BGP_OPT_CAP:
bgp_capabilities_print(ndo, &opt[i+BGP_OPT_SIZE],
bgpopt.bgpopt_len);
break;
case BGP_OPT_AUTH:
default:
ND_PRINT((ndo, "\n\t no decoder for option %u",
bgpopt.bgpopt_type));
break;
}
i += BGP_OPT_SIZE + bgpopt.bgpopt_len;
}
return;
trunc:
ND_PRINT((ndo, "[|BGP]"));
}
static void
bgp_update_print(netdissect_options *ndo,
const u_char *dat, int length)
{
struct bgp bgp;
const u_char *p;
int withdrawn_routes_len;
int len;
int i;
ND_TCHECK2(dat[0], BGP_SIZE);
if (length < BGP_SIZE)
goto trunc;
memcpy(&bgp, dat, BGP_SIZE);
p = dat + BGP_SIZE; /*XXX*/
length -= BGP_SIZE;
/* Unfeasible routes */
ND_TCHECK2(p[0], 2);
if (length < 2)
goto trunc;
withdrawn_routes_len = EXTRACT_16BITS(p);
p += 2;
length -= 2;
if (withdrawn_routes_len) {
/*
* Without keeping state from the original NLRI message,
* it's not possible to tell if this a v4 or v6 route,
* so only try to decode it if we're not v6 enabled.
*/
ND_TCHECK2(p[0], withdrawn_routes_len);
if (length < withdrawn_routes_len)
goto trunc;
ND_PRINT((ndo, "\n\t Withdrawn routes: %d bytes", withdrawn_routes_len));
p += withdrawn_routes_len;
length -= withdrawn_routes_len;
}
ND_TCHECK2(p[0], 2);
if (length < 2)
goto trunc;
len = EXTRACT_16BITS(p);
p += 2;
length -= 2;
if (withdrawn_routes_len == 0 && len == 0 && length == 0) {
/* No withdrawn routes, no path attributes, no NLRI */
ND_PRINT((ndo, "\n\t End-of-Rib Marker (empty NLRI)"));
return;
}
if (len) {
/* do something more useful!*/
while (len) {
int aflags, atype, alenlen, alen;
ND_TCHECK2(p[0], 2);
if (len < 2)
goto trunc;
if (length < 2)
goto trunc;
aflags = *p;
atype = *(p + 1);
p += 2;
len -= 2;
length -= 2;
alenlen = bgp_attr_lenlen(aflags, p);
ND_TCHECK2(p[0], alenlen);
if (len < alenlen)
goto trunc;
if (length < alenlen)
goto trunc;
alen = bgp_attr_len(aflags, p);
p += alenlen;
len -= alenlen;
length -= alenlen;
ND_PRINT((ndo, "\n\t %s (%u), length: %u",
tok2str(bgp_attr_values, "Unknown Attribute",
atype),
atype,
alen));
if (aflags) {
ND_PRINT((ndo, ", Flags [%s%s%s%s",
aflags & 0x80 ? "O" : "",
aflags & 0x40 ? "T" : "",
aflags & 0x20 ? "P" : "",
aflags & 0x10 ? "E" : ""));
if (aflags & 0xf)
ND_PRINT((ndo, "+%x", aflags & 0xf));
ND_PRINT((ndo, "]: "));
}
if (len < alen)
goto trunc;
if (length < alen)
goto trunc;
if (!bgp_attr_print(ndo, atype, p, alen))
goto trunc;
p += alen;
len -= alen;
length -= alen;
}
}
if (length) {
/*
* XXX - what if they're using the "Advertisement of
* Multiple Paths in BGP" feature:
*
* https://datatracker.ietf.org/doc/draft-ietf-idr-add-paths/
*
* http://tools.ietf.org/html/draft-ietf-idr-add-paths-06
*/
ND_PRINT((ndo, "\n\t Updated routes:"));
while (length) {
char buf[MAXHOSTNAMELEN + 100];
i = decode_prefix4(ndo, p, length, buf, sizeof(buf));
if (i == -1) {
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
break;
} else if (i == -2)
goto trunc;
else if (i == -3)
goto trunc; /* bytes left, but not enough */
else {
ND_PRINT((ndo, "\n\t %s", buf));
p += i;
length -= i;
}
}
}
return;
trunc:
ND_PRINT((ndo, "[|BGP]"));
}
static void
bgp_notification_print(netdissect_options *ndo,
const u_char *dat, int length)
{
struct bgp_notification bgpn;
const u_char *tptr;
ND_TCHECK2(dat[0], BGP_NOTIFICATION_SIZE);
memcpy(&bgpn, dat, BGP_NOTIFICATION_SIZE);
/* some little sanity checking */
if (length<BGP_NOTIFICATION_SIZE)
return;
ND_PRINT((ndo, ", %s (%u)",
tok2str(bgp_notify_major_values, "Unknown Error",
bgpn.bgpn_major),
bgpn.bgpn_major));
switch (bgpn.bgpn_major) {
case BGP_NOTIFY_MAJOR_MSG:
ND_PRINT((ndo, ", subcode %s (%u)",
tok2str(bgp_notify_minor_msg_values, "Unknown",
bgpn.bgpn_minor),
bgpn.bgpn_minor));
break;
case BGP_NOTIFY_MAJOR_OPEN:
ND_PRINT((ndo, ", subcode %s (%u)",
tok2str(bgp_notify_minor_open_values, "Unknown",
bgpn.bgpn_minor),
bgpn.bgpn_minor));
break;
case BGP_NOTIFY_MAJOR_UPDATE:
ND_PRINT((ndo, ", subcode %s (%u)",
tok2str(bgp_notify_minor_update_values, "Unknown",
bgpn.bgpn_minor),
bgpn.bgpn_minor));
break;
case BGP_NOTIFY_MAJOR_FSM:
ND_PRINT((ndo, " subcode %s (%u)",
tok2str(bgp_notify_minor_fsm_values, "Unknown",
bgpn.bgpn_minor),
bgpn.bgpn_minor));
break;
case BGP_NOTIFY_MAJOR_CAP:
ND_PRINT((ndo, " subcode %s (%u)",
tok2str(bgp_notify_minor_cap_values, "Unknown",
bgpn.bgpn_minor),
bgpn.bgpn_minor));
break;
case BGP_NOTIFY_MAJOR_CEASE:
ND_PRINT((ndo, ", subcode %s (%u)",
tok2str(bgp_notify_minor_cease_values, "Unknown",
bgpn.bgpn_minor),
bgpn.bgpn_minor));
/* draft-ietf-idr-cease-subcode-02 mentions optionally 7 bytes
* for the maxprefix subtype, which may contain AFI, SAFI and MAXPREFIXES
*/
if(bgpn.bgpn_minor == BGP_NOTIFY_MINOR_CEASE_MAXPRFX && length >= BGP_NOTIFICATION_SIZE + 7) {
tptr = dat + BGP_NOTIFICATION_SIZE;
ND_TCHECK2(*tptr, 7);
ND_PRINT((ndo, ", AFI %s (%u), SAFI %s (%u), Max Prefixes: %u",
tok2str(af_values, "Unknown",
EXTRACT_16BITS(tptr)),
EXTRACT_16BITS(tptr),
tok2str(bgp_safi_values, "Unknown", *(tptr+2)),
*(tptr+2),
EXTRACT_32BITS(tptr+3)));
}
break;
default:
break;
}
return;
trunc:
ND_PRINT((ndo, "[|BGP]"));
}
static void
bgp_route_refresh_print(netdissect_options *ndo,
const u_char *pptr, int len)
{
const struct bgp_route_refresh *bgp_route_refresh_header;
ND_TCHECK2(pptr[0], BGP_ROUTE_REFRESH_SIZE);
/* some little sanity checking */
if (len<BGP_ROUTE_REFRESH_SIZE)
return;
bgp_route_refresh_header = (const struct bgp_route_refresh *)pptr;
ND_PRINT((ndo, "\n\t AFI %s (%u), SAFI %s (%u)",
tok2str(af_values,"Unknown",
/* this stinks but the compiler pads the structure
* weird */
EXTRACT_16BITS(&bgp_route_refresh_header->afi)),
EXTRACT_16BITS(&bgp_route_refresh_header->afi),
tok2str(bgp_safi_values,"Unknown",
bgp_route_refresh_header->safi),
bgp_route_refresh_header->safi));
if (ndo->ndo_vflag > 1) {
ND_TCHECK2(*pptr, len);
print_unknown_data(ndo, pptr, "\n\t ", len);
}
return;
trunc:
ND_PRINT((ndo, "[|BGP]"));
}
static int
bgp_header_print(netdissect_options *ndo,
const u_char *dat, int length)
{
struct bgp bgp;
ND_TCHECK2(dat[0], BGP_SIZE);
memcpy(&bgp, dat, BGP_SIZE);
ND_PRINT((ndo, "\n\t%s Message (%u), length: %u",
tok2str(bgp_msg_values, "Unknown", bgp.bgp_type),
bgp.bgp_type,
length));
switch (bgp.bgp_type) {
case BGP_OPEN:
bgp_open_print(ndo, dat, length);
break;
case BGP_UPDATE:
bgp_update_print(ndo, dat, length);
break;
case BGP_NOTIFICATION:
bgp_notification_print(ndo, dat, length);
break;
case BGP_KEEPALIVE:
break;
case BGP_ROUTE_REFRESH:
bgp_route_refresh_print(ndo, dat, length);
break;
default:
/* we have no decoder for the BGP message */
ND_TCHECK2(*dat, length);
ND_PRINT((ndo, "\n\t no Message %u decoder", bgp.bgp_type));
print_unknown_data(ndo, dat, "\n\t ", length);
break;
}
return 1;
trunc:
ND_PRINT((ndo, "[|BGP]"));
return 0;
}
void
bgp_print(netdissect_options *ndo,
const u_char *dat, int length)
{
const u_char *p;
const u_char *ep;
const u_char *start;
const u_char marker[] = {
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
};
struct bgp bgp;
uint16_t hlen;
ep = dat + length;
if (ndo->ndo_snapend < dat + length)
ep = ndo->ndo_snapend;
ND_PRINT((ndo, ": BGP"));
if (ndo->ndo_vflag < 1) /* lets be less chatty */
return;
p = dat;
start = p;
while (p < ep) {
if (!ND_TTEST2(p[0], 1))
break;
if (p[0] != 0xff) {
p++;
continue;
}
if (!ND_TTEST2(p[0], sizeof(marker)))
break;
if (memcmp(p, marker, sizeof(marker)) != 0) {
p++;
continue;
}
/* found BGP header */
ND_TCHECK2(p[0], BGP_SIZE); /*XXX*/
memcpy(&bgp, p, BGP_SIZE);
if (start != p)
ND_PRINT((ndo, " [|BGP]"));
hlen = ntohs(bgp.bgp_len);
if (hlen < BGP_SIZE) {
ND_PRINT((ndo, "\n[|BGP Bogus header length %u < %u]", hlen,
BGP_SIZE));
break;
}
if (ND_TTEST2(p[0], hlen)) {
if (!bgp_header_print(ndo, p, hlen))
return;
p += hlen;
start = p;
} else {
ND_PRINT((ndo, "\n[|BGP %s]",
tok2str(bgp_msg_values,
"Unknown Message Type",
bgp.bgp_type)));
break;
}
}
return;
trunc:
ND_PRINT((ndo, " [|BGP]"));
}
/*
* Local Variables:
* c-style: whitesmith
* c-basic-offset: 4
* End:
*/
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_265_0 |
crossvul-cpp_data_good_5241_0 | /*
* io_dp.c
*
* Implements the dynamic pointer interface.
*
* Based on GD.pm code by Lincoln Stein for interfacing to libgd.
* Added support for reading as well as support for 'tell' and 'seek'.
*
* As will all I/O modules, most functions are for local use only (called
* via function pointers in the I/O context).
*
* gdDPExtractData is the exception to this: it will return the pointer to
* the internal data, and reset the internal storage.
*
* Written/Modified 1999, Philip Warner.
*/
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif
#include <math.h>
#include <string.h>
#include <stdlib.h>
#include "gd.h"
#include "gdhelpers.h"
#define TRUE 1
#define FALSE 0
/* this is used for creating images in main memory */
typedef struct dpStruct {
void *data;
int logicalSize;
int realSize;
int dataGood;
int pos;
int freeOK;
}
dynamicPtr;
typedef struct dpIOCtx {
gdIOCtx ctx;
dynamicPtr *dp;
}
dpIOCtx;
typedef struct dpIOCtx *dpIOCtxPtr;
/* these functions operate on in-memory dynamic pointers */
static int allocDynamic(dynamicPtr *dp, int initialSize, void *data);
static int appendDynamic(dynamicPtr *dp, const void *src, int size);
static int gdReallocDynamic(dynamicPtr *dp, int required);
static int trimDynamic(dynamicPtr *dp);
static void gdFreeDynamicCtx(struct gdIOCtx *ctx);
static dynamicPtr *newDynamic(int initialSize, void *data, int freeOKFlag);
static int dynamicPutbuf(struct gdIOCtx *, const void *, int);
static void dynamicPutchar(struct gdIOCtx *, int a);
static int dynamicGetbuf(gdIOCtxPtr ctx, void *buf, int len);
static int dynamicGetchar(gdIOCtxPtr ctx);
static int dynamicSeek(struct gdIOCtx *, const int);
static long dynamicTell(struct gdIOCtx *);
/*
Function: gdNewDynamicCtx
Return data as a dynamic pointer.
*/
BGD_DECLARE(gdIOCtx *) gdNewDynamicCtx(int initialSize, void *data)
{
/* 2.0.23: Phil Moore: 'return' keyword was missing! */
return gdNewDynamicCtxEx(initialSize, data, 1);
}
/*
Function: gdNewDynamicCtxEx
*/
BGD_DECLARE(gdIOCtx *) gdNewDynamicCtxEx(int initialSize, void *data, int freeOKFlag)
{
dpIOCtx *ctx;
dynamicPtr *dp;
ctx = (dpIOCtx *)gdMalloc(sizeof (dpIOCtx));
if(ctx == NULL) {
return NULL;
}
dp = newDynamic(initialSize, data, freeOKFlag);
if(!dp) {
gdFree (ctx);
return NULL;
};
ctx->dp = dp;
ctx->ctx.getC = dynamicGetchar;
ctx->ctx.putC = dynamicPutchar;
ctx->ctx.getBuf = dynamicGetbuf;
ctx->ctx.putBuf = dynamicPutbuf;
ctx->ctx.seek = dynamicSeek;
ctx->ctx.tell = dynamicTell;
ctx->ctx.gd_free = gdFreeDynamicCtx;
return (gdIOCtx *)ctx;
}
/*
Function: gdDPExtractData
*/
BGD_DECLARE(void *) gdDPExtractData (struct gdIOCtx *ctx, int *size)
{
dynamicPtr *dp;
dpIOCtx *dctx;
void *data;
dctx = (dpIOCtx *)ctx;
dp = dctx->dp;
/* clean up the data block and return it */
if(dp->dataGood) {
trimDynamic(dp);
*size = dp->logicalSize;
data = dp->data;
} else {
*size = 0;
data = NULL;
/* 2.0.21: never free memory we don't own */
if((dp->data != NULL) && (dp->freeOK)) {
gdFree(dp->data);
}
}
dp->data = NULL;
dp->realSize = 0;
dp->logicalSize = 0;
return data;
}
static void gdFreeDynamicCtx(struct gdIOCtx *ctx)
{
dynamicPtr *dp;
dpIOCtx *dctx;
dctx = (dpIOCtx *)ctx;
dp = dctx->dp;
gdFree(ctx);
/* clean up the data block and return it */
/* 2.0.21: never free memory we don't own */
if((dp->data != NULL) && (dp->freeOK)) {
gdFree(dp->data);
dp->data = NULL;
}
dp->realSize = 0;
dp->logicalSize = 0;
gdFree(dp);
}
static long dynamicTell(struct gdIOCtx *ctx)
{
dpIOCtx *dctx;
dctx = (dpIOCtx *)ctx;
return (dctx->dp->pos);
}
static int dynamicSeek(struct gdIOCtx *ctx, const int pos)
{
int bytesNeeded;
dynamicPtr *dp;
dpIOCtx *dctx;
dctx = (dpIOCtx *)ctx;
dp = dctx->dp;
if(!dp->dataGood) {
return FALSE;
}
bytesNeeded = pos;
if(bytesNeeded > dp->realSize) {
/* 2.0.21 */
if(!dp->freeOK) {
return FALSE;
}
if(overflow2(dp->realSize, 2)) {
return FALSE;
}
if(!gdReallocDynamic(dp, dp->realSize * 2)) {
dp->dataGood = FALSE;
return FALSE;
}
}
/* if we get here, we can be sure that we have enough bytes
* to copy safely */
/* Extend the logical size if we seek beyond EOF. */
if(pos > dp->logicalSize) {
dp->logicalSize = pos;
};
dp->pos = pos;
return TRUE;
}
/* return data as a dynamic pointer */
static dynamicPtr *newDynamic(int initialSize, void *data, int freeOKFlag)
{
dynamicPtr *dp;
dp = (dynamicPtr *) gdMalloc(sizeof (dynamicPtr));
if(dp == NULL) {
return NULL;
}
if(!allocDynamic(dp, initialSize, data)) {
gdFree(dp);
return NULL;
}
dp->pos = 0;
dp->freeOK = freeOKFlag;
return dp;
}
static int dynamicPutbuf(struct gdIOCtx *ctx, const void *buf, int size)
{
dpIOCtx *dctx;
dctx = (dpIOCtx *)ctx;
appendDynamic(dctx->dp, buf, size);
if(dctx->dp->dataGood) {
return size;
} else {
return -1;
};
}
static void dynamicPutchar(struct gdIOCtx *ctx, int a)
{
unsigned char b;
dpIOCtxPtr dctx;
b = a;
dctx = (dpIOCtxPtr) ctx;
appendDynamic(dctx->dp, &b, 1);
}
/* returns the number of bytes actually read; 0 on EOF and error */
static int dynamicGetbuf(gdIOCtxPtr ctx, void *buf, int len)
{
int rlen, remain;
dpIOCtxPtr dctx;
dynamicPtr *dp;
dctx = (dpIOCtxPtr) ctx;
dp = dctx->dp;
if (dp->pos < 0 || dp->pos >= dp->realSize) {
return 0;
}
remain = dp->logicalSize - dp->pos;
if(remain >= len) {
rlen = len;
} else {
if(remain <= 0) {
return 0;
}
rlen = remain;
}
if (dp->pos + rlen > dp->realSize) {
rlen = dp->realSize - dp->pos;
}
memcpy(buf, (void *) ((char *)dp->data + dp->pos), rlen);
dp->pos += rlen;
return rlen;
}
static int dynamicGetchar(gdIOCtxPtr ctx)
{
unsigned char b;
int rv;
rv = dynamicGetbuf(ctx, &b, 1);
if(rv != 1) {
return EOF;
} else {
return b; /* (b & 0xff); */
}
}
/**********************************************************************
* InitDynamic - Return a dynamically resizable void*
**********************************************************************/
static int allocDynamic(dynamicPtr *dp, int initialSize, void *data)
{
if(data == NULL) {
dp->logicalSize = 0;
dp->dataGood = FALSE;
dp->data = gdMalloc(initialSize);
} else {
dp->logicalSize = initialSize;
dp->dataGood = TRUE;
dp->data = data;
}
if(dp->data != NULL) {
dp->realSize = initialSize;
dp->dataGood = TRUE;
dp->pos = 0;
return TRUE;
} else {
dp->realSize = 0;
return FALSE;
}
}
/* append bytes to the end of a dynamic pointer */
static int appendDynamic(dynamicPtr * dp, const void *src, int size)
{
int bytesNeeded;
char *tmp;
if(!dp->dataGood) {
return FALSE;
}
/* bytesNeeded = dp->logicalSize + size; */
bytesNeeded = dp->pos + size;
if(bytesNeeded > dp->realSize) {
/* 2.0.21 */
if(!dp->freeOK) {
return FALSE;
}
if(overflow2(dp->realSize, 2)) {
return FALSE;
}
if(!gdReallocDynamic(dp, bytesNeeded * 2)) {
dp->dataGood = FALSE;
return FALSE;
}
}
/* if we get here, we can be sure that we have enough bytes
* to copy safely */
/*printf("Mem OK Size: %d, Pos: %d\n", dp->realSize, dp->pos); */
tmp = (char *)dp->data;
memcpy ((void *)(tmp + (dp->pos)), src, size);
dp->pos += size;
if(dp->pos > dp->logicalSize) {
dp->logicalSize = dp->pos;
};
return TRUE;
}
/* grow (or shrink) dynamic pointer */
static int gdReallocDynamic(dynamicPtr *dp, int required)
{
void *newPtr;
/* First try gdRealloc(). If that doesn't work, make a new
* memory block and copy. */
if((newPtr = gdRealloc(dp->data, required))) {
dp->realSize = required;
dp->data = newPtr;
return TRUE;
}
/* create a new pointer */
newPtr = gdMalloc(required);
if(!newPtr) {
dp->dataGood = FALSE;
return FALSE;
}
/* copy the old data into it */
memcpy(newPtr, dp->data, dp->logicalSize);
gdFree(dp->data);
dp->data = newPtr;
dp->realSize = required;
return TRUE;
}
/* trim pointer so that its real and logical sizes match */
static int trimDynamic(dynamicPtr *dp)
{
/* 2.0.21: we don't reallocate memory we don't own */
if(!dp->freeOK) {
return TRUE;
}
return gdReallocDynamic(dp, dp->logicalSize);
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/good_5241_0 |
crossvul-cpp_data_good_2702_0 | /*
* Copyright (c) 1992, 1993, 1994, 1995, 1996
* The Regents of the University of California. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that: (1) source code distributions
* retain the above copyright notice and this paragraph in its entirety, (2)
* distributions including binary code include the above copyright notice and
* this paragraph in its entirety in the documentation or other materials
* provided with the distribution, and (3) all advertising materials mentioning
* features or use of this software display the following acknowledgement:
* ``This product includes software developed by the University of California,
* Lawrence Berkeley Laboratory and its contributors.'' Neither the name of
* the University nor the names of its contributors may be used to endorse
* or promote products derived from this software without specific prior
* written permission.
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*
* Original code by Matt Thomas, Digital Equipment Corporation
*
* Extensively modified by Hannes Gredler (hannes@gredler.at) for more
* complete IS-IS & CLNP support.
*/
/* \summary: ISO CLNS, ESIS, and ISIS printer */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <netdissect-stdinc.h>
#include <string.h>
#include "netdissect.h"
#include "addrtoname.h"
#include "ether.h"
#include "nlpid.h"
#include "extract.h"
#include "gmpls.h"
#include "oui.h"
#include "signature.h"
static const char tstr[] = " [|isis]";
/*
* IS-IS is defined in ISO 10589. Look there for protocol definitions.
*/
#define SYSTEM_ID_LEN ETHER_ADDR_LEN
#define NODE_ID_LEN SYSTEM_ID_LEN+1
#define LSP_ID_LEN SYSTEM_ID_LEN+2
#define ISIS_VERSION 1
#define ESIS_VERSION 1
#define CLNP_VERSION 1
#define ISIS_PDU_TYPE_MASK 0x1F
#define ESIS_PDU_TYPE_MASK 0x1F
#define CLNP_PDU_TYPE_MASK 0x1F
#define CLNP_FLAG_MASK 0xE0
#define ISIS_LAN_PRIORITY_MASK 0x7F
#define ISIS_PDU_L1_LAN_IIH 15
#define ISIS_PDU_L2_LAN_IIH 16
#define ISIS_PDU_PTP_IIH 17
#define ISIS_PDU_L1_LSP 18
#define ISIS_PDU_L2_LSP 20
#define ISIS_PDU_L1_CSNP 24
#define ISIS_PDU_L2_CSNP 25
#define ISIS_PDU_L1_PSNP 26
#define ISIS_PDU_L2_PSNP 27
static const struct tok isis_pdu_values[] = {
{ ISIS_PDU_L1_LAN_IIH, "L1 Lan IIH"},
{ ISIS_PDU_L2_LAN_IIH, "L2 Lan IIH"},
{ ISIS_PDU_PTP_IIH, "p2p IIH"},
{ ISIS_PDU_L1_LSP, "L1 LSP"},
{ ISIS_PDU_L2_LSP, "L2 LSP"},
{ ISIS_PDU_L1_CSNP, "L1 CSNP"},
{ ISIS_PDU_L2_CSNP, "L2 CSNP"},
{ ISIS_PDU_L1_PSNP, "L1 PSNP"},
{ ISIS_PDU_L2_PSNP, "L2 PSNP"},
{ 0, NULL}
};
/*
* A TLV is a tuple of a type, length and a value and is normally used for
* encoding information in all sorts of places. This is an enumeration of
* the well known types.
*
* list taken from rfc3359 plus some memory from veterans ;-)
*/
#define ISIS_TLV_AREA_ADDR 1 /* iso10589 */
#define ISIS_TLV_IS_REACH 2 /* iso10589 */
#define ISIS_TLV_ESNEIGH 3 /* iso10589 */
#define ISIS_TLV_PART_DIS 4 /* iso10589 */
#define ISIS_TLV_PREFIX_NEIGH 5 /* iso10589 */
#define ISIS_TLV_ISNEIGH 6 /* iso10589 */
#define ISIS_TLV_ISNEIGH_VARLEN 7 /* iso10589 */
#define ISIS_TLV_PADDING 8 /* iso10589 */
#define ISIS_TLV_LSP 9 /* iso10589 */
#define ISIS_TLV_AUTH 10 /* iso10589, rfc3567 */
#define ISIS_TLV_CHECKSUM 12 /* rfc3358 */
#define ISIS_TLV_CHECKSUM_MINLEN 2
#define ISIS_TLV_POI 13 /* rfc6232 */
#define ISIS_TLV_LSP_BUFFERSIZE 14 /* iso10589 rev2 */
#define ISIS_TLV_LSP_BUFFERSIZE_MINLEN 2
#define ISIS_TLV_EXT_IS_REACH 22 /* draft-ietf-isis-traffic-05 */
#define ISIS_TLV_IS_ALIAS_ID 24 /* draft-ietf-isis-ext-lsp-frags-02 */
#define ISIS_TLV_DECNET_PHASE4 42
#define ISIS_TLV_LUCENT_PRIVATE 66
#define ISIS_TLV_INT_IP_REACH 128 /* rfc1195, rfc2966 */
#define ISIS_TLV_PROTOCOLS 129 /* rfc1195 */
#define ISIS_TLV_EXT_IP_REACH 130 /* rfc1195, rfc2966 */
#define ISIS_TLV_IDRP_INFO 131 /* rfc1195 */
#define ISIS_TLV_IDRP_INFO_MINLEN 1
#define ISIS_TLV_IPADDR 132 /* rfc1195 */
#define ISIS_TLV_IPAUTH 133 /* rfc1195 */
#define ISIS_TLV_TE_ROUTER_ID 134 /* draft-ietf-isis-traffic-05 */
#define ISIS_TLV_EXTD_IP_REACH 135 /* draft-ietf-isis-traffic-05 */
#define ISIS_TLV_HOSTNAME 137 /* rfc2763 */
#define ISIS_TLV_SHARED_RISK_GROUP 138 /* draft-ietf-isis-gmpls-extensions */
#define ISIS_TLV_MT_PORT_CAP 143 /* rfc6165 */
#define ISIS_TLV_MT_CAPABILITY 144 /* rfc6329 */
#define ISIS_TLV_NORTEL_PRIVATE1 176
#define ISIS_TLV_NORTEL_PRIVATE2 177
#define ISIS_TLV_RESTART_SIGNALING 211 /* rfc3847 */
#define ISIS_TLV_RESTART_SIGNALING_FLAGLEN 1
#define ISIS_TLV_RESTART_SIGNALING_HOLDTIMELEN 2
#define ISIS_TLV_MT_IS_REACH 222 /* draft-ietf-isis-wg-multi-topology-05 */
#define ISIS_TLV_MT_SUPPORTED 229 /* draft-ietf-isis-wg-multi-topology-05 */
#define ISIS_TLV_MT_SUPPORTED_MINLEN 2
#define ISIS_TLV_IP6ADDR 232 /* draft-ietf-isis-ipv6-02 */
#define ISIS_TLV_MT_IP_REACH 235 /* draft-ietf-isis-wg-multi-topology-05 */
#define ISIS_TLV_IP6_REACH 236 /* draft-ietf-isis-ipv6-02 */
#define ISIS_TLV_MT_IP6_REACH 237 /* draft-ietf-isis-wg-multi-topology-05 */
#define ISIS_TLV_PTP_ADJ 240 /* rfc3373 */
#define ISIS_TLV_IIH_SEQNR 241 /* draft-shen-isis-iih-sequence-00 */
#define ISIS_TLV_IIH_SEQNR_MINLEN 4
#define ISIS_TLV_VENDOR_PRIVATE 250 /* draft-ietf-isis-experimental-tlv-01 */
#define ISIS_TLV_VENDOR_PRIVATE_MINLEN 3
static const struct tok isis_tlv_values[] = {
{ ISIS_TLV_AREA_ADDR, "Area address(es)"},
{ ISIS_TLV_IS_REACH, "IS Reachability"},
{ ISIS_TLV_ESNEIGH, "ES Neighbor(s)"},
{ ISIS_TLV_PART_DIS, "Partition DIS"},
{ ISIS_TLV_PREFIX_NEIGH, "Prefix Neighbors"},
{ ISIS_TLV_ISNEIGH, "IS Neighbor(s)"},
{ ISIS_TLV_ISNEIGH_VARLEN, "IS Neighbor(s) (variable length)"},
{ ISIS_TLV_PADDING, "Padding"},
{ ISIS_TLV_LSP, "LSP entries"},
{ ISIS_TLV_AUTH, "Authentication"},
{ ISIS_TLV_CHECKSUM, "Checksum"},
{ ISIS_TLV_POI, "Purge Originator Identifier"},
{ ISIS_TLV_LSP_BUFFERSIZE, "LSP Buffersize"},
{ ISIS_TLV_EXT_IS_REACH, "Extended IS Reachability"},
{ ISIS_TLV_IS_ALIAS_ID, "IS Alias ID"},
{ ISIS_TLV_DECNET_PHASE4, "DECnet Phase IV"},
{ ISIS_TLV_LUCENT_PRIVATE, "Lucent Proprietary"},
{ ISIS_TLV_INT_IP_REACH, "IPv4 Internal Reachability"},
{ ISIS_TLV_PROTOCOLS, "Protocols supported"},
{ ISIS_TLV_EXT_IP_REACH, "IPv4 External Reachability"},
{ ISIS_TLV_IDRP_INFO, "Inter-Domain Information Type"},
{ ISIS_TLV_IPADDR, "IPv4 Interface address(es)"},
{ ISIS_TLV_IPAUTH, "IPv4 authentication (deprecated)"},
{ ISIS_TLV_TE_ROUTER_ID, "Traffic Engineering Router ID"},
{ ISIS_TLV_EXTD_IP_REACH, "Extended IPv4 Reachability"},
{ ISIS_TLV_SHARED_RISK_GROUP, "Shared Risk Link Group"},
{ ISIS_TLV_MT_PORT_CAP, "Multi-Topology-Aware Port Capability"},
{ ISIS_TLV_MT_CAPABILITY, "Multi-Topology Capability"},
{ ISIS_TLV_NORTEL_PRIVATE1, "Nortel Proprietary"},
{ ISIS_TLV_NORTEL_PRIVATE2, "Nortel Proprietary"},
{ ISIS_TLV_HOSTNAME, "Hostname"},
{ ISIS_TLV_RESTART_SIGNALING, "Restart Signaling"},
{ ISIS_TLV_MT_IS_REACH, "Multi Topology IS Reachability"},
{ ISIS_TLV_MT_SUPPORTED, "Multi Topology"},
{ ISIS_TLV_IP6ADDR, "IPv6 Interface address(es)"},
{ ISIS_TLV_MT_IP_REACH, "Multi-Topology IPv4 Reachability"},
{ ISIS_TLV_IP6_REACH, "IPv6 reachability"},
{ ISIS_TLV_MT_IP6_REACH, "Multi-Topology IP6 Reachability"},
{ ISIS_TLV_PTP_ADJ, "Point-to-point Adjacency State"},
{ ISIS_TLV_IIH_SEQNR, "Hello PDU Sequence Number"},
{ ISIS_TLV_VENDOR_PRIVATE, "Vendor Private"},
{ 0, NULL }
};
#define ESIS_OPTION_PROTOCOLS 129
#define ESIS_OPTION_QOS_MAINTENANCE 195 /* iso9542 */
#define ESIS_OPTION_SECURITY 197 /* iso9542 */
#define ESIS_OPTION_ES_CONF_TIME 198 /* iso9542 */
#define ESIS_OPTION_PRIORITY 205 /* iso9542 */
#define ESIS_OPTION_ADDRESS_MASK 225 /* iso9542 */
#define ESIS_OPTION_SNPA_MASK 226 /* iso9542 */
static const struct tok esis_option_values[] = {
{ ESIS_OPTION_PROTOCOLS, "Protocols supported"},
{ ESIS_OPTION_QOS_MAINTENANCE, "QoS Maintenance" },
{ ESIS_OPTION_SECURITY, "Security" },
{ ESIS_OPTION_ES_CONF_TIME, "ES Configuration Time" },
{ ESIS_OPTION_PRIORITY, "Priority" },
{ ESIS_OPTION_ADDRESS_MASK, "Addressk Mask" },
{ ESIS_OPTION_SNPA_MASK, "SNPA Mask" },
{ 0, NULL }
};
#define CLNP_OPTION_DISCARD_REASON 193
#define CLNP_OPTION_QOS_MAINTENANCE 195 /* iso8473 */
#define CLNP_OPTION_SECURITY 197 /* iso8473 */
#define CLNP_OPTION_SOURCE_ROUTING 200 /* iso8473 */
#define CLNP_OPTION_ROUTE_RECORDING 203 /* iso8473 */
#define CLNP_OPTION_PADDING 204 /* iso8473 */
#define CLNP_OPTION_PRIORITY 205 /* iso8473 */
static const struct tok clnp_option_values[] = {
{ CLNP_OPTION_DISCARD_REASON, "Discard Reason"},
{ CLNP_OPTION_PRIORITY, "Priority"},
{ CLNP_OPTION_QOS_MAINTENANCE, "QoS Maintenance"},
{ CLNP_OPTION_SECURITY, "Security"},
{ CLNP_OPTION_SOURCE_ROUTING, "Source Routing"},
{ CLNP_OPTION_ROUTE_RECORDING, "Route Recording"},
{ CLNP_OPTION_PADDING, "Padding"},
{ 0, NULL }
};
static const struct tok clnp_option_rfd_class_values[] = {
{ 0x0, "General"},
{ 0x8, "Address"},
{ 0x9, "Source Routeing"},
{ 0xa, "Lifetime"},
{ 0xb, "PDU Discarded"},
{ 0xc, "Reassembly"},
{ 0, NULL }
};
static const struct tok clnp_option_rfd_general_values[] = {
{ 0x0, "Reason not specified"},
{ 0x1, "Protocol procedure error"},
{ 0x2, "Incorrect checksum"},
{ 0x3, "PDU discarded due to congestion"},
{ 0x4, "Header syntax error (cannot be parsed)"},
{ 0x5, "Segmentation needed but not permitted"},
{ 0x6, "Incomplete PDU received"},
{ 0x7, "Duplicate option"},
{ 0, NULL }
};
static const struct tok clnp_option_rfd_address_values[] = {
{ 0x0, "Destination address unreachable"},
{ 0x1, "Destination address unknown"},
{ 0, NULL }
};
static const struct tok clnp_option_rfd_source_routeing_values[] = {
{ 0x0, "Unspecified source routeing error"},
{ 0x1, "Syntax error in source routeing field"},
{ 0x2, "Unknown address in source routeing field"},
{ 0x3, "Path not acceptable"},
{ 0, NULL }
};
static const struct tok clnp_option_rfd_lifetime_values[] = {
{ 0x0, "Lifetime expired while data unit in transit"},
{ 0x1, "Lifetime expired during reassembly"},
{ 0, NULL }
};
static const struct tok clnp_option_rfd_pdu_discard_values[] = {
{ 0x0, "Unsupported option not specified"},
{ 0x1, "Unsupported protocol version"},
{ 0x2, "Unsupported security option"},
{ 0x3, "Unsupported source routeing option"},
{ 0x4, "Unsupported recording of route option"},
{ 0, NULL }
};
static const struct tok clnp_option_rfd_reassembly_values[] = {
{ 0x0, "Reassembly interference"},
{ 0, NULL }
};
/* array of 16 error-classes */
static const struct tok *clnp_option_rfd_error_class[] = {
clnp_option_rfd_general_values,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
clnp_option_rfd_address_values,
clnp_option_rfd_source_routeing_values,
clnp_option_rfd_lifetime_values,
clnp_option_rfd_pdu_discard_values,
clnp_option_rfd_reassembly_values,
NULL,
NULL,
NULL
};
#define CLNP_OPTION_OPTION_QOS_MASK 0x3f
#define CLNP_OPTION_SCOPE_MASK 0xc0
#define CLNP_OPTION_SCOPE_SA_SPEC 0x40
#define CLNP_OPTION_SCOPE_DA_SPEC 0x80
#define CLNP_OPTION_SCOPE_GLOBAL 0xc0
static const struct tok clnp_option_scope_values[] = {
{ CLNP_OPTION_SCOPE_SA_SPEC, "Source Address Specific"},
{ CLNP_OPTION_SCOPE_DA_SPEC, "Destination Address Specific"},
{ CLNP_OPTION_SCOPE_GLOBAL, "Globally unique"},
{ 0, NULL }
};
static const struct tok clnp_option_sr_rr_values[] = {
{ 0x0, "partial"},
{ 0x1, "complete"},
{ 0, NULL }
};
static const struct tok clnp_option_sr_rr_string_values[] = {
{ CLNP_OPTION_SOURCE_ROUTING, "source routing"},
{ CLNP_OPTION_ROUTE_RECORDING, "recording of route in progress"},
{ 0, NULL }
};
static const struct tok clnp_option_qos_global_values[] = {
{ 0x20, "reserved"},
{ 0x10, "sequencing vs. delay"},
{ 0x08, "congested"},
{ 0x04, "delay vs. cost"},
{ 0x02, "error vs. delay"},
{ 0x01, "error vs. cost"},
{ 0, NULL }
};
#define ISIS_SUBTLV_EXT_IS_REACH_ADMIN_GROUP 3 /* draft-ietf-isis-traffic-05 */
#define ISIS_SUBTLV_EXT_IS_REACH_LINK_LOCAL_REMOTE_ID 4 /* rfc4205 */
#define ISIS_SUBTLV_EXT_IS_REACH_LINK_REMOTE_ID 5 /* draft-ietf-isis-traffic-05 */
#define ISIS_SUBTLV_EXT_IS_REACH_IPV4_INTF_ADDR 6 /* draft-ietf-isis-traffic-05 */
#define ISIS_SUBTLV_EXT_IS_REACH_IPV4_NEIGHBOR_ADDR 8 /* draft-ietf-isis-traffic-05 */
#define ISIS_SUBTLV_EXT_IS_REACH_MAX_LINK_BW 9 /* draft-ietf-isis-traffic-05 */
#define ISIS_SUBTLV_EXT_IS_REACH_RESERVABLE_BW 10 /* draft-ietf-isis-traffic-05 */
#define ISIS_SUBTLV_EXT_IS_REACH_UNRESERVED_BW 11 /* rfc4124 */
#define ISIS_SUBTLV_EXT_IS_REACH_BW_CONSTRAINTS_OLD 12 /* draft-ietf-tewg-diff-te-proto-06 */
#define ISIS_SUBTLV_EXT_IS_REACH_TE_METRIC 18 /* draft-ietf-isis-traffic-05 */
#define ISIS_SUBTLV_EXT_IS_REACH_LINK_ATTRIBUTE 19 /* draft-ietf-isis-link-attr-01 */
#define ISIS_SUBTLV_EXT_IS_REACH_LINK_PROTECTION_TYPE 20 /* rfc4205 */
#define ISIS_SUBTLV_EXT_IS_REACH_INTF_SW_CAP_DESCR 21 /* rfc4205 */
#define ISIS_SUBTLV_EXT_IS_REACH_BW_CONSTRAINTS 22 /* rfc4124 */
#define ISIS_SUBTLV_SPB_METRIC 29 /* rfc6329 */
static const struct tok isis_ext_is_reach_subtlv_values[] = {
{ ISIS_SUBTLV_EXT_IS_REACH_ADMIN_GROUP, "Administrative groups" },
{ ISIS_SUBTLV_EXT_IS_REACH_LINK_LOCAL_REMOTE_ID, "Link Local/Remote Identifier" },
{ ISIS_SUBTLV_EXT_IS_REACH_LINK_REMOTE_ID, "Link Remote Identifier" },
{ ISIS_SUBTLV_EXT_IS_REACH_IPV4_INTF_ADDR, "IPv4 interface address" },
{ ISIS_SUBTLV_EXT_IS_REACH_IPV4_NEIGHBOR_ADDR, "IPv4 neighbor address" },
{ ISIS_SUBTLV_EXT_IS_REACH_MAX_LINK_BW, "Maximum link bandwidth" },
{ ISIS_SUBTLV_EXT_IS_REACH_RESERVABLE_BW, "Reservable link bandwidth" },
{ ISIS_SUBTLV_EXT_IS_REACH_UNRESERVED_BW, "Unreserved bandwidth" },
{ ISIS_SUBTLV_EXT_IS_REACH_TE_METRIC, "Traffic Engineering Metric" },
{ ISIS_SUBTLV_EXT_IS_REACH_LINK_ATTRIBUTE, "Link Attribute" },
{ ISIS_SUBTLV_EXT_IS_REACH_LINK_PROTECTION_TYPE, "Link Protection Type" },
{ ISIS_SUBTLV_EXT_IS_REACH_INTF_SW_CAP_DESCR, "Interface Switching Capability" },
{ ISIS_SUBTLV_EXT_IS_REACH_BW_CONSTRAINTS_OLD, "Bandwidth Constraints (old)" },
{ ISIS_SUBTLV_EXT_IS_REACH_BW_CONSTRAINTS, "Bandwidth Constraints" },
{ ISIS_SUBTLV_SPB_METRIC, "SPB Metric" },
{ 250, "Reserved for cisco specific extensions" },
{ 251, "Reserved for cisco specific extensions" },
{ 252, "Reserved for cisco specific extensions" },
{ 253, "Reserved for cisco specific extensions" },
{ 254, "Reserved for cisco specific extensions" },
{ 255, "Reserved for future expansion" },
{ 0, NULL }
};
#define ISIS_SUBTLV_EXTD_IP_REACH_ADMIN_TAG32 1 /* draft-ietf-isis-admin-tags-01 */
#define ISIS_SUBTLV_EXTD_IP_REACH_ADMIN_TAG64 2 /* draft-ietf-isis-admin-tags-01 */
#define ISIS_SUBTLV_EXTD_IP_REACH_MGMT_PREFIX_COLOR 117 /* draft-ietf-isis-wg-multi-topology-05 */
static const struct tok isis_ext_ip_reach_subtlv_values[] = {
{ ISIS_SUBTLV_EXTD_IP_REACH_ADMIN_TAG32, "32-Bit Administrative tag" },
{ ISIS_SUBTLV_EXTD_IP_REACH_ADMIN_TAG64, "64-Bit Administrative tag" },
{ ISIS_SUBTLV_EXTD_IP_REACH_MGMT_PREFIX_COLOR, "Management Prefix Color" },
{ 0, NULL }
};
static const struct tok isis_subtlv_link_attribute_values[] = {
{ 0x01, "Local Protection Available" },
{ 0x02, "Link excluded from local protection path" },
{ 0x04, "Local maintenance required"},
{ 0, NULL }
};
#define ISIS_SUBTLV_AUTH_SIMPLE 1
#define ISIS_SUBTLV_AUTH_GENERIC 3 /* rfc 5310 */
#define ISIS_SUBTLV_AUTH_MD5 54
#define ISIS_SUBTLV_AUTH_MD5_LEN 16
#define ISIS_SUBTLV_AUTH_PRIVATE 255
static const struct tok isis_subtlv_auth_values[] = {
{ ISIS_SUBTLV_AUTH_SIMPLE, "simple text password"},
{ ISIS_SUBTLV_AUTH_GENERIC, "Generic Crypto key-id"},
{ ISIS_SUBTLV_AUTH_MD5, "HMAC-MD5 password"},
{ ISIS_SUBTLV_AUTH_PRIVATE, "Routing Domain private password"},
{ 0, NULL }
};
#define ISIS_SUBTLV_IDRP_RES 0
#define ISIS_SUBTLV_IDRP_LOCAL 1
#define ISIS_SUBTLV_IDRP_ASN 2
static const struct tok isis_subtlv_idrp_values[] = {
{ ISIS_SUBTLV_IDRP_RES, "Reserved"},
{ ISIS_SUBTLV_IDRP_LOCAL, "Routing-Domain Specific"},
{ ISIS_SUBTLV_IDRP_ASN, "AS Number Tag"},
{ 0, NULL}
};
#define ISIS_SUBTLV_SPB_MCID 4
#define ISIS_SUBTLV_SPB_DIGEST 5
#define ISIS_SUBTLV_SPB_BVID 6
#define ISIS_SUBTLV_SPB_INSTANCE 1
#define ISIS_SUBTLV_SPBM_SI 3
#define ISIS_SPB_MCID_LEN 51
#define ISIS_SUBTLV_SPB_MCID_MIN_LEN 102
#define ISIS_SUBTLV_SPB_DIGEST_MIN_LEN 33
#define ISIS_SUBTLV_SPB_BVID_MIN_LEN 6
#define ISIS_SUBTLV_SPB_INSTANCE_MIN_LEN 19
#define ISIS_SUBTLV_SPB_INSTANCE_VLAN_TUPLE_LEN 8
static const struct tok isis_mt_port_cap_subtlv_values[] = {
{ ISIS_SUBTLV_SPB_MCID, "SPB MCID" },
{ ISIS_SUBTLV_SPB_DIGEST, "SPB Digest" },
{ ISIS_SUBTLV_SPB_BVID, "SPB BVID" },
{ 0, NULL }
};
static const struct tok isis_mt_capability_subtlv_values[] = {
{ ISIS_SUBTLV_SPB_INSTANCE, "SPB Instance" },
{ ISIS_SUBTLV_SPBM_SI, "SPBM Service Identifier and Unicast Address" },
{ 0, NULL }
};
struct isis_spb_mcid {
uint8_t format_id;
uint8_t name[32];
uint8_t revision_lvl[2];
uint8_t digest[16];
};
struct isis_subtlv_spb_mcid {
struct isis_spb_mcid mcid;
struct isis_spb_mcid aux_mcid;
};
struct isis_subtlv_spb_instance {
uint8_t cist_root_id[8];
uint8_t cist_external_root_path_cost[4];
uint8_t bridge_priority[2];
uint8_t spsourceid[4];
uint8_t no_of_trees;
};
#define CLNP_SEGMENT_PART 0x80
#define CLNP_MORE_SEGMENTS 0x40
#define CLNP_REQUEST_ER 0x20
static const struct tok clnp_flag_values[] = {
{ CLNP_SEGMENT_PART, "Segmentation permitted"},
{ CLNP_MORE_SEGMENTS, "more Segments"},
{ CLNP_REQUEST_ER, "request Error Report"},
{ 0, NULL}
};
#define ISIS_MASK_LSP_OL_BIT(x) ((x)&0x4)
#define ISIS_MASK_LSP_ISTYPE_BITS(x) ((x)&0x3)
#define ISIS_MASK_LSP_PARTITION_BIT(x) ((x)&0x80)
#define ISIS_MASK_LSP_ATT_BITS(x) ((x)&0x78)
#define ISIS_MASK_LSP_ATT_ERROR_BIT(x) ((x)&0x40)
#define ISIS_MASK_LSP_ATT_EXPENSE_BIT(x) ((x)&0x20)
#define ISIS_MASK_LSP_ATT_DELAY_BIT(x) ((x)&0x10)
#define ISIS_MASK_LSP_ATT_DEFAULT_BIT(x) ((x)&0x8)
#define ISIS_MASK_MTID(x) ((x)&0x0fff)
#define ISIS_MASK_MTFLAGS(x) ((x)&0xf000)
static const struct tok isis_mt_flag_values[] = {
{ 0x4000, "ATT bit set"},
{ 0x8000, "Overload bit set"},
{ 0, NULL}
};
#define ISIS_MASK_TLV_EXTD_IP_UPDOWN(x) ((x)&0x80)
#define ISIS_MASK_TLV_EXTD_IP_SUBTLV(x) ((x)&0x40)
#define ISIS_MASK_TLV_EXTD_IP6_IE(x) ((x)&0x40)
#define ISIS_MASK_TLV_EXTD_IP6_SUBTLV(x) ((x)&0x20)
#define ISIS_LSP_TLV_METRIC_SUPPORTED(x) ((x)&0x80)
#define ISIS_LSP_TLV_METRIC_IE(x) ((x)&0x40)
#define ISIS_LSP_TLV_METRIC_UPDOWN(x) ((x)&0x80)
#define ISIS_LSP_TLV_METRIC_VALUE(x) ((x)&0x3f)
#define ISIS_MASK_TLV_SHARED_RISK_GROUP(x) ((x)&0x1)
static const struct tok isis_mt_values[] = {
{ 0, "IPv4 unicast"},
{ 1, "In-Band Management"},
{ 2, "IPv6 unicast"},
{ 3, "Multicast"},
{ 4095, "Development, Experimental or Proprietary"},
{ 0, NULL }
};
static const struct tok isis_iih_circuit_type_values[] = {
{ 1, "Level 1 only"},
{ 2, "Level 2 only"},
{ 3, "Level 1, Level 2"},
{ 0, NULL}
};
#define ISIS_LSP_TYPE_UNUSED0 0
#define ISIS_LSP_TYPE_LEVEL_1 1
#define ISIS_LSP_TYPE_UNUSED2 2
#define ISIS_LSP_TYPE_LEVEL_2 3
static const struct tok isis_lsp_istype_values[] = {
{ ISIS_LSP_TYPE_UNUSED0, "Unused 0x0 (invalid)"},
{ ISIS_LSP_TYPE_LEVEL_1, "L1 IS"},
{ ISIS_LSP_TYPE_UNUSED2, "Unused 0x2 (invalid)"},
{ ISIS_LSP_TYPE_LEVEL_2, "L2 IS"},
{ 0, NULL }
};
/*
* Katz's point to point adjacency TLV uses codes to tell us the state of
* the remote adjacency. Enumerate them.
*/
#define ISIS_PTP_ADJ_UP 0
#define ISIS_PTP_ADJ_INIT 1
#define ISIS_PTP_ADJ_DOWN 2
static const struct tok isis_ptp_adjancey_values[] = {
{ ISIS_PTP_ADJ_UP, "Up" },
{ ISIS_PTP_ADJ_INIT, "Initializing" },
{ ISIS_PTP_ADJ_DOWN, "Down" },
{ 0, NULL}
};
struct isis_tlv_ptp_adj {
uint8_t adjacency_state;
uint8_t extd_local_circuit_id[4];
uint8_t neighbor_sysid[SYSTEM_ID_LEN];
uint8_t neighbor_extd_local_circuit_id[4];
};
static void osi_print_cksum(netdissect_options *, const uint8_t *pptr,
uint16_t checksum, int checksum_offset, u_int length);
static int clnp_print(netdissect_options *, const uint8_t *, u_int);
static void esis_print(netdissect_options *, const uint8_t *, u_int);
static int isis_print(netdissect_options *, const uint8_t *, u_int);
struct isis_metric_block {
uint8_t metric_default;
uint8_t metric_delay;
uint8_t metric_expense;
uint8_t metric_error;
};
struct isis_tlv_is_reach {
struct isis_metric_block isis_metric_block;
uint8_t neighbor_nodeid[NODE_ID_LEN];
};
struct isis_tlv_es_reach {
struct isis_metric_block isis_metric_block;
uint8_t neighbor_sysid[SYSTEM_ID_LEN];
};
struct isis_tlv_ip_reach {
struct isis_metric_block isis_metric_block;
uint8_t prefix[4];
uint8_t mask[4];
};
static const struct tok isis_is_reach_virtual_values[] = {
{ 0, "IsNotVirtual"},
{ 1, "IsVirtual"},
{ 0, NULL }
};
static const struct tok isis_restart_flag_values[] = {
{ 0x1, "Restart Request"},
{ 0x2, "Restart Acknowledgement"},
{ 0x4, "Suppress adjacency advertisement"},
{ 0, NULL }
};
struct isis_common_header {
uint8_t nlpid;
uint8_t fixed_len;
uint8_t version; /* Protocol version */
uint8_t id_length;
uint8_t pdu_type; /* 3 MSbits are reserved */
uint8_t pdu_version; /* Packet format version */
uint8_t reserved;
uint8_t max_area;
};
struct isis_iih_lan_header {
uint8_t circuit_type;
uint8_t source_id[SYSTEM_ID_LEN];
uint8_t holding_time[2];
uint8_t pdu_len[2];
uint8_t priority;
uint8_t lan_id[NODE_ID_LEN];
};
struct isis_iih_ptp_header {
uint8_t circuit_type;
uint8_t source_id[SYSTEM_ID_LEN];
uint8_t holding_time[2];
uint8_t pdu_len[2];
uint8_t circuit_id;
};
struct isis_lsp_header {
uint8_t pdu_len[2];
uint8_t remaining_lifetime[2];
uint8_t lsp_id[LSP_ID_LEN];
uint8_t sequence_number[4];
uint8_t checksum[2];
uint8_t typeblock;
};
struct isis_csnp_header {
uint8_t pdu_len[2];
uint8_t source_id[NODE_ID_LEN];
uint8_t start_lsp_id[LSP_ID_LEN];
uint8_t end_lsp_id[LSP_ID_LEN];
};
struct isis_psnp_header {
uint8_t pdu_len[2];
uint8_t source_id[NODE_ID_LEN];
};
struct isis_tlv_lsp {
uint8_t remaining_lifetime[2];
uint8_t lsp_id[LSP_ID_LEN];
uint8_t sequence_number[4];
uint8_t checksum[2];
};
#define ISIS_COMMON_HEADER_SIZE (sizeof(struct isis_common_header))
#define ISIS_IIH_LAN_HEADER_SIZE (sizeof(struct isis_iih_lan_header))
#define ISIS_IIH_PTP_HEADER_SIZE (sizeof(struct isis_iih_ptp_header))
#define ISIS_LSP_HEADER_SIZE (sizeof(struct isis_lsp_header))
#define ISIS_CSNP_HEADER_SIZE (sizeof(struct isis_csnp_header))
#define ISIS_PSNP_HEADER_SIZE (sizeof(struct isis_psnp_header))
void
isoclns_print(netdissect_options *ndo, const uint8_t *p, u_int length)
{
if (!ND_TTEST(*p)) { /* enough bytes on the wire ? */
ND_PRINT((ndo, "|OSI"));
return;
}
if (ndo->ndo_eflag)
ND_PRINT((ndo, "OSI NLPID %s (0x%02x): ", tok2str(nlpid_values, "Unknown", *p), *p));
switch (*p) {
case NLPID_CLNP:
if (!clnp_print(ndo, p, length))
print_unknown_data(ndo, p, "\n\t", length);
break;
case NLPID_ESIS:
esis_print(ndo, p, length);
return;
case NLPID_ISIS:
if (!isis_print(ndo, p, length))
print_unknown_data(ndo, p, "\n\t", length);
break;
case NLPID_NULLNS:
ND_PRINT((ndo, "%slength: %u", ndo->ndo_eflag ? "" : ", ", length));
break;
case NLPID_Q933:
q933_print(ndo, p + 1, length - 1);
break;
case NLPID_IP:
ip_print(ndo, p + 1, length - 1);
break;
case NLPID_IP6:
ip6_print(ndo, p + 1, length - 1);
break;
case NLPID_PPP:
ppp_print(ndo, p + 1, length - 1);
break;
default:
if (!ndo->ndo_eflag)
ND_PRINT((ndo, "OSI NLPID 0x%02x unknown", *p));
ND_PRINT((ndo, "%slength: %u", ndo->ndo_eflag ? "" : ", ", length));
if (length > 1)
print_unknown_data(ndo, p, "\n\t", length);
break;
}
}
#define CLNP_PDU_ER 1
#define CLNP_PDU_DT 28
#define CLNP_PDU_MD 29
#define CLNP_PDU_ERQ 30
#define CLNP_PDU_ERP 31
static const struct tok clnp_pdu_values[] = {
{ CLNP_PDU_ER, "Error Report"},
{ CLNP_PDU_MD, "MD"},
{ CLNP_PDU_DT, "Data"},
{ CLNP_PDU_ERQ, "Echo Request"},
{ CLNP_PDU_ERP, "Echo Response"},
{ 0, NULL }
};
struct clnp_header_t {
uint8_t nlpid;
uint8_t length_indicator;
uint8_t version;
uint8_t lifetime; /* units of 500ms */
uint8_t type;
uint8_t segment_length[2];
uint8_t cksum[2];
};
struct clnp_segment_header_t {
uint8_t data_unit_id[2];
uint8_t segment_offset[2];
uint8_t total_length[2];
};
/*
* clnp_print
* Decode CLNP packets. Return 0 on error.
*/
static int
clnp_print(netdissect_options *ndo,
const uint8_t *pptr, u_int length)
{
const uint8_t *optr,*source_address,*dest_address;
u_int li,tlen,nsap_offset,source_address_length,dest_address_length, clnp_pdu_type, clnp_flags;
const struct clnp_header_t *clnp_header;
const struct clnp_segment_header_t *clnp_segment_header;
uint8_t rfd_error_major,rfd_error_minor;
clnp_header = (const struct clnp_header_t *) pptr;
ND_TCHECK(*clnp_header);
li = clnp_header->length_indicator;
optr = pptr;
if (!ndo->ndo_eflag)
ND_PRINT((ndo, "CLNP"));
/*
* Sanity checking of the header.
*/
if (clnp_header->version != CLNP_VERSION) {
ND_PRINT((ndo, "version %d packet not supported", clnp_header->version));
return (0);
}
if (li > length) {
ND_PRINT((ndo, " length indicator(%u) > PDU size (%u)!", li, length));
return (0);
}
if (li < sizeof(struct clnp_header_t)) {
ND_PRINT((ndo, " length indicator %u < min PDU size:", li));
while (pptr < ndo->ndo_snapend)
ND_PRINT((ndo, "%02X", *pptr++));
return (0);
}
/* FIXME further header sanity checking */
clnp_pdu_type = clnp_header->type & CLNP_PDU_TYPE_MASK;
clnp_flags = clnp_header->type & CLNP_FLAG_MASK;
pptr += sizeof(struct clnp_header_t);
li -= sizeof(struct clnp_header_t);
if (li < 1) {
ND_PRINT((ndo, "li < size of fixed part of CLNP header and addresses"));
return (0);
}
ND_TCHECK(*pptr);
dest_address_length = *pptr;
pptr += 1;
li -= 1;
if (li < dest_address_length) {
ND_PRINT((ndo, "li < size of fixed part of CLNP header and addresses"));
return (0);
}
ND_TCHECK2(*pptr, dest_address_length);
dest_address = pptr;
pptr += dest_address_length;
li -= dest_address_length;
if (li < 1) {
ND_PRINT((ndo, "li < size of fixed part of CLNP header and addresses"));
return (0);
}
ND_TCHECK(*pptr);
source_address_length = *pptr;
pptr += 1;
li -= 1;
if (li < source_address_length) {
ND_PRINT((ndo, "li < size of fixed part of CLNP header and addresses"));
return (0);
}
ND_TCHECK2(*pptr, source_address_length);
source_address = pptr;
pptr += source_address_length;
li -= source_address_length;
if (ndo->ndo_vflag < 1) {
ND_PRINT((ndo, "%s%s > %s, %s, length %u",
ndo->ndo_eflag ? "" : ", ",
isonsap_string(ndo, source_address, source_address_length),
isonsap_string(ndo, dest_address, dest_address_length),
tok2str(clnp_pdu_values,"unknown (%u)",clnp_pdu_type),
length));
return (1);
}
ND_PRINT((ndo, "%slength %u", ndo->ndo_eflag ? "" : ", ", length));
ND_PRINT((ndo, "\n\t%s PDU, hlen: %u, v: %u, lifetime: %u.%us, Segment PDU length: %u, checksum: 0x%04x",
tok2str(clnp_pdu_values, "unknown (%u)",clnp_pdu_type),
clnp_header->length_indicator,
clnp_header->version,
clnp_header->lifetime/2,
(clnp_header->lifetime%2)*5,
EXTRACT_16BITS(clnp_header->segment_length),
EXTRACT_16BITS(clnp_header->cksum)));
osi_print_cksum(ndo, optr, EXTRACT_16BITS(clnp_header->cksum), 7,
clnp_header->length_indicator);
ND_PRINT((ndo, "\n\tFlags [%s]",
bittok2str(clnp_flag_values, "none", clnp_flags)));
ND_PRINT((ndo, "\n\tsource address (length %u): %s\n\tdest address (length %u): %s",
source_address_length,
isonsap_string(ndo, source_address, source_address_length),
dest_address_length,
isonsap_string(ndo, dest_address, dest_address_length)));
if (clnp_flags & CLNP_SEGMENT_PART) {
if (li < sizeof(const struct clnp_segment_header_t)) {
ND_PRINT((ndo, "li < size of fixed part of CLNP header, addresses, and segment part"));
return (0);
}
clnp_segment_header = (const struct clnp_segment_header_t *) pptr;
ND_TCHECK(*clnp_segment_header);
ND_PRINT((ndo, "\n\tData Unit ID: 0x%04x, Segment Offset: %u, Total PDU Length: %u",
EXTRACT_16BITS(clnp_segment_header->data_unit_id),
EXTRACT_16BITS(clnp_segment_header->segment_offset),
EXTRACT_16BITS(clnp_segment_header->total_length)));
pptr+=sizeof(const struct clnp_segment_header_t);
li-=sizeof(const struct clnp_segment_header_t);
}
/* now walk the options */
while (li >= 2) {
u_int op, opli;
const uint8_t *tptr;
if (li < 2) {
ND_PRINT((ndo, ", bad opts/li"));
return (0);
}
ND_TCHECK2(*pptr, 2);
op = *pptr++;
opli = *pptr++;
li -= 2;
if (opli > li) {
ND_PRINT((ndo, ", opt (%d) too long", op));
return (0);
}
ND_TCHECK2(*pptr, opli);
li -= opli;
tptr = pptr;
tlen = opli;
ND_PRINT((ndo, "\n\t %s Option #%u, length %u, value: ",
tok2str(clnp_option_values,"Unknown",op),
op,
opli));
/*
* We've already checked that the entire option is present
* in the captured packet with the ND_TCHECK2() call.
* Therefore, we don't need to do ND_TCHECK()/ND_TCHECK2()
* checks.
* We do, however, need to check tlen, to make sure we
* don't run past the end of the option.
*/
switch (op) {
case CLNP_OPTION_ROUTE_RECORDING: /* those two options share the format */
case CLNP_OPTION_SOURCE_ROUTING:
if (tlen < 2) {
ND_PRINT((ndo, ", bad opt len"));
return (0);
}
ND_PRINT((ndo, "%s %s",
tok2str(clnp_option_sr_rr_values,"Unknown",*tptr),
tok2str(clnp_option_sr_rr_string_values, "Unknown Option %u", op)));
nsap_offset=*(tptr+1);
if (nsap_offset == 0) {
ND_PRINT((ndo, " Bad NSAP offset (0)"));
break;
}
nsap_offset-=1; /* offset to nsap list */
if (nsap_offset > tlen) {
ND_PRINT((ndo, " Bad NSAP offset (past end of option)"));
break;
}
tptr+=nsap_offset;
tlen-=nsap_offset;
while (tlen > 0) {
source_address_length=*tptr;
if (tlen < source_address_length+1) {
ND_PRINT((ndo, "\n\t NSAP address goes past end of option"));
break;
}
if (source_address_length > 0) {
source_address=(tptr+1);
ND_TCHECK2(*source_address, source_address_length);
ND_PRINT((ndo, "\n\t NSAP address (length %u): %s",
source_address_length,
isonsap_string(ndo, source_address, source_address_length)));
}
tlen-=source_address_length+1;
}
break;
case CLNP_OPTION_PRIORITY:
if (tlen < 1) {
ND_PRINT((ndo, ", bad opt len"));
return (0);
}
ND_PRINT((ndo, "0x%1x", *tptr&0x0f));
break;
case CLNP_OPTION_QOS_MAINTENANCE:
if (tlen < 1) {
ND_PRINT((ndo, ", bad opt len"));
return (0);
}
ND_PRINT((ndo, "\n\t Format Code: %s",
tok2str(clnp_option_scope_values, "Reserved", *tptr&CLNP_OPTION_SCOPE_MASK)));
if ((*tptr&CLNP_OPTION_SCOPE_MASK) == CLNP_OPTION_SCOPE_GLOBAL)
ND_PRINT((ndo, "\n\t QoS Flags [%s]",
bittok2str(clnp_option_qos_global_values,
"none",
*tptr&CLNP_OPTION_OPTION_QOS_MASK)));
break;
case CLNP_OPTION_SECURITY:
if (tlen < 2) {
ND_PRINT((ndo, ", bad opt len"));
return (0);
}
ND_PRINT((ndo, "\n\t Format Code: %s, Security-Level %u",
tok2str(clnp_option_scope_values,"Reserved",*tptr&CLNP_OPTION_SCOPE_MASK),
*(tptr+1)));
break;
case CLNP_OPTION_DISCARD_REASON:
if (tlen < 1) {
ND_PRINT((ndo, ", bad opt len"));
return (0);
}
rfd_error_major = (*tptr&0xf0) >> 4;
rfd_error_minor = *tptr&0x0f;
ND_PRINT((ndo, "\n\t Class: %s Error (0x%01x), %s (0x%01x)",
tok2str(clnp_option_rfd_class_values,"Unknown",rfd_error_major),
rfd_error_major,
tok2str(clnp_option_rfd_error_class[rfd_error_major],"Unknown",rfd_error_minor),
rfd_error_minor));
break;
case CLNP_OPTION_PADDING:
ND_PRINT((ndo, "padding data"));
break;
/*
* FIXME those are the defined Options that lack a decoder
* you are welcome to contribute code ;-)
*/
default:
print_unknown_data(ndo, tptr, "\n\t ", opli);
break;
}
if (ndo->ndo_vflag > 1)
print_unknown_data(ndo, pptr, "\n\t ", opli);
pptr += opli;
}
switch (clnp_pdu_type) {
case CLNP_PDU_ER: /* fall through */
case CLNP_PDU_ERP:
ND_TCHECK(*pptr);
if (*(pptr) == NLPID_CLNP) {
ND_PRINT((ndo, "\n\t-----original packet-----\n\t"));
/* FIXME recursion protection */
clnp_print(ndo, pptr, length - clnp_header->length_indicator);
break;
}
case CLNP_PDU_DT:
case CLNP_PDU_MD:
case CLNP_PDU_ERQ:
default:
/* dump the PDU specific data */
if (length-(pptr-optr) > 0) {
ND_PRINT((ndo, "\n\t undecoded non-header data, length %u", length-clnp_header->length_indicator));
print_unknown_data(ndo, pptr, "\n\t ", length - (pptr - optr));
}
}
return (1);
trunc:
ND_PRINT((ndo, "[|clnp]"));
return (1);
}
#define ESIS_PDU_REDIRECT 6
#define ESIS_PDU_ESH 2
#define ESIS_PDU_ISH 4
static const struct tok esis_pdu_values[] = {
{ ESIS_PDU_REDIRECT, "redirect"},
{ ESIS_PDU_ESH, "ESH"},
{ ESIS_PDU_ISH, "ISH"},
{ 0, NULL }
};
struct esis_header_t {
uint8_t nlpid;
uint8_t length_indicator;
uint8_t version;
uint8_t reserved;
uint8_t type;
uint8_t holdtime[2];
uint8_t cksum[2];
};
static void
esis_print(netdissect_options *ndo,
const uint8_t *pptr, u_int length)
{
const uint8_t *optr;
u_int li,esis_pdu_type,source_address_length, source_address_number;
const struct esis_header_t *esis_header;
if (!ndo->ndo_eflag)
ND_PRINT((ndo, "ES-IS"));
if (length <= 2) {
ND_PRINT((ndo, ndo->ndo_qflag ? "bad pkt!" : "no header at all!"));
return;
}
esis_header = (const struct esis_header_t *) pptr;
ND_TCHECK(*esis_header);
li = esis_header->length_indicator;
optr = pptr;
/*
* Sanity checking of the header.
*/
if (esis_header->nlpid != NLPID_ESIS) {
ND_PRINT((ndo, " nlpid 0x%02x packet not supported", esis_header->nlpid));
return;
}
if (esis_header->version != ESIS_VERSION) {
ND_PRINT((ndo, " version %d packet not supported", esis_header->version));
return;
}
if (li > length) {
ND_PRINT((ndo, " length indicator(%u) > PDU size (%u)!", li, length));
return;
}
if (li < sizeof(struct esis_header_t) + 2) {
ND_PRINT((ndo, " length indicator %u < min PDU size:", li));
while (pptr < ndo->ndo_snapend)
ND_PRINT((ndo, "%02X", *pptr++));
return;
}
esis_pdu_type = esis_header->type & ESIS_PDU_TYPE_MASK;
if (ndo->ndo_vflag < 1) {
ND_PRINT((ndo, "%s%s, length %u",
ndo->ndo_eflag ? "" : ", ",
tok2str(esis_pdu_values,"unknown type (%u)",esis_pdu_type),
length));
return;
} else
ND_PRINT((ndo, "%slength %u\n\t%s (%u)",
ndo->ndo_eflag ? "" : ", ",
length,
tok2str(esis_pdu_values,"unknown type: %u", esis_pdu_type),
esis_pdu_type));
ND_PRINT((ndo, ", v: %u%s", esis_header->version, esis_header->version == ESIS_VERSION ? "" : "unsupported" ));
ND_PRINT((ndo, ", checksum: 0x%04x", EXTRACT_16BITS(esis_header->cksum)));
osi_print_cksum(ndo, pptr, EXTRACT_16BITS(esis_header->cksum), 7, li);
ND_PRINT((ndo, ", holding time: %us, length indicator: %u",
EXTRACT_16BITS(esis_header->holdtime), li));
if (ndo->ndo_vflag > 1)
print_unknown_data(ndo, optr, "\n\t", sizeof(struct esis_header_t));
pptr += sizeof(struct esis_header_t);
li -= sizeof(struct esis_header_t);
switch (esis_pdu_type) {
case ESIS_PDU_REDIRECT: {
const uint8_t *dst, *snpa, *neta;
u_int dstl, snpal, netal;
ND_TCHECK(*pptr);
if (li < 1) {
ND_PRINT((ndo, ", bad redirect/li"));
return;
}
dstl = *pptr;
pptr++;
li--;
ND_TCHECK2(*pptr, dstl);
if (li < dstl) {
ND_PRINT((ndo, ", bad redirect/li"));
return;
}
dst = pptr;
pptr += dstl;
li -= dstl;
ND_PRINT((ndo, "\n\t %s", isonsap_string(ndo, dst, dstl)));
ND_TCHECK(*pptr);
if (li < 1) {
ND_PRINT((ndo, ", bad redirect/li"));
return;
}
snpal = *pptr;
pptr++;
li--;
ND_TCHECK2(*pptr, snpal);
if (li < snpal) {
ND_PRINT((ndo, ", bad redirect/li"));
return;
}
snpa = pptr;
pptr += snpal;
li -= snpal;
ND_TCHECK(*pptr);
if (li < 1) {
ND_PRINT((ndo, ", bad redirect/li"));
return;
}
netal = *pptr;
pptr++;
ND_TCHECK2(*pptr, netal);
if (li < netal) {
ND_PRINT((ndo, ", bad redirect/li"));
return;
}
neta = pptr;
pptr += netal;
li -= netal;
if (snpal == 6)
ND_PRINT((ndo, "\n\t SNPA (length: %u): %s",
snpal,
etheraddr_string(ndo, snpa)));
else
ND_PRINT((ndo, "\n\t SNPA (length: %u): %s",
snpal,
linkaddr_string(ndo, snpa, LINKADDR_OTHER, snpal)));
if (netal != 0)
ND_PRINT((ndo, "\n\t NET (length: %u) %s",
netal,
isonsap_string(ndo, neta, netal)));
break;
}
case ESIS_PDU_ESH:
ND_TCHECK(*pptr);
if (li < 1) {
ND_PRINT((ndo, ", bad esh/li"));
return;
}
source_address_number = *pptr;
pptr++;
li--;
ND_PRINT((ndo, "\n\t Number of Source Addresses: %u", source_address_number));
while (source_address_number > 0) {
ND_TCHECK(*pptr);
if (li < 1) {
ND_PRINT((ndo, ", bad esh/li"));
return;
}
source_address_length = *pptr;
pptr++;
li--;
ND_TCHECK2(*pptr, source_address_length);
if (li < source_address_length) {
ND_PRINT((ndo, ", bad esh/li"));
return;
}
ND_PRINT((ndo, "\n\t NET (length: %u): %s",
source_address_length,
isonsap_string(ndo, pptr, source_address_length)));
pptr += source_address_length;
li -= source_address_length;
source_address_number--;
}
break;
case ESIS_PDU_ISH: {
ND_TCHECK(*pptr);
if (li < 1) {
ND_PRINT((ndo, ", bad ish/li"));
return;
}
source_address_length = *pptr;
pptr++;
li--;
ND_TCHECK2(*pptr, source_address_length);
if (li < source_address_length) {
ND_PRINT((ndo, ", bad ish/li"));
return;
}
ND_PRINT((ndo, "\n\t NET (length: %u): %s", source_address_length, isonsap_string(ndo, pptr, source_address_length)));
pptr += source_address_length;
li -= source_address_length;
break;
}
default:
if (ndo->ndo_vflag <= 1) {
if (pptr < ndo->ndo_snapend)
print_unknown_data(ndo, pptr, "\n\t ", ndo->ndo_snapend - pptr);
}
return;
}
/* now walk the options */
while (li != 0) {
u_int op, opli;
const uint8_t *tptr;
if (li < 2) {
ND_PRINT((ndo, ", bad opts/li"));
return;
}
ND_TCHECK2(*pptr, 2);
op = *pptr++;
opli = *pptr++;
li -= 2;
if (opli > li) {
ND_PRINT((ndo, ", opt (%d) too long", op));
return;
}
li -= opli;
tptr = pptr;
ND_PRINT((ndo, "\n\t %s Option #%u, length %u, value: ",
tok2str(esis_option_values,"Unknown",op),
op,
opli));
switch (op) {
case ESIS_OPTION_ES_CONF_TIME:
if (opli == 2) {
ND_TCHECK2(*pptr, 2);
ND_PRINT((ndo, "%us", EXTRACT_16BITS(tptr)));
} else
ND_PRINT((ndo, "(bad length)"));
break;
case ESIS_OPTION_PROTOCOLS:
while (opli>0) {
ND_TCHECK(*pptr);
ND_PRINT((ndo, "%s (0x%02x)",
tok2str(nlpid_values,
"unknown",
*tptr),
*tptr));
if (opli>1) /* further NPLIDs ? - put comma */
ND_PRINT((ndo, ", "));
tptr++;
opli--;
}
break;
/*
* FIXME those are the defined Options that lack a decoder
* you are welcome to contribute code ;-)
*/
case ESIS_OPTION_QOS_MAINTENANCE:
case ESIS_OPTION_SECURITY:
case ESIS_OPTION_PRIORITY:
case ESIS_OPTION_ADDRESS_MASK:
case ESIS_OPTION_SNPA_MASK:
default:
print_unknown_data(ndo, tptr, "\n\t ", opli);
break;
}
if (ndo->ndo_vflag > 1)
print_unknown_data(ndo, pptr, "\n\t ", opli);
pptr += opli;
}
trunc:
return;
}
static void
isis_print_mcid(netdissect_options *ndo,
const struct isis_spb_mcid *mcid)
{
int i;
ND_TCHECK(*mcid);
ND_PRINT((ndo, "ID: %d, Name: ", mcid->format_id));
if (fn_printzp(ndo, mcid->name, 32, ndo->ndo_snapend))
goto trunc;
ND_PRINT((ndo, "\n\t Lvl: %d", EXTRACT_16BITS(mcid->revision_lvl)));
ND_PRINT((ndo, ", Digest: "));
for(i=0;i<16;i++)
ND_PRINT((ndo, "%.2x ", mcid->digest[i]));
trunc:
ND_PRINT((ndo, "%s", tstr));
}
static int
isis_print_mt_port_cap_subtlv(netdissect_options *ndo,
const uint8_t *tptr, int len)
{
int stlv_type, stlv_len;
const struct isis_subtlv_spb_mcid *subtlv_spb_mcid;
int i;
while (len > 2)
{
ND_TCHECK2(*tptr, 2);
stlv_type = *(tptr++);
stlv_len = *(tptr++);
/* first lets see if we know the subTLVs name*/
ND_PRINT((ndo, "\n\t %s subTLV #%u, length: %u",
tok2str(isis_mt_port_cap_subtlv_values, "unknown", stlv_type),
stlv_type,
stlv_len));
/*len -= TLV_TYPE_LEN_OFFSET;*/
len = len -2;
/* Make sure the subTLV fits within the space left */
if (len < stlv_len)
goto trunc;
/* Make sure the entire subTLV is in the captured data */
ND_TCHECK2(*(tptr), stlv_len);
switch (stlv_type)
{
case ISIS_SUBTLV_SPB_MCID:
{
if (stlv_len < ISIS_SUBTLV_SPB_MCID_MIN_LEN)
goto trunc;
subtlv_spb_mcid = (const struct isis_subtlv_spb_mcid *)tptr;
ND_PRINT((ndo, "\n\t MCID: "));
isis_print_mcid(ndo, &(subtlv_spb_mcid->mcid));
/*tptr += SPB_MCID_MIN_LEN;
len -= SPB_MCID_MIN_LEN; */
ND_PRINT((ndo, "\n\t AUX-MCID: "));
isis_print_mcid(ndo, &(subtlv_spb_mcid->aux_mcid));
/*tptr += SPB_MCID_MIN_LEN;
len -= SPB_MCID_MIN_LEN; */
tptr = tptr + ISIS_SUBTLV_SPB_MCID_MIN_LEN;
len = len - ISIS_SUBTLV_SPB_MCID_MIN_LEN;
stlv_len = stlv_len - ISIS_SUBTLV_SPB_MCID_MIN_LEN;
break;
}
case ISIS_SUBTLV_SPB_DIGEST:
{
if (stlv_len < ISIS_SUBTLV_SPB_DIGEST_MIN_LEN)
goto trunc;
ND_PRINT((ndo, "\n\t RES: %d V: %d A: %d D: %d",
(*(tptr) >> 5), (((*tptr)>> 4) & 0x01),
((*(tptr) >> 2) & 0x03), ((*tptr) & 0x03)));
tptr++;
ND_PRINT((ndo, "\n\t Digest: "));
for(i=1;i<=8; i++)
{
ND_PRINT((ndo, "%08x ", EXTRACT_32BITS(tptr)));
if (i%4 == 0 && i != 8)
ND_PRINT((ndo, "\n\t "));
tptr = tptr + 4;
}
len = len - ISIS_SUBTLV_SPB_DIGEST_MIN_LEN;
stlv_len = stlv_len - ISIS_SUBTLV_SPB_DIGEST_MIN_LEN;
break;
}
case ISIS_SUBTLV_SPB_BVID:
{
while (stlv_len >= ISIS_SUBTLV_SPB_BVID_MIN_LEN)
{
ND_PRINT((ndo, "\n\t ECT: %08x",
EXTRACT_32BITS(tptr)));
tptr = tptr+4;
ND_PRINT((ndo, " BVID: %d, U:%01x M:%01x ",
(EXTRACT_16BITS (tptr) >> 4) ,
(EXTRACT_16BITS (tptr) >> 3) & 0x01,
(EXTRACT_16BITS (tptr) >> 2) & 0x01));
tptr = tptr + 2;
len = len - ISIS_SUBTLV_SPB_BVID_MIN_LEN;
stlv_len = stlv_len - ISIS_SUBTLV_SPB_BVID_MIN_LEN;
}
break;
}
default:
break;
}
tptr += stlv_len;
len -= stlv_len;
}
return 0;
trunc:
ND_PRINT((ndo, "\n\t\t"));
ND_PRINT((ndo, "%s", tstr));
return(1);
}
static int
isis_print_mt_capability_subtlv(netdissect_options *ndo,
const uint8_t *tptr, int len)
{
int stlv_type, stlv_len, tmp;
while (len > 2)
{
ND_TCHECK2(*tptr, 2);
stlv_type = *(tptr++);
stlv_len = *(tptr++);
/* first lets see if we know the subTLVs name*/
ND_PRINT((ndo, "\n\t %s subTLV #%u, length: %u",
tok2str(isis_mt_capability_subtlv_values, "unknown", stlv_type),
stlv_type,
stlv_len));
len = len - 2;
/* Make sure the subTLV fits within the space left */
if (len < stlv_len)
goto trunc;
/* Make sure the entire subTLV is in the captured data */
ND_TCHECK2(*(tptr), stlv_len);
switch (stlv_type)
{
case ISIS_SUBTLV_SPB_INSTANCE:
if (stlv_len < ISIS_SUBTLV_SPB_INSTANCE_MIN_LEN)
goto trunc;
ND_PRINT((ndo, "\n\t CIST Root-ID: %08x", EXTRACT_32BITS(tptr)));
tptr = tptr+4;
ND_PRINT((ndo, " %08x", EXTRACT_32BITS(tptr)));
tptr = tptr+4;
ND_PRINT((ndo, ", Path Cost: %08x", EXTRACT_32BITS(tptr)));
tptr = tptr+4;
ND_PRINT((ndo, ", Prio: %d", EXTRACT_16BITS(tptr)));
tptr = tptr + 2;
ND_PRINT((ndo, "\n\t RES: %d",
EXTRACT_16BITS(tptr) >> 5));
ND_PRINT((ndo, ", V: %d",
(EXTRACT_16BITS(tptr) >> 4) & 0x0001));
ND_PRINT((ndo, ", SPSource-ID: %d",
(EXTRACT_32BITS(tptr) & 0x000fffff)));
tptr = tptr+4;
ND_PRINT((ndo, ", No of Trees: %x", *(tptr)));
tmp = *(tptr++);
len = len - ISIS_SUBTLV_SPB_INSTANCE_MIN_LEN;
stlv_len = stlv_len - ISIS_SUBTLV_SPB_INSTANCE_MIN_LEN;
while (tmp)
{
if (stlv_len < ISIS_SUBTLV_SPB_INSTANCE_VLAN_TUPLE_LEN)
goto trunc;
ND_PRINT((ndo, "\n\t U:%d, M:%d, A:%d, RES:%d",
*(tptr) >> 7, (*(tptr) >> 6) & 0x01,
(*(tptr) >> 5) & 0x01, (*(tptr) & 0x1f)));
tptr++;
ND_PRINT((ndo, ", ECT: %08x", EXTRACT_32BITS(tptr)));
tptr = tptr + 4;
ND_PRINT((ndo, ", BVID: %d, SPVID: %d",
(EXTRACT_24BITS(tptr) >> 12) & 0x000fff,
EXTRACT_24BITS(tptr) & 0x000fff));
tptr = tptr + 3;
len = len - ISIS_SUBTLV_SPB_INSTANCE_VLAN_TUPLE_LEN;
stlv_len = stlv_len - ISIS_SUBTLV_SPB_INSTANCE_VLAN_TUPLE_LEN;
tmp--;
}
break;
case ISIS_SUBTLV_SPBM_SI:
if (stlv_len < 8)
goto trunc;
ND_PRINT((ndo, "\n\t BMAC: %08x", EXTRACT_32BITS(tptr)));
tptr = tptr+4;
ND_PRINT((ndo, "%04x", EXTRACT_16BITS(tptr)));
tptr = tptr+2;
ND_PRINT((ndo, ", RES: %d, VID: %d", EXTRACT_16BITS(tptr) >> 12,
(EXTRACT_16BITS(tptr)) & 0x0fff));
tptr = tptr+2;
len = len - 8;
stlv_len = stlv_len - 8;
while (stlv_len >= 4) {
ND_TCHECK2(*tptr, 4);
ND_PRINT((ndo, "\n\t T: %d, R: %d, RES: %d, ISID: %d",
(EXTRACT_32BITS(tptr) >> 31),
(EXTRACT_32BITS(tptr) >> 30) & 0x01,
(EXTRACT_32BITS(tptr) >> 24) & 0x03f,
(EXTRACT_32BITS(tptr)) & 0x0ffffff));
tptr = tptr + 4;
len = len - 4;
stlv_len = stlv_len - 4;
}
break;
default:
break;
}
tptr += stlv_len;
len -= stlv_len;
}
return 0;
trunc:
ND_PRINT((ndo, "\n\t\t"));
ND_PRINT((ndo, "%s", tstr));
return(1);
}
/* shared routine for printing system, node and lsp-ids */
static char *
isis_print_id(const uint8_t *cp, int id_len)
{
int i;
static char id[sizeof("xxxx.xxxx.xxxx.yy-zz")];
char *pos = id;
for (i = 1; i <= SYSTEM_ID_LEN; i++) {
snprintf(pos, sizeof(id) - (pos - id), "%02x", *cp++);
pos += strlen(pos);
if (i == 2 || i == 4)
*pos++ = '.';
}
if (id_len >= NODE_ID_LEN) {
snprintf(pos, sizeof(id) - (pos - id), ".%02x", *cp++);
pos += strlen(pos);
}
if (id_len == LSP_ID_LEN)
snprintf(pos, sizeof(id) - (pos - id), "-%02x", *cp);
return (id);
}
/* print the 4-byte metric block which is common found in the old-style TLVs */
static int
isis_print_metric_block(netdissect_options *ndo,
const struct isis_metric_block *isis_metric_block)
{
ND_PRINT((ndo, ", Default Metric: %d, %s",
ISIS_LSP_TLV_METRIC_VALUE(isis_metric_block->metric_default),
ISIS_LSP_TLV_METRIC_IE(isis_metric_block->metric_default) ? "External" : "Internal"));
if (!ISIS_LSP_TLV_METRIC_SUPPORTED(isis_metric_block->metric_delay))
ND_PRINT((ndo, "\n\t\t Delay Metric: %d, %s",
ISIS_LSP_TLV_METRIC_VALUE(isis_metric_block->metric_delay),
ISIS_LSP_TLV_METRIC_IE(isis_metric_block->metric_delay) ? "External" : "Internal"));
if (!ISIS_LSP_TLV_METRIC_SUPPORTED(isis_metric_block->metric_expense))
ND_PRINT((ndo, "\n\t\t Expense Metric: %d, %s",
ISIS_LSP_TLV_METRIC_VALUE(isis_metric_block->metric_expense),
ISIS_LSP_TLV_METRIC_IE(isis_metric_block->metric_expense) ? "External" : "Internal"));
if (!ISIS_LSP_TLV_METRIC_SUPPORTED(isis_metric_block->metric_error))
ND_PRINT((ndo, "\n\t\t Error Metric: %d, %s",
ISIS_LSP_TLV_METRIC_VALUE(isis_metric_block->metric_error),
ISIS_LSP_TLV_METRIC_IE(isis_metric_block->metric_error) ? "External" : "Internal"));
return(1); /* everything is ok */
}
static int
isis_print_tlv_ip_reach(netdissect_options *ndo,
const uint8_t *cp, const char *ident, int length)
{
int prefix_len;
const struct isis_tlv_ip_reach *tlv_ip_reach;
tlv_ip_reach = (const struct isis_tlv_ip_reach *)cp;
while (length > 0) {
if ((size_t)length < sizeof(*tlv_ip_reach)) {
ND_PRINT((ndo, "short IPv4 Reachability (%d vs %lu)",
length,
(unsigned long)sizeof(*tlv_ip_reach)));
return (0);
}
if (!ND_TTEST(*tlv_ip_reach))
return (0);
prefix_len = mask2plen(EXTRACT_32BITS(tlv_ip_reach->mask));
if (prefix_len == -1)
ND_PRINT((ndo, "%sIPv4 prefix: %s mask %s",
ident,
ipaddr_string(ndo, (tlv_ip_reach->prefix)),
ipaddr_string(ndo, (tlv_ip_reach->mask))));
else
ND_PRINT((ndo, "%sIPv4 prefix: %15s/%u",
ident,
ipaddr_string(ndo, (tlv_ip_reach->prefix)),
prefix_len));
ND_PRINT((ndo, ", Distribution: %s, Metric: %u, %s",
ISIS_LSP_TLV_METRIC_UPDOWN(tlv_ip_reach->isis_metric_block.metric_default) ? "down" : "up",
ISIS_LSP_TLV_METRIC_VALUE(tlv_ip_reach->isis_metric_block.metric_default),
ISIS_LSP_TLV_METRIC_IE(tlv_ip_reach->isis_metric_block.metric_default) ? "External" : "Internal"));
if (!ISIS_LSP_TLV_METRIC_SUPPORTED(tlv_ip_reach->isis_metric_block.metric_delay))
ND_PRINT((ndo, "%s Delay Metric: %u, %s",
ident,
ISIS_LSP_TLV_METRIC_VALUE(tlv_ip_reach->isis_metric_block.metric_delay),
ISIS_LSP_TLV_METRIC_IE(tlv_ip_reach->isis_metric_block.metric_delay) ? "External" : "Internal"));
if (!ISIS_LSP_TLV_METRIC_SUPPORTED(tlv_ip_reach->isis_metric_block.metric_expense))
ND_PRINT((ndo, "%s Expense Metric: %u, %s",
ident,
ISIS_LSP_TLV_METRIC_VALUE(tlv_ip_reach->isis_metric_block.metric_expense),
ISIS_LSP_TLV_METRIC_IE(tlv_ip_reach->isis_metric_block.metric_expense) ? "External" : "Internal"));
if (!ISIS_LSP_TLV_METRIC_SUPPORTED(tlv_ip_reach->isis_metric_block.metric_error))
ND_PRINT((ndo, "%s Error Metric: %u, %s",
ident,
ISIS_LSP_TLV_METRIC_VALUE(tlv_ip_reach->isis_metric_block.metric_error),
ISIS_LSP_TLV_METRIC_IE(tlv_ip_reach->isis_metric_block.metric_error) ? "External" : "Internal"));
length -= sizeof(struct isis_tlv_ip_reach);
tlv_ip_reach++;
}
return (1);
}
/*
* this is the common IP-REACH subTLV decoder it is called
* from various EXTD-IP REACH TLVs (135,235,236,237)
*/
static int
isis_print_ip_reach_subtlv(netdissect_options *ndo,
const uint8_t *tptr, int subt, int subl,
const char *ident)
{
/* first lets see if we know the subTLVs name*/
ND_PRINT((ndo, "%s%s subTLV #%u, length: %u",
ident, tok2str(isis_ext_ip_reach_subtlv_values, "unknown", subt),
subt, subl));
ND_TCHECK2(*tptr,subl);
switch(subt) {
case ISIS_SUBTLV_EXTD_IP_REACH_MGMT_PREFIX_COLOR: /* fall through */
case ISIS_SUBTLV_EXTD_IP_REACH_ADMIN_TAG32:
while (subl >= 4) {
ND_PRINT((ndo, ", 0x%08x (=%u)",
EXTRACT_32BITS(tptr),
EXTRACT_32BITS(tptr)));
tptr+=4;
subl-=4;
}
break;
case ISIS_SUBTLV_EXTD_IP_REACH_ADMIN_TAG64:
while (subl >= 8) {
ND_PRINT((ndo, ", 0x%08x%08x",
EXTRACT_32BITS(tptr),
EXTRACT_32BITS(tptr+4)));
tptr+=8;
subl-=8;
}
break;
default:
if (!print_unknown_data(ndo, tptr, "\n\t\t ", subl))
return(0);
break;
}
return(1);
trunc:
ND_PRINT((ndo, "%s", ident));
ND_PRINT((ndo, "%s", tstr));
return(0);
}
/*
* this is the common IS-REACH subTLV decoder it is called
* from isis_print_ext_is_reach()
*/
static int
isis_print_is_reach_subtlv(netdissect_options *ndo,
const uint8_t *tptr, u_int subt, u_int subl,
const char *ident)
{
u_int te_class,priority_level,gmpls_switch_cap;
union { /* int to float conversion buffer for several subTLVs */
float f;
uint32_t i;
} bw;
/* first lets see if we know the subTLVs name*/
ND_PRINT((ndo, "%s%s subTLV #%u, length: %u",
ident, tok2str(isis_ext_is_reach_subtlv_values, "unknown", subt),
subt, subl));
ND_TCHECK2(*tptr, subl);
switch(subt) {
case ISIS_SUBTLV_EXT_IS_REACH_ADMIN_GROUP:
case ISIS_SUBTLV_EXT_IS_REACH_LINK_LOCAL_REMOTE_ID:
case ISIS_SUBTLV_EXT_IS_REACH_LINK_REMOTE_ID:
if (subl >= 4) {
ND_PRINT((ndo, ", 0x%08x", EXTRACT_32BITS(tptr)));
if (subl == 8) /* rfc4205 */
ND_PRINT((ndo, ", 0x%08x", EXTRACT_32BITS(tptr+4)));
}
break;
case ISIS_SUBTLV_EXT_IS_REACH_IPV4_INTF_ADDR:
case ISIS_SUBTLV_EXT_IS_REACH_IPV4_NEIGHBOR_ADDR:
if (subl >= sizeof(struct in_addr))
ND_PRINT((ndo, ", %s", ipaddr_string(ndo, tptr)));
break;
case ISIS_SUBTLV_EXT_IS_REACH_MAX_LINK_BW :
case ISIS_SUBTLV_EXT_IS_REACH_RESERVABLE_BW:
if (subl >= 4) {
bw.i = EXTRACT_32BITS(tptr);
ND_PRINT((ndo, ", %.3f Mbps", bw.f * 8 / 1000000));
}
break;
case ISIS_SUBTLV_EXT_IS_REACH_UNRESERVED_BW :
if (subl >= 32) {
for (te_class = 0; te_class < 8; te_class++) {
bw.i = EXTRACT_32BITS(tptr);
ND_PRINT((ndo, "%s TE-Class %u: %.3f Mbps",
ident,
te_class,
bw.f * 8 / 1000000));
tptr+=4;
}
}
break;
case ISIS_SUBTLV_EXT_IS_REACH_BW_CONSTRAINTS: /* fall through */
case ISIS_SUBTLV_EXT_IS_REACH_BW_CONSTRAINTS_OLD:
ND_PRINT((ndo, "%sBandwidth Constraints Model ID: %s (%u)",
ident,
tok2str(diffserv_te_bc_values, "unknown", *tptr),
*tptr));
tptr++;
/* decode BCs until the subTLV ends */
for (te_class = 0; te_class < (subl-1)/4; te_class++) {
ND_TCHECK2(*tptr, 4);
bw.i = EXTRACT_32BITS(tptr);
ND_PRINT((ndo, "%s Bandwidth constraint CT%u: %.3f Mbps",
ident,
te_class,
bw.f * 8 / 1000000));
tptr+=4;
}
break;
case ISIS_SUBTLV_EXT_IS_REACH_TE_METRIC:
if (subl >= 3)
ND_PRINT((ndo, ", %u", EXTRACT_24BITS(tptr)));
break;
case ISIS_SUBTLV_EXT_IS_REACH_LINK_ATTRIBUTE:
if (subl == 2) {
ND_PRINT((ndo, ", [ %s ] (0x%04x)",
bittok2str(isis_subtlv_link_attribute_values,
"Unknown",
EXTRACT_16BITS(tptr)),
EXTRACT_16BITS(tptr)));
}
break;
case ISIS_SUBTLV_EXT_IS_REACH_LINK_PROTECTION_TYPE:
if (subl >= 2) {
ND_PRINT((ndo, ", %s, Priority %u",
bittok2str(gmpls_link_prot_values, "none", *tptr),
*(tptr+1)));
}
break;
case ISIS_SUBTLV_SPB_METRIC:
if (subl >= 6) {
ND_PRINT((ndo, ", LM: %u", EXTRACT_24BITS(tptr)));
tptr=tptr+3;
ND_PRINT((ndo, ", P: %u", *(tptr)));
tptr++;
ND_PRINT((ndo, ", P-ID: %u", EXTRACT_16BITS(tptr)));
}
break;
case ISIS_SUBTLV_EXT_IS_REACH_INTF_SW_CAP_DESCR:
if (subl >= 36) {
gmpls_switch_cap = *tptr;
ND_PRINT((ndo, "%s Interface Switching Capability:%s",
ident,
tok2str(gmpls_switch_cap_values, "Unknown", gmpls_switch_cap)));
ND_PRINT((ndo, ", LSP Encoding: %s",
tok2str(gmpls_encoding_values, "Unknown", *(tptr + 1))));
tptr+=4;
ND_PRINT((ndo, "%s Max LSP Bandwidth:", ident));
for (priority_level = 0; priority_level < 8; priority_level++) {
bw.i = EXTRACT_32BITS(tptr);
ND_PRINT((ndo, "%s priority level %d: %.3f Mbps",
ident,
priority_level,
bw.f * 8 / 1000000));
tptr+=4;
}
subl-=36;
switch (gmpls_switch_cap) {
case GMPLS_PSC1:
case GMPLS_PSC2:
case GMPLS_PSC3:
case GMPLS_PSC4:
ND_TCHECK2(*tptr, 6);
bw.i = EXTRACT_32BITS(tptr);
ND_PRINT((ndo, "%s Min LSP Bandwidth: %.3f Mbps", ident, bw.f * 8 / 1000000));
ND_PRINT((ndo, "%s Interface MTU: %u", ident, EXTRACT_16BITS(tptr + 4)));
break;
case GMPLS_TSC:
ND_TCHECK2(*tptr, 8);
bw.i = EXTRACT_32BITS(tptr);
ND_PRINT((ndo, "%s Min LSP Bandwidth: %.3f Mbps", ident, bw.f * 8 / 1000000));
ND_PRINT((ndo, "%s Indication %s", ident,
tok2str(gmpls_switch_cap_tsc_indication_values, "Unknown (%u)", *(tptr + 4))));
break;
default:
/* there is some optional stuff left to decode but this is as of yet
not specified so just lets hexdump what is left */
if(subl>0){
if (!print_unknown_data(ndo, tptr, "\n\t\t ", subl))
return(0);
}
}
}
break;
default:
if (!print_unknown_data(ndo, tptr, "\n\t\t ", subl))
return(0);
break;
}
return(1);
trunc:
return(0);
}
/*
* this is the common IS-REACH decoder it is called
* from various EXTD-IS REACH style TLVs (22,24,222)
*/
static int
isis_print_ext_is_reach(netdissect_options *ndo,
const uint8_t *tptr, const char *ident, int tlv_type)
{
char ident_buffer[20];
int subtlv_type,subtlv_len,subtlv_sum_len;
int proc_bytes = 0; /* how many bytes did we process ? */
if (!ND_TTEST2(*tptr, NODE_ID_LEN))
return(0);
ND_PRINT((ndo, "%sIS Neighbor: %s", ident, isis_print_id(tptr, NODE_ID_LEN)));
tptr+=(NODE_ID_LEN);
if (tlv_type != ISIS_TLV_IS_ALIAS_ID) { /* the Alias TLV Metric field is implicit 0 */
if (!ND_TTEST2(*tptr, 3)) /* and is therefore skipped */
return(0);
ND_PRINT((ndo, ", Metric: %d", EXTRACT_24BITS(tptr)));
tptr+=3;
}
if (!ND_TTEST2(*tptr, 1))
return(0);
subtlv_sum_len=*(tptr++); /* read out subTLV length */
proc_bytes=NODE_ID_LEN+3+1;
ND_PRINT((ndo, ", %ssub-TLVs present",subtlv_sum_len ? "" : "no "));
if (subtlv_sum_len) {
ND_PRINT((ndo, " (%u)", subtlv_sum_len));
while (subtlv_sum_len>0) {
if (!ND_TTEST2(*tptr,2))
return(0);
subtlv_type=*(tptr++);
subtlv_len=*(tptr++);
/* prepend the indent string */
snprintf(ident_buffer, sizeof(ident_buffer), "%s ",ident);
if (!isis_print_is_reach_subtlv(ndo, tptr, subtlv_type, subtlv_len, ident_buffer))
return(0);
tptr+=subtlv_len;
subtlv_sum_len-=(subtlv_len+2);
proc_bytes+=(subtlv_len+2);
}
}
return(proc_bytes);
}
/*
* this is the common Multi Topology ID decoder
* it is called from various MT-TLVs (222,229,235,237)
*/
static int
isis_print_mtid(netdissect_options *ndo,
const uint8_t *tptr, const char *ident)
{
if (!ND_TTEST2(*tptr, 2))
return(0);
ND_PRINT((ndo, "%s%s",
ident,
tok2str(isis_mt_values,
"Reserved for IETF Consensus",
ISIS_MASK_MTID(EXTRACT_16BITS(tptr)))));
ND_PRINT((ndo, " Topology (0x%03x), Flags: [%s]",
ISIS_MASK_MTID(EXTRACT_16BITS(tptr)),
bittok2str(isis_mt_flag_values, "none",ISIS_MASK_MTFLAGS(EXTRACT_16BITS(tptr)))));
return(2);
}
/*
* this is the common extended IP reach decoder
* it is called from TLVs (135,235,236,237)
* we process the TLV and optional subTLVs and return
* the amount of processed bytes
*/
static int
isis_print_extd_ip_reach(netdissect_options *ndo,
const uint8_t *tptr, const char *ident, uint16_t afi)
{
char ident_buffer[20];
uint8_t prefix[sizeof(struct in6_addr)]; /* shared copy buffer for IPv4 and IPv6 prefixes */
u_int metric, status_byte, bit_length, byte_length, sublen, processed, subtlvtype, subtlvlen;
if (!ND_TTEST2(*tptr, 4))
return (0);
metric = EXTRACT_32BITS(tptr);
processed=4;
tptr+=4;
if (afi == AF_INET) {
if (!ND_TTEST2(*tptr, 1)) /* fetch status byte */
return (0);
status_byte=*(tptr++);
bit_length = status_byte&0x3f;
if (bit_length > 32) {
ND_PRINT((ndo, "%sIPv4 prefix: bad bit length %u",
ident,
bit_length));
return (0);
}
processed++;
} else if (afi == AF_INET6) {
if (!ND_TTEST2(*tptr, 2)) /* fetch status & prefix_len byte */
return (0);
status_byte=*(tptr++);
bit_length=*(tptr++);
if (bit_length > 128) {
ND_PRINT((ndo, "%sIPv6 prefix: bad bit length %u",
ident,
bit_length));
return (0);
}
processed+=2;
} else
return (0); /* somebody is fooling us */
byte_length = (bit_length + 7) / 8; /* prefix has variable length encoding */
if (!ND_TTEST2(*tptr, byte_length))
return (0);
memset(prefix, 0, sizeof prefix); /* clear the copy buffer */
memcpy(prefix,tptr,byte_length); /* copy as much as is stored in the TLV */
tptr+=byte_length;
processed+=byte_length;
if (afi == AF_INET)
ND_PRINT((ndo, "%sIPv4 prefix: %15s/%u",
ident,
ipaddr_string(ndo, prefix),
bit_length));
else if (afi == AF_INET6)
ND_PRINT((ndo, "%sIPv6 prefix: %s/%u",
ident,
ip6addr_string(ndo, prefix),
bit_length));
ND_PRINT((ndo, ", Distribution: %s, Metric: %u",
ISIS_MASK_TLV_EXTD_IP_UPDOWN(status_byte) ? "down" : "up",
metric));
if (afi == AF_INET && ISIS_MASK_TLV_EXTD_IP_SUBTLV(status_byte))
ND_PRINT((ndo, ", sub-TLVs present"));
else if (afi == AF_INET6)
ND_PRINT((ndo, ", %s%s",
ISIS_MASK_TLV_EXTD_IP6_IE(status_byte) ? "External" : "Internal",
ISIS_MASK_TLV_EXTD_IP6_SUBTLV(status_byte) ? ", sub-TLVs present" : ""));
if ((afi == AF_INET && ISIS_MASK_TLV_EXTD_IP_SUBTLV(status_byte))
|| (afi == AF_INET6 && ISIS_MASK_TLV_EXTD_IP6_SUBTLV(status_byte))
) {
/* assume that one prefix can hold more
than one subTLV - therefore the first byte must reflect
the aggregate bytecount of the subTLVs for this prefix
*/
if (!ND_TTEST2(*tptr, 1))
return (0);
sublen=*(tptr++);
processed+=sublen+1;
ND_PRINT((ndo, " (%u)", sublen)); /* print out subTLV length */
while (sublen>0) {
if (!ND_TTEST2(*tptr,2))
return (0);
subtlvtype=*(tptr++);
subtlvlen=*(tptr++);
/* prepend the indent string */
snprintf(ident_buffer, sizeof(ident_buffer), "%s ",ident);
if (!isis_print_ip_reach_subtlv(ndo, tptr, subtlvtype, subtlvlen, ident_buffer))
return(0);
tptr+=subtlvlen;
sublen-=(subtlvlen+2);
}
}
return (processed);
}
/*
* Clear checksum and lifetime prior to signature verification.
*/
static void
isis_clear_checksum_lifetime(void *header)
{
struct isis_lsp_header *header_lsp = (struct isis_lsp_header *) header;
header_lsp->checksum[0] = 0;
header_lsp->checksum[1] = 0;
header_lsp->remaining_lifetime[0] = 0;
header_lsp->remaining_lifetime[1] = 0;
}
/*
* isis_print
* Decode IS-IS packets. Return 0 on error.
*/
static int
isis_print(netdissect_options *ndo,
const uint8_t *p, u_int length)
{
const struct isis_common_header *isis_header;
const struct isis_iih_lan_header *header_iih_lan;
const struct isis_iih_ptp_header *header_iih_ptp;
const struct isis_lsp_header *header_lsp;
const struct isis_csnp_header *header_csnp;
const struct isis_psnp_header *header_psnp;
const struct isis_tlv_lsp *tlv_lsp;
const struct isis_tlv_ptp_adj *tlv_ptp_adj;
const struct isis_tlv_is_reach *tlv_is_reach;
const struct isis_tlv_es_reach *tlv_es_reach;
uint8_t pdu_type, max_area, id_length, tlv_type, tlv_len, tmp, alen, lan_alen, prefix_len;
uint8_t ext_is_len, ext_ip_len, mt_len;
const uint8_t *optr, *pptr, *tptr;
u_short packet_len,pdu_len, key_id;
u_int i,vendor_id;
int sigcheck;
packet_len=length;
optr = p; /* initialize the _o_riginal pointer to the packet start -
need it for parsing the checksum TLV and authentication
TLV verification */
isis_header = (const struct isis_common_header *)p;
ND_TCHECK(*isis_header);
if (length < ISIS_COMMON_HEADER_SIZE)
goto trunc;
pptr = p+(ISIS_COMMON_HEADER_SIZE);
header_iih_lan = (const struct isis_iih_lan_header *)pptr;
header_iih_ptp = (const struct isis_iih_ptp_header *)pptr;
header_lsp = (const struct isis_lsp_header *)pptr;
header_csnp = (const struct isis_csnp_header *)pptr;
header_psnp = (const struct isis_psnp_header *)pptr;
if (!ndo->ndo_eflag)
ND_PRINT((ndo, "IS-IS"));
/*
* Sanity checking of the header.
*/
if (isis_header->version != ISIS_VERSION) {
ND_PRINT((ndo, "version %d packet not supported", isis_header->version));
return (0);
}
if ((isis_header->id_length != SYSTEM_ID_LEN) && (isis_header->id_length != 0)) {
ND_PRINT((ndo, "system ID length of %d is not supported",
isis_header->id_length));
return (0);
}
if (isis_header->pdu_version != ISIS_VERSION) {
ND_PRINT((ndo, "version %d packet not supported", isis_header->pdu_version));
return (0);
}
if (length < isis_header->fixed_len) {
ND_PRINT((ndo, "fixed header length %u > packet length %u", isis_header->fixed_len, length));
return (0);
}
if (isis_header->fixed_len < ISIS_COMMON_HEADER_SIZE) {
ND_PRINT((ndo, "fixed header length %u < minimum header size %u", isis_header->fixed_len, (u_int)ISIS_COMMON_HEADER_SIZE));
return (0);
}
max_area = isis_header->max_area;
switch(max_area) {
case 0:
max_area = 3; /* silly shit */
break;
case 255:
ND_PRINT((ndo, "bad packet -- 255 areas"));
return (0);
default:
break;
}
id_length = isis_header->id_length;
switch(id_length) {
case 0:
id_length = 6; /* silly shit again */
break;
case 1: /* 1-8 are valid sys-ID lenghts */
case 2:
case 3:
case 4:
case 5:
case 6:
case 7:
case 8:
break;
case 255:
id_length = 0; /* entirely useless */
break;
default:
break;
}
/* toss any non 6-byte sys-ID len PDUs */
if (id_length != 6 ) {
ND_PRINT((ndo, "bad packet -- illegal sys-ID length (%u)", id_length));
return (0);
}
pdu_type=isis_header->pdu_type;
/* in non-verbose mode print the basic PDU Type plus PDU specific brief information*/
if (ndo->ndo_vflag == 0) {
ND_PRINT((ndo, "%s%s",
ndo->ndo_eflag ? "" : ", ",
tok2str(isis_pdu_values, "unknown PDU-Type %u", pdu_type)));
} else {
/* ok they seem to want to know everything - lets fully decode it */
ND_PRINT((ndo, "%slength %u", ndo->ndo_eflag ? "" : ", ", length));
ND_PRINT((ndo, "\n\t%s, hlen: %u, v: %u, pdu-v: %u, sys-id-len: %u (%u), max-area: %u (%u)",
tok2str(isis_pdu_values,
"unknown, type %u",
pdu_type),
isis_header->fixed_len,
isis_header->version,
isis_header->pdu_version,
id_length,
isis_header->id_length,
max_area,
isis_header->max_area));
if (ndo->ndo_vflag > 1) {
if (!print_unknown_data(ndo, optr, "\n\t", 8)) /* provide the _o_riginal pointer */
return (0); /* for optionally debugging the common header */
}
}
switch (pdu_type) {
case ISIS_PDU_L1_LAN_IIH:
case ISIS_PDU_L2_LAN_IIH:
if (isis_header->fixed_len != (ISIS_COMMON_HEADER_SIZE+ISIS_IIH_LAN_HEADER_SIZE)) {
ND_PRINT((ndo, ", bogus fixed header length %u should be %lu",
isis_header->fixed_len, (unsigned long)(ISIS_COMMON_HEADER_SIZE+ISIS_IIH_LAN_HEADER_SIZE)));
return (0);
}
ND_TCHECK(*header_iih_lan);
if (length < ISIS_COMMON_HEADER_SIZE+ISIS_IIH_LAN_HEADER_SIZE)
goto trunc;
if (ndo->ndo_vflag == 0) {
ND_PRINT((ndo, ", src-id %s",
isis_print_id(header_iih_lan->source_id, SYSTEM_ID_LEN)));
ND_PRINT((ndo, ", lan-id %s, prio %u",
isis_print_id(header_iih_lan->lan_id,NODE_ID_LEN),
header_iih_lan->priority));
ND_PRINT((ndo, ", length %u", length));
return (1);
}
pdu_len=EXTRACT_16BITS(header_iih_lan->pdu_len);
if (packet_len>pdu_len) {
packet_len=pdu_len; /* do TLV decoding as long as it makes sense */
length=pdu_len;
}
ND_PRINT((ndo, "\n\t source-id: %s, holding time: %us, Flags: [%s]",
isis_print_id(header_iih_lan->source_id,SYSTEM_ID_LEN),
EXTRACT_16BITS(header_iih_lan->holding_time),
tok2str(isis_iih_circuit_type_values,
"unknown circuit type 0x%02x",
header_iih_lan->circuit_type)));
ND_PRINT((ndo, "\n\t lan-id: %s, Priority: %u, PDU length: %u",
isis_print_id(header_iih_lan->lan_id, NODE_ID_LEN),
(header_iih_lan->priority) & ISIS_LAN_PRIORITY_MASK,
pdu_len));
if (ndo->ndo_vflag > 1) {
if (!print_unknown_data(ndo, pptr, "\n\t ", ISIS_IIH_LAN_HEADER_SIZE))
return (0);
}
packet_len -= (ISIS_COMMON_HEADER_SIZE+ISIS_IIH_LAN_HEADER_SIZE);
pptr = p + (ISIS_COMMON_HEADER_SIZE+ISIS_IIH_LAN_HEADER_SIZE);
break;
case ISIS_PDU_PTP_IIH:
if (isis_header->fixed_len != (ISIS_COMMON_HEADER_SIZE+ISIS_IIH_PTP_HEADER_SIZE)) {
ND_PRINT((ndo, ", bogus fixed header length %u should be %lu",
isis_header->fixed_len, (unsigned long)(ISIS_COMMON_HEADER_SIZE+ISIS_IIH_PTP_HEADER_SIZE)));
return (0);
}
ND_TCHECK(*header_iih_ptp);
if (length < ISIS_COMMON_HEADER_SIZE+ISIS_IIH_PTP_HEADER_SIZE)
goto trunc;
if (ndo->ndo_vflag == 0) {
ND_PRINT((ndo, ", src-id %s", isis_print_id(header_iih_ptp->source_id, SYSTEM_ID_LEN)));
ND_PRINT((ndo, ", length %u", length));
return (1);
}
pdu_len=EXTRACT_16BITS(header_iih_ptp->pdu_len);
if (packet_len>pdu_len) {
packet_len=pdu_len; /* do TLV decoding as long as it makes sense */
length=pdu_len;
}
ND_PRINT((ndo, "\n\t source-id: %s, holding time: %us, Flags: [%s]",
isis_print_id(header_iih_ptp->source_id,SYSTEM_ID_LEN),
EXTRACT_16BITS(header_iih_ptp->holding_time),
tok2str(isis_iih_circuit_type_values,
"unknown circuit type 0x%02x",
header_iih_ptp->circuit_type)));
ND_PRINT((ndo, "\n\t circuit-id: 0x%02x, PDU length: %u",
header_iih_ptp->circuit_id,
pdu_len));
if (ndo->ndo_vflag > 1) {
if (!print_unknown_data(ndo, pptr, "\n\t ", ISIS_IIH_PTP_HEADER_SIZE))
return (0);
}
packet_len -= (ISIS_COMMON_HEADER_SIZE+ISIS_IIH_PTP_HEADER_SIZE);
pptr = p + (ISIS_COMMON_HEADER_SIZE+ISIS_IIH_PTP_HEADER_SIZE);
break;
case ISIS_PDU_L1_LSP:
case ISIS_PDU_L2_LSP:
if (isis_header->fixed_len != (ISIS_COMMON_HEADER_SIZE+ISIS_LSP_HEADER_SIZE)) {
ND_PRINT((ndo, ", bogus fixed header length %u should be %lu",
isis_header->fixed_len, (unsigned long)ISIS_LSP_HEADER_SIZE));
return (0);
}
ND_TCHECK(*header_lsp);
if (length < ISIS_COMMON_HEADER_SIZE+ISIS_LSP_HEADER_SIZE)
goto trunc;
if (ndo->ndo_vflag == 0) {
ND_PRINT((ndo, ", lsp-id %s, seq 0x%08x, lifetime %5us",
isis_print_id(header_lsp->lsp_id, LSP_ID_LEN),
EXTRACT_32BITS(header_lsp->sequence_number),
EXTRACT_16BITS(header_lsp->remaining_lifetime)));
ND_PRINT((ndo, ", length %u", length));
return (1);
}
pdu_len=EXTRACT_16BITS(header_lsp->pdu_len);
if (packet_len>pdu_len) {
packet_len=pdu_len; /* do TLV decoding as long as it makes sense */
length=pdu_len;
}
ND_PRINT((ndo, "\n\t lsp-id: %s, seq: 0x%08x, lifetime: %5us\n\t chksum: 0x%04x",
isis_print_id(header_lsp->lsp_id, LSP_ID_LEN),
EXTRACT_32BITS(header_lsp->sequence_number),
EXTRACT_16BITS(header_lsp->remaining_lifetime),
EXTRACT_16BITS(header_lsp->checksum)));
osi_print_cksum(ndo, (const uint8_t *)header_lsp->lsp_id,
EXTRACT_16BITS(header_lsp->checksum),
12, length-12);
ND_PRINT((ndo, ", PDU length: %u, Flags: [ %s",
pdu_len,
ISIS_MASK_LSP_OL_BIT(header_lsp->typeblock) ? "Overload bit set, " : ""));
if (ISIS_MASK_LSP_ATT_BITS(header_lsp->typeblock)) {
ND_PRINT((ndo, "%s", ISIS_MASK_LSP_ATT_DEFAULT_BIT(header_lsp->typeblock) ? "default " : ""));
ND_PRINT((ndo, "%s", ISIS_MASK_LSP_ATT_DELAY_BIT(header_lsp->typeblock) ? "delay " : ""));
ND_PRINT((ndo, "%s", ISIS_MASK_LSP_ATT_EXPENSE_BIT(header_lsp->typeblock) ? "expense " : ""));
ND_PRINT((ndo, "%s", ISIS_MASK_LSP_ATT_ERROR_BIT(header_lsp->typeblock) ? "error " : ""));
ND_PRINT((ndo, "ATT bit set, "));
}
ND_PRINT((ndo, "%s", ISIS_MASK_LSP_PARTITION_BIT(header_lsp->typeblock) ? "P bit set, " : ""));
ND_PRINT((ndo, "%s ]", tok2str(isis_lsp_istype_values, "Unknown(0x%x)",
ISIS_MASK_LSP_ISTYPE_BITS(header_lsp->typeblock))));
if (ndo->ndo_vflag > 1) {
if (!print_unknown_data(ndo, pptr, "\n\t ", ISIS_LSP_HEADER_SIZE))
return (0);
}
packet_len -= (ISIS_COMMON_HEADER_SIZE+ISIS_LSP_HEADER_SIZE);
pptr = p + (ISIS_COMMON_HEADER_SIZE+ISIS_LSP_HEADER_SIZE);
break;
case ISIS_PDU_L1_CSNP:
case ISIS_PDU_L2_CSNP:
if (isis_header->fixed_len != (ISIS_COMMON_HEADER_SIZE+ISIS_CSNP_HEADER_SIZE)) {
ND_PRINT((ndo, ", bogus fixed header length %u should be %lu",
isis_header->fixed_len, (unsigned long)(ISIS_COMMON_HEADER_SIZE+ISIS_CSNP_HEADER_SIZE)));
return (0);
}
ND_TCHECK(*header_csnp);
if (length < ISIS_COMMON_HEADER_SIZE+ISIS_CSNP_HEADER_SIZE)
goto trunc;
if (ndo->ndo_vflag == 0) {
ND_PRINT((ndo, ", src-id %s", isis_print_id(header_csnp->source_id, NODE_ID_LEN)));
ND_PRINT((ndo, ", length %u", length));
return (1);
}
pdu_len=EXTRACT_16BITS(header_csnp->pdu_len);
if (packet_len>pdu_len) {
packet_len=pdu_len; /* do TLV decoding as long as it makes sense */
length=pdu_len;
}
ND_PRINT((ndo, "\n\t source-id: %s, PDU length: %u",
isis_print_id(header_csnp->source_id, NODE_ID_LEN),
pdu_len));
ND_PRINT((ndo, "\n\t start lsp-id: %s",
isis_print_id(header_csnp->start_lsp_id, LSP_ID_LEN)));
ND_PRINT((ndo, "\n\t end lsp-id: %s",
isis_print_id(header_csnp->end_lsp_id, LSP_ID_LEN)));
if (ndo->ndo_vflag > 1) {
if (!print_unknown_data(ndo, pptr, "\n\t ", ISIS_CSNP_HEADER_SIZE))
return (0);
}
packet_len -= (ISIS_COMMON_HEADER_SIZE+ISIS_CSNP_HEADER_SIZE);
pptr = p + (ISIS_COMMON_HEADER_SIZE+ISIS_CSNP_HEADER_SIZE);
break;
case ISIS_PDU_L1_PSNP:
case ISIS_PDU_L2_PSNP:
if (isis_header->fixed_len != (ISIS_COMMON_HEADER_SIZE+ISIS_PSNP_HEADER_SIZE)) {
ND_PRINT((ndo, "- bogus fixed header length %u should be %lu",
isis_header->fixed_len, (unsigned long)(ISIS_COMMON_HEADER_SIZE+ISIS_PSNP_HEADER_SIZE)));
return (0);
}
ND_TCHECK(*header_psnp);
if (length < ISIS_COMMON_HEADER_SIZE+ISIS_PSNP_HEADER_SIZE)
goto trunc;
if (ndo->ndo_vflag == 0) {
ND_PRINT((ndo, ", src-id %s", isis_print_id(header_psnp->source_id, NODE_ID_LEN)));
ND_PRINT((ndo, ", length %u", length));
return (1);
}
pdu_len=EXTRACT_16BITS(header_psnp->pdu_len);
if (packet_len>pdu_len) {
packet_len=pdu_len; /* do TLV decoding as long as it makes sense */
length=pdu_len;
}
ND_PRINT((ndo, "\n\t source-id: %s, PDU length: %u",
isis_print_id(header_psnp->source_id, NODE_ID_LEN),
pdu_len));
if (ndo->ndo_vflag > 1) {
if (!print_unknown_data(ndo, pptr, "\n\t ", ISIS_PSNP_HEADER_SIZE))
return (0);
}
packet_len -= (ISIS_COMMON_HEADER_SIZE+ISIS_PSNP_HEADER_SIZE);
pptr = p + (ISIS_COMMON_HEADER_SIZE+ISIS_PSNP_HEADER_SIZE);
break;
default:
if (ndo->ndo_vflag == 0) {
ND_PRINT((ndo, ", length %u", length));
return (1);
}
(void)print_unknown_data(ndo, pptr, "\n\t ", length);
return (0);
}
/*
* Now print the TLV's.
*/
while (packet_len > 0) {
ND_TCHECK2(*pptr, 2);
if (packet_len < 2)
goto trunc;
tlv_type = *pptr++;
tlv_len = *pptr++;
tmp =tlv_len; /* copy temporary len & pointer to packet data */
tptr = pptr;
packet_len -= 2;
/* first lets see if we know the TLVs name*/
ND_PRINT((ndo, "\n\t %s TLV #%u, length: %u",
tok2str(isis_tlv_values,
"unknown",
tlv_type),
tlv_type,
tlv_len));
if (tlv_len == 0) /* something is invalid */
continue;
if (packet_len < tlv_len)
goto trunc;
/* now check if we have a decoder otherwise do a hexdump at the end*/
switch (tlv_type) {
case ISIS_TLV_AREA_ADDR:
ND_TCHECK2(*tptr, 1);
alen = *tptr++;
while (tmp && alen < tmp) {
ND_TCHECK2(*tptr, alen);
ND_PRINT((ndo, "\n\t Area address (length: %u): %s",
alen,
isonsap_string(ndo, tptr, alen)));
tptr += alen;
tmp -= alen + 1;
if (tmp==0) /* if this is the last area address do not attemt a boundary check */
break;
ND_TCHECK2(*tptr, 1);
alen = *tptr++;
}
break;
case ISIS_TLV_ISNEIGH:
while (tmp >= ETHER_ADDR_LEN) {
ND_TCHECK2(*tptr, ETHER_ADDR_LEN);
ND_PRINT((ndo, "\n\t SNPA: %s", isis_print_id(tptr, ETHER_ADDR_LEN)));
tmp -= ETHER_ADDR_LEN;
tptr += ETHER_ADDR_LEN;
}
break;
case ISIS_TLV_ISNEIGH_VARLEN:
if (!ND_TTEST2(*tptr, 1) || tmp < 3) /* min. TLV length */
goto trunctlv;
lan_alen = *tptr++; /* LAN address length */
if (lan_alen == 0) {
ND_PRINT((ndo, "\n\t LAN address length 0 bytes (invalid)"));
break;
}
tmp --;
ND_PRINT((ndo, "\n\t LAN address length %u bytes ", lan_alen));
while (tmp >= lan_alen) {
ND_TCHECK2(*tptr, lan_alen);
ND_PRINT((ndo, "\n\t\tIS Neighbor: %s", isis_print_id(tptr, lan_alen)));
tmp -= lan_alen;
tptr +=lan_alen;
}
break;
case ISIS_TLV_PADDING:
break;
case ISIS_TLV_MT_IS_REACH:
mt_len = isis_print_mtid(ndo, tptr, "\n\t ");
if (mt_len == 0) /* did something go wrong ? */
goto trunctlv;
tptr+=mt_len;
tmp-=mt_len;
while (tmp >= 2+NODE_ID_LEN+3+1) {
ext_is_len = isis_print_ext_is_reach(ndo, tptr, "\n\t ", tlv_type);
if (ext_is_len == 0) /* did something go wrong ? */
goto trunctlv;
tmp-=ext_is_len;
tptr+=ext_is_len;
}
break;
case ISIS_TLV_IS_ALIAS_ID:
while (tmp >= NODE_ID_LEN+1) { /* is it worth attempting a decode ? */
ext_is_len = isis_print_ext_is_reach(ndo, tptr, "\n\t ", tlv_type);
if (ext_is_len == 0) /* did something go wrong ? */
goto trunctlv;
tmp-=ext_is_len;
tptr+=ext_is_len;
}
break;
case ISIS_TLV_EXT_IS_REACH:
while (tmp >= NODE_ID_LEN+3+1) { /* is it worth attempting a decode ? */
ext_is_len = isis_print_ext_is_reach(ndo, tptr, "\n\t ", tlv_type);
if (ext_is_len == 0) /* did something go wrong ? */
goto trunctlv;
tmp-=ext_is_len;
tptr+=ext_is_len;
}
break;
case ISIS_TLV_IS_REACH:
ND_TCHECK2(*tptr,1); /* check if there is one byte left to read out the virtual flag */
ND_PRINT((ndo, "\n\t %s",
tok2str(isis_is_reach_virtual_values,
"bogus virtual flag 0x%02x",
*tptr++)));
tlv_is_reach = (const struct isis_tlv_is_reach *)tptr;
while (tmp >= sizeof(struct isis_tlv_is_reach)) {
ND_TCHECK(*tlv_is_reach);
ND_PRINT((ndo, "\n\t IS Neighbor: %s",
isis_print_id(tlv_is_reach->neighbor_nodeid, NODE_ID_LEN)));
isis_print_metric_block(ndo, &tlv_is_reach->isis_metric_block);
tmp -= sizeof(struct isis_tlv_is_reach);
tlv_is_reach++;
}
break;
case ISIS_TLV_ESNEIGH:
tlv_es_reach = (const struct isis_tlv_es_reach *)tptr;
while (tmp >= sizeof(struct isis_tlv_es_reach)) {
ND_TCHECK(*tlv_es_reach);
ND_PRINT((ndo, "\n\t ES Neighbor: %s",
isis_print_id(tlv_es_reach->neighbor_sysid, SYSTEM_ID_LEN)));
isis_print_metric_block(ndo, &tlv_es_reach->isis_metric_block);
tmp -= sizeof(struct isis_tlv_es_reach);
tlv_es_reach++;
}
break;
/* those two TLVs share the same format */
case ISIS_TLV_INT_IP_REACH:
case ISIS_TLV_EXT_IP_REACH:
if (!isis_print_tlv_ip_reach(ndo, pptr, "\n\t ", tlv_len))
return (1);
break;
case ISIS_TLV_EXTD_IP_REACH:
while (tmp>0) {
ext_ip_len = isis_print_extd_ip_reach(ndo, tptr, "\n\t ", AF_INET);
if (ext_ip_len == 0) /* did something go wrong ? */
goto trunctlv;
tptr+=ext_ip_len;
tmp-=ext_ip_len;
}
break;
case ISIS_TLV_MT_IP_REACH:
mt_len = isis_print_mtid(ndo, tptr, "\n\t ");
if (mt_len == 0) { /* did something go wrong ? */
goto trunctlv;
}
tptr+=mt_len;
tmp-=mt_len;
while (tmp>0) {
ext_ip_len = isis_print_extd_ip_reach(ndo, tptr, "\n\t ", AF_INET);
if (ext_ip_len == 0) /* did something go wrong ? */
goto trunctlv;
tptr+=ext_ip_len;
tmp-=ext_ip_len;
}
break;
case ISIS_TLV_IP6_REACH:
while (tmp>0) {
ext_ip_len = isis_print_extd_ip_reach(ndo, tptr, "\n\t ", AF_INET6);
if (ext_ip_len == 0) /* did something go wrong ? */
goto trunctlv;
tptr+=ext_ip_len;
tmp-=ext_ip_len;
}
break;
case ISIS_TLV_MT_IP6_REACH:
mt_len = isis_print_mtid(ndo, tptr, "\n\t ");
if (mt_len == 0) { /* did something go wrong ? */
goto trunctlv;
}
tptr+=mt_len;
tmp-=mt_len;
while (tmp>0) {
ext_ip_len = isis_print_extd_ip_reach(ndo, tptr, "\n\t ", AF_INET6);
if (ext_ip_len == 0) /* did something go wrong ? */
goto trunctlv;
tptr+=ext_ip_len;
tmp-=ext_ip_len;
}
break;
case ISIS_TLV_IP6ADDR:
while (tmp>=sizeof(struct in6_addr)) {
ND_TCHECK2(*tptr, sizeof(struct in6_addr));
ND_PRINT((ndo, "\n\t IPv6 interface address: %s",
ip6addr_string(ndo, tptr)));
tptr += sizeof(struct in6_addr);
tmp -= sizeof(struct in6_addr);
}
break;
case ISIS_TLV_AUTH:
ND_TCHECK2(*tptr, 1);
ND_PRINT((ndo, "\n\t %s: ",
tok2str(isis_subtlv_auth_values,
"unknown Authentication type 0x%02x",
*tptr)));
switch (*tptr) {
case ISIS_SUBTLV_AUTH_SIMPLE:
if (fn_printzp(ndo, tptr + 1, tlv_len - 1, ndo->ndo_snapend))
goto trunctlv;
break;
case ISIS_SUBTLV_AUTH_MD5:
for(i=1;i<tlv_len;i++) {
ND_TCHECK2(*(tptr + i), 1);
ND_PRINT((ndo, "%02x", *(tptr + i)));
}
if (tlv_len != ISIS_SUBTLV_AUTH_MD5_LEN+1)
ND_PRINT((ndo, ", (invalid subTLV) "));
sigcheck = signature_verify(ndo, optr, length, tptr + 1,
isis_clear_checksum_lifetime,
header_lsp);
ND_PRINT((ndo, " (%s)", tok2str(signature_check_values, "Unknown", sigcheck)));
break;
case ISIS_SUBTLV_AUTH_GENERIC:
ND_TCHECK2(*(tptr + 1), 2);
key_id = EXTRACT_16BITS((tptr+1));
ND_PRINT((ndo, "%u, password: ", key_id));
for(i=1 + sizeof(uint16_t);i<tlv_len;i++) {
ND_TCHECK2(*(tptr + i), 1);
ND_PRINT((ndo, "%02x", *(tptr + i)));
}
break;
case ISIS_SUBTLV_AUTH_PRIVATE:
default:
if (!print_unknown_data(ndo, tptr + 1, "\n\t\t ", tlv_len - 1))
return(0);
break;
}
break;
case ISIS_TLV_PTP_ADJ:
tlv_ptp_adj = (const struct isis_tlv_ptp_adj *)tptr;
if(tmp>=1) {
ND_TCHECK2(*tptr, 1);
ND_PRINT((ndo, "\n\t Adjacency State: %s (%u)",
tok2str(isis_ptp_adjancey_values, "unknown", *tptr),
*tptr));
tmp--;
}
if(tmp>sizeof(tlv_ptp_adj->extd_local_circuit_id)) {
ND_TCHECK(tlv_ptp_adj->extd_local_circuit_id);
ND_PRINT((ndo, "\n\t Extended Local circuit-ID: 0x%08x",
EXTRACT_32BITS(tlv_ptp_adj->extd_local_circuit_id)));
tmp-=sizeof(tlv_ptp_adj->extd_local_circuit_id);
}
if(tmp>=SYSTEM_ID_LEN) {
ND_TCHECK2(tlv_ptp_adj->neighbor_sysid, SYSTEM_ID_LEN);
ND_PRINT((ndo, "\n\t Neighbor System-ID: %s",
isis_print_id(tlv_ptp_adj->neighbor_sysid, SYSTEM_ID_LEN)));
tmp-=SYSTEM_ID_LEN;
}
if(tmp>=sizeof(tlv_ptp_adj->neighbor_extd_local_circuit_id)) {
ND_TCHECK(tlv_ptp_adj->neighbor_extd_local_circuit_id);
ND_PRINT((ndo, "\n\t Neighbor Extended Local circuit-ID: 0x%08x",
EXTRACT_32BITS(tlv_ptp_adj->neighbor_extd_local_circuit_id)));
}
break;
case ISIS_TLV_PROTOCOLS:
ND_PRINT((ndo, "\n\t NLPID(s): "));
while (tmp>0) {
ND_TCHECK2(*(tptr), 1);
ND_PRINT((ndo, "%s (0x%02x)",
tok2str(nlpid_values,
"unknown",
*tptr),
*tptr));
if (tmp>1) /* further NPLIDs ? - put comma */
ND_PRINT((ndo, ", "));
tptr++;
tmp--;
}
break;
case ISIS_TLV_MT_PORT_CAP:
{
ND_TCHECK2(*(tptr), 2);
ND_PRINT((ndo, "\n\t RES: %d, MTID(s): %d",
(EXTRACT_16BITS (tptr) >> 12),
(EXTRACT_16BITS (tptr) & 0x0fff)));
tmp = tmp-2;
tptr = tptr+2;
if (tmp)
isis_print_mt_port_cap_subtlv(ndo, tptr, tmp);
break;
}
case ISIS_TLV_MT_CAPABILITY:
ND_TCHECK2(*(tptr), 2);
ND_PRINT((ndo, "\n\t O: %d, RES: %d, MTID(s): %d",
(EXTRACT_16BITS(tptr) >> 15) & 0x01,
(EXTRACT_16BITS(tptr) >> 12) & 0x07,
EXTRACT_16BITS(tptr) & 0x0fff));
tmp = tmp-2;
tptr = tptr+2;
if (tmp)
isis_print_mt_capability_subtlv(ndo, tptr, tmp);
break;
case ISIS_TLV_TE_ROUTER_ID:
ND_TCHECK2(*pptr, sizeof(struct in_addr));
ND_PRINT((ndo, "\n\t Traffic Engineering Router ID: %s", ipaddr_string(ndo, pptr)));
break;
case ISIS_TLV_IPADDR:
while (tmp>=sizeof(struct in_addr)) {
ND_TCHECK2(*tptr, sizeof(struct in_addr));
ND_PRINT((ndo, "\n\t IPv4 interface address: %s", ipaddr_string(ndo, tptr)));
tptr += sizeof(struct in_addr);
tmp -= sizeof(struct in_addr);
}
break;
case ISIS_TLV_HOSTNAME:
ND_PRINT((ndo, "\n\t Hostname: "));
if (fn_printzp(ndo, tptr, tmp, ndo->ndo_snapend))
goto trunctlv;
break;
case ISIS_TLV_SHARED_RISK_GROUP:
if (tmp < NODE_ID_LEN)
break;
ND_TCHECK2(*tptr, NODE_ID_LEN);
ND_PRINT((ndo, "\n\t IS Neighbor: %s", isis_print_id(tptr, NODE_ID_LEN)));
tptr+=(NODE_ID_LEN);
tmp-=(NODE_ID_LEN);
if (tmp < 1)
break;
ND_TCHECK2(*tptr, 1);
ND_PRINT((ndo, ", Flags: [%s]", ISIS_MASK_TLV_SHARED_RISK_GROUP(*tptr++) ? "numbered" : "unnumbered"));
tmp--;
if (tmp < sizeof(struct in_addr))
break;
ND_TCHECK2(*tptr, sizeof(struct in_addr));
ND_PRINT((ndo, "\n\t IPv4 interface address: %s", ipaddr_string(ndo, tptr)));
tptr+=sizeof(struct in_addr);
tmp-=sizeof(struct in_addr);
if (tmp < sizeof(struct in_addr))
break;
ND_TCHECK2(*tptr, sizeof(struct in_addr));
ND_PRINT((ndo, "\n\t IPv4 neighbor address: %s", ipaddr_string(ndo, tptr)));
tptr+=sizeof(struct in_addr);
tmp-=sizeof(struct in_addr);
while (tmp>=4) {
ND_TCHECK2(*tptr, 4);
ND_PRINT((ndo, "\n\t Link-ID: 0x%08x", EXTRACT_32BITS(tptr)));
tptr+=4;
tmp-=4;
}
break;
case ISIS_TLV_LSP:
tlv_lsp = (const struct isis_tlv_lsp *)tptr;
while(tmp>=sizeof(struct isis_tlv_lsp)) {
ND_TCHECK((tlv_lsp->lsp_id)[LSP_ID_LEN-1]);
ND_PRINT((ndo, "\n\t lsp-id: %s",
isis_print_id(tlv_lsp->lsp_id, LSP_ID_LEN)));
ND_TCHECK2(tlv_lsp->sequence_number, 4);
ND_PRINT((ndo, ", seq: 0x%08x", EXTRACT_32BITS(tlv_lsp->sequence_number)));
ND_TCHECK2(tlv_lsp->remaining_lifetime, 2);
ND_PRINT((ndo, ", lifetime: %5ds", EXTRACT_16BITS(tlv_lsp->remaining_lifetime)));
ND_TCHECK2(tlv_lsp->checksum, 2);
ND_PRINT((ndo, ", chksum: 0x%04x", EXTRACT_16BITS(tlv_lsp->checksum)));
tmp-=sizeof(struct isis_tlv_lsp);
tlv_lsp++;
}
break;
case ISIS_TLV_CHECKSUM:
if (tmp < ISIS_TLV_CHECKSUM_MINLEN)
break;
ND_TCHECK2(*tptr, ISIS_TLV_CHECKSUM_MINLEN);
ND_PRINT((ndo, "\n\t checksum: 0x%04x ", EXTRACT_16BITS(tptr)));
/* do not attempt to verify the checksum if it is zero
* most likely a HMAC-MD5 TLV is also present and
* to avoid conflicts the checksum TLV is zeroed.
* see rfc3358 for details
*/
osi_print_cksum(ndo, optr, EXTRACT_16BITS(tptr), tptr-optr,
length);
break;
case ISIS_TLV_POI:
if (tlv_len >= SYSTEM_ID_LEN + 1) {
ND_TCHECK2(*tptr, SYSTEM_ID_LEN + 1);
ND_PRINT((ndo, "\n\t Purge Originator System-ID: %s",
isis_print_id(tptr + 1, SYSTEM_ID_LEN)));
}
if (tlv_len == 2 * SYSTEM_ID_LEN + 1) {
ND_TCHECK2(*tptr, 2 * SYSTEM_ID_LEN + 1);
ND_PRINT((ndo, "\n\t Received from System-ID: %s",
isis_print_id(tptr + SYSTEM_ID_LEN + 1, SYSTEM_ID_LEN)));
}
break;
case ISIS_TLV_MT_SUPPORTED:
if (tmp < ISIS_TLV_MT_SUPPORTED_MINLEN)
break;
while (tmp>1) {
/* length can only be a multiple of 2, otherwise there is
something broken -> so decode down until length is 1 */
if (tmp!=1) {
mt_len = isis_print_mtid(ndo, tptr, "\n\t ");
if (mt_len == 0) /* did something go wrong ? */
goto trunctlv;
tptr+=mt_len;
tmp-=mt_len;
} else {
ND_PRINT((ndo, "\n\t invalid MT-ID"));
break;
}
}
break;
case ISIS_TLV_RESTART_SIGNALING:
/* first attempt to decode the flags */
if (tmp < ISIS_TLV_RESTART_SIGNALING_FLAGLEN)
break;
ND_TCHECK2(*tptr, ISIS_TLV_RESTART_SIGNALING_FLAGLEN);
ND_PRINT((ndo, "\n\t Flags [%s]",
bittok2str(isis_restart_flag_values, "none", *tptr)));
tptr+=ISIS_TLV_RESTART_SIGNALING_FLAGLEN;
tmp-=ISIS_TLV_RESTART_SIGNALING_FLAGLEN;
/* is there anything other than the flags field? */
if (tmp == 0)
break;
if (tmp < ISIS_TLV_RESTART_SIGNALING_HOLDTIMELEN)
break;
ND_TCHECK2(*tptr, ISIS_TLV_RESTART_SIGNALING_HOLDTIMELEN);
ND_PRINT((ndo, ", Remaining holding time %us", EXTRACT_16BITS(tptr)));
tptr+=ISIS_TLV_RESTART_SIGNALING_HOLDTIMELEN;
tmp-=ISIS_TLV_RESTART_SIGNALING_HOLDTIMELEN;
/* is there an additional sysid field present ?*/
if (tmp == SYSTEM_ID_LEN) {
ND_TCHECK2(*tptr, SYSTEM_ID_LEN);
ND_PRINT((ndo, ", for %s", isis_print_id(tptr,SYSTEM_ID_LEN)));
}
break;
case ISIS_TLV_IDRP_INFO:
if (tmp < ISIS_TLV_IDRP_INFO_MINLEN)
break;
ND_TCHECK2(*tptr, ISIS_TLV_IDRP_INFO_MINLEN);
ND_PRINT((ndo, "\n\t Inter-Domain Information Type: %s",
tok2str(isis_subtlv_idrp_values,
"Unknown (0x%02x)",
*tptr)));
switch (*tptr++) {
case ISIS_SUBTLV_IDRP_ASN:
ND_TCHECK2(*tptr, 2); /* fetch AS number */
ND_PRINT((ndo, "AS Number: %u", EXTRACT_16BITS(tptr)));
break;
case ISIS_SUBTLV_IDRP_LOCAL:
case ISIS_SUBTLV_IDRP_RES:
default:
if (!print_unknown_data(ndo, tptr, "\n\t ", tlv_len - 1))
return(0);
break;
}
break;
case ISIS_TLV_LSP_BUFFERSIZE:
if (tmp < ISIS_TLV_LSP_BUFFERSIZE_MINLEN)
break;
ND_TCHECK2(*tptr, ISIS_TLV_LSP_BUFFERSIZE_MINLEN);
ND_PRINT((ndo, "\n\t LSP Buffersize: %u", EXTRACT_16BITS(tptr)));
break;
case ISIS_TLV_PART_DIS:
while (tmp >= SYSTEM_ID_LEN) {
ND_TCHECK2(*tptr, SYSTEM_ID_LEN);
ND_PRINT((ndo, "\n\t %s", isis_print_id(tptr, SYSTEM_ID_LEN)));
tptr+=SYSTEM_ID_LEN;
tmp-=SYSTEM_ID_LEN;
}
break;
case ISIS_TLV_PREFIX_NEIGH:
if (tmp < sizeof(struct isis_metric_block))
break;
ND_TCHECK2(*tptr, sizeof(struct isis_metric_block));
ND_PRINT((ndo, "\n\t Metric Block"));
isis_print_metric_block(ndo, (const struct isis_metric_block *)tptr);
tptr+=sizeof(struct isis_metric_block);
tmp-=sizeof(struct isis_metric_block);
while(tmp>0) {
ND_TCHECK2(*tptr, 1);
prefix_len=*tptr++; /* read out prefix length in semioctets*/
if (prefix_len < 2) {
ND_PRINT((ndo, "\n\t\tAddress: prefix length %u < 2", prefix_len));
break;
}
tmp--;
if (tmp < prefix_len/2)
break;
ND_TCHECK2(*tptr, prefix_len / 2);
ND_PRINT((ndo, "\n\t\tAddress: %s/%u",
isonsap_string(ndo, tptr, prefix_len / 2), prefix_len * 4));
tptr+=prefix_len/2;
tmp-=prefix_len/2;
}
break;
case ISIS_TLV_IIH_SEQNR:
if (tmp < ISIS_TLV_IIH_SEQNR_MINLEN)
break;
ND_TCHECK2(*tptr, ISIS_TLV_IIH_SEQNR_MINLEN); /* check if four bytes are on the wire */
ND_PRINT((ndo, "\n\t Sequence number: %u", EXTRACT_32BITS(tptr)));
break;
case ISIS_TLV_VENDOR_PRIVATE:
if (tmp < ISIS_TLV_VENDOR_PRIVATE_MINLEN)
break;
ND_TCHECK2(*tptr, ISIS_TLV_VENDOR_PRIVATE_MINLEN); /* check if enough byte for a full oui */
vendor_id = EXTRACT_24BITS(tptr);
ND_PRINT((ndo, "\n\t Vendor: %s (%u)",
tok2str(oui_values, "Unknown", vendor_id),
vendor_id));
tptr+=3;
tmp-=3;
if (tmp > 0) /* hexdump the rest */
if (!print_unknown_data(ndo, tptr, "\n\t\t", tmp))
return(0);
break;
/*
* FIXME those are the defined TLVs that lack a decoder
* you are welcome to contribute code ;-)
*/
case ISIS_TLV_DECNET_PHASE4:
case ISIS_TLV_LUCENT_PRIVATE:
case ISIS_TLV_IPAUTH:
case ISIS_TLV_NORTEL_PRIVATE1:
case ISIS_TLV_NORTEL_PRIVATE2:
default:
if (ndo->ndo_vflag <= 1) {
if (!print_unknown_data(ndo, pptr, "\n\t\t", tlv_len))
return(0);
}
break;
}
/* do we want to see an additionally hexdump ? */
if (ndo->ndo_vflag> 1) {
if (!print_unknown_data(ndo, pptr, "\n\t ", tlv_len))
return(0);
}
pptr += tlv_len;
packet_len -= tlv_len;
}
if (packet_len != 0) {
ND_PRINT((ndo, "\n\t %u straggler bytes", packet_len));
}
return (1);
trunc:
ND_PRINT((ndo, "%s", tstr));
return (1);
trunctlv:
ND_PRINT((ndo, "\n\t\t"));
ND_PRINT((ndo, "%s", tstr));
return(1);
}
static void
osi_print_cksum(netdissect_options *ndo, const uint8_t *pptr,
uint16_t checksum, int checksum_offset, u_int length)
{
uint16_t calculated_checksum;
/* do not attempt to verify the checksum if it is zero,
* if the offset is nonsense,
* or the base pointer is not sane
*/
if (!checksum
|| checksum_offset < 0
|| !ND_TTEST2(*(pptr + checksum_offset), 2)
|| (u_int)checksum_offset > length
|| !ND_TTEST2(*pptr, length)) {
ND_PRINT((ndo, " (unverified)"));
} else {
#if 0
printf("\nosi_print_cksum: %p %u %u\n", pptr, checksum_offset, length);
#endif
calculated_checksum = create_osi_cksum(pptr, checksum_offset, length);
if (checksum == calculated_checksum) {
ND_PRINT((ndo, " (correct)"));
} else {
ND_PRINT((ndo, " (incorrect should be 0x%04x)", calculated_checksum));
}
}
}
/*
* Local Variables:
* c-style: whitesmith
* c-basic-offset: 8
* End:
*/
| ./CrossVul/dataset_final_sorted/CWE-125/c/good_2702_0 |
crossvul-cpp_data_good_2688_0 | /*
* Copyright (c) 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997
* The Regents of the University of California. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that: (1) source code distributions
* retain the above copyright notice and this paragraph in its entirety, (2)
* distributions including binary code include the above copyright notice and
* this paragraph in its entirety in the documentation or other materials
* provided with the distribution, and (3) all advertising materials mentioning
* features or use of this software display the following acknowledgement:
* ``This product includes software developed by the University of California,
* Lawrence Berkeley Laboratory and its contributors.'' Neither the name of
* the University nor the names of its contributors may be used to endorse
* or promote products derived from this software without specific prior
* written permission.
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
/* \summary: Address Resolution Protocol (ARP) printer */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <netdissect-stdinc.h>
#include <string.h>
#include "netdissect.h"
#include "addrtoname.h"
#include "ether.h"
#include "ethertype.h"
#include "extract.h"
static const char tstr[] = "[|ARP]";
/*
* Address Resolution Protocol.
*
* See RFC 826 for protocol description. ARP packets are variable
* in size; the arphdr structure defines the fixed-length portion.
* Protocol type values are the same as those for 10 Mb/s Ethernet.
* It is followed by the variable-sized fields ar_sha, arp_spa,
* arp_tha and arp_tpa in that order, according to the lengths
* specified. Field names used correspond to RFC 826.
*/
struct arp_pkthdr {
u_short ar_hrd; /* format of hardware address */
#define ARPHRD_ETHER 1 /* ethernet hardware format */
#define ARPHRD_IEEE802 6 /* token-ring hardware format */
#define ARPHRD_ARCNET 7 /* arcnet hardware format */
#define ARPHRD_FRELAY 15 /* frame relay hardware format */
#define ARPHRD_ATM2225 19 /* ATM (RFC 2225) */
#define ARPHRD_STRIP 23 /* Ricochet Starmode Radio hardware format */
#define ARPHRD_IEEE1394 24 /* IEEE 1394 (FireWire) hardware format */
u_short ar_pro; /* format of protocol address */
u_char ar_hln; /* length of hardware address */
u_char ar_pln; /* length of protocol address */
u_short ar_op; /* one of: */
#define ARPOP_REQUEST 1 /* request to resolve address */
#define ARPOP_REPLY 2 /* response to previous request */
#define ARPOP_REVREQUEST 3 /* request protocol address given hardware */
#define ARPOP_REVREPLY 4 /* response giving protocol address */
#define ARPOP_INVREQUEST 8 /* request to identify peer */
#define ARPOP_INVREPLY 9 /* response identifying peer */
#define ARPOP_NAK 10 /* NAK - only valif for ATM ARP */
/*
* The remaining fields are variable in size,
* according to the sizes above.
*/
#ifdef COMMENT_ONLY
u_char ar_sha[]; /* sender hardware address */
u_char ar_spa[]; /* sender protocol address */
u_char ar_tha[]; /* target hardware address */
u_char ar_tpa[]; /* target protocol address */
#endif
#define ar_sha(ap) (((const u_char *)((ap)+1))+ 0)
#define ar_spa(ap) (((const u_char *)((ap)+1))+ (ap)->ar_hln)
#define ar_tha(ap) (((const u_char *)((ap)+1))+ (ap)->ar_hln+(ap)->ar_pln)
#define ar_tpa(ap) (((const u_char *)((ap)+1))+2*(ap)->ar_hln+(ap)->ar_pln)
};
#define ARP_HDRLEN 8
#define HRD(ap) EXTRACT_16BITS(&(ap)->ar_hrd)
#define HRD_LEN(ap) ((ap)->ar_hln)
#define PROTO_LEN(ap) ((ap)->ar_pln)
#define OP(ap) EXTRACT_16BITS(&(ap)->ar_op)
#define PRO(ap) EXTRACT_16BITS(&(ap)->ar_pro)
#define SHA(ap) (ar_sha(ap))
#define SPA(ap) (ar_spa(ap))
#define THA(ap) (ar_tha(ap))
#define TPA(ap) (ar_tpa(ap))
static const struct tok arpop_values[] = {
{ ARPOP_REQUEST, "Request" },
{ ARPOP_REPLY, "Reply" },
{ ARPOP_REVREQUEST, "Reverse Request" },
{ ARPOP_REVREPLY, "Reverse Reply" },
{ ARPOP_INVREQUEST, "Inverse Request" },
{ ARPOP_INVREPLY, "Inverse Reply" },
{ ARPOP_NAK, "NACK Reply" },
{ 0, NULL }
};
static const struct tok arphrd_values[] = {
{ ARPHRD_ETHER, "Ethernet" },
{ ARPHRD_IEEE802, "TokenRing" },
{ ARPHRD_ARCNET, "ArcNet" },
{ ARPHRD_FRELAY, "FrameRelay" },
{ ARPHRD_STRIP, "Strip" },
{ ARPHRD_IEEE1394, "IEEE 1394" },
{ ARPHRD_ATM2225, "ATM" },
{ 0, NULL }
};
/*
* ATM Address Resolution Protocol.
*
* See RFC 2225 for protocol description. ATMARP packets are similar
* to ARP packets, except that there are no length fields for the
* protocol address - instead, there are type/length fields for
* the ATM number and subaddress - and the hardware addresses consist
* of an ATM number and an ATM subaddress.
*/
struct atmarp_pkthdr {
u_short aar_hrd; /* format of hardware address */
u_short aar_pro; /* format of protocol address */
u_char aar_shtl; /* length of source ATM number */
u_char aar_sstl; /* length of source ATM subaddress */
#define ATMARP_IS_E164 0x40 /* bit in type/length for E.164 format */
#define ATMARP_LEN_MASK 0x3F /* length of {sub}address in type/length */
u_short aar_op; /* same as regular ARP */
u_char aar_spln; /* length of source protocol address */
u_char aar_thtl; /* length of target ATM number */
u_char aar_tstl; /* length of target ATM subaddress */
u_char aar_tpln; /* length of target protocol address */
/*
* The remaining fields are variable in size,
* according to the sizes above.
*/
#ifdef COMMENT_ONLY
u_char aar_sha[]; /* source ATM number */
u_char aar_ssa[]; /* source ATM subaddress */
u_char aar_spa[]; /* sender protocol address */
u_char aar_tha[]; /* target ATM number */
u_char aar_tsa[]; /* target ATM subaddress */
u_char aar_tpa[]; /* target protocol address */
#endif
#define ATMHRD(ap) EXTRACT_16BITS(&(ap)->aar_hrd)
#define ATMSHRD_LEN(ap) ((ap)->aar_shtl & ATMARP_LEN_MASK)
#define ATMSSLN(ap) ((ap)->aar_sstl & ATMARP_LEN_MASK)
#define ATMSPROTO_LEN(ap) ((ap)->aar_spln)
#define ATMOP(ap) EXTRACT_16BITS(&(ap)->aar_op)
#define ATMPRO(ap) EXTRACT_16BITS(&(ap)->aar_pro)
#define ATMTHRD_LEN(ap) ((ap)->aar_thtl & ATMARP_LEN_MASK)
#define ATMTSLN(ap) ((ap)->aar_tstl & ATMARP_LEN_MASK)
#define ATMTPROTO_LEN(ap) ((ap)->aar_tpln)
#define aar_sha(ap) ((const u_char *)((ap)+1))
#define aar_ssa(ap) (aar_sha(ap) + ATMSHRD_LEN(ap))
#define aar_spa(ap) (aar_ssa(ap) + ATMSSLN(ap))
#define aar_tha(ap) (aar_spa(ap) + ATMSPROTO_LEN(ap))
#define aar_tsa(ap) (aar_tha(ap) + ATMTHRD_LEN(ap))
#define aar_tpa(ap) (aar_tsa(ap) + ATMTSLN(ap))
};
#define ATMSHA(ap) (aar_sha(ap))
#define ATMSSA(ap) (aar_ssa(ap))
#define ATMSPA(ap) (aar_spa(ap))
#define ATMTHA(ap) (aar_tha(ap))
#define ATMTSA(ap) (aar_tsa(ap))
#define ATMTPA(ap) (aar_tpa(ap))
static int
isnonzero(const u_char *a, size_t len)
{
while (len > 0) {
if (*a != 0)
return (1);
a++;
len--;
}
return (0);
}
static void
tpaddr_print_ip(netdissect_options *ndo,
const struct arp_pkthdr *ap, u_short pro)
{
if (pro != ETHERTYPE_IP && pro != ETHERTYPE_TRAIL)
ND_PRINT((ndo, "<wrong proto type>"));
else if (PROTO_LEN(ap) != 4)
ND_PRINT((ndo, "<wrong len>"));
else
ND_PRINT((ndo, "%s", ipaddr_string(ndo, TPA(ap))));
}
static void
spaddr_print_ip(netdissect_options *ndo,
const struct arp_pkthdr *ap, u_short pro)
{
if (pro != ETHERTYPE_IP && pro != ETHERTYPE_TRAIL)
ND_PRINT((ndo, "<wrong proto type>"));
else if (PROTO_LEN(ap) != 4)
ND_PRINT((ndo, "<wrong len>"));
else
ND_PRINT((ndo, "%s", ipaddr_string(ndo, SPA(ap))));
}
static void
atmarp_addr_print(netdissect_options *ndo,
const u_char *ha, u_int ha_len, const u_char *srca,
u_int srca_len)
{
if (ha_len == 0)
ND_PRINT((ndo, "<No address>"));
else {
ND_PRINT((ndo, "%s", linkaddr_string(ndo, ha, LINKADDR_ATM, ha_len)));
if (srca_len != 0)
ND_PRINT((ndo, ",%s",
linkaddr_string(ndo, srca, LINKADDR_ATM, srca_len)));
}
}
static void
atmarp_tpaddr_print(netdissect_options *ndo,
const struct atmarp_pkthdr *ap, u_short pro)
{
if (pro != ETHERTYPE_IP && pro != ETHERTYPE_TRAIL)
ND_PRINT((ndo, "<wrong proto type>"));
else if (ATMTPROTO_LEN(ap) != 4)
ND_PRINT((ndo, "<wrong tplen>"));
else
ND_PRINT((ndo, "%s", ipaddr_string(ndo, ATMTPA(ap))));
}
static void
atmarp_spaddr_print(netdissect_options *ndo,
const struct atmarp_pkthdr *ap, u_short pro)
{
if (pro != ETHERTYPE_IP && pro != ETHERTYPE_TRAIL)
ND_PRINT((ndo, "<wrong proto type>"));
else if (ATMSPROTO_LEN(ap) != 4)
ND_PRINT((ndo, "<wrong splen>"));
else
ND_PRINT((ndo, "%s", ipaddr_string(ndo, ATMSPA(ap))));
}
static void
atmarp_print(netdissect_options *ndo,
const u_char *bp, u_int length, u_int caplen)
{
const struct atmarp_pkthdr *ap;
u_short pro, hrd, op;
ap = (const struct atmarp_pkthdr *)bp;
ND_TCHECK(*ap);
hrd = ATMHRD(ap);
pro = ATMPRO(ap);
op = ATMOP(ap);
if (!ND_TTEST2(*aar_tpa(ap), ATMTPROTO_LEN(ap))) {
ND_PRINT((ndo, "%s", tstr));
ND_DEFAULTPRINT((const u_char *)ap, length);
return;
}
if (!ndo->ndo_eflag) {
ND_PRINT((ndo, "ARP, "));
}
if ((pro != ETHERTYPE_IP && pro != ETHERTYPE_TRAIL) ||
ATMSPROTO_LEN(ap) != 4 ||
ATMTPROTO_LEN(ap) != 4 ||
ndo->ndo_vflag) {
ND_PRINT((ndo, "%s, %s (len %u/%u)",
tok2str(arphrd_values, "Unknown Hardware (%u)", hrd),
tok2str(ethertype_values, "Unknown Protocol (0x%04x)", pro),
ATMSPROTO_LEN(ap),
ATMTPROTO_LEN(ap)));
/* don't know know about the address formats */
if (!ndo->ndo_vflag) {
goto out;
}
}
/* print operation */
ND_PRINT((ndo, "%s%s ",
ndo->ndo_vflag ? ", " : "",
tok2str(arpop_values, "Unknown (%u)", op)));
switch (op) {
case ARPOP_REQUEST:
ND_PRINT((ndo, "who-has "));
atmarp_tpaddr_print(ndo, ap, pro);
if (ATMTHRD_LEN(ap) != 0) {
ND_PRINT((ndo, " ("));
atmarp_addr_print(ndo, ATMTHA(ap), ATMTHRD_LEN(ap),
ATMTSA(ap), ATMTSLN(ap));
ND_PRINT((ndo, ")"));
}
ND_PRINT((ndo, " tell "));
atmarp_spaddr_print(ndo, ap, pro);
break;
case ARPOP_REPLY:
atmarp_spaddr_print(ndo, ap, pro);
ND_PRINT((ndo, " is-at "));
atmarp_addr_print(ndo, ATMSHA(ap), ATMSHRD_LEN(ap), ATMSSA(ap),
ATMSSLN(ap));
break;
case ARPOP_INVREQUEST:
ND_PRINT((ndo, "who-is "));
atmarp_addr_print(ndo, ATMTHA(ap), ATMTHRD_LEN(ap), ATMTSA(ap),
ATMTSLN(ap));
ND_PRINT((ndo, " tell "));
atmarp_addr_print(ndo, ATMSHA(ap), ATMSHRD_LEN(ap), ATMSSA(ap),
ATMSSLN(ap));
break;
case ARPOP_INVREPLY:
atmarp_addr_print(ndo, ATMSHA(ap), ATMSHRD_LEN(ap), ATMSSA(ap),
ATMSSLN(ap));
ND_PRINT((ndo, "at "));
atmarp_spaddr_print(ndo, ap, pro);
break;
case ARPOP_NAK:
ND_PRINT((ndo, "for "));
atmarp_spaddr_print(ndo, ap, pro);
break;
default:
ND_DEFAULTPRINT((const u_char *)ap, caplen);
return;
}
out:
ND_PRINT((ndo, ", length %u", length));
return;
trunc:
ND_PRINT((ndo, "%s", tstr));
}
void
arp_print(netdissect_options *ndo,
const u_char *bp, u_int length, u_int caplen)
{
const struct arp_pkthdr *ap;
u_short pro, hrd, op, linkaddr;
ap = (const struct arp_pkthdr *)bp;
ND_TCHECK(*ap);
hrd = HRD(ap);
pro = PRO(ap);
op = OP(ap);
/* if its ATM then call the ATM ARP printer
for Frame-relay ARP most of the fields
are similar to Ethernet so overload the Ethernet Printer
and set the linkaddr type for linkaddr_string(ndo, ) accordingly */
switch(hrd) {
case ARPHRD_ATM2225:
atmarp_print(ndo, bp, length, caplen);
return;
case ARPHRD_FRELAY:
linkaddr = LINKADDR_FRELAY;
break;
default:
linkaddr = LINKADDR_ETHER;
break;
}
if (!ND_TTEST2(*TPA(ap), PROTO_LEN(ap))) {
ND_PRINT((ndo, "%s", tstr));
ND_DEFAULTPRINT((const u_char *)ap, length);
return;
}
if (!ndo->ndo_eflag) {
ND_PRINT((ndo, "ARP, "));
}
/* print hardware type/len and proto type/len */
if ((pro != ETHERTYPE_IP && pro != ETHERTYPE_TRAIL) ||
PROTO_LEN(ap) != 4 ||
HRD_LEN(ap) == 0 ||
ndo->ndo_vflag) {
ND_PRINT((ndo, "%s (len %u), %s (len %u)",
tok2str(arphrd_values, "Unknown Hardware (%u)", hrd),
HRD_LEN(ap),
tok2str(ethertype_values, "Unknown Protocol (0x%04x)", pro),
PROTO_LEN(ap)));
/* don't know know about the address formats */
if (!ndo->ndo_vflag) {
goto out;
}
}
/* print operation */
ND_PRINT((ndo, "%s%s ",
ndo->ndo_vflag ? ", " : "",
tok2str(arpop_values, "Unknown (%u)", op)));
switch (op) {
case ARPOP_REQUEST:
ND_PRINT((ndo, "who-has "));
tpaddr_print_ip(ndo, ap, pro);
if (isnonzero((const u_char *)THA(ap), HRD_LEN(ap)))
ND_PRINT((ndo, " (%s)",
linkaddr_string(ndo, THA(ap), linkaddr, HRD_LEN(ap))));
ND_PRINT((ndo, " tell "));
spaddr_print_ip(ndo, ap, pro);
break;
case ARPOP_REPLY:
spaddr_print_ip(ndo, ap, pro);
ND_PRINT((ndo, " is-at %s",
linkaddr_string(ndo, SHA(ap), linkaddr, HRD_LEN(ap))));
break;
case ARPOP_REVREQUEST:
ND_PRINT((ndo, "who-is %s tell %s",
linkaddr_string(ndo, THA(ap), linkaddr, HRD_LEN(ap)),
linkaddr_string(ndo, SHA(ap), linkaddr, HRD_LEN(ap))));
break;
case ARPOP_REVREPLY:
ND_PRINT((ndo, "%s at ",
linkaddr_string(ndo, THA(ap), linkaddr, HRD_LEN(ap))));
tpaddr_print_ip(ndo, ap, pro);
break;
case ARPOP_INVREQUEST:
ND_PRINT((ndo, "who-is %s tell %s",
linkaddr_string(ndo, THA(ap), linkaddr, HRD_LEN(ap)),
linkaddr_string(ndo, SHA(ap), linkaddr, HRD_LEN(ap))));
break;
case ARPOP_INVREPLY:
ND_PRINT((ndo,"%s at ",
linkaddr_string(ndo, SHA(ap), linkaddr, HRD_LEN(ap))));
spaddr_print_ip(ndo, ap, pro);
break;
default:
ND_DEFAULTPRINT((const u_char *)ap, caplen);
return;
}
out:
ND_PRINT((ndo, ", length %u", length));
return;
trunc:
ND_PRINT((ndo, "%s", tstr));
}
/*
* Local Variables:
* c-style: bsd
* End:
*/
| ./CrossVul/dataset_final_sorted/CWE-125/c/good_2688_0 |
crossvul-cpp_data_good_17_0 | /*
* Copyright (C) 2015 Cisco Systems, Inc. and/or its affiliates. All rights reserved.
* Copyright (C) 2013 Sourcefire, Inc.
*
* Authors: Steven Morgan <smorgan@sourcefire.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, 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
#include <errno.h>
#include "xar.h"
#include "fmap.h"
#if HAVE_LIBXML2
#ifdef _WIN32
#ifndef LIBXML_WRITER_ENABLED
#define LIBXML_WRITER_ENABLED 1
#endif
#endif
#include <libxml/xmlreader.h>
#include "clamav.h"
#include "str.h"
#include "scanners.h"
#include "inflate64.h"
#include "lzma_iface.h"
/*
xar_cleanup_temp_file - cleanup after cli_gentempfd
parameters:
ctx - cli_ctx context pointer
fd - fd to close
tmpname - name of file to unlink, address of storage to free
returns - CL_SUCCESS or CL_EUNLINK
*/
static int xar_cleanup_temp_file(cli_ctx *ctx, int fd, char * tmpname)
{
int rc = CL_SUCCESS;
if (fd > -1)
close(fd);
if (tmpname != NULL) {
if (!ctx->engine->keeptmp) {
if (cli_unlink(tmpname)) {
cli_dbgmsg("cli_scanxar: error unlinking tmpfile %s\n", tmpname);
rc = CL_EUNLINK;
}
}
free(tmpname);
}
return rc;
}
/*
xar_get_numeric_from_xml_element - extract xml element value as numeric
parameters:
reader - xmlTextReaderPtr
value - pointer to long to contain the returned value
returns - CL_SUCCESS or CL_EFORMAT
*/
static int xar_get_numeric_from_xml_element(xmlTextReaderPtr reader, size_t * value)
{
const xmlChar * numstr;
ssize_t numval;
if (xmlTextReaderRead(reader) == 1 && xmlTextReaderNodeType(reader) == XML_READER_TYPE_TEXT) {
numstr = xmlTextReaderConstValue(reader);
if (numstr) {
numval = atol((const char *)numstr);
if (numval < 0) {
cli_dbgmsg("cli_scanxar: XML element value %li\n", *value);
return CL_EFORMAT;
}
*value = numval;
return CL_SUCCESS;
}
}
cli_dbgmsg("cli_scanxar: No text for XML element\n");
return CL_EFORMAT;
}
/*
xar_get_checksum_values - extract checksum and hash algorithm from xml element
parameters:
reader - xmlTextReaderPtr
cksum - pointer to char* for returning checksum value.
hash - pointer to int for returning checksum algorithm.
returns - void
*/
static void xar_get_checksum_values(xmlTextReaderPtr reader, unsigned char ** cksum, int * hash)
{
xmlChar * style = xmlTextReaderGetAttribute(reader, (const xmlChar *)"style");
const xmlChar * xmlval;
*hash = XAR_CKSUM_NONE;
if (style == NULL) {
cli_dbgmsg("cli_scaxar: xmlTextReaderGetAttribute no style attribute "
"for checksum element\n");
} else {
cli_dbgmsg("cli_scanxar: checksum algorithm is %s.\n", style);
if (0 == xmlStrcasecmp(style, (const xmlChar *)"sha1")) {
*hash = XAR_CKSUM_SHA1;
} else if (0 == xmlStrcasecmp(style, (const xmlChar *)"md5")) {
*hash = XAR_CKSUM_MD5;
} else {
cli_dbgmsg("cli_scanxar: checksum algorithm %s is unsupported.\n", style);
*hash = XAR_CKSUM_OTHER;
}
}
if (style != NULL)
xmlFree(style);
if (xmlTextReaderRead(reader) == 1 && xmlTextReaderNodeType(reader) == XML_READER_TYPE_TEXT) {
xmlval = xmlTextReaderConstValue(reader);
if (xmlval) {
cli_dbgmsg("cli_scanxar: checksum value is %s.\n", xmlval);
if (*hash == XAR_CKSUM_SHA1 && xmlStrlen(xmlval) == 2 * CLI_HASHLEN_SHA1 ||
*hash == XAR_CKSUM_MD5 && xmlStrlen(xmlval) == 2 * CLI_HASHLEN_MD5)
{
*cksum = xmlStrdup(xmlval);
}
else
{
cli_dbgmsg("cli_scanxar: checksum type is unknown or length is invalid.\n");
*hash = XAR_CKSUM_OTHER;
*cksum = NULL;
}
} else {
*cksum = NULL;
cli_dbgmsg("cli_scanxar: xmlTextReaderConstValue() returns NULL for checksum value.\n");
}
}
else
cli_dbgmsg("cli_scanxar: No text for XML checksum element.\n");
}
/*
xar_get_toc_data_values - return the values of a <data> or <ea> xml element that represent
an extent of data on the heap.
parameters:
reader - xmlTextReaderPtr
length - pointer to long for returning value of the <length> element.
offset - pointer to long for returning value of the <offset> element.
size - pointer to long for returning value of the <size> element.
encoding - pointer to int for returning indication of the <encoding> style attribute.
a_cksum - pointer to char* for return archived checksum value.
a_hash - pointer to int for returning archived checksum algorithm.
e_cksum - pointer to char* for return extracted checksum value.
e_hash - pointer to int for returning extracted checksum algorithm.
returns - CL_FORMAT, CL_SUCCESS, CL_BREAK. CL_BREAK indicates no more <data>/<ea> element.
*/
static int xar_get_toc_data_values(xmlTextReaderPtr reader, size_t *length, size_t *offset, size_t *size, int *encoding,
unsigned char ** a_cksum, int * a_hash, unsigned char ** e_cksum, int * e_hash)
{
const xmlChar *name;
int indata = 0, inea = 0;
int rc, gotoffset=0, gotlength=0, gotsize=0;
*a_cksum = NULL;
*a_hash = XAR_CKSUM_NONE;
*e_cksum = NULL;
*e_hash = XAR_CKSUM_NONE;
*encoding = CL_TYPE_ANY;
rc = xmlTextReaderRead(reader);
while (rc == 1) {
name = xmlTextReaderConstLocalName(reader);
if (indata || inea) {
/* cli_dbgmsg("cli_scanxar: xmlTextReaderRead read %s\n", name); */
if (xmlStrEqual(name, (const xmlChar *)"offset") &&
xmlTextReaderNodeType(reader) == XML_READER_TYPE_ELEMENT) {
if (CL_SUCCESS == xar_get_numeric_from_xml_element(reader, offset))
gotoffset=1;
} else if (xmlStrEqual(name, (const xmlChar *)"length") &&
xmlTextReaderNodeType(reader) == XML_READER_TYPE_ELEMENT) {
if (CL_SUCCESS == xar_get_numeric_from_xml_element(reader, length))
gotlength=1;
} else if (xmlStrEqual(name, (const xmlChar *)"size") &&
xmlTextReaderNodeType(reader) == XML_READER_TYPE_ELEMENT) {
if (CL_SUCCESS == xar_get_numeric_from_xml_element(reader, size))
gotsize=1;
} else if (xmlStrEqual(name, (const xmlChar *)"archived-checksum") &&
xmlTextReaderNodeType(reader) == XML_READER_TYPE_ELEMENT) {
cli_dbgmsg("cli_scanxar: <archived-checksum>:\n");
xar_get_checksum_values(reader, a_cksum, a_hash);
} else if ((xmlStrEqual(name, (const xmlChar *)"extracted-checksum") ||
xmlStrEqual(name, (const xmlChar *)"unarchived-checksum")) &&
xmlTextReaderNodeType(reader) == XML_READER_TYPE_ELEMENT) {
cli_dbgmsg("cli_scanxar: <extracted-checksum>:\n");
xar_get_checksum_values(reader, e_cksum, e_hash);
} else if (xmlStrEqual(name, (const xmlChar *)"encoding") &&
xmlTextReaderNodeType(reader) == XML_READER_TYPE_ELEMENT) {
xmlChar * style = xmlTextReaderGetAttribute(reader, (const xmlChar *)"style");
if (style == NULL) {
cli_dbgmsg("cli_scaxar: xmlTextReaderGetAttribute no style attribute "
"for encoding element\n");
*encoding = CL_TYPE_ANY;
} else if (xmlStrEqual(style, (const xmlChar *)"application/x-gzip")) {
cli_dbgmsg("cli_scanxar: encoding = application/x-gzip.\n");
*encoding = CL_TYPE_GZ;
} else if (xmlStrEqual(style, (const xmlChar *)"application/octet-stream")) {
cli_dbgmsg("cli_scanxar: encoding = application/octet-stream.\n");
*encoding = CL_TYPE_ANY;
} else if (xmlStrEqual(style, (const xmlChar *)"application/x-bzip2")) {
cli_dbgmsg("cli_scanxar: encoding = application/x-bzip2.\n");
*encoding = CL_TYPE_BZ;
} else if (xmlStrEqual(style, (const xmlChar *)"application/x-lzma")) {
cli_dbgmsg("cli_scanxar: encoding = application/x-lzma.\n");
*encoding = CL_TYPE_7Z;
} else if (xmlStrEqual(style, (const xmlChar *)"application/x-xz")) {
cli_dbgmsg("cli_scanxar: encoding = application/x-xz.\n");
*encoding = CL_TYPE_XZ;
} else {
cli_dbgmsg("cli_scaxar: unknown style value=%s for encoding element\n", style);
*encoding = CL_TYPE_ANY;
}
if (style != NULL)
xmlFree(style);
} else if (indata && xmlStrEqual(name, (const xmlChar *)"data") &&
xmlTextReaderNodeType(reader) == XML_READER_TYPE_END_ELEMENT) {
break;
} else if (inea && xmlStrEqual(name, (const xmlChar *)"ea") &&
xmlTextReaderNodeType(reader) == XML_READER_TYPE_END_ELEMENT) {
break;
}
} else {
if (xmlTextReaderNodeType(reader) == XML_READER_TYPE_ELEMENT) {
if (xmlStrEqual(name, (const xmlChar *)"data")) {
cli_dbgmsg("cli_scanxar: xmlTextReaderRead read <data>\n");
indata = 1;
} else if (xmlStrEqual(name, (const xmlChar *)"ea")) {
cli_dbgmsg("cli_scanxar: xmlTextReaderRead read <ea>\n");
inea = 1;
}
} else if ((xmlTextReaderNodeType(reader) == XML_READER_TYPE_END_ELEMENT) &&
xmlStrEqual(name, (const xmlChar *)"xar")) {
cli_dbgmsg("cli_scanxar: finished parsing xar TOC.\n");
break;
}
}
rc = xmlTextReaderRead(reader);
}
if (gotoffset && gotlength && gotsize) {
rc = CL_SUCCESS;
}
else if (0 == gotoffset + gotlength + gotsize)
rc = CL_BREAK;
else
rc = CL_EFORMAT;
return rc;
}
/*
xar_process_subdocument - check TOC for xml subdocument. If found, extract and
scan in memory.
Parameters:
reader - xmlTextReaderPtr
ctx - pointer to cli_ctx
Returns:
CL_SUCCESS - subdoc found and clean scan (or virus found and SCAN_ALL), or no subdocument
other - error return code from cli_mem_scandesc()
*/
static int xar_scan_subdocuments(xmlTextReaderPtr reader, cli_ctx *ctx)
{
int rc = CL_SUCCESS, subdoc_len, fd;
xmlChar * subdoc;
const xmlChar *name;
char * tmpname;
while (xmlTextReaderRead(reader) == 1) {
name = xmlTextReaderConstLocalName(reader);
if (name == NULL) {
cli_dbgmsg("cli_scanxar: xmlTextReaderConstLocalName() no name.\n");
rc = CL_EFORMAT;
break;
}
if (xmlStrEqual(name, (const xmlChar *)"toc") &&
xmlTextReaderNodeType(reader) == XML_READER_TYPE_ELEMENT)
return CL_SUCCESS;
if (xmlStrEqual(name, (const xmlChar *)"subdoc") &&
xmlTextReaderNodeType(reader) == XML_READER_TYPE_ELEMENT) {
subdoc = xmlTextReaderReadInnerXml(reader);
if (subdoc == NULL) {
cli_dbgmsg("cli_scanxar: no content in subdoc element.\n");
xmlTextReaderNext(reader);
continue;
}
subdoc_len = xmlStrlen(subdoc);
cli_dbgmsg("cli_scanxar: in-memory scan of xml subdocument, len %i.\n", subdoc_len);
rc = cli_mem_scandesc(subdoc, subdoc_len, ctx);
if (rc == CL_VIRUS && SCAN_ALL)
rc = CL_SUCCESS;
/* make a file to leave if --leave-temps in effect */
if(ctx->engine->keeptmp) {
if ((rc = cli_gentempfd(ctx->engine->tmpdir, &tmpname, &fd)) != CL_SUCCESS) {
cli_dbgmsg("cli_scanxar: Can't create temporary file for subdocument.\n");
} else {
cli_dbgmsg("cli_scanxar: Writing subdoc to temp file %s.\n", tmpname);
if (cli_writen(fd, subdoc, subdoc_len) < 0) {
cli_dbgmsg("cli_scanxar: cli_writen error writing subdoc temporary file.\n");
rc = CL_EWRITE;
}
rc = xar_cleanup_temp_file(ctx, fd, tmpname);
}
}
xmlFree(subdoc);
if (rc != CL_SUCCESS)
return rc;
xmlTextReaderNext(reader);
}
}
return rc;
}
static void * xar_hash_init(int hash, void **sc, void **mc)
{
if (!sc && !mc)
return NULL;
switch (hash) {
case XAR_CKSUM_SHA1:
*sc = cl_hash_init("sha1");
if (!(*sc)) {
return NULL;
}
return *sc;
case XAR_CKSUM_MD5:
*mc = cl_hash_init("md5");
if (!(*mc)) {
return NULL;
}
return *mc;
case XAR_CKSUM_OTHER:
case XAR_CKSUM_NONE:
default:
return NULL;
}
}
static void xar_hash_update(void * hash_ctx, void * data, unsigned long size, int hash)
{
if (!hash_ctx || !data || !size)
return;
switch (hash) {
case XAR_CKSUM_NONE:
case XAR_CKSUM_OTHER:
return;
}
cl_update_hash(hash_ctx, data, size);
}
static void xar_hash_final(void * hash_ctx, void * result, int hash)
{
if (!hash_ctx || !result)
return;
switch (hash) {
case XAR_CKSUM_OTHER:
case XAR_CKSUM_NONE:
return;
}
cl_finish_hash(hash_ctx, result);
}
static int xar_hash_check(int hash, const void * result, const void * expected)
{
int len;
if (!result || !expected)
return 1;
switch (hash) {
case XAR_CKSUM_SHA1:
len = CLI_HASHLEN_SHA1;
break;
case XAR_CKSUM_MD5:
len = CLI_HASHLEN_MD5;
break;
case XAR_CKSUM_OTHER:
case XAR_CKSUM_NONE:
default:
return 1;
}
return memcmp(result, expected, len);
}
#endif
/*
cli_scanxar - scan an xar archive.
Parameters:
ctx - pointer to cli_ctx.
returns - CL_SUCCESS or CL_ error code.
*/
int cli_scanxar(cli_ctx *ctx)
{
int rc = CL_SUCCESS;
unsigned int cksum_fails = 0;
unsigned int extract_errors = 0;
#if HAVE_LIBXML2
int fd = -1;
struct xar_header hdr;
fmap_t *map = *ctx->fmap;
size_t length, offset, size, at;
int encoding;
z_stream strm;
char *toc, *tmpname;
xmlTextReaderPtr reader = NULL;
int a_hash, e_hash;
unsigned char *a_cksum = NULL, *e_cksum = NULL;
void *a_hash_ctx = NULL, *e_hash_ctx = NULL;
char result[SHA1_HASH_SIZE];
memset(&strm, 0x00, sizeof(z_stream));
/* retrieve xar header */
if (fmap_readn(*ctx->fmap, &hdr, 0, sizeof(hdr)) != sizeof(hdr)) {
cli_dbgmsg("cli_scanxar: Invalid header, too short.\n");
return CL_EFORMAT;
}
hdr.magic = be32_to_host(hdr.magic);
if (hdr.magic == XAR_HEADER_MAGIC) {
cli_dbgmsg("cli_scanxar: Matched magic\n");
}
else {
cli_dbgmsg("cli_scanxar: Invalid magic\n");
return CL_EFORMAT;
}
hdr.size = be16_to_host(hdr.size);
hdr.version = be16_to_host(hdr.version);
hdr.toc_length_compressed = be64_to_host(hdr.toc_length_compressed);
hdr.toc_length_decompressed = be64_to_host(hdr.toc_length_decompressed);
hdr.chksum_alg = be32_to_host(hdr.chksum_alg);
/* cli_dbgmsg("hdr.magic %x\n", hdr.magic); */
/* cli_dbgmsg("hdr.size %i\n", hdr.size); */
/* cli_dbgmsg("hdr.version %i\n", hdr.version); */
/* cli_dbgmsg("hdr.toc_length_compressed %lu\n", hdr.toc_length_compressed); */
/* cli_dbgmsg("hdr.toc_length_decompressed %lu\n", hdr.toc_length_decompressed); */
/* cli_dbgmsg("hdr.chksum_alg %i\n", hdr.chksum_alg); */
/* Uncompress TOC */
strm.next_in = (unsigned char *)fmap_need_off_once(*ctx->fmap, hdr.size, hdr.toc_length_compressed);
if (strm.next_in == NULL) {
cli_dbgmsg("cli_scanxar: fmap_need_off_once fails on TOC.\n");
return CL_EREAD;
}
strm.avail_in = hdr.toc_length_compressed;
toc = cli_malloc(hdr.toc_length_decompressed+1);
if (toc == NULL) {
cli_dbgmsg("cli_scanxar: cli_malloc fails on TOC decompress buffer.\n");
return CL_EMEM;
}
toc[hdr.toc_length_decompressed] = '\0';
strm.avail_out = hdr.toc_length_decompressed;
strm.next_out = (unsigned char *)toc;
rc = inflateInit(&strm);
if (rc != Z_OK) {
cli_dbgmsg("cli_scanxar:inflateInit error %i \n", rc);
rc = CL_EFORMAT;
goto exit_toc;
}
rc = inflate(&strm, Z_SYNC_FLUSH);
if (rc != Z_OK && rc != Z_STREAM_END) {
cli_dbgmsg("cli_scanxar:inflate error %i \n", rc);
rc = CL_EFORMAT;
goto exit_toc;
}
rc = inflateEnd(&strm);
if (rc != Z_OK) {
cli_dbgmsg("cli_scanxar:inflateEnd error %i \n", rc);
rc = CL_EFORMAT;
goto exit_toc;
}
if (hdr.toc_length_decompressed != strm.total_out) {
cli_dbgmsg("TOC decompress length %" PRIu64 " does not match amount decompressed %lu\n",
hdr.toc_length_decompressed, strm.total_out);
toc[strm.total_out] = '\0';
hdr.toc_length_decompressed = strm.total_out;
}
/* cli_dbgmsg("cli_scanxar: TOC xml:\n%s\n", toc); */
/* printf("cli_scanxar: TOC xml:\n%s\n", toc); */
/* cli_dbgmsg("cli_scanxar: TOC end:\n"); */
/* printf("cli_scanxar: TOC end:\n"); */
/* scan the xml */
cli_dbgmsg("cli_scanxar: scanning xar TOC xml in memory.\n");
rc = cli_mem_scandesc(toc, hdr.toc_length_decompressed, ctx);
if (rc != CL_SUCCESS) {
if (rc != CL_VIRUS || !SCAN_ALL)
goto exit_toc;
}
/* make a file to leave if --leave-temps in effect */
if(ctx->engine->keeptmp) {
if ((rc = cli_gentempfd(ctx->engine->tmpdir, &tmpname, &fd)) != CL_SUCCESS) {
cli_dbgmsg("cli_scanxar: Can't create temporary file for TOC.\n");
goto exit_toc;
}
if (cli_writen(fd, toc, hdr.toc_length_decompressed) < 0) {
cli_dbgmsg("cli_scanxar: cli_writen error writing TOC.\n");
rc = CL_EWRITE;
xar_cleanup_temp_file(ctx, fd, tmpname);
goto exit_toc;
}
rc = xar_cleanup_temp_file(ctx, fd, tmpname);
if (rc != CL_SUCCESS)
goto exit_toc;
}
reader = xmlReaderForMemory(toc, hdr.toc_length_decompressed, "noname.xml", NULL, CLAMAV_MIN_XMLREADER_FLAGS);
if (reader == NULL) {
cli_dbgmsg("cli_scanxar: xmlReaderForMemory error for TOC\n");
goto exit_toc;
}
rc = xar_scan_subdocuments(reader, ctx);
if (rc != CL_SUCCESS) {
cli_dbgmsg("xar_scan_subdocuments returns %i.\n", rc);
goto exit_reader;
}
/* Walk the TOC XML and extract files */
fd = -1;
tmpname = NULL;
while (CL_SUCCESS == (rc = xar_get_toc_data_values(reader, &length, &offset, &size, &encoding,
&a_cksum, &a_hash, &e_cksum, &e_hash))) {
int do_extract_cksum = 1;
unsigned char * blockp;
void *a_sc, *e_sc;
void *a_mc, *e_mc;
char * expected;
/* clean up temp file from previous loop iteration */
if (fd > -1 && tmpname) {
rc = xar_cleanup_temp_file(ctx, fd, tmpname);
if (rc != CL_SUCCESS)
goto exit_reader;
}
at = offset + hdr.toc_length_compressed + hdr.size;
if ((rc = cli_gentempfd(ctx->engine->tmpdir, &tmpname, &fd)) != CL_SUCCESS) {
cli_dbgmsg("cli_scanxar: Can't generate temporary file.\n");
goto exit_reader;
}
cli_dbgmsg("cli_scanxar: decompress into temp file:\n%s, size %zu,\n"
"from xar heap offset %zu length %zu\n",
tmpname, size, offset, length);
a_hash_ctx = xar_hash_init(a_hash, &a_sc, &a_mc);
e_hash_ctx = xar_hash_init(e_hash, &e_sc, &e_mc);
switch (encoding) {
case CL_TYPE_GZ:
/* inflate gzip directly because file segments do not contain magic */
memset(&strm, 0, sizeof(strm));
if ((rc = inflateInit(&strm)) != Z_OK) {
cli_dbgmsg("cli_scanxar: InflateInit failed: %d\n", rc);
rc = CL_EFORMAT;
extract_errors++;
break;
}
while ((size_t)at < map->len && (unsigned long)at < offset+hdr.toc_length_compressed+hdr.size+length) {
unsigned long avail_in;
void * next_in;
unsigned int bytes = MIN(map->len - at, map->pgsz);
bytes = MIN(length, bytes);
if(!(strm.next_in = next_in = (void*)fmap_need_off_once(map, at, bytes))) {
cli_dbgmsg("cli_scanxar: Can't read %u bytes @ %lu.\n", bytes, (long unsigned)at);
inflateEnd(&strm);
rc = CL_EREAD;
goto exit_tmpfile;
}
at += bytes;
strm.avail_in = avail_in = bytes;
do {
int inf, outsize = 0;
unsigned char buff[FILEBUFF];
strm.avail_out = sizeof(buff);
strm.next_out = buff;
inf = inflate(&strm, Z_SYNC_FLUSH);
if (inf != Z_OK && inf != Z_STREAM_END && inf != Z_BUF_ERROR) {
cli_dbgmsg("cli_scanxar: inflate error %i %s.\n", inf, strm.msg?strm.msg:"");
rc = CL_EFORMAT;
extract_errors++;
break;
}
bytes = sizeof(buff) - strm.avail_out;
if (e_hash_ctx != NULL)
xar_hash_update(e_hash_ctx, buff, bytes, e_hash);
if (cli_writen(fd, buff, bytes) < 0) {
cli_dbgmsg("cli_scanxar: cli_writen error file %s.\n", tmpname);
inflateEnd(&strm);
rc = CL_EWRITE;
goto exit_tmpfile;
}
outsize += sizeof(buff) - strm.avail_out;
if (cli_checklimits("cli_scanxar", ctx, outsize, 0, 0) != CL_CLEAN) {
break;
}
if (inf == Z_STREAM_END) {
break;
}
} while (strm.avail_out == 0);
if (rc != CL_SUCCESS)
break;
avail_in -= strm.avail_in;
if (a_hash_ctx != NULL)
xar_hash_update(a_hash_ctx, next_in, avail_in, a_hash);
}
inflateEnd(&strm);
break;
case CL_TYPE_7Z:
#define CLI_LZMA_OBUF_SIZE 1024*1024
#define CLI_LZMA_HDR_SIZE LZMA_PROPS_SIZE+8
#define CLI_LZMA_IBUF_SIZE CLI_LZMA_OBUF_SIZE>>2 /* estimated compression ratio 25% */
{
struct CLI_LZMA lz;
unsigned long in_remaining = MIN(length, map->len - at);
unsigned long out_size = 0;
unsigned char * buff = __lzma_wrap_alloc(NULL, CLI_LZMA_OBUF_SIZE);
int lret;
if (length > in_remaining)
length = in_remaining;
memset(&lz, 0, sizeof(lz));
if (buff == NULL) {
cli_dbgmsg("cli_scanxar: memory request for lzma decompression buffer fails.\n");
rc = CL_EMEM;
goto exit_tmpfile;
}
blockp = (void*)fmap_need_off_once(map, at, CLI_LZMA_HDR_SIZE);
if (blockp == NULL) {
char errbuff[128];
cli_strerror(errno, errbuff, sizeof(errbuff));
cli_dbgmsg("cli_scanxar: Can't read %i bytes @ %li, errno:%s.\n",
CLI_LZMA_HDR_SIZE, at, errbuff);
rc = CL_EREAD;
__lzma_wrap_free(NULL, buff);
goto exit_tmpfile;
}
lz.next_in = blockp;
lz.avail_in = CLI_LZMA_HDR_SIZE;
if (a_hash_ctx != NULL)
xar_hash_update(a_hash_ctx, blockp, CLI_LZMA_HDR_SIZE, a_hash);
lret = cli_LzmaInit(&lz, 0);
if (lret != LZMA_RESULT_OK) {
cli_dbgmsg("cli_scanxar: cli_LzmaInit() fails: %i.\n", lret);
rc = CL_EFORMAT;
__lzma_wrap_free(NULL, buff);
extract_errors++;
break;
}
at += CLI_LZMA_HDR_SIZE;
in_remaining -= CLI_LZMA_HDR_SIZE;
while ((size_t)at < map->len && (unsigned long)at < offset+hdr.toc_length_compressed+hdr.size+length) {
SizeT avail_in;
SizeT avail_out;
void * next_in;
unsigned long in_consumed;
lz.next_out = buff;
lz.avail_out = CLI_LZMA_OBUF_SIZE;
lz.avail_in = avail_in = MIN(CLI_LZMA_IBUF_SIZE, in_remaining);
lz.next_in = next_in = (void*)fmap_need_off_once(map, at, lz.avail_in);
if (lz.next_in == NULL) {
char errbuff[128];
cli_strerror(errno, errbuff, sizeof(errbuff));
cli_dbgmsg("cli_scanxar: Can't read %li bytes @ %li, errno: %s.\n",
lz.avail_in, at, errbuff);
rc = CL_EREAD;
__lzma_wrap_free(NULL, buff);
cli_LzmaShutdown(&lz);
goto exit_tmpfile;
}
lret = cli_LzmaDecode(&lz);
if (lret != LZMA_RESULT_OK && lret != LZMA_STREAM_END) {
cli_dbgmsg("cli_scanxar: cli_LzmaDecode() fails: %i.\n", lret);
rc = CL_EFORMAT;
extract_errors++;
break;
}
in_consumed = avail_in - lz.avail_in;
in_remaining -= in_consumed;
at += in_consumed;
avail_out = CLI_LZMA_OBUF_SIZE - lz.avail_out;
if (avail_out == 0)
cli_dbgmsg("cli_scanxar: cli_LzmaDecode() produces no output for "
"avail_in %llu, avail_out %llu.\n",
(long long unsigned)avail_in, (long long unsigned)avail_out);
if (a_hash_ctx != NULL)
xar_hash_update(a_hash_ctx, next_in, in_consumed, a_hash);
if (e_hash_ctx != NULL)
xar_hash_update(e_hash_ctx, buff, avail_out, e_hash);
/* Write a decompressed block. */
/* cli_dbgmsg("Writing %li bytes to LZMA decompress temp file, " */
/* "consumed %li of %li available compressed bytes.\n", */
/* avail_out, in_consumed, avail_in); */
if (cli_writen(fd, buff, avail_out) < 0) {
cli_dbgmsg("cli_scanxar: cli_writen error writing lzma temp file for %llu bytes.\n",
(long long unsigned)avail_out);
__lzma_wrap_free(NULL, buff);
cli_LzmaShutdown(&lz);
rc = CL_EWRITE;
goto exit_tmpfile;
}
/* Check file size limitation. */
out_size += avail_out;
if (cli_checklimits("cli_scanxar", ctx, out_size, 0, 0) != CL_CLEAN) {
break;
}
if (lret == LZMA_STREAM_END)
break;
}
cli_LzmaShutdown(&lz);
__lzma_wrap_free(NULL, buff);
}
break;
case CL_TYPE_ANY:
default:
case CL_TYPE_BZ:
case CL_TYPE_XZ:
/* for uncompressed, bzip2, xz, and unknown, just pull the file, cli_magic_scandesc does the rest */
do_extract_cksum = 0;
{
size_t writelen = MIN(map->len - at, length);
if (ctx->engine->maxfilesize)
writelen = MIN((size_t)(ctx->engine->maxfilesize), writelen);
if (!(blockp = (void*)fmap_need_off_once(map, at, writelen))) {
char errbuff[128];
cli_strerror(errno, errbuff, sizeof(errbuff));
cli_dbgmsg("cli_scanxar: Can't read %zu bytes @ %zu, errno:%s.\n",
writelen, at, errbuff);
rc = CL_EREAD;
goto exit_tmpfile;
}
if (a_hash_ctx != NULL)
xar_hash_update(a_hash_ctx, blockp, writelen, a_hash);
if (cli_writen(fd, blockp, writelen) < 0) {
cli_dbgmsg("cli_scanxar: cli_writen error %zu bytes @ %li.\n", writelen, at);
rc = CL_EWRITE;
goto exit_tmpfile;
}
/*break;*/
}
} /* end of switch */
if (rc == CL_SUCCESS) {
if (a_hash_ctx != NULL) {
xar_hash_final(a_hash_ctx, result, a_hash);
a_hash_ctx = NULL;
} else {
cli_dbgmsg("cli_scanxar: archived-checksum missing.\n");
cksum_fails++;
}
if (a_cksum != NULL) {
expected = cli_hex2str((char *)a_cksum);
if (xar_hash_check(a_hash, result, expected) != 0) {
cli_dbgmsg("cli_scanxar: archived-checksum mismatch.\n");
cksum_fails++;
} else {
cli_dbgmsg("cli_scanxar: archived-checksum matched.\n");
}
free(expected);
}
if (e_hash_ctx != NULL) {
xar_hash_final(e_hash_ctx, result, e_hash);
e_hash_ctx = NULL;
} else {
cli_dbgmsg("cli_scanxar: extracted-checksum(unarchived-checksum) missing.\n");
cksum_fails++;
}
if (e_cksum != NULL) {
if (do_extract_cksum) {
expected = cli_hex2str((char *)e_cksum);
if (xar_hash_check(e_hash, result, expected) != 0) {
cli_dbgmsg("cli_scanxar: extracted-checksum mismatch.\n");
cksum_fails++;
} else {
cli_dbgmsg("cli_scanxar: extracted-checksum matched.\n");
}
free(expected);
}
}
rc = cli_magic_scandesc(fd, ctx);
if (rc != CL_SUCCESS) {
if (rc == CL_VIRUS) {
cli_dbgmsg("cli_scanxar: Infected with %s\n", cli_get_last_virus(ctx));
if (!SCAN_ALL)
goto exit_tmpfile;
} else if (rc != CL_BREAK) {
cli_dbgmsg("cli_scanxar: cli_magic_scandesc error %i\n", rc);
goto exit_tmpfile;
}
}
}
if (a_cksum != NULL) {
xmlFree(a_cksum);
a_cksum = NULL;
}
if (e_cksum != NULL) {
xmlFree(e_cksum);
e_cksum = NULL;
}
}
exit_tmpfile:
xar_cleanup_temp_file(ctx, fd, tmpname);
if (a_hash_ctx != NULL)
xar_hash_final(a_hash_ctx, result, a_hash);
if (e_hash_ctx != NULL)
xar_hash_final(e_hash_ctx, result, e_hash);
exit_reader:
if (a_cksum != NULL)
xmlFree(a_cksum);
if (e_cksum != NULL)
xmlFree(e_cksum);
xmlTextReaderClose(reader);
xmlFreeTextReader(reader);
exit_toc:
free(toc);
if (rc == CL_BREAK)
rc = CL_SUCCESS;
#else
cli_dbgmsg("cli_scanxar: can't scan xar files, need libxml2.\n");
#endif
if (cksum_fails + extract_errors != 0) {
cli_dbgmsg("cli_scanxar: %u checksum errors and %u extraction errors.\n",
cksum_fails, extract_errors);
}
return rc;
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/good_17_0 |
crossvul-cpp_data_bad_2925_0 | /*
* Driver for IMS Passenger Control Unit Devices
*
* Copyright (C) 2013 The IMS Company
*
* 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/completion.h>
#include <linux/device.h>
#include <linux/firmware.h>
#include <linux/ihex.h>
#include <linux/input.h>
#include <linux/kernel.h>
#include <linux/leds.h>
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/types.h>
#include <linux/usb/input.h>
#include <linux/usb/cdc.h>
#include <asm/unaligned.h>
#define IMS_PCU_KEYMAP_LEN 32
struct ims_pcu_buttons {
struct input_dev *input;
char name[32];
char phys[32];
unsigned short keymap[IMS_PCU_KEYMAP_LEN];
};
struct ims_pcu_gamepad {
struct input_dev *input;
char name[32];
char phys[32];
};
struct ims_pcu_backlight {
struct led_classdev cdev;
struct work_struct work;
enum led_brightness desired_brightness;
char name[32];
};
#define IMS_PCU_PART_NUMBER_LEN 15
#define IMS_PCU_SERIAL_NUMBER_LEN 8
#define IMS_PCU_DOM_LEN 8
#define IMS_PCU_FW_VERSION_LEN (9 + 1)
#define IMS_PCU_BL_VERSION_LEN (9 + 1)
#define IMS_PCU_BL_RESET_REASON_LEN (2 + 1)
#define IMS_PCU_PCU_B_DEVICE_ID 5
#define IMS_PCU_BUF_SIZE 128
struct ims_pcu {
struct usb_device *udev;
struct device *dev; /* control interface's device, used for logging */
unsigned int device_no;
bool bootloader_mode;
char part_number[IMS_PCU_PART_NUMBER_LEN];
char serial_number[IMS_PCU_SERIAL_NUMBER_LEN];
char date_of_manufacturing[IMS_PCU_DOM_LEN];
char fw_version[IMS_PCU_FW_VERSION_LEN];
char bl_version[IMS_PCU_BL_VERSION_LEN];
char reset_reason[IMS_PCU_BL_RESET_REASON_LEN];
int update_firmware_status;
u8 device_id;
u8 ofn_reg_addr;
struct usb_interface *ctrl_intf;
struct usb_endpoint_descriptor *ep_ctrl;
struct urb *urb_ctrl;
u8 *urb_ctrl_buf;
dma_addr_t ctrl_dma;
size_t max_ctrl_size;
struct usb_interface *data_intf;
struct usb_endpoint_descriptor *ep_in;
struct urb *urb_in;
u8 *urb_in_buf;
dma_addr_t read_dma;
size_t max_in_size;
struct usb_endpoint_descriptor *ep_out;
u8 *urb_out_buf;
size_t max_out_size;
u8 read_buf[IMS_PCU_BUF_SIZE];
u8 read_pos;
u8 check_sum;
bool have_stx;
bool have_dle;
u8 cmd_buf[IMS_PCU_BUF_SIZE];
u8 ack_id;
u8 expected_response;
u8 cmd_buf_len;
struct completion cmd_done;
struct mutex cmd_mutex;
u32 fw_start_addr;
u32 fw_end_addr;
struct completion async_firmware_done;
struct ims_pcu_buttons buttons;
struct ims_pcu_gamepad *gamepad;
struct ims_pcu_backlight backlight;
bool setup_complete; /* Input and LED devices have been created */
};
/*********************************************************************
* Buttons Input device support *
*********************************************************************/
static const unsigned short ims_pcu_keymap_1[] = {
[1] = KEY_ATTENDANT_OFF,
[2] = KEY_ATTENDANT_ON,
[3] = KEY_LIGHTS_TOGGLE,
[4] = KEY_VOLUMEUP,
[5] = KEY_VOLUMEDOWN,
[6] = KEY_INFO,
};
static const unsigned short ims_pcu_keymap_2[] = {
[4] = KEY_VOLUMEUP,
[5] = KEY_VOLUMEDOWN,
[6] = KEY_INFO,
};
static const unsigned short ims_pcu_keymap_3[] = {
[1] = KEY_HOMEPAGE,
[2] = KEY_ATTENDANT_TOGGLE,
[3] = KEY_LIGHTS_TOGGLE,
[4] = KEY_VOLUMEUP,
[5] = KEY_VOLUMEDOWN,
[6] = KEY_DISPLAYTOGGLE,
[18] = KEY_PLAYPAUSE,
};
static const unsigned short ims_pcu_keymap_4[] = {
[1] = KEY_ATTENDANT_OFF,
[2] = KEY_ATTENDANT_ON,
[3] = KEY_LIGHTS_TOGGLE,
[4] = KEY_VOLUMEUP,
[5] = KEY_VOLUMEDOWN,
[6] = KEY_INFO,
[18] = KEY_PLAYPAUSE,
};
static const unsigned short ims_pcu_keymap_5[] = {
[1] = KEY_ATTENDANT_OFF,
[2] = KEY_ATTENDANT_ON,
[3] = KEY_LIGHTS_TOGGLE,
};
struct ims_pcu_device_info {
const unsigned short *keymap;
size_t keymap_len;
bool has_gamepad;
};
#define IMS_PCU_DEVINFO(_n, _gamepad) \
[_n] = { \
.keymap = ims_pcu_keymap_##_n, \
.keymap_len = ARRAY_SIZE(ims_pcu_keymap_##_n), \
.has_gamepad = _gamepad, \
}
static const struct ims_pcu_device_info ims_pcu_device_info[] = {
IMS_PCU_DEVINFO(1, true),
IMS_PCU_DEVINFO(2, true),
IMS_PCU_DEVINFO(3, true),
IMS_PCU_DEVINFO(4, true),
IMS_PCU_DEVINFO(5, false),
};
static void ims_pcu_buttons_report(struct ims_pcu *pcu, u32 data)
{
struct ims_pcu_buttons *buttons = &pcu->buttons;
struct input_dev *input = buttons->input;
int i;
for (i = 0; i < 32; i++) {
unsigned short keycode = buttons->keymap[i];
if (keycode != KEY_RESERVED)
input_report_key(input, keycode, data & (1UL << i));
}
input_sync(input);
}
static int ims_pcu_setup_buttons(struct ims_pcu *pcu,
const unsigned short *keymap,
size_t keymap_len)
{
struct ims_pcu_buttons *buttons = &pcu->buttons;
struct input_dev *input;
int i;
int error;
input = input_allocate_device();
if (!input) {
dev_err(pcu->dev,
"Not enough memory for input input device\n");
return -ENOMEM;
}
snprintf(buttons->name, sizeof(buttons->name),
"IMS PCU#%d Button Interface", pcu->device_no);
usb_make_path(pcu->udev, buttons->phys, sizeof(buttons->phys));
strlcat(buttons->phys, "/input0", sizeof(buttons->phys));
memcpy(buttons->keymap, keymap, sizeof(*keymap) * keymap_len);
input->name = buttons->name;
input->phys = buttons->phys;
usb_to_input_id(pcu->udev, &input->id);
input->dev.parent = &pcu->ctrl_intf->dev;
input->keycode = buttons->keymap;
input->keycodemax = ARRAY_SIZE(buttons->keymap);
input->keycodesize = sizeof(buttons->keymap[0]);
__set_bit(EV_KEY, input->evbit);
for (i = 0; i < IMS_PCU_KEYMAP_LEN; i++)
__set_bit(buttons->keymap[i], input->keybit);
__clear_bit(KEY_RESERVED, input->keybit);
error = input_register_device(input);
if (error) {
dev_err(pcu->dev,
"Failed to register buttons input device: %d\n",
error);
input_free_device(input);
return error;
}
buttons->input = input;
return 0;
}
static void ims_pcu_destroy_buttons(struct ims_pcu *pcu)
{
struct ims_pcu_buttons *buttons = &pcu->buttons;
input_unregister_device(buttons->input);
}
/*********************************************************************
* Gamepad Input device support *
*********************************************************************/
static void ims_pcu_gamepad_report(struct ims_pcu *pcu, u32 data)
{
struct ims_pcu_gamepad *gamepad = pcu->gamepad;
struct input_dev *input = gamepad->input;
int x, y;
x = !!(data & (1 << 14)) - !!(data & (1 << 13));
y = !!(data & (1 << 12)) - !!(data & (1 << 11));
input_report_abs(input, ABS_X, x);
input_report_abs(input, ABS_Y, y);
input_report_key(input, BTN_A, data & (1 << 7));
input_report_key(input, BTN_B, data & (1 << 8));
input_report_key(input, BTN_X, data & (1 << 9));
input_report_key(input, BTN_Y, data & (1 << 10));
input_report_key(input, BTN_START, data & (1 << 15));
input_report_key(input, BTN_SELECT, data & (1 << 16));
input_sync(input);
}
static int ims_pcu_setup_gamepad(struct ims_pcu *pcu)
{
struct ims_pcu_gamepad *gamepad;
struct input_dev *input;
int error;
gamepad = kzalloc(sizeof(struct ims_pcu_gamepad), GFP_KERNEL);
input = input_allocate_device();
if (!gamepad || !input) {
dev_err(pcu->dev,
"Not enough memory for gamepad device\n");
error = -ENOMEM;
goto err_free_mem;
}
gamepad->input = input;
snprintf(gamepad->name, sizeof(gamepad->name),
"IMS PCU#%d Gamepad Interface", pcu->device_no);
usb_make_path(pcu->udev, gamepad->phys, sizeof(gamepad->phys));
strlcat(gamepad->phys, "/input1", sizeof(gamepad->phys));
input->name = gamepad->name;
input->phys = gamepad->phys;
usb_to_input_id(pcu->udev, &input->id);
input->dev.parent = &pcu->ctrl_intf->dev;
__set_bit(EV_KEY, input->evbit);
__set_bit(BTN_A, input->keybit);
__set_bit(BTN_B, input->keybit);
__set_bit(BTN_X, input->keybit);
__set_bit(BTN_Y, input->keybit);
__set_bit(BTN_START, input->keybit);
__set_bit(BTN_SELECT, input->keybit);
__set_bit(EV_ABS, input->evbit);
input_set_abs_params(input, ABS_X, -1, 1, 0, 0);
input_set_abs_params(input, ABS_Y, -1, 1, 0, 0);
error = input_register_device(input);
if (error) {
dev_err(pcu->dev,
"Failed to register gamepad input device: %d\n",
error);
goto err_free_mem;
}
pcu->gamepad = gamepad;
return 0;
err_free_mem:
input_free_device(input);
kfree(gamepad);
return -ENOMEM;
}
static void ims_pcu_destroy_gamepad(struct ims_pcu *pcu)
{
struct ims_pcu_gamepad *gamepad = pcu->gamepad;
input_unregister_device(gamepad->input);
kfree(gamepad);
}
/*********************************************************************
* PCU Communication protocol handling *
*********************************************************************/
#define IMS_PCU_PROTOCOL_STX 0x02
#define IMS_PCU_PROTOCOL_ETX 0x03
#define IMS_PCU_PROTOCOL_DLE 0x10
/* PCU commands */
#define IMS_PCU_CMD_STATUS 0xa0
#define IMS_PCU_CMD_PCU_RESET 0xa1
#define IMS_PCU_CMD_RESET_REASON 0xa2
#define IMS_PCU_CMD_SEND_BUTTONS 0xa3
#define IMS_PCU_CMD_JUMP_TO_BTLDR 0xa4
#define IMS_PCU_CMD_GET_INFO 0xa5
#define IMS_PCU_CMD_SET_BRIGHTNESS 0xa6
#define IMS_PCU_CMD_EEPROM 0xa7
#define IMS_PCU_CMD_GET_FW_VERSION 0xa8
#define IMS_PCU_CMD_GET_BL_VERSION 0xa9
#define IMS_PCU_CMD_SET_INFO 0xab
#define IMS_PCU_CMD_GET_BRIGHTNESS 0xac
#define IMS_PCU_CMD_GET_DEVICE_ID 0xae
#define IMS_PCU_CMD_SPECIAL_INFO 0xb0
#define IMS_PCU_CMD_BOOTLOADER 0xb1 /* Pass data to bootloader */
#define IMS_PCU_CMD_OFN_SET_CONFIG 0xb3
#define IMS_PCU_CMD_OFN_GET_CONFIG 0xb4
/* PCU responses */
#define IMS_PCU_RSP_STATUS 0xc0
#define IMS_PCU_RSP_PCU_RESET 0 /* Originally 0xc1 */
#define IMS_PCU_RSP_RESET_REASON 0xc2
#define IMS_PCU_RSP_SEND_BUTTONS 0xc3
#define IMS_PCU_RSP_JUMP_TO_BTLDR 0 /* Originally 0xc4 */
#define IMS_PCU_RSP_GET_INFO 0xc5
#define IMS_PCU_RSP_SET_BRIGHTNESS 0xc6
#define IMS_PCU_RSP_EEPROM 0xc7
#define IMS_PCU_RSP_GET_FW_VERSION 0xc8
#define IMS_PCU_RSP_GET_BL_VERSION 0xc9
#define IMS_PCU_RSP_SET_INFO 0xcb
#define IMS_PCU_RSP_GET_BRIGHTNESS 0xcc
#define IMS_PCU_RSP_CMD_INVALID 0xcd
#define IMS_PCU_RSP_GET_DEVICE_ID 0xce
#define IMS_PCU_RSP_SPECIAL_INFO 0xd0
#define IMS_PCU_RSP_BOOTLOADER 0xd1 /* Bootloader response */
#define IMS_PCU_RSP_OFN_SET_CONFIG 0xd2
#define IMS_PCU_RSP_OFN_GET_CONFIG 0xd3
#define IMS_PCU_RSP_EVNT_BUTTONS 0xe0 /* Unsolicited, button state */
#define IMS_PCU_GAMEPAD_MASK 0x0001ff80UL /* Bits 7 through 16 */
#define IMS_PCU_MIN_PACKET_LEN 3
#define IMS_PCU_DATA_OFFSET 2
#define IMS_PCU_CMD_WRITE_TIMEOUT 100 /* msec */
#define IMS_PCU_CMD_RESPONSE_TIMEOUT 500 /* msec */
static void ims_pcu_report_events(struct ims_pcu *pcu)
{
u32 data = get_unaligned_be32(&pcu->read_buf[3]);
ims_pcu_buttons_report(pcu, data & ~IMS_PCU_GAMEPAD_MASK);
if (pcu->gamepad)
ims_pcu_gamepad_report(pcu, data);
}
static void ims_pcu_handle_response(struct ims_pcu *pcu)
{
switch (pcu->read_buf[0]) {
case IMS_PCU_RSP_EVNT_BUTTONS:
if (likely(pcu->setup_complete))
ims_pcu_report_events(pcu);
break;
default:
/*
* See if we got command completion.
* If both the sequence and response code match save
* the data and signal completion.
*/
if (pcu->read_buf[0] == pcu->expected_response &&
pcu->read_buf[1] == pcu->ack_id - 1) {
memcpy(pcu->cmd_buf, pcu->read_buf, pcu->read_pos);
pcu->cmd_buf_len = pcu->read_pos;
complete(&pcu->cmd_done);
}
break;
}
}
static void ims_pcu_process_data(struct ims_pcu *pcu, struct urb *urb)
{
int i;
for (i = 0; i < urb->actual_length; i++) {
u8 data = pcu->urb_in_buf[i];
/* Skip everything until we get Start Xmit */
if (!pcu->have_stx && data != IMS_PCU_PROTOCOL_STX)
continue;
if (pcu->have_dle) {
pcu->have_dle = false;
pcu->read_buf[pcu->read_pos++] = data;
pcu->check_sum += data;
continue;
}
switch (data) {
case IMS_PCU_PROTOCOL_STX:
if (pcu->have_stx)
dev_warn(pcu->dev,
"Unexpected STX at byte %d, discarding old data\n",
pcu->read_pos);
pcu->have_stx = true;
pcu->have_dle = false;
pcu->read_pos = 0;
pcu->check_sum = 0;
break;
case IMS_PCU_PROTOCOL_DLE:
pcu->have_dle = true;
break;
case IMS_PCU_PROTOCOL_ETX:
if (pcu->read_pos < IMS_PCU_MIN_PACKET_LEN) {
dev_warn(pcu->dev,
"Short packet received (%d bytes), ignoring\n",
pcu->read_pos);
} else if (pcu->check_sum != 0) {
dev_warn(pcu->dev,
"Invalid checksum in packet (%d bytes), ignoring\n",
pcu->read_pos);
} else {
ims_pcu_handle_response(pcu);
}
pcu->have_stx = false;
pcu->have_dle = false;
pcu->read_pos = 0;
break;
default:
pcu->read_buf[pcu->read_pos++] = data;
pcu->check_sum += data;
break;
}
}
}
static bool ims_pcu_byte_needs_escape(u8 byte)
{
return byte == IMS_PCU_PROTOCOL_STX ||
byte == IMS_PCU_PROTOCOL_ETX ||
byte == IMS_PCU_PROTOCOL_DLE;
}
static int ims_pcu_send_cmd_chunk(struct ims_pcu *pcu,
u8 command, int chunk, int len)
{
int error;
error = usb_bulk_msg(pcu->udev,
usb_sndbulkpipe(pcu->udev,
pcu->ep_out->bEndpointAddress),
pcu->urb_out_buf, len,
NULL, IMS_PCU_CMD_WRITE_TIMEOUT);
if (error < 0) {
dev_dbg(pcu->dev,
"Sending 0x%02x command failed at chunk %d: %d\n",
command, chunk, error);
return error;
}
return 0;
}
static int ims_pcu_send_command(struct ims_pcu *pcu,
u8 command, const u8 *data, int len)
{
int count = 0;
int chunk = 0;
int delta;
int i;
int error;
u8 csum = 0;
u8 ack_id;
pcu->urb_out_buf[count++] = IMS_PCU_PROTOCOL_STX;
/* We know the command need not be escaped */
pcu->urb_out_buf[count++] = command;
csum += command;
ack_id = pcu->ack_id++;
if (ack_id == 0xff)
ack_id = pcu->ack_id++;
if (ims_pcu_byte_needs_escape(ack_id))
pcu->urb_out_buf[count++] = IMS_PCU_PROTOCOL_DLE;
pcu->urb_out_buf[count++] = ack_id;
csum += ack_id;
for (i = 0; i < len; i++) {
delta = ims_pcu_byte_needs_escape(data[i]) ? 2 : 1;
if (count + delta >= pcu->max_out_size) {
error = ims_pcu_send_cmd_chunk(pcu, command,
++chunk, count);
if (error)
return error;
count = 0;
}
if (delta == 2)
pcu->urb_out_buf[count++] = IMS_PCU_PROTOCOL_DLE;
pcu->urb_out_buf[count++] = data[i];
csum += data[i];
}
csum = 1 + ~csum;
delta = ims_pcu_byte_needs_escape(csum) ? 3 : 2;
if (count + delta >= pcu->max_out_size) {
error = ims_pcu_send_cmd_chunk(pcu, command, ++chunk, count);
if (error)
return error;
count = 0;
}
if (delta == 3)
pcu->urb_out_buf[count++] = IMS_PCU_PROTOCOL_DLE;
pcu->urb_out_buf[count++] = csum;
pcu->urb_out_buf[count++] = IMS_PCU_PROTOCOL_ETX;
return ims_pcu_send_cmd_chunk(pcu, command, ++chunk, count);
}
static int __ims_pcu_execute_command(struct ims_pcu *pcu,
u8 command, const void *data, size_t len,
u8 expected_response, int response_time)
{
int error;
pcu->expected_response = expected_response;
init_completion(&pcu->cmd_done);
error = ims_pcu_send_command(pcu, command, data, len);
if (error)
return error;
if (expected_response &&
!wait_for_completion_timeout(&pcu->cmd_done,
msecs_to_jiffies(response_time))) {
dev_dbg(pcu->dev, "Command 0x%02x timed out\n", command);
return -ETIMEDOUT;
}
return 0;
}
#define ims_pcu_execute_command(pcu, code, data, len) \
__ims_pcu_execute_command(pcu, \
IMS_PCU_CMD_##code, data, len, \
IMS_PCU_RSP_##code, \
IMS_PCU_CMD_RESPONSE_TIMEOUT)
#define ims_pcu_execute_query(pcu, code) \
ims_pcu_execute_command(pcu, code, NULL, 0)
/* Bootloader commands */
#define IMS_PCU_BL_CMD_QUERY_DEVICE 0xa1
#define IMS_PCU_BL_CMD_UNLOCK_CONFIG 0xa2
#define IMS_PCU_BL_CMD_ERASE_APP 0xa3
#define IMS_PCU_BL_CMD_PROGRAM_DEVICE 0xa4
#define IMS_PCU_BL_CMD_PROGRAM_COMPLETE 0xa5
#define IMS_PCU_BL_CMD_READ_APP 0xa6
#define IMS_PCU_BL_CMD_RESET_DEVICE 0xa7
#define IMS_PCU_BL_CMD_LAUNCH_APP 0xa8
/* Bootloader commands */
#define IMS_PCU_BL_RSP_QUERY_DEVICE 0xc1
#define IMS_PCU_BL_RSP_UNLOCK_CONFIG 0xc2
#define IMS_PCU_BL_RSP_ERASE_APP 0xc3
#define IMS_PCU_BL_RSP_PROGRAM_DEVICE 0xc4
#define IMS_PCU_BL_RSP_PROGRAM_COMPLETE 0xc5
#define IMS_PCU_BL_RSP_READ_APP 0xc6
#define IMS_PCU_BL_RSP_RESET_DEVICE 0 /* originally 0xa7 */
#define IMS_PCU_BL_RSP_LAUNCH_APP 0 /* originally 0xa8 */
#define IMS_PCU_BL_DATA_OFFSET 3
static int __ims_pcu_execute_bl_command(struct ims_pcu *pcu,
u8 command, const void *data, size_t len,
u8 expected_response, int response_time)
{
int error;
pcu->cmd_buf[0] = command;
if (data)
memcpy(&pcu->cmd_buf[1], data, len);
error = __ims_pcu_execute_command(pcu,
IMS_PCU_CMD_BOOTLOADER, pcu->cmd_buf, len + 1,
expected_response ? IMS_PCU_RSP_BOOTLOADER : 0,
response_time);
if (error) {
dev_err(pcu->dev,
"Failure when sending 0x%02x command to bootloader, error: %d\n",
pcu->cmd_buf[0], error);
return error;
}
if (expected_response && pcu->cmd_buf[2] != expected_response) {
dev_err(pcu->dev,
"Unexpected response from bootloader: 0x%02x, wanted 0x%02x\n",
pcu->cmd_buf[2], expected_response);
return -EINVAL;
}
return 0;
}
#define ims_pcu_execute_bl_command(pcu, code, data, len, timeout) \
__ims_pcu_execute_bl_command(pcu, \
IMS_PCU_BL_CMD_##code, data, len, \
IMS_PCU_BL_RSP_##code, timeout) \
#define IMS_PCU_INFO_PART_OFFSET 2
#define IMS_PCU_INFO_DOM_OFFSET 17
#define IMS_PCU_INFO_SERIAL_OFFSET 25
#define IMS_PCU_SET_INFO_SIZE 31
static int ims_pcu_get_info(struct ims_pcu *pcu)
{
int error;
error = ims_pcu_execute_query(pcu, GET_INFO);
if (error) {
dev_err(pcu->dev,
"GET_INFO command failed, error: %d\n", error);
return error;
}
memcpy(pcu->part_number,
&pcu->cmd_buf[IMS_PCU_INFO_PART_OFFSET],
sizeof(pcu->part_number));
memcpy(pcu->date_of_manufacturing,
&pcu->cmd_buf[IMS_PCU_INFO_DOM_OFFSET],
sizeof(pcu->date_of_manufacturing));
memcpy(pcu->serial_number,
&pcu->cmd_buf[IMS_PCU_INFO_SERIAL_OFFSET],
sizeof(pcu->serial_number));
return 0;
}
static int ims_pcu_set_info(struct ims_pcu *pcu)
{
int error;
memcpy(&pcu->cmd_buf[IMS_PCU_INFO_PART_OFFSET],
pcu->part_number, sizeof(pcu->part_number));
memcpy(&pcu->cmd_buf[IMS_PCU_INFO_DOM_OFFSET],
pcu->date_of_manufacturing, sizeof(pcu->date_of_manufacturing));
memcpy(&pcu->cmd_buf[IMS_PCU_INFO_SERIAL_OFFSET],
pcu->serial_number, sizeof(pcu->serial_number));
error = ims_pcu_execute_command(pcu, SET_INFO,
&pcu->cmd_buf[IMS_PCU_DATA_OFFSET],
IMS_PCU_SET_INFO_SIZE);
if (error) {
dev_err(pcu->dev,
"Failed to update device information, error: %d\n",
error);
return error;
}
return 0;
}
static int ims_pcu_switch_to_bootloader(struct ims_pcu *pcu)
{
int error;
/* Execute jump to the bootoloader */
error = ims_pcu_execute_command(pcu, JUMP_TO_BTLDR, NULL, 0);
if (error) {
dev_err(pcu->dev,
"Failure when sending JUMP TO BOOLTLOADER command, error: %d\n",
error);
return error;
}
return 0;
}
/*********************************************************************
* Firmware Update handling *
*********************************************************************/
#define IMS_PCU_FIRMWARE_NAME "imspcu.fw"
struct ims_pcu_flash_fmt {
__le32 addr;
u8 len;
u8 data[];
};
static unsigned int ims_pcu_count_fw_records(const struct firmware *fw)
{
const struct ihex_binrec *rec = (const struct ihex_binrec *)fw->data;
unsigned int count = 0;
while (rec) {
count++;
rec = ihex_next_binrec(rec);
}
return count;
}
static int ims_pcu_verify_block(struct ims_pcu *pcu,
u32 addr, u8 len, const u8 *data)
{
struct ims_pcu_flash_fmt *fragment;
int error;
fragment = (void *)&pcu->cmd_buf[1];
put_unaligned_le32(addr, &fragment->addr);
fragment->len = len;
error = ims_pcu_execute_bl_command(pcu, READ_APP, NULL, 5,
IMS_PCU_CMD_RESPONSE_TIMEOUT);
if (error) {
dev_err(pcu->dev,
"Failed to retrieve block at 0x%08x, len %d, error: %d\n",
addr, len, error);
return error;
}
fragment = (void *)&pcu->cmd_buf[IMS_PCU_BL_DATA_OFFSET];
if (get_unaligned_le32(&fragment->addr) != addr ||
fragment->len != len) {
dev_err(pcu->dev,
"Wrong block when retrieving 0x%08x (0x%08x), len %d (%d)\n",
addr, get_unaligned_le32(&fragment->addr),
len, fragment->len);
return -EINVAL;
}
if (memcmp(fragment->data, data, len)) {
dev_err(pcu->dev,
"Mismatch in block at 0x%08x, len %d\n",
addr, len);
return -EINVAL;
}
return 0;
}
static int ims_pcu_flash_firmware(struct ims_pcu *pcu,
const struct firmware *fw,
unsigned int n_fw_records)
{
const struct ihex_binrec *rec = (const struct ihex_binrec *)fw->data;
struct ims_pcu_flash_fmt *fragment;
unsigned int count = 0;
u32 addr;
u8 len;
int error;
error = ims_pcu_execute_bl_command(pcu, ERASE_APP, NULL, 0, 2000);
if (error) {
dev_err(pcu->dev,
"Failed to erase application image, error: %d\n",
error);
return error;
}
while (rec) {
/*
* The firmware format is messed up for some reason.
* The address twice that of what is needed for some
* reason and we end up overwriting half of the data
* with the next record.
*/
addr = be32_to_cpu(rec->addr) / 2;
len = be16_to_cpu(rec->len);
fragment = (void *)&pcu->cmd_buf[1];
put_unaligned_le32(addr, &fragment->addr);
fragment->len = len;
memcpy(fragment->data, rec->data, len);
error = ims_pcu_execute_bl_command(pcu, PROGRAM_DEVICE,
NULL, len + 5,
IMS_PCU_CMD_RESPONSE_TIMEOUT);
if (error) {
dev_err(pcu->dev,
"Failed to write block at 0x%08x, len %d, error: %d\n",
addr, len, error);
return error;
}
if (addr >= pcu->fw_start_addr && addr < pcu->fw_end_addr) {
error = ims_pcu_verify_block(pcu, addr, len, rec->data);
if (error)
return error;
}
count++;
pcu->update_firmware_status = (count * 100) / n_fw_records;
rec = ihex_next_binrec(rec);
}
error = ims_pcu_execute_bl_command(pcu, PROGRAM_COMPLETE,
NULL, 0, 2000);
if (error)
dev_err(pcu->dev,
"Failed to send PROGRAM_COMPLETE, error: %d\n",
error);
return 0;
}
static int ims_pcu_handle_firmware_update(struct ims_pcu *pcu,
const struct firmware *fw)
{
unsigned int n_fw_records;
int retval;
dev_info(pcu->dev, "Updating firmware %s, size: %zu\n",
IMS_PCU_FIRMWARE_NAME, fw->size);
n_fw_records = ims_pcu_count_fw_records(fw);
retval = ims_pcu_flash_firmware(pcu, fw, n_fw_records);
if (retval)
goto out;
retval = ims_pcu_execute_bl_command(pcu, LAUNCH_APP, NULL, 0, 0);
if (retval)
dev_err(pcu->dev,
"Failed to start application image, error: %d\n",
retval);
out:
pcu->update_firmware_status = retval;
sysfs_notify(&pcu->dev->kobj, NULL, "update_firmware_status");
return retval;
}
static void ims_pcu_process_async_firmware(const struct firmware *fw,
void *context)
{
struct ims_pcu *pcu = context;
int error;
if (!fw) {
dev_err(pcu->dev, "Failed to get firmware %s\n",
IMS_PCU_FIRMWARE_NAME);
goto out;
}
error = ihex_validate_fw(fw);
if (error) {
dev_err(pcu->dev, "Firmware %s is invalid\n",
IMS_PCU_FIRMWARE_NAME);
goto out;
}
mutex_lock(&pcu->cmd_mutex);
ims_pcu_handle_firmware_update(pcu, fw);
mutex_unlock(&pcu->cmd_mutex);
release_firmware(fw);
out:
complete(&pcu->async_firmware_done);
}
/*********************************************************************
* Backlight LED device support *
*********************************************************************/
#define IMS_PCU_MAX_BRIGHTNESS 31998
static void ims_pcu_backlight_work(struct work_struct *work)
{
struct ims_pcu_backlight *backlight =
container_of(work, struct ims_pcu_backlight, work);
struct ims_pcu *pcu =
container_of(backlight, struct ims_pcu, backlight);
int desired_brightness = backlight->desired_brightness;
__le16 br_val = cpu_to_le16(desired_brightness);
int error;
mutex_lock(&pcu->cmd_mutex);
error = ims_pcu_execute_command(pcu, SET_BRIGHTNESS,
&br_val, sizeof(br_val));
if (error && error != -ENODEV)
dev_warn(pcu->dev,
"Failed to set desired brightness %u, error: %d\n",
desired_brightness, error);
mutex_unlock(&pcu->cmd_mutex);
}
static void ims_pcu_backlight_set_brightness(struct led_classdev *cdev,
enum led_brightness value)
{
struct ims_pcu_backlight *backlight =
container_of(cdev, struct ims_pcu_backlight, cdev);
backlight->desired_brightness = value;
schedule_work(&backlight->work);
}
static enum led_brightness
ims_pcu_backlight_get_brightness(struct led_classdev *cdev)
{
struct ims_pcu_backlight *backlight =
container_of(cdev, struct ims_pcu_backlight, cdev);
struct ims_pcu *pcu =
container_of(backlight, struct ims_pcu, backlight);
int brightness;
int error;
mutex_lock(&pcu->cmd_mutex);
error = ims_pcu_execute_query(pcu, GET_BRIGHTNESS);
if (error) {
dev_warn(pcu->dev,
"Failed to get current brightness, error: %d\n",
error);
/* Assume the LED is OFF */
brightness = LED_OFF;
} else {
brightness =
get_unaligned_le16(&pcu->cmd_buf[IMS_PCU_DATA_OFFSET]);
}
mutex_unlock(&pcu->cmd_mutex);
return brightness;
}
static int ims_pcu_setup_backlight(struct ims_pcu *pcu)
{
struct ims_pcu_backlight *backlight = &pcu->backlight;
int error;
INIT_WORK(&backlight->work, ims_pcu_backlight_work);
snprintf(backlight->name, sizeof(backlight->name),
"pcu%d::kbd_backlight", pcu->device_no);
backlight->cdev.name = backlight->name;
backlight->cdev.max_brightness = IMS_PCU_MAX_BRIGHTNESS;
backlight->cdev.brightness_get = ims_pcu_backlight_get_brightness;
backlight->cdev.brightness_set = ims_pcu_backlight_set_brightness;
error = led_classdev_register(pcu->dev, &backlight->cdev);
if (error) {
dev_err(pcu->dev,
"Failed to register backlight LED device, error: %d\n",
error);
return error;
}
return 0;
}
static void ims_pcu_destroy_backlight(struct ims_pcu *pcu)
{
struct ims_pcu_backlight *backlight = &pcu->backlight;
led_classdev_unregister(&backlight->cdev);
cancel_work_sync(&backlight->work);
}
/*********************************************************************
* Sysfs attributes handling *
*********************************************************************/
struct ims_pcu_attribute {
struct device_attribute dattr;
size_t field_offset;
int field_length;
};
static ssize_t ims_pcu_attribute_show(struct device *dev,
struct device_attribute *dattr,
char *buf)
{
struct usb_interface *intf = to_usb_interface(dev);
struct ims_pcu *pcu = usb_get_intfdata(intf);
struct ims_pcu_attribute *attr =
container_of(dattr, struct ims_pcu_attribute, dattr);
char *field = (char *)pcu + attr->field_offset;
return scnprintf(buf, PAGE_SIZE, "%.*s\n", attr->field_length, field);
}
static ssize_t ims_pcu_attribute_store(struct device *dev,
struct device_attribute *dattr,
const char *buf, size_t count)
{
struct usb_interface *intf = to_usb_interface(dev);
struct ims_pcu *pcu = usb_get_intfdata(intf);
struct ims_pcu_attribute *attr =
container_of(dattr, struct ims_pcu_attribute, dattr);
char *field = (char *)pcu + attr->field_offset;
size_t data_len;
int error;
if (count > attr->field_length)
return -EINVAL;
data_len = strnlen(buf, attr->field_length);
if (data_len > attr->field_length)
return -EINVAL;
error = mutex_lock_interruptible(&pcu->cmd_mutex);
if (error)
return error;
memset(field, 0, attr->field_length);
memcpy(field, buf, data_len);
error = ims_pcu_set_info(pcu);
/*
* Even if update failed, let's fetch the info again as we just
* clobbered one of the fields.
*/
ims_pcu_get_info(pcu);
mutex_unlock(&pcu->cmd_mutex);
return error < 0 ? error : count;
}
#define IMS_PCU_ATTR(_field, _mode) \
struct ims_pcu_attribute ims_pcu_attr_##_field = { \
.dattr = __ATTR(_field, _mode, \
ims_pcu_attribute_show, \
ims_pcu_attribute_store), \
.field_offset = offsetof(struct ims_pcu, _field), \
.field_length = sizeof(((struct ims_pcu *)NULL)->_field), \
}
#define IMS_PCU_RO_ATTR(_field) \
IMS_PCU_ATTR(_field, S_IRUGO)
#define IMS_PCU_RW_ATTR(_field) \
IMS_PCU_ATTR(_field, S_IRUGO | S_IWUSR)
static IMS_PCU_RW_ATTR(part_number);
static IMS_PCU_RW_ATTR(serial_number);
static IMS_PCU_RW_ATTR(date_of_manufacturing);
static IMS_PCU_RO_ATTR(fw_version);
static IMS_PCU_RO_ATTR(bl_version);
static IMS_PCU_RO_ATTR(reset_reason);
static ssize_t ims_pcu_reset_device(struct device *dev,
struct device_attribute *dattr,
const char *buf, size_t count)
{
static const u8 reset_byte = 1;
struct usb_interface *intf = to_usb_interface(dev);
struct ims_pcu *pcu = usb_get_intfdata(intf);
int value;
int error;
error = kstrtoint(buf, 0, &value);
if (error)
return error;
if (value != 1)
return -EINVAL;
dev_info(pcu->dev, "Attempting to reset device\n");
error = ims_pcu_execute_command(pcu, PCU_RESET, &reset_byte, 1);
if (error) {
dev_info(pcu->dev,
"Failed to reset device, error: %d\n",
error);
return error;
}
return count;
}
static DEVICE_ATTR(reset_device, S_IWUSR, NULL, ims_pcu_reset_device);
static ssize_t ims_pcu_update_firmware_store(struct device *dev,
struct device_attribute *dattr,
const char *buf, size_t count)
{
struct usb_interface *intf = to_usb_interface(dev);
struct ims_pcu *pcu = usb_get_intfdata(intf);
const struct firmware *fw = NULL;
int value;
int error;
error = kstrtoint(buf, 0, &value);
if (error)
return error;
if (value != 1)
return -EINVAL;
error = mutex_lock_interruptible(&pcu->cmd_mutex);
if (error)
return error;
error = request_ihex_firmware(&fw, IMS_PCU_FIRMWARE_NAME, pcu->dev);
if (error) {
dev_err(pcu->dev, "Failed to request firmware %s, error: %d\n",
IMS_PCU_FIRMWARE_NAME, error);
goto out;
}
/*
* If we are already in bootloader mode we can proceed with
* flashing the firmware.
*
* If we are in application mode, then we need to switch into
* bootloader mode, which will cause the device to disconnect
* and reconnect as different device.
*/
if (pcu->bootloader_mode)
error = ims_pcu_handle_firmware_update(pcu, fw);
else
error = ims_pcu_switch_to_bootloader(pcu);
release_firmware(fw);
out:
mutex_unlock(&pcu->cmd_mutex);
return error ?: count;
}
static DEVICE_ATTR(update_firmware, S_IWUSR,
NULL, ims_pcu_update_firmware_store);
static ssize_t
ims_pcu_update_firmware_status_show(struct device *dev,
struct device_attribute *dattr,
char *buf)
{
struct usb_interface *intf = to_usb_interface(dev);
struct ims_pcu *pcu = usb_get_intfdata(intf);
return scnprintf(buf, PAGE_SIZE, "%d\n", pcu->update_firmware_status);
}
static DEVICE_ATTR(update_firmware_status, S_IRUGO,
ims_pcu_update_firmware_status_show, NULL);
static struct attribute *ims_pcu_attrs[] = {
&ims_pcu_attr_part_number.dattr.attr,
&ims_pcu_attr_serial_number.dattr.attr,
&ims_pcu_attr_date_of_manufacturing.dattr.attr,
&ims_pcu_attr_fw_version.dattr.attr,
&ims_pcu_attr_bl_version.dattr.attr,
&ims_pcu_attr_reset_reason.dattr.attr,
&dev_attr_reset_device.attr,
&dev_attr_update_firmware.attr,
&dev_attr_update_firmware_status.attr,
NULL
};
static umode_t ims_pcu_is_attr_visible(struct kobject *kobj,
struct attribute *attr, int n)
{
struct device *dev = container_of(kobj, struct device, kobj);
struct usb_interface *intf = to_usb_interface(dev);
struct ims_pcu *pcu = usb_get_intfdata(intf);
umode_t mode = attr->mode;
if (pcu->bootloader_mode) {
if (attr != &dev_attr_update_firmware_status.attr &&
attr != &dev_attr_update_firmware.attr &&
attr != &dev_attr_reset_device.attr) {
mode = 0;
}
} else {
if (attr == &dev_attr_update_firmware_status.attr)
mode = 0;
}
return mode;
}
static const struct attribute_group ims_pcu_attr_group = {
.is_visible = ims_pcu_is_attr_visible,
.attrs = ims_pcu_attrs,
};
/* Support for a separate OFN attribute group */
#define OFN_REG_RESULT_OFFSET 2
static int ims_pcu_read_ofn_config(struct ims_pcu *pcu, u8 addr, u8 *data)
{
int error;
s16 result;
error = ims_pcu_execute_command(pcu, OFN_GET_CONFIG,
&addr, sizeof(addr));
if (error)
return error;
result = (s16)get_unaligned_le16(pcu->cmd_buf + OFN_REG_RESULT_OFFSET);
if (result < 0)
return -EIO;
/* We only need LSB */
*data = pcu->cmd_buf[OFN_REG_RESULT_OFFSET];
return 0;
}
static int ims_pcu_write_ofn_config(struct ims_pcu *pcu, u8 addr, u8 data)
{
u8 buffer[] = { addr, data };
int error;
s16 result;
error = ims_pcu_execute_command(pcu, OFN_SET_CONFIG,
&buffer, sizeof(buffer));
if (error)
return error;
result = (s16)get_unaligned_le16(pcu->cmd_buf + OFN_REG_RESULT_OFFSET);
if (result < 0)
return -EIO;
return 0;
}
static ssize_t ims_pcu_ofn_reg_data_show(struct device *dev,
struct device_attribute *dattr,
char *buf)
{
struct usb_interface *intf = to_usb_interface(dev);
struct ims_pcu *pcu = usb_get_intfdata(intf);
int error;
u8 data;
mutex_lock(&pcu->cmd_mutex);
error = ims_pcu_read_ofn_config(pcu, pcu->ofn_reg_addr, &data);
mutex_unlock(&pcu->cmd_mutex);
if (error)
return error;
return scnprintf(buf, PAGE_SIZE, "%x\n", data);
}
static ssize_t ims_pcu_ofn_reg_data_store(struct device *dev,
struct device_attribute *dattr,
const char *buf, size_t count)
{
struct usb_interface *intf = to_usb_interface(dev);
struct ims_pcu *pcu = usb_get_intfdata(intf);
int error;
u8 value;
error = kstrtou8(buf, 0, &value);
if (error)
return error;
mutex_lock(&pcu->cmd_mutex);
error = ims_pcu_write_ofn_config(pcu, pcu->ofn_reg_addr, value);
mutex_unlock(&pcu->cmd_mutex);
return error ?: count;
}
static DEVICE_ATTR(reg_data, S_IRUGO | S_IWUSR,
ims_pcu_ofn_reg_data_show, ims_pcu_ofn_reg_data_store);
static ssize_t ims_pcu_ofn_reg_addr_show(struct device *dev,
struct device_attribute *dattr,
char *buf)
{
struct usb_interface *intf = to_usb_interface(dev);
struct ims_pcu *pcu = usb_get_intfdata(intf);
int error;
mutex_lock(&pcu->cmd_mutex);
error = scnprintf(buf, PAGE_SIZE, "%x\n", pcu->ofn_reg_addr);
mutex_unlock(&pcu->cmd_mutex);
return error;
}
static ssize_t ims_pcu_ofn_reg_addr_store(struct device *dev,
struct device_attribute *dattr,
const char *buf, size_t count)
{
struct usb_interface *intf = to_usb_interface(dev);
struct ims_pcu *pcu = usb_get_intfdata(intf);
int error;
u8 value;
error = kstrtou8(buf, 0, &value);
if (error)
return error;
mutex_lock(&pcu->cmd_mutex);
pcu->ofn_reg_addr = value;
mutex_unlock(&pcu->cmd_mutex);
return count;
}
static DEVICE_ATTR(reg_addr, S_IRUGO | S_IWUSR,
ims_pcu_ofn_reg_addr_show, ims_pcu_ofn_reg_addr_store);
struct ims_pcu_ofn_bit_attribute {
struct device_attribute dattr;
u8 addr;
u8 nr;
};
static ssize_t ims_pcu_ofn_bit_show(struct device *dev,
struct device_attribute *dattr,
char *buf)
{
struct usb_interface *intf = to_usb_interface(dev);
struct ims_pcu *pcu = usb_get_intfdata(intf);
struct ims_pcu_ofn_bit_attribute *attr =
container_of(dattr, struct ims_pcu_ofn_bit_attribute, dattr);
int error;
u8 data;
mutex_lock(&pcu->cmd_mutex);
error = ims_pcu_read_ofn_config(pcu, attr->addr, &data);
mutex_unlock(&pcu->cmd_mutex);
if (error)
return error;
return scnprintf(buf, PAGE_SIZE, "%d\n", !!(data & (1 << attr->nr)));
}
static ssize_t ims_pcu_ofn_bit_store(struct device *dev,
struct device_attribute *dattr,
const char *buf, size_t count)
{
struct usb_interface *intf = to_usb_interface(dev);
struct ims_pcu *pcu = usb_get_intfdata(intf);
struct ims_pcu_ofn_bit_attribute *attr =
container_of(dattr, struct ims_pcu_ofn_bit_attribute, dattr);
int error;
int value;
u8 data;
error = kstrtoint(buf, 0, &value);
if (error)
return error;
if (value > 1)
return -EINVAL;
mutex_lock(&pcu->cmd_mutex);
error = ims_pcu_read_ofn_config(pcu, attr->addr, &data);
if (!error) {
if (value)
data |= 1U << attr->nr;
else
data &= ~(1U << attr->nr);
error = ims_pcu_write_ofn_config(pcu, attr->addr, data);
}
mutex_unlock(&pcu->cmd_mutex);
return error ?: count;
}
#define IMS_PCU_OFN_BIT_ATTR(_field, _addr, _nr) \
struct ims_pcu_ofn_bit_attribute ims_pcu_ofn_attr_##_field = { \
.dattr = __ATTR(_field, S_IWUSR | S_IRUGO, \
ims_pcu_ofn_bit_show, ims_pcu_ofn_bit_store), \
.addr = _addr, \
.nr = _nr, \
}
static IMS_PCU_OFN_BIT_ATTR(engine_enable, 0x60, 7);
static IMS_PCU_OFN_BIT_ATTR(speed_enable, 0x60, 6);
static IMS_PCU_OFN_BIT_ATTR(assert_enable, 0x60, 5);
static IMS_PCU_OFN_BIT_ATTR(xyquant_enable, 0x60, 4);
static IMS_PCU_OFN_BIT_ATTR(xyscale_enable, 0x60, 1);
static IMS_PCU_OFN_BIT_ATTR(scale_x2, 0x63, 6);
static IMS_PCU_OFN_BIT_ATTR(scale_y2, 0x63, 7);
static struct attribute *ims_pcu_ofn_attrs[] = {
&dev_attr_reg_data.attr,
&dev_attr_reg_addr.attr,
&ims_pcu_ofn_attr_engine_enable.dattr.attr,
&ims_pcu_ofn_attr_speed_enable.dattr.attr,
&ims_pcu_ofn_attr_assert_enable.dattr.attr,
&ims_pcu_ofn_attr_xyquant_enable.dattr.attr,
&ims_pcu_ofn_attr_xyscale_enable.dattr.attr,
&ims_pcu_ofn_attr_scale_x2.dattr.attr,
&ims_pcu_ofn_attr_scale_y2.dattr.attr,
NULL
};
static const struct attribute_group ims_pcu_ofn_attr_group = {
.name = "ofn",
.attrs = ims_pcu_ofn_attrs,
};
static void ims_pcu_irq(struct urb *urb)
{
struct ims_pcu *pcu = urb->context;
int retval, status;
status = urb->status;
switch (status) {
case 0:
/* success */
break;
case -ECONNRESET:
case -ENOENT:
case -ESHUTDOWN:
/* this urb is terminated, clean up */
dev_dbg(pcu->dev, "%s - urb shutting down with status: %d\n",
__func__, status);
return;
default:
dev_dbg(pcu->dev, "%s - nonzero urb status received: %d\n",
__func__, status);
goto exit;
}
dev_dbg(pcu->dev, "%s: received %d: %*ph\n", __func__,
urb->actual_length, urb->actual_length, pcu->urb_in_buf);
if (urb == pcu->urb_in)
ims_pcu_process_data(pcu, urb);
exit:
retval = usb_submit_urb(urb, GFP_ATOMIC);
if (retval && retval != -ENODEV)
dev_err(pcu->dev, "%s - usb_submit_urb failed with result %d\n",
__func__, retval);
}
static int ims_pcu_buffers_alloc(struct ims_pcu *pcu)
{
int error;
pcu->urb_in_buf = usb_alloc_coherent(pcu->udev, pcu->max_in_size,
GFP_KERNEL, &pcu->read_dma);
if (!pcu->urb_in_buf) {
dev_err(pcu->dev,
"Failed to allocate memory for read buffer\n");
return -ENOMEM;
}
pcu->urb_in = usb_alloc_urb(0, GFP_KERNEL);
if (!pcu->urb_in) {
dev_err(pcu->dev, "Failed to allocate input URB\n");
error = -ENOMEM;
goto err_free_urb_in_buf;
}
pcu->urb_in->transfer_flags |= URB_NO_TRANSFER_DMA_MAP;
pcu->urb_in->transfer_dma = pcu->read_dma;
usb_fill_bulk_urb(pcu->urb_in, pcu->udev,
usb_rcvbulkpipe(pcu->udev,
pcu->ep_in->bEndpointAddress),
pcu->urb_in_buf, pcu->max_in_size,
ims_pcu_irq, pcu);
/*
* We are using usb_bulk_msg() for sending so there is no point
* in allocating memory with usb_alloc_coherent().
*/
pcu->urb_out_buf = kmalloc(pcu->max_out_size, GFP_KERNEL);
if (!pcu->urb_out_buf) {
dev_err(pcu->dev, "Failed to allocate memory for write buffer\n");
error = -ENOMEM;
goto err_free_in_urb;
}
pcu->urb_ctrl_buf = usb_alloc_coherent(pcu->udev, pcu->max_ctrl_size,
GFP_KERNEL, &pcu->ctrl_dma);
if (!pcu->urb_ctrl_buf) {
dev_err(pcu->dev,
"Failed to allocate memory for read buffer\n");
error = -ENOMEM;
goto err_free_urb_out_buf;
}
pcu->urb_ctrl = usb_alloc_urb(0, GFP_KERNEL);
if (!pcu->urb_ctrl) {
dev_err(pcu->dev, "Failed to allocate input URB\n");
error = -ENOMEM;
goto err_free_urb_ctrl_buf;
}
pcu->urb_ctrl->transfer_flags |= URB_NO_TRANSFER_DMA_MAP;
pcu->urb_ctrl->transfer_dma = pcu->ctrl_dma;
usb_fill_int_urb(pcu->urb_ctrl, pcu->udev,
usb_rcvintpipe(pcu->udev,
pcu->ep_ctrl->bEndpointAddress),
pcu->urb_ctrl_buf, pcu->max_ctrl_size,
ims_pcu_irq, pcu, pcu->ep_ctrl->bInterval);
return 0;
err_free_urb_ctrl_buf:
usb_free_coherent(pcu->udev, pcu->max_ctrl_size,
pcu->urb_ctrl_buf, pcu->ctrl_dma);
err_free_urb_out_buf:
kfree(pcu->urb_out_buf);
err_free_in_urb:
usb_free_urb(pcu->urb_in);
err_free_urb_in_buf:
usb_free_coherent(pcu->udev, pcu->max_in_size,
pcu->urb_in_buf, pcu->read_dma);
return error;
}
static void ims_pcu_buffers_free(struct ims_pcu *pcu)
{
usb_kill_urb(pcu->urb_in);
usb_free_urb(pcu->urb_in);
usb_free_coherent(pcu->udev, pcu->max_out_size,
pcu->urb_in_buf, pcu->read_dma);
kfree(pcu->urb_out_buf);
usb_kill_urb(pcu->urb_ctrl);
usb_free_urb(pcu->urb_ctrl);
usb_free_coherent(pcu->udev, pcu->max_ctrl_size,
pcu->urb_ctrl_buf, pcu->ctrl_dma);
}
static const struct usb_cdc_union_desc *
ims_pcu_get_cdc_union_desc(struct usb_interface *intf)
{
const void *buf = intf->altsetting->extra;
size_t buflen = intf->altsetting->extralen;
struct usb_cdc_union_desc *union_desc;
if (!buf) {
dev_err(&intf->dev, "Missing descriptor data\n");
return NULL;
}
if (!buflen) {
dev_err(&intf->dev, "Zero length descriptor\n");
return NULL;
}
while (buflen > 0) {
union_desc = (struct usb_cdc_union_desc *)buf;
if (union_desc->bDescriptorType == USB_DT_CS_INTERFACE &&
union_desc->bDescriptorSubType == USB_CDC_UNION_TYPE) {
dev_dbg(&intf->dev, "Found union header\n");
return union_desc;
}
buflen -= union_desc->bLength;
buf += union_desc->bLength;
}
dev_err(&intf->dev, "Missing CDC union descriptor\n");
return NULL;
}
static int ims_pcu_parse_cdc_data(struct usb_interface *intf, struct ims_pcu *pcu)
{
const struct usb_cdc_union_desc *union_desc;
struct usb_host_interface *alt;
union_desc = ims_pcu_get_cdc_union_desc(intf);
if (!union_desc)
return -EINVAL;
pcu->ctrl_intf = usb_ifnum_to_if(pcu->udev,
union_desc->bMasterInterface0);
if (!pcu->ctrl_intf)
return -EINVAL;
alt = pcu->ctrl_intf->cur_altsetting;
if (alt->desc.bNumEndpoints < 1)
return -ENODEV;
pcu->ep_ctrl = &alt->endpoint[0].desc;
pcu->max_ctrl_size = usb_endpoint_maxp(pcu->ep_ctrl);
pcu->data_intf = usb_ifnum_to_if(pcu->udev,
union_desc->bSlaveInterface0);
if (!pcu->data_intf)
return -EINVAL;
alt = pcu->data_intf->cur_altsetting;
if (alt->desc.bNumEndpoints != 2) {
dev_err(pcu->dev,
"Incorrect number of endpoints on data interface (%d)\n",
alt->desc.bNumEndpoints);
return -EINVAL;
}
pcu->ep_out = &alt->endpoint[0].desc;
if (!usb_endpoint_is_bulk_out(pcu->ep_out)) {
dev_err(pcu->dev,
"First endpoint on data interface is not BULK OUT\n");
return -EINVAL;
}
pcu->max_out_size = usb_endpoint_maxp(pcu->ep_out);
if (pcu->max_out_size < 8) {
dev_err(pcu->dev,
"Max OUT packet size is too small (%zd)\n",
pcu->max_out_size);
return -EINVAL;
}
pcu->ep_in = &alt->endpoint[1].desc;
if (!usb_endpoint_is_bulk_in(pcu->ep_in)) {
dev_err(pcu->dev,
"Second endpoint on data interface is not BULK IN\n");
return -EINVAL;
}
pcu->max_in_size = usb_endpoint_maxp(pcu->ep_in);
if (pcu->max_in_size < 8) {
dev_err(pcu->dev,
"Max IN packet size is too small (%zd)\n",
pcu->max_in_size);
return -EINVAL;
}
return 0;
}
static int ims_pcu_start_io(struct ims_pcu *pcu)
{
int error;
error = usb_submit_urb(pcu->urb_ctrl, GFP_KERNEL);
if (error) {
dev_err(pcu->dev,
"Failed to start control IO - usb_submit_urb failed with result: %d\n",
error);
return -EIO;
}
error = usb_submit_urb(pcu->urb_in, GFP_KERNEL);
if (error) {
dev_err(pcu->dev,
"Failed to start IO - usb_submit_urb failed with result: %d\n",
error);
usb_kill_urb(pcu->urb_ctrl);
return -EIO;
}
return 0;
}
static void ims_pcu_stop_io(struct ims_pcu *pcu)
{
usb_kill_urb(pcu->urb_in);
usb_kill_urb(pcu->urb_ctrl);
}
static int ims_pcu_line_setup(struct ims_pcu *pcu)
{
struct usb_host_interface *interface = pcu->ctrl_intf->cur_altsetting;
struct usb_cdc_line_coding *line = (void *)pcu->cmd_buf;
int error;
memset(line, 0, sizeof(*line));
line->dwDTERate = cpu_to_le32(57600);
line->bDataBits = 8;
error = usb_control_msg(pcu->udev, usb_sndctrlpipe(pcu->udev, 0),
USB_CDC_REQ_SET_LINE_CODING,
USB_TYPE_CLASS | USB_RECIP_INTERFACE,
0, interface->desc.bInterfaceNumber,
line, sizeof(struct usb_cdc_line_coding),
5000);
if (error < 0) {
dev_err(pcu->dev, "Failed to set line coding, error: %d\n",
error);
return error;
}
error = usb_control_msg(pcu->udev, usb_sndctrlpipe(pcu->udev, 0),
USB_CDC_REQ_SET_CONTROL_LINE_STATE,
USB_TYPE_CLASS | USB_RECIP_INTERFACE,
0x03, interface->desc.bInterfaceNumber,
NULL, 0, 5000);
if (error < 0) {
dev_err(pcu->dev, "Failed to set line state, error: %d\n",
error);
return error;
}
return 0;
}
static int ims_pcu_get_device_info(struct ims_pcu *pcu)
{
int error;
error = ims_pcu_get_info(pcu);
if (error)
return error;
error = ims_pcu_execute_query(pcu, GET_FW_VERSION);
if (error) {
dev_err(pcu->dev,
"GET_FW_VERSION command failed, error: %d\n", error);
return error;
}
snprintf(pcu->fw_version, sizeof(pcu->fw_version),
"%02d%02d%02d%02d.%c%c",
pcu->cmd_buf[2], pcu->cmd_buf[3], pcu->cmd_buf[4], pcu->cmd_buf[5],
pcu->cmd_buf[6], pcu->cmd_buf[7]);
error = ims_pcu_execute_query(pcu, GET_BL_VERSION);
if (error) {
dev_err(pcu->dev,
"GET_BL_VERSION command failed, error: %d\n", error);
return error;
}
snprintf(pcu->bl_version, sizeof(pcu->bl_version),
"%02d%02d%02d%02d.%c%c",
pcu->cmd_buf[2], pcu->cmd_buf[3], pcu->cmd_buf[4], pcu->cmd_buf[5],
pcu->cmd_buf[6], pcu->cmd_buf[7]);
error = ims_pcu_execute_query(pcu, RESET_REASON);
if (error) {
dev_err(pcu->dev,
"RESET_REASON command failed, error: %d\n", error);
return error;
}
snprintf(pcu->reset_reason, sizeof(pcu->reset_reason),
"%02x", pcu->cmd_buf[IMS_PCU_DATA_OFFSET]);
dev_dbg(pcu->dev,
"P/N: %s, MD: %s, S/N: %s, FW: %s, BL: %s, RR: %s\n",
pcu->part_number,
pcu->date_of_manufacturing,
pcu->serial_number,
pcu->fw_version,
pcu->bl_version,
pcu->reset_reason);
return 0;
}
static int ims_pcu_identify_type(struct ims_pcu *pcu, u8 *device_id)
{
int error;
error = ims_pcu_execute_query(pcu, GET_DEVICE_ID);
if (error) {
dev_err(pcu->dev,
"GET_DEVICE_ID command failed, error: %d\n", error);
return error;
}
*device_id = pcu->cmd_buf[IMS_PCU_DATA_OFFSET];
dev_dbg(pcu->dev, "Detected device ID: %d\n", *device_id);
return 0;
}
static int ims_pcu_init_application_mode(struct ims_pcu *pcu)
{
static atomic_t device_no = ATOMIC_INIT(-1);
const struct ims_pcu_device_info *info;
int error;
error = ims_pcu_get_device_info(pcu);
if (error) {
/* Device does not respond to basic queries, hopeless */
return error;
}
error = ims_pcu_identify_type(pcu, &pcu->device_id);
if (error) {
dev_err(pcu->dev,
"Failed to identify device, error: %d\n", error);
/*
* Do not signal error, but do not create input nor
* backlight devices either, let userspace figure this
* out (flash a new firmware?).
*/
return 0;
}
if (pcu->device_id >= ARRAY_SIZE(ims_pcu_device_info) ||
!ims_pcu_device_info[pcu->device_id].keymap) {
dev_err(pcu->dev, "Device ID %d is not valid\n", pcu->device_id);
/* Same as above, punt to userspace */
return 0;
}
/* Device appears to be operable, complete initialization */
pcu->device_no = atomic_inc_return(&device_no);
/*
* PCU-B devices, both GEN_1 and GEN_2 do not have OFN sensor
*/
if (pcu->device_id != IMS_PCU_PCU_B_DEVICE_ID) {
error = sysfs_create_group(&pcu->dev->kobj,
&ims_pcu_ofn_attr_group);
if (error)
return error;
}
error = ims_pcu_setup_backlight(pcu);
if (error)
return error;
info = &ims_pcu_device_info[pcu->device_id];
error = ims_pcu_setup_buttons(pcu, info->keymap, info->keymap_len);
if (error)
goto err_destroy_backlight;
if (info->has_gamepad) {
error = ims_pcu_setup_gamepad(pcu);
if (error)
goto err_destroy_buttons;
}
pcu->setup_complete = true;
return 0;
err_destroy_buttons:
ims_pcu_destroy_buttons(pcu);
err_destroy_backlight:
ims_pcu_destroy_backlight(pcu);
return error;
}
static void ims_pcu_destroy_application_mode(struct ims_pcu *pcu)
{
if (pcu->setup_complete) {
pcu->setup_complete = false;
mb(); /* make sure flag setting is not reordered */
if (pcu->gamepad)
ims_pcu_destroy_gamepad(pcu);
ims_pcu_destroy_buttons(pcu);
ims_pcu_destroy_backlight(pcu);
if (pcu->device_id != IMS_PCU_PCU_B_DEVICE_ID)
sysfs_remove_group(&pcu->dev->kobj,
&ims_pcu_ofn_attr_group);
}
}
static int ims_pcu_init_bootloader_mode(struct ims_pcu *pcu)
{
int error;
error = ims_pcu_execute_bl_command(pcu, QUERY_DEVICE, NULL, 0,
IMS_PCU_CMD_RESPONSE_TIMEOUT);
if (error) {
dev_err(pcu->dev, "Bootloader does not respond, aborting\n");
return error;
}
pcu->fw_start_addr =
get_unaligned_le32(&pcu->cmd_buf[IMS_PCU_DATA_OFFSET + 11]);
pcu->fw_end_addr =
get_unaligned_le32(&pcu->cmd_buf[IMS_PCU_DATA_OFFSET + 15]);
dev_info(pcu->dev,
"Device is in bootloader mode (addr 0x%08x-0x%08x), requesting firmware\n",
pcu->fw_start_addr, pcu->fw_end_addr);
error = request_firmware_nowait(THIS_MODULE, true,
IMS_PCU_FIRMWARE_NAME,
pcu->dev, GFP_KERNEL, pcu,
ims_pcu_process_async_firmware);
if (error) {
/* This error is not fatal, let userspace have another chance */
complete(&pcu->async_firmware_done);
}
return 0;
}
static void ims_pcu_destroy_bootloader_mode(struct ims_pcu *pcu)
{
/* Make sure our initial firmware request has completed */
wait_for_completion(&pcu->async_firmware_done);
}
#define IMS_PCU_APPLICATION_MODE 0
#define IMS_PCU_BOOTLOADER_MODE 1
static struct usb_driver ims_pcu_driver;
static int ims_pcu_probe(struct usb_interface *intf,
const struct usb_device_id *id)
{
struct usb_device *udev = interface_to_usbdev(intf);
struct ims_pcu *pcu;
int error;
pcu = kzalloc(sizeof(struct ims_pcu), GFP_KERNEL);
if (!pcu)
return -ENOMEM;
pcu->dev = &intf->dev;
pcu->udev = udev;
pcu->bootloader_mode = id->driver_info == IMS_PCU_BOOTLOADER_MODE;
mutex_init(&pcu->cmd_mutex);
init_completion(&pcu->cmd_done);
init_completion(&pcu->async_firmware_done);
error = ims_pcu_parse_cdc_data(intf, pcu);
if (error)
goto err_free_mem;
error = usb_driver_claim_interface(&ims_pcu_driver,
pcu->data_intf, pcu);
if (error) {
dev_err(&intf->dev,
"Unable to claim corresponding data interface: %d\n",
error);
goto err_free_mem;
}
usb_set_intfdata(pcu->ctrl_intf, pcu);
usb_set_intfdata(pcu->data_intf, pcu);
error = ims_pcu_buffers_alloc(pcu);
if (error)
goto err_unclaim_intf;
error = ims_pcu_start_io(pcu);
if (error)
goto err_free_buffers;
error = ims_pcu_line_setup(pcu);
if (error)
goto err_stop_io;
error = sysfs_create_group(&intf->dev.kobj, &ims_pcu_attr_group);
if (error)
goto err_stop_io;
error = pcu->bootloader_mode ?
ims_pcu_init_bootloader_mode(pcu) :
ims_pcu_init_application_mode(pcu);
if (error)
goto err_remove_sysfs;
return 0;
err_remove_sysfs:
sysfs_remove_group(&intf->dev.kobj, &ims_pcu_attr_group);
err_stop_io:
ims_pcu_stop_io(pcu);
err_free_buffers:
ims_pcu_buffers_free(pcu);
err_unclaim_intf:
usb_driver_release_interface(&ims_pcu_driver, pcu->data_intf);
err_free_mem:
kfree(pcu);
return error;
}
static void ims_pcu_disconnect(struct usb_interface *intf)
{
struct ims_pcu *pcu = usb_get_intfdata(intf);
struct usb_host_interface *alt = intf->cur_altsetting;
usb_set_intfdata(intf, NULL);
/*
* See if we are dealing with control or data interface. The cleanup
* happens when we unbind primary (control) interface.
*/
if (alt->desc.bInterfaceClass != USB_CLASS_COMM)
return;
sysfs_remove_group(&intf->dev.kobj, &ims_pcu_attr_group);
ims_pcu_stop_io(pcu);
if (pcu->bootloader_mode)
ims_pcu_destroy_bootloader_mode(pcu);
else
ims_pcu_destroy_application_mode(pcu);
ims_pcu_buffers_free(pcu);
kfree(pcu);
}
#ifdef CONFIG_PM
static int ims_pcu_suspend(struct usb_interface *intf,
pm_message_t message)
{
struct ims_pcu *pcu = usb_get_intfdata(intf);
struct usb_host_interface *alt = intf->cur_altsetting;
if (alt->desc.bInterfaceClass == USB_CLASS_COMM)
ims_pcu_stop_io(pcu);
return 0;
}
static int ims_pcu_resume(struct usb_interface *intf)
{
struct ims_pcu *pcu = usb_get_intfdata(intf);
struct usb_host_interface *alt = intf->cur_altsetting;
int retval = 0;
if (alt->desc.bInterfaceClass == USB_CLASS_COMM) {
retval = ims_pcu_start_io(pcu);
if (retval == 0)
retval = ims_pcu_line_setup(pcu);
}
return retval;
}
#endif
static const struct usb_device_id ims_pcu_id_table[] = {
{
USB_DEVICE_AND_INTERFACE_INFO(0x04d8, 0x0082,
USB_CLASS_COMM,
USB_CDC_SUBCLASS_ACM,
USB_CDC_ACM_PROTO_AT_V25TER),
.driver_info = IMS_PCU_APPLICATION_MODE,
},
{
USB_DEVICE_AND_INTERFACE_INFO(0x04d8, 0x0083,
USB_CLASS_COMM,
USB_CDC_SUBCLASS_ACM,
USB_CDC_ACM_PROTO_AT_V25TER),
.driver_info = IMS_PCU_BOOTLOADER_MODE,
},
{ }
};
static struct usb_driver ims_pcu_driver = {
.name = "ims_pcu",
.id_table = ims_pcu_id_table,
.probe = ims_pcu_probe,
.disconnect = ims_pcu_disconnect,
#ifdef CONFIG_PM
.suspend = ims_pcu_suspend,
.resume = ims_pcu_resume,
.reset_resume = ims_pcu_resume,
#endif
};
module_usb_driver(ims_pcu_driver);
MODULE_DESCRIPTION("IMS Passenger Control Unit driver");
MODULE_AUTHOR("Dmitry Torokhov <dmitry.torokhov@gmail.com>");
MODULE_LICENSE("GPL");
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_2925_0 |
crossvul-cpp_data_bad_5294_0 | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% PPPP SSSSS DDDD %
% P P SS D D %
% PPPP SSS D D %
% P SS D D %
% P SSSSS DDDD %
% %
% %
% Read/Write Adobe Photoshop Image Format %
% %
% Software Design %
% Cristy %
% Leonard Rosenthol %
% July 1992 %
% Dirk Lemstra %
% December 2013 %
% %
% %
% 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/artifact.h"
#include "MagickCore/attribute.h"
#include "MagickCore/blob.h"
#include "MagickCore/blob-private.h"
#include "MagickCore/cache.h"
#include "MagickCore/channel.h"
#include "MagickCore/colormap.h"
#include "MagickCore/colormap-private.h"
#include "MagickCore/colorspace.h"
#include "MagickCore/colorspace-private.h"
#include "MagickCore/constitute.h"
#include "MagickCore/enhance.h"
#include "MagickCore/exception.h"
#include "MagickCore/exception-private.h"
#include "MagickCore/image.h"
#include "MagickCore/image-private.h"
#include "MagickCore/list.h"
#include "MagickCore/log.h"
#include "MagickCore/magick.h"
#include "MagickCore/memory_.h"
#include "MagickCore/module.h"
#include "MagickCore/monitor-private.h"
#include "MagickCore/option.h"
#include "MagickCore/pixel.h"
#include "MagickCore/pixel-accessor.h"
#include "MagickCore/profile.h"
#include "MagickCore/property.h"
#include "MagickCore/quantum-private.h"
#include "MagickCore/static.h"
#include "MagickCore/string_.h"
#include "MagickCore/thread-private.h"
#ifdef MAGICKCORE_ZLIB_DELEGATE
#include <zlib.h>
#endif
#include "psd-private.h"
/*
Define declaractions.
*/
#define MaxPSDChannels 56
#define PSDQuantum(x) (((ssize_t) (x)+1) & -2)
/*
Enumerated declaractions.
*/
typedef enum
{
Raw = 0,
RLE = 1,
ZipWithoutPrediction = 2,
ZipWithPrediction = 3
} PSDCompressionType;
typedef enum
{
BitmapMode = 0,
GrayscaleMode = 1,
IndexedMode = 2,
RGBMode = 3,
CMYKMode = 4,
MultichannelMode = 7,
DuotoneMode = 8,
LabMode = 9
} PSDImageType;
/*
Typedef declaractions.
*/
typedef struct _ChannelInfo
{
short int
type;
size_t
size;
} ChannelInfo;
typedef struct _MaskInfo
{
Image
*image;
RectangleInfo
page;
unsigned char
background,
flags;
} MaskInfo;
typedef struct _LayerInfo
{
ChannelInfo
channel_info[MaxPSDChannels];
char
blendkey[4];
Image
*image;
MaskInfo
mask;
Quantum
opacity;
RectangleInfo
page;
size_t
offset_x,
offset_y;
unsigned char
clipping,
flags,
name[256],
visible;
unsigned short
channels;
} LayerInfo;
/*
Forward declarations.
*/
static MagickBooleanType
WritePSDImage(const ImageInfo *,Image *,ExceptionInfo *);
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% I s P S D %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% IsPSD()() returns MagickTrue if the image format type, identified by the
% magick string, is PSD.
%
% The format of the IsPSD method is:
%
% MagickBooleanType IsPSD(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 IsPSD(const unsigned char *magick,const size_t length)
{
if (length < 4)
return(MagickFalse);
if (LocaleNCompare((const char *) magick,"8BPS",4) == 0)
return(MagickTrue);
return(MagickFalse);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e a d P S D I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ReadPSDImage() reads an Adobe Photoshop 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 ReadPSDImage method is:
%
% Image *ReadPSDImage(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 const char *CompositeOperatorToPSDBlendMode(CompositeOperator op)
{
const char
*blend_mode;
switch (op)
{
case ColorBurnCompositeOp: blend_mode = "idiv"; break;
case ColorDodgeCompositeOp: blend_mode = "div "; break;
case ColorizeCompositeOp: blend_mode = "colr"; break;
case DarkenCompositeOp: blend_mode = "dark"; break;
case DifferenceCompositeOp: blend_mode = "diff"; break;
case DissolveCompositeOp: blend_mode = "diss"; break;
case ExclusionCompositeOp: blend_mode = "smud"; break;
case HardLightCompositeOp: blend_mode = "hLit"; break;
case HardMixCompositeOp: blend_mode = "hMix"; break;
case HueCompositeOp: blend_mode = "hue "; break;
case LightenCompositeOp: blend_mode = "lite"; break;
case LinearBurnCompositeOp: blend_mode = "lbrn"; break;
case LinearDodgeCompositeOp:blend_mode = "lddg"; break;
case LinearLightCompositeOp:blend_mode = "lLit"; break;
case LuminizeCompositeOp: blend_mode = "lum "; break;
case MultiplyCompositeOp: blend_mode = "mul "; break;
case OverCompositeOp: blend_mode = "norm"; break;
case OverlayCompositeOp: blend_mode = "over"; break;
case PinLightCompositeOp: blend_mode = "pLit"; break;
case SaturateCompositeOp: blend_mode = "sat "; break;
case ScreenCompositeOp: blend_mode = "scrn"; break;
case SoftLightCompositeOp: blend_mode = "sLit"; break;
case VividLightCompositeOp: blend_mode = "vLit"; break;
default: blend_mode = "norm";
}
return(blend_mode);
}
/*
For some reason Photoshop seems to blend semi-transparent pixels with white.
This method reverts the blending. This can be disabled by setting the
option 'psd:alpha-unblend' to off.
*/
static MagickBooleanType CorrectPSDAlphaBlend(const ImageInfo *image_info,
Image *image,ExceptionInfo* exception)
{
const char
*option;
MagickBooleanType
status;
ssize_t
y;
if (image->alpha_trait != BlendPixelTrait || image->colorspace != sRGBColorspace)
return(MagickTrue);
option=GetImageOption(image_info,"psd:alpha-unblend");
if (IsStringFalse(option) != MagickFalse)
return(MagickTrue);
status=MagickTrue;
#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=GetAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
double
gamma;
register ssize_t
i;
gamma=QuantumScale*GetPixelAlpha(image, q);
if (gamma != 0.0 && gamma != 1.0)
{
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
PixelChannel channel=GetPixelChannelChannel(image,i);
if (channel != AlphaPixelChannel)
q[i]=ClampToQuantum((q[i]-((1.0-gamma)*QuantumRange))/gamma);
}
}
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
status=MagickFalse;
}
return(status);
}
static inline CompressionType ConvertPSDCompression(
PSDCompressionType compression)
{
switch (compression)
{
case RLE:
return RLECompression;
case ZipWithPrediction:
case ZipWithoutPrediction:
return ZipCompression;
default:
return NoCompression;
}
}
static MagickBooleanType CorrectPSDOpacity(LayerInfo *layer_info,
ExceptionInfo *exception)
{
MagickBooleanType
status;
ssize_t
y;
if (layer_info->opacity == OpaqueAlpha)
return(MagickTrue);
layer_info->image->alpha_trait=BlendPixelTrait;
status=MagickTrue;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(status) \
magick_threads(layer_info->image,layer_info->image,layer_info->image->rows,1)
#endif
for (y=0; y < (ssize_t) layer_info->image->rows; y++)
{
register Quantum
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
q=GetAuthenticPixels(layer_info->image,0,y,layer_info->image->columns,1,
exception);
if (q == (Quantum *)NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) layer_info->image->columns; x++)
{
SetPixelAlpha(layer_info->image,(Quantum) (QuantumScale*(GetPixelAlpha(
layer_info->image,q))*layer_info->opacity),q);
q+=GetPixelChannels(layer_info->image);
}
if (SyncAuthenticPixels(layer_info->image,exception) == MagickFalse)
status=MagickFalse;
}
return(status);
}
static ssize_t DecodePSDPixels(const size_t number_compact_pixels,
const unsigned char *compact_pixels,const ssize_t depth,
const size_t number_pixels,unsigned char *pixels)
{
#define CheckNumberCompactPixels \
if (packets == 0) \
return(i); \
packets--
#define CheckNumberPixels(count) \
if (((ssize_t) i + count) > (ssize_t) number_pixels) \
return(i); \
i+=count
int
pixel;
register ssize_t
i,
j;
size_t
length;
ssize_t
packets;
packets=(ssize_t) number_compact_pixels;
for (i=0; (packets > 1) && (i < (ssize_t) number_pixels); )
{
packets--;
length=(size_t) (*compact_pixels++);
if (length == 128)
continue;
if (length > 128)
{
length=256-length+1;
CheckNumberCompactPixels;
pixel=(*compact_pixels++);
for (j=0; j < (ssize_t) length; j++)
{
switch (depth)
{
case 1:
{
CheckNumberPixels(8);
*pixels++=(pixel >> 7) & 0x01 ? 0U : 255U;
*pixels++=(pixel >> 6) & 0x01 ? 0U : 255U;
*pixels++=(pixel >> 5) & 0x01 ? 0U : 255U;
*pixels++=(pixel >> 4) & 0x01 ? 0U : 255U;
*pixels++=(pixel >> 3) & 0x01 ? 0U : 255U;
*pixels++=(pixel >> 2) & 0x01 ? 0U : 255U;
*pixels++=(pixel >> 1) & 0x01 ? 0U : 255U;
*pixels++=(pixel >> 0) & 0x01 ? 0U : 255U;
break;
}
case 2:
{
CheckNumberPixels(4);
*pixels++=(unsigned char) ((pixel >> 6) & 0x03);
*pixels++=(unsigned char) ((pixel >> 4) & 0x03);
*pixels++=(unsigned char) ((pixel >> 2) & 0x03);
*pixels++=(unsigned char) ((pixel & 0x03) & 0x03);
break;
}
case 4:
{
CheckNumberPixels(2);
*pixels++=(unsigned char) ((pixel >> 4) & 0xff);
*pixels++=(unsigned char) ((pixel & 0x0f) & 0xff);
break;
}
default:
{
CheckNumberPixels(1);
*pixels++=(unsigned char) pixel;
break;
}
}
}
continue;
}
length++;
for (j=0; j < (ssize_t) length; j++)
{
switch (depth)
{
case 1:
{
CheckNumberPixels(8);
*pixels++=(*compact_pixels >> 7) & 0x01 ? 0U : 255U;
*pixels++=(*compact_pixels >> 6) & 0x01 ? 0U : 255U;
*pixels++=(*compact_pixels >> 5) & 0x01 ? 0U : 255U;
*pixels++=(*compact_pixels >> 4) & 0x01 ? 0U : 255U;
*pixels++=(*compact_pixels >> 3) & 0x01 ? 0U : 255U;
*pixels++=(*compact_pixels >> 2) & 0x01 ? 0U : 255U;
*pixels++=(*compact_pixels >> 1) & 0x01 ? 0U : 255U;
*pixels++=(*compact_pixels >> 0) & 0x01 ? 0U : 255U;
break;
}
case 2:
{
CheckNumberPixels(4);
*pixels++=(*compact_pixels >> 6) & 0x03;
*pixels++=(*compact_pixels >> 4) & 0x03;
*pixels++=(*compact_pixels >> 2) & 0x03;
*pixels++=(*compact_pixels & 0x03) & 0x03;
break;
}
case 4:
{
CheckNumberPixels(2);
*pixels++=(*compact_pixels >> 4) & 0xff;
*pixels++=(*compact_pixels & 0x0f) & 0xff;
break;
}
default:
{
CheckNumberPixels(1);
*pixels++=(*compact_pixels);
break;
}
}
CheckNumberCompactPixels;
compact_pixels++;
}
}
return(i);
}
static inline LayerInfo *DestroyLayerInfo(LayerInfo *layer_info,
const ssize_t number_layers)
{
ssize_t
i;
for (i=0; i<number_layers; i++)
{
if (layer_info[i].image != (Image *) NULL)
layer_info[i].image=DestroyImage(layer_info[i].image);
if (layer_info[i].mask.image != (Image *) NULL)
layer_info[i].mask.image=DestroyImage(layer_info[i].mask.image);
}
return (LayerInfo *) RelinquishMagickMemory(layer_info);
}
static inline size_t GetPSDPacketSize(Image *image)
{
if (image->storage_class == PseudoClass)
{
if (image->colors > 256)
return(2);
else if (image->depth > 8)
return(2);
}
else
if (image->depth > 8)
return(2);
return(1);
}
static inline MagickSizeType GetPSDSize(const PSDInfo *psd_info,Image *image)
{
if (psd_info->version == 1)
return((MagickSizeType) ReadBlobLong(image));
return((MagickSizeType) ReadBlobLongLong(image));
}
static inline size_t GetPSDRowSize(Image *image)
{
if (image->depth == 1)
return((image->columns+7)/8);
else
return(image->columns*GetPSDPacketSize(image));
}
static const char *ModeToString(PSDImageType type)
{
switch (type)
{
case BitmapMode: return "Bitmap";
case GrayscaleMode: return "Grayscale";
case IndexedMode: return "Indexed";
case RGBMode: return "RGB";
case CMYKMode: return "CMYK";
case MultichannelMode: return "Multichannel";
case DuotoneMode: return "Duotone";
case LabMode: return "L*A*B";
default: return "unknown";
}
}
static MagickBooleanType NegateCMYK(Image *image,ExceptionInfo *exception)
{
ChannelType
channel_mask;
MagickBooleanType
status;
channel_mask=SetImageChannelMask(image,(ChannelType)(AllChannels &~
AlphaChannel));
status=NegateImage(image,MagickFalse,exception);
(void) SetImageChannelMask(image,channel_mask);
return(status);
}
static void ParseImageResourceBlocks(Image *image,
const unsigned char *blocks,size_t length,
MagickBooleanType *has_merged_image,ExceptionInfo *exception)
{
const unsigned char
*p;
StringInfo
*profile;
unsigned int
count,
long_sans;
unsigned short
id,
short_sans;
if (length < 16)
return;
profile=BlobToStringInfo((const unsigned char *) NULL,length);
SetStringInfoDatum(profile,blocks);
(void) SetImageProfile(image,"8bim",profile,exception);
profile=DestroyStringInfo(profile);
for (p=blocks; (p >= blocks) && (p < (blocks+length-16)); )
{
if (LocaleNCompare((const char *) p,"8BIM",4) != 0)
break;
p=PushLongPixel(MSBEndian,p,&long_sans);
p=PushShortPixel(MSBEndian,p,&id);
p=PushShortPixel(MSBEndian,p,&short_sans);
p=PushLongPixel(MSBEndian,p,&count);
if (p+count > blocks+length)
return;
switch (id)
{
case 0x03ed:
{
char
value[MagickPathExtent];
unsigned short
resolution;
/*
Resolution info.
*/
p=PushShortPixel(MSBEndian,p,&resolution);
image->resolution.x=(double) resolution;
(void) FormatLocaleString(value,MagickPathExtent,"%g",image->resolution.x);
(void) SetImageProperty(image,"tiff:XResolution",value,exception);
p=PushShortPixel(MSBEndian,p,&short_sans);
p=PushShortPixel(MSBEndian,p,&short_sans);
p=PushShortPixel(MSBEndian,p,&short_sans);
p=PushShortPixel(MSBEndian,p,&resolution);
image->resolution.y=(double) resolution;
(void) FormatLocaleString(value,MagickPathExtent,"%g",image->resolution.y);
(void) SetImageProperty(image,"tiff:YResolution",value,exception);
p=PushShortPixel(MSBEndian,p,&short_sans);
p=PushShortPixel(MSBEndian,p,&short_sans);
p=PushShortPixel(MSBEndian,p,&short_sans);
image->units=PixelsPerInchResolution;
break;
}
case 0x0421:
{
if (*(p+4) == 0)
*has_merged_image=MagickFalse;
p+=count;
break;
}
default:
{
p+=count;
break;
}
}
if ((count & 0x01) != 0)
p++;
}
return;
}
static CompositeOperator PSDBlendModeToCompositeOperator(const char *mode)
{
if (mode == (const char *) NULL)
return(OverCompositeOp);
if (LocaleNCompare(mode,"norm",4) == 0)
return(OverCompositeOp);
if (LocaleNCompare(mode,"mul ",4) == 0)
return(MultiplyCompositeOp);
if (LocaleNCompare(mode,"diss",4) == 0)
return(DissolveCompositeOp);
if (LocaleNCompare(mode,"diff",4) == 0)
return(DifferenceCompositeOp);
if (LocaleNCompare(mode,"dark",4) == 0)
return(DarkenCompositeOp);
if (LocaleNCompare(mode,"lite",4) == 0)
return(LightenCompositeOp);
if (LocaleNCompare(mode,"hue ",4) == 0)
return(HueCompositeOp);
if (LocaleNCompare(mode,"sat ",4) == 0)
return(SaturateCompositeOp);
if (LocaleNCompare(mode,"colr",4) == 0)
return(ColorizeCompositeOp);
if (LocaleNCompare(mode,"lum ",4) == 0)
return(LuminizeCompositeOp);
if (LocaleNCompare(mode,"scrn",4) == 0)
return(ScreenCompositeOp);
if (LocaleNCompare(mode,"over",4) == 0)
return(OverlayCompositeOp);
if (LocaleNCompare(mode,"hLit",4) == 0)
return(HardLightCompositeOp);
if (LocaleNCompare(mode,"sLit",4) == 0)
return(SoftLightCompositeOp);
if (LocaleNCompare(mode,"smud",4) == 0)
return(ExclusionCompositeOp);
if (LocaleNCompare(mode,"div ",4) == 0)
return(ColorDodgeCompositeOp);
if (LocaleNCompare(mode,"idiv",4) == 0)
return(ColorBurnCompositeOp);
if (LocaleNCompare(mode,"lbrn",4) == 0)
return(LinearBurnCompositeOp);
if (LocaleNCompare(mode,"lddg",4) == 0)
return(LinearDodgeCompositeOp);
if (LocaleNCompare(mode,"lLit",4) == 0)
return(LinearLightCompositeOp);
if (LocaleNCompare(mode,"vLit",4) == 0)
return(VividLightCompositeOp);
if (LocaleNCompare(mode,"pLit",4) == 0)
return(PinLightCompositeOp);
if (LocaleNCompare(mode,"hMix",4) == 0)
return(HardMixCompositeOp);
return(OverCompositeOp);
}
static inline void ReversePSDString(Image *image,char *p,size_t length)
{
char
*q;
if (image->endian == MSBEndian)
return;
q=p+length;
for(--q; p < q; ++p, --q)
{
*p = *p ^ *q,
*q = *p ^ *q,
*p = *p ^ *q;
}
}
static MagickBooleanType ReadPSDChannelPixels(Image *image,
const size_t channels,const size_t row,const ssize_t type,
const unsigned char *pixels,ExceptionInfo *exception)
{
Quantum
pixel;
register const unsigned char
*p;
register Quantum
*q;
register ssize_t
x;
size_t
packet_size;
unsigned short
nibble;
p=pixels;
q=GetAuthenticPixels(image,0,row,image->columns,1,exception);
if (q == (Quantum *) NULL)
return MagickFalse;
packet_size=GetPSDPacketSize(image);
for (x=0; x < (ssize_t) image->columns; x++)
{
if (packet_size == 1)
pixel=ScaleCharToQuantum(*p++);
else
{
p=PushShortPixel(MSBEndian,p,&nibble);
pixel=ScaleShortToQuantum(nibble);
}
switch (type)
{
case -1:
{
SetPixelAlpha(image,pixel,q);
break;
}
case -2:
case 0:
{
SetPixelRed(image,pixel,q);
if (channels == 1 || type == -2)
SetPixelGray(image,pixel,q);
if (image->storage_class == PseudoClass)
{
if (packet_size == 1)
SetPixelIndex(image,ScaleQuantumToChar(pixel),q);
else
SetPixelIndex(image,ScaleQuantumToShort(pixel),q);
SetPixelViaPixelInfo(image,image->colormap+(ssize_t)
ConstrainColormapIndex(image,GetPixelIndex(image,q),exception),q);
if (image->depth == 1)
{
ssize_t
bit,
number_bits;
number_bits=image->columns-x;
if (number_bits > 8)
number_bits=8;
for (bit=0; bit < number_bits; bit++)
{
SetPixelIndex(image,(((unsigned char) pixel) &
(0x01 << (7-bit))) != 0 ? 0 : 255,q);
SetPixelViaPixelInfo(image,image->colormap+(ssize_t)
ConstrainColormapIndex(image,GetPixelIndex(image,q),
exception),q);
q+=GetPixelChannels(image);
x++;
}
x--;
continue;
}
}
break;
}
case 1:
{
if (image->storage_class == PseudoClass)
SetPixelAlpha(image,pixel,q);
else
SetPixelGreen(image,pixel,q);
break;
}
case 2:
{
if (image->storage_class == PseudoClass)
SetPixelAlpha(image,pixel,q);
else
SetPixelBlue(image,pixel,q);
break;
}
case 3:
{
if (image->colorspace == CMYKColorspace)
SetPixelBlack(image,pixel,q);
else
if (image->alpha_trait != UndefinedPixelTrait)
SetPixelAlpha(image,pixel,q);
break;
}
case 4:
{
if ((IssRGBCompatibleColorspace(image->colorspace) != MagickFalse) &&
(channels > 3))
break;
if (image->alpha_trait != UndefinedPixelTrait)
SetPixelAlpha(image,pixel,q);
break;
}
default:
break;
}
q+=GetPixelChannels(image);
}
return(SyncAuthenticPixels(image,exception));
}
static MagickBooleanType ReadPSDChannelRaw(Image *image,const size_t channels,
const ssize_t type,ExceptionInfo *exception)
{
MagickBooleanType
status;
size_t
count,
row_size;
ssize_t
y;
unsigned char
*pixels;
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" layer data is RAW");
row_size=GetPSDRowSize(image);
pixels=(unsigned char *) AcquireQuantumMemory(row_size,sizeof(*pixels));
if (pixels == (unsigned char *) NULL)
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
status=MagickTrue;
for (y=0; y < (ssize_t) image->rows; y++)
{
status=MagickFalse;
count=ReadBlob(image,row_size,pixels);
if (count != row_size)
break;
status=ReadPSDChannelPixels(image,channels,y,type,pixels,exception);
if (status == MagickFalse)
break;
}
pixels=(unsigned char *) RelinquishMagickMemory(pixels);
return(status);
}
static inline MagickOffsetType *ReadPSDRLEOffsets(Image *image,
const PSDInfo *psd_info,const size_t size)
{
MagickOffsetType
*offsets;
ssize_t
y;
offsets=(MagickOffsetType *) AcquireQuantumMemory(size,sizeof(*offsets));
if(offsets != (MagickOffsetType *) NULL)
{
for (y=0; y < (ssize_t) size; y++)
{
if (psd_info->version == 1)
offsets[y]=(MagickOffsetType) ReadBlobShort(image);
else
offsets[y]=(MagickOffsetType) ReadBlobLong(image);
}
}
return offsets;
}
static MagickBooleanType ReadPSDChannelRLE(Image *image,const PSDInfo *psd_info,
const ssize_t type,MagickOffsetType *offsets,ExceptionInfo *exception)
{
MagickBooleanType
status;
size_t
length,
row_size;
ssize_t
count,
y;
unsigned char
*compact_pixels,
*pixels;
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" layer data is RLE compressed");
row_size=GetPSDRowSize(image);
pixels=(unsigned char *) AcquireQuantumMemory(row_size,sizeof(*pixels));
if (pixels == (unsigned char *) NULL)
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
length=0;
for (y=0; y < (ssize_t) image->rows; y++)
if ((MagickOffsetType) length < offsets[y])
length=(size_t) offsets[y];
if (length > row_size + 256) // arbitrary number
{
pixels=(unsigned char *) RelinquishMagickMemory(pixels);
ThrowBinaryException(ResourceLimitError,"InvalidLength",
image->filename);
}
compact_pixels=(unsigned char *) AcquireQuantumMemory(length,sizeof(*pixels));
if (compact_pixels == (unsigned char *) NULL)
{
pixels=(unsigned char *) RelinquishMagickMemory(pixels);
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
}
(void) ResetMagickMemory(compact_pixels,0,length*sizeof(*compact_pixels));
status=MagickTrue;
for (y=0; y < (ssize_t) image->rows; y++)
{
status=MagickFalse;
count=ReadBlob(image,(size_t) offsets[y],compact_pixels);
if (count != (ssize_t) offsets[y])
break;
count=DecodePSDPixels((size_t) offsets[y],compact_pixels,
(ssize_t) (image->depth == 1 ? 123456 : image->depth),row_size,pixels);
if (count != (ssize_t) row_size)
break;
status=ReadPSDChannelPixels(image,psd_info->channels,y,type,pixels,
exception);
if (status == MagickFalse)
break;
}
compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels);
pixels=(unsigned char *) RelinquishMagickMemory(pixels);
return(status);
}
#ifdef MAGICKCORE_ZLIB_DELEGATE
static MagickBooleanType ReadPSDChannelZip(Image *image,const size_t channels,
const ssize_t type,const PSDCompressionType compression,
const size_t compact_size,ExceptionInfo *exception)
{
MagickBooleanType
status;
register unsigned char
*p;
size_t
count,
length,
packet_size,
row_size;
ssize_t
y;
unsigned char
*compact_pixels,
*pixels;
z_stream
stream;
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" layer data is ZIP compressed");
compact_pixels=(unsigned char *) AcquireQuantumMemory(compact_size,
sizeof(*compact_pixels));
if (compact_pixels == (unsigned char *) NULL)
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
packet_size=GetPSDPacketSize(image);
row_size=image->columns*packet_size;
count=image->rows*row_size;
pixels=(unsigned char *) AcquireQuantumMemory(count,sizeof(*pixels));
if (pixels == (unsigned char *) NULL)
{
compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels);
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
}
ResetMagickMemory(&stream, 0, sizeof(z_stream));
stream.data_type=Z_BINARY;
(void) ReadBlob(image,compact_size,compact_pixels);
stream.next_in=(Bytef *)compact_pixels;
stream.avail_in=(unsigned int) compact_size;
stream.next_out=(Bytef *)pixels;
stream.avail_out=(unsigned int) count;
if(inflateInit(&stream) == Z_OK)
{
int
ret;
while (stream.avail_out > 0)
{
ret=inflate(&stream, Z_SYNC_FLUSH);
if (ret != Z_OK && ret != Z_STREAM_END)
{
compact_pixels=(unsigned char *) RelinquishMagickMemory(
compact_pixels);
pixels=(unsigned char *) RelinquishMagickMemory(pixels);
return(MagickFalse);
}
}
}
if (compression == ZipWithPrediction)
{
p=pixels;
while(count > 0)
{
length=image->columns;
while(--length)
{
if (packet_size == 2)
{
p[2]+=p[0]+((p[1]+p[3]) >> 8);
p[3]+=p[1];
}
else
*(p+1)+=*p;
p+=packet_size;
}
p+=packet_size;
count-=row_size;
}
}
status=MagickTrue;
p=pixels;
for (y=0; y < (ssize_t) image->rows; y++)
{
status=ReadPSDChannelPixels(image,channels,y,type,p,exception);
if (status == MagickFalse)
break;
p+=row_size;
}
compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels);
pixels=(unsigned char *) RelinquishMagickMemory(pixels);
return(status);
}
#endif
static MagickBooleanType ReadPSDChannel(Image *image,const PSDInfo *psd_info,
LayerInfo* layer_info,const size_t channel,
const PSDCompressionType compression,ExceptionInfo *exception)
{
Image
*channel_image,
*mask;
MagickOffsetType
offset;
MagickBooleanType
status;
channel_image=image;
mask=(Image *) NULL;
if (layer_info->channel_info[channel].type < -1)
{
/*
Ignore mask that is not a user supplied layer mask, if the mask is
disabled or if the flags have unsupported values.
*/
if (layer_info->channel_info[channel].type != -2 ||
(layer_info->mask.flags > 3) || (layer_info->mask.flags & 0x02))
{
SeekBlob(image,layer_info->channel_info[channel].size-2,SEEK_CUR);
return(MagickTrue);
}
mask=CloneImage(image,layer_info->mask.page.width,
layer_info->mask.page.height,MagickFalse,exception);
SetImageType(mask,GrayscaleType,exception);
channel_image=mask;
}
offset=TellBlob(channel_image);
status=MagickTrue;
switch(compression)
{
case Raw:
status=ReadPSDChannelRaw(channel_image,psd_info->channels,
layer_info->channel_info[channel].type,exception);
break;
case RLE:
{
MagickOffsetType
*offsets;
offsets=ReadPSDRLEOffsets(channel_image,psd_info,channel_image->rows);
if (offsets == (MagickOffsetType *) NULL)
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
status=ReadPSDChannelRLE(channel_image,psd_info,
layer_info->channel_info[channel].type,offsets,exception);
offsets=(MagickOffsetType *) RelinquishMagickMemory(offsets);
}
break;
case ZipWithPrediction:
case ZipWithoutPrediction:
#ifdef MAGICKCORE_ZLIB_DELEGATE
status=ReadPSDChannelZip(channel_image,layer_info->channels,
layer_info->channel_info[channel].type,compression,
layer_info->channel_info[channel].size-2,exception);
#else
SeekBlob(image,offset+layer_info->channel_info[channel].size-2,SEEK_SET);
(void) ThrowMagickException(exception,GetMagickModule(),
MissingDelegateWarning,"DelegateLibrarySupportNotBuiltIn",
"'%s' (ZLIB)",image->filename);
#endif
break;
default:
SeekBlob(image,offset+layer_info->channel_info[channel].size-2,SEEK_SET);
(void) ThrowMagickException(exception,GetMagickModule(),TypeWarning,
"CompressionNotSupported","'%.20g'",(double) compression);
break;
}
if (status == MagickFalse)
{
if (mask != (Image *) NULL)
DestroyImage(mask);
SeekBlob(image,offset+layer_info->channel_info[channel].size-2,SEEK_SET);
ThrowBinaryException(CoderError,"UnableToDecompressImage",
image->filename);
}
if (mask != (Image *) NULL)
{
if (status != MagickFalse)
{
PixelInfo
color;
layer_info->mask.image=CloneImage(image,image->columns,image->rows,
MagickTrue,exception);
layer_info->mask.image->alpha_trait=UndefinedPixelTrait;
GetPixelInfo(layer_info->mask.image,&color);
color.red=layer_info->mask.background == 0 ? 0 : QuantumRange;
SetImageColor(layer_info->mask.image,&color,exception);
(void) CompositeImage(layer_info->mask.image,mask,OverCompositeOp,
MagickTrue,layer_info->mask.page.x,layer_info->mask.page.y,
exception);
}
DestroyImage(mask);
}
return(status);
}
static MagickBooleanType ReadPSDLayer(Image *image,const PSDInfo *psd_info,
LayerInfo* layer_info,ExceptionInfo *exception)
{
char
message[MagickPathExtent];
MagickBooleanType
status;
PSDCompressionType
compression;
ssize_t
j;
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" setting up new layer image");
(void) SetImageBackgroundColor(layer_info->image,exception);
layer_info->image->compose=PSDBlendModeToCompositeOperator(
layer_info->blendkey);
if (layer_info->visible == MagickFalse)
layer_info->image->compose=NoCompositeOp;
if (psd_info->mode == CMYKMode)
SetImageColorspace(layer_info->image,CMYKColorspace,exception);
if ((psd_info->mode == BitmapMode) || (psd_info->mode == GrayscaleMode) ||
(psd_info->mode == DuotoneMode))
SetImageColorspace(layer_info->image,GRAYColorspace,exception);
/*
Set up some hidden attributes for folks that need them.
*/
(void) FormatLocaleString(message,MagickPathExtent,"%.20g",
(double) layer_info->page.x);
(void) SetImageArtifact(layer_info->image,"psd:layer.x",message);
(void) FormatLocaleString(message,MagickPathExtent,"%.20g",
(double) layer_info->page.y);
(void) SetImageArtifact(layer_info->image,"psd:layer.y",message);
(void) FormatLocaleString(message,MagickPathExtent,"%.20g",(double)
layer_info->opacity);
(void) SetImageArtifact(layer_info->image,"psd:layer.opacity",message);
(void) SetImageProperty(layer_info->image,"label",(char *) layer_info->name,
exception);
status=MagickTrue;
for (j=0; j < (ssize_t) layer_info->channels; j++)
{
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" reading data for channel %.20g",(double) j);
compression=(PSDCompressionType) ReadBlobShort(layer_info->image);
layer_info->image->compression=ConvertPSDCompression(compression);
if (layer_info->channel_info[j].type == -1)
layer_info->image->alpha_trait=BlendPixelTrait;
status=ReadPSDChannel(layer_info->image,psd_info,layer_info,j,
compression,exception);
if (status == MagickFalse)
break;
}
if (status != MagickFalse)
status=CorrectPSDOpacity(layer_info,exception);
if ((status != MagickFalse) &&
(layer_info->image->colorspace == CMYKColorspace))
status=NegateCMYK(layer_info->image,exception);
if ((status != MagickFalse) && (layer_info->mask.image != (Image *) NULL))
{
status=CompositeImage(layer_info->image,layer_info->mask.image,
CopyAlphaCompositeOp,MagickTrue,0,0,exception);
layer_info->mask.image=DestroyImage(layer_info->mask.image);
}
return(status);
}
ModuleExport MagickBooleanType ReadPSDLayers(Image *image,
const ImageInfo *image_info,const PSDInfo *psd_info,
const MagickBooleanType skip_layers,ExceptionInfo *exception)
{
char
type[4];
LayerInfo
*layer_info;
MagickSizeType
size;
MagickBooleanType
status;
register ssize_t
i;
ssize_t
count,
j,
number_layers;
size=GetPSDSize(psd_info,image);
if (size == 0)
{
/*
Skip layers & masks.
*/
(void) ReadBlobLong(image);
count=ReadBlob(image,4,(unsigned char *) type);
ReversePSDString(image,type,4);
status=MagickFalse;
if ((count == 0) || (LocaleNCompare(type,"8BIM",4) != 0))
return(MagickTrue);
else
{
count=ReadBlob(image,4,(unsigned char *) type);
ReversePSDString(image,type,4);
if ((count != 0) && (LocaleNCompare(type,"Lr16",4) == 0))
size=GetPSDSize(psd_info,image);
else
return(MagickTrue);
}
}
status=MagickTrue;
if (size != 0)
{
layer_info=(LayerInfo *) NULL;
number_layers=(short) ReadBlobShort(image);
if (number_layers < 0)
{
/*
The first alpha channel in the merged result contains the
transparency data for the merged result.
*/
number_layers=MagickAbsoluteValue(number_layers);
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" negative layer count corrected for");
image->alpha_trait=BlendPixelTrait;
}
/*
We only need to know if the image has an alpha channel
*/
if (skip_layers != MagickFalse)
return(MagickTrue);
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image contains %.20g layers",(double) number_layers);
if (number_layers == 0)
ThrowBinaryException(CorruptImageError,"InvalidNumberOfLayers",
image->filename);
layer_info=(LayerInfo *) AcquireQuantumMemory((size_t) number_layers,
sizeof(*layer_info));
if (layer_info == (LayerInfo *) NULL)
{
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" allocation of LayerInfo failed");
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
}
(void) ResetMagickMemory(layer_info,0,(size_t) number_layers*
sizeof(*layer_info));
for (i=0; i < number_layers; i++)
{
ssize_t
x,
y;
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" reading layer #%.20g",(double) i+1);
layer_info[i].page.y=(int) ReadBlobLong(image);
layer_info[i].page.x=(int) ReadBlobLong(image);
y=(int) ReadBlobLong(image);
x=(int) ReadBlobLong(image);
layer_info[i].page.width=(size_t) (x-layer_info[i].page.x);
layer_info[i].page.height=(size_t) (y-layer_info[i].page.y);
layer_info[i].channels=ReadBlobShort(image);
if (layer_info[i].channels > MaxPSDChannels)
{
layer_info=DestroyLayerInfo(layer_info,number_layers);
ThrowBinaryException(CorruptImageError,"MaximumChannelsExceeded",
image->filename);
}
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" offset(%.20g,%.20g), size(%.20g,%.20g), channels=%.20g",
(double) layer_info[i].page.x,(double) layer_info[i].page.y,
(double) layer_info[i].page.height,(double)
layer_info[i].page.width,(double) layer_info[i].channels);
for (j=0; j < (ssize_t) layer_info[i].channels; j++)
{
layer_info[i].channel_info[j].type=(short) ReadBlobShort(image);
layer_info[i].channel_info[j].size=(size_t) GetPSDSize(psd_info,
image);
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" channel[%.20g]: type=%.20g, size=%.20g",(double) j,
(double) layer_info[i].channel_info[j].type,
(double) layer_info[i].channel_info[j].size);
}
count=ReadBlob(image,4,(unsigned char *) type);
ReversePSDString(image,type,4);
if ((count == 0) || (LocaleNCompare(type,"8BIM",4) != 0))
{
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" layer type was %.4s instead of 8BIM", type);
layer_info=DestroyLayerInfo(layer_info,number_layers);
ThrowBinaryException(CorruptImageError,"ImproperImageHeader",
image->filename);
}
count=ReadBlob(image,4,(unsigned char *) layer_info[i].blendkey);
ReversePSDString(image,layer_info[i].blendkey,4);
layer_info[i].opacity=(Quantum) ScaleCharToQuantum((unsigned char)
ReadBlobByte(image));
layer_info[i].clipping=(unsigned char) ReadBlobByte(image);
layer_info[i].flags=(unsigned char) ReadBlobByte(image);
layer_info[i].visible=!(layer_info[i].flags & 0x02);
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" blend=%.4s, opacity=%.20g, clipping=%s, flags=%d, visible=%s",
layer_info[i].blendkey,(double) layer_info[i].opacity,
layer_info[i].clipping ? "true" : "false",layer_info[i].flags,
layer_info[i].visible ? "true" : "false");
(void) ReadBlobByte(image); /* filler */
size=ReadBlobLong(image);
if (size != 0)
{
MagickSizeType
combined_length,
length;
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" layer contains additional info");
length=ReadBlobLong(image);
combined_length=length+4;
if (length != 0)
{
/*
Layer mask info.
*/
layer_info[i].mask.page.y=(int) ReadBlobLong(image);
layer_info[i].mask.page.x=(int) ReadBlobLong(image);
layer_info[i].mask.page.height=(size_t) (ReadBlobLong(image)-
layer_info[i].mask.page.y);
layer_info[i].mask.page.width=(size_t) (ReadBlobLong(image)-
layer_info[i].mask.page.x);
layer_info[i].mask.background=(unsigned char) ReadBlobByte(
image);
layer_info[i].mask.flags=(unsigned char) ReadBlobByte(image);
if (!(layer_info[i].mask.flags & 0x01))
{
layer_info[i].mask.page.y=layer_info[i].mask.page.y-
layer_info[i].page.y;
layer_info[i].mask.page.x=layer_info[i].mask.page.x-
layer_info[i].page.x;
}
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" layer mask: offset(%.20g,%.20g), size(%.20g,%.20g), length=%.20g",
(double) layer_info[i].mask.page.x,(double)
layer_info[i].mask.page.y,(double) layer_info[i].mask.page.width,
(double) layer_info[i].mask.page.height,(double)
((MagickOffsetType) length)-18);
/*
Skip over the rest of the layer mask information.
*/
if (DiscardBlobBytes(image,(MagickSizeType) (length-18)) == MagickFalse)
{
layer_info=DestroyLayerInfo(layer_info,number_layers);
ThrowBinaryException(CorruptImageError,"UnexpectedEndOfFile",
image->filename);
}
}
length=ReadBlobLong(image);
combined_length+=length+4;
if (length != 0)
{
/*
Layer blending ranges info.
*/
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" layer blending ranges: length=%.20g",(double)
((MagickOffsetType) length));
/*
We read it, but don't use it...
*/
for (j=0; j < (ssize_t) (length); j+=8)
{
size_t blend_source=ReadBlobLong(image);
size_t blend_dest=ReadBlobLong(image);
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" source(%x), dest(%x)",(unsigned int)
blend_source,(unsigned int) blend_dest);
}
}
/*
Layer name.
*/
length=(size_t) ReadBlobByte(image);
combined_length+=length+1;
if (length > 0)
(void) ReadBlob(image,(size_t) length++,layer_info[i].name);
layer_info[i].name[length]='\0';
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" layer name: %s",layer_info[i].name);
/*
Skip the rest of the variable data until we support it.
*/
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" unsupported data: length=%.20g",(double)
((MagickOffsetType) (size-combined_length)));
if (DiscardBlobBytes(image,(MagickSizeType) (size-combined_length)) == MagickFalse)
{
layer_info=DestroyLayerInfo(layer_info,number_layers);
ThrowBinaryException(CorruptImageError,
"UnexpectedEndOfFile",image->filename);
}
}
}
for (i=0; i < number_layers; i++)
{
if ((layer_info[i].page.width == 0) ||
(layer_info[i].page.height == 0))
{
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" layer data is empty");
continue;
}
/*
Allocate layered image.
*/
layer_info[i].image=CloneImage(image,layer_info[i].page.width,
layer_info[i].page.height,MagickFalse,exception);
if (layer_info[i].image == (Image *) NULL)
{
layer_info=DestroyLayerInfo(layer_info,number_layers);
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" allocation of image for layer %.20g failed",(double) i);
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
}
}
if (image_info->ping == MagickFalse)
{
for (i=0; i < number_layers; i++)
{
if (layer_info[i].image == (Image *) NULL)
{
for (j=0; j < layer_info[i].channels; j++)
{
if (DiscardBlobBytes(image,(MagickSizeType)
layer_info[i].channel_info[j].size) == MagickFalse)
{
layer_info=DestroyLayerInfo(layer_info,number_layers);
ThrowBinaryException(CorruptImageError,
"UnexpectedEndOfFile",image->filename);
}
}
continue;
}
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" reading data for layer %.20g",(double) i);
status=ReadPSDLayer(image,psd_info,&layer_info[i],exception);
if (status == MagickFalse)
break;
status=SetImageProgress(image,LoadImagesTag,i,(MagickSizeType)
number_layers);
if (status == MagickFalse)
break;
}
}
if (status != MagickFalse)
{
for (i=0; i < number_layers; i++)
{
if (layer_info[i].image == (Image *) NULL)
{
for (j=i; j < number_layers - 1; j++)
layer_info[j] = layer_info[j+1];
number_layers--;
i--;
}
}
if (number_layers > 0)
{
for (i=0; i < number_layers; i++)
{
if (i > 0)
layer_info[i].image->previous=layer_info[i-1].image;
if (i < (number_layers-1))
layer_info[i].image->next=layer_info[i+1].image;
layer_info[i].image->page=layer_info[i].page;
}
image->next=layer_info[0].image;
layer_info[0].image->previous=image;
}
layer_info=(LayerInfo *) RelinquishMagickMemory(layer_info);
}
else
layer_info=DestroyLayerInfo(layer_info,number_layers);
}
return(status);
}
static MagickBooleanType ReadPSDMergedImage(const ImageInfo *image_info,
Image *image,const PSDInfo *psd_info,ExceptionInfo *exception)
{
MagickOffsetType
*offsets;
MagickBooleanType
status;
PSDCompressionType
compression;
register ssize_t
i;
compression=(PSDCompressionType) ReadBlobMSBShort(image);
image->compression=ConvertPSDCompression(compression);
if (compression != Raw && compression != RLE)
{
(void) ThrowMagickException(exception,GetMagickModule(),
TypeWarning,"CompressionNotSupported","'%.20g'",(double) compression);
return(MagickFalse);
}
offsets=(MagickOffsetType *) NULL;
if (compression == RLE)
{
offsets=ReadPSDRLEOffsets(image,psd_info,image->rows*psd_info->channels);
if (offsets == (MagickOffsetType *) NULL)
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
}
status=MagickTrue;
for (i=0; i < (ssize_t) psd_info->channels; i++)
{
if (compression == RLE)
status=ReadPSDChannelRLE(image,psd_info,i,offsets+(i*image->rows),
exception);
else
status=ReadPSDChannelRaw(image,psd_info->channels,i,exception);
if (status != MagickFalse)
status=SetImageProgress(image,LoadImagesTag,i,psd_info->channels);
if (status == MagickFalse)
break;
}
if ((status != MagickFalse) && (image->colorspace == CMYKColorspace))
status=NegateCMYK(image,exception);
if (status != MagickFalse)
status=CorrectPSDAlphaBlend(image_info,image,exception);
if (offsets != (MagickOffsetType *) NULL)
offsets=(MagickOffsetType *) RelinquishMagickMemory(offsets);
return(status);
}
static Image *ReadPSDImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
Image
*image;
MagickBooleanType
has_merged_image,
skip_layers;
MagickOffsetType
offset;
MagickSizeType
length;
MagickBooleanType
status;
PSDInfo
psd_info;
register ssize_t
i;
ssize_t
count;
unsigned char
*data;
/*
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 image header.
*/
image->endian=MSBEndian;
count=ReadBlob(image,4,(unsigned char *) psd_info.signature);
psd_info.version=ReadBlobMSBShort(image);
if ((count == 0) || (LocaleNCompare(psd_info.signature,"8BPS",4) != 0) ||
((psd_info.version != 1) && (psd_info.version != 2)))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
(void) ReadBlob(image,6,psd_info.reserved);
psd_info.channels=ReadBlobMSBShort(image);
if (psd_info.channels > MaxPSDChannels)
ThrowReaderException(CorruptImageError,"MaximumChannelsExceeded");
psd_info.rows=ReadBlobMSBLong(image);
psd_info.columns=ReadBlobMSBLong(image);
if ((psd_info.version == 1) && ((psd_info.rows > 30000) ||
(psd_info.columns > 30000)))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
psd_info.depth=ReadBlobMSBShort(image);
if ((psd_info.depth != 1) && (psd_info.depth != 8) && (psd_info.depth != 16))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
psd_info.mode=ReadBlobMSBShort(image);
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Image is %.20g x %.20g with channels=%.20g, depth=%.20g, mode=%s",
(double) psd_info.columns,(double) psd_info.rows,(double)
psd_info.channels,(double) psd_info.depth,ModeToString((PSDImageType)
psd_info.mode));
/*
Initialize image.
*/
image->depth=psd_info.depth;
image->columns=psd_info.columns;
image->rows=psd_info.rows;
status=SetImageExtent(image,image->columns,image->rows,exception);
if (status == MagickFalse)
return(DestroyImageList(image));
if (SetImageBackgroundColor(image,exception) == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
if (psd_info.mode == LabMode)
SetImageColorspace(image,LabColorspace,exception);
if (psd_info.mode == CMYKMode)
{
SetImageColorspace(image,CMYKColorspace,exception);
image->alpha_trait=psd_info.channels > 4 ? BlendPixelTrait :
UndefinedPixelTrait;
}
else if ((psd_info.mode == BitmapMode) || (psd_info.mode == GrayscaleMode) ||
(psd_info.mode == DuotoneMode))
{
status=AcquireImageColormap(image,psd_info.depth != 16 ? 256 : 65536,
exception);
if (status == MagickFalse)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Image colormap allocated");
SetImageColorspace(image,GRAYColorspace,exception);
image->alpha_trait=psd_info.channels > 1 ? BlendPixelTrait :
UndefinedPixelTrait;
}
else
image->alpha_trait=psd_info.channels > 3 ? BlendPixelTrait :
UndefinedPixelTrait;
/*
Read PSD raster colormap only present for indexed and duotone images.
*/
length=ReadBlobMSBLong(image);
if (length != 0)
{
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" reading colormap");
if (psd_info.mode == DuotoneMode)
{
/*
Duotone image data; the format of this data is undocumented.
*/
data=(unsigned char *) AcquireQuantumMemory((size_t) length,
sizeof(*data));
if (data == (unsigned char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
(void) ReadBlob(image,(size_t) length,data);
data=(unsigned char *) RelinquishMagickMemory(data);
}
else
{
size_t
number_colors;
/*
Read PSD raster colormap.
*/
number_colors=length/3;
if (number_colors > 65536)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if (AcquireImageColormap(image,number_colors,exception) == MagickFalse)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
for (i=0; i < (ssize_t) image->colors; i++)
image->colormap[i].red=ScaleCharToQuantum((unsigned char)
ReadBlobByte(image));
for (i=0; i < (ssize_t) image->colors; i++)
image->colormap[i].green=ScaleCharToQuantum((unsigned char)
ReadBlobByte(image));
for (i=0; i < (ssize_t) image->colors; i++)
image->colormap[i].blue=ScaleCharToQuantum((unsigned char)
ReadBlobByte(image));
image->alpha_trait=UndefinedPixelTrait;
}
}
if ((image->depth == 1) && (image->storage_class != PseudoClass))
ThrowReaderException(CorruptImageError, "ImproperImageHeader");
has_merged_image=MagickTrue;
length=ReadBlobMSBLong(image);
if (length != 0)
{
unsigned char
*blocks;
/*
Image resources block.
*/
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" reading image resource blocks - %.20g bytes",(double)
((MagickOffsetType) length));
blocks=(unsigned char *) AcquireQuantumMemory((size_t) length,
sizeof(*blocks));
if (blocks == (unsigned char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
count=ReadBlob(image,(size_t) length,blocks);
if ((count != (ssize_t) length) ||
(LocaleNCompare((char *) blocks,"8BIM",4) != 0))
{
blocks=(unsigned char *) RelinquishMagickMemory(blocks);
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
ParseImageResourceBlocks(image,blocks,(size_t) length,&has_merged_image,
exception);
blocks=(unsigned char *) RelinquishMagickMemory(blocks);
}
/*
Layer and mask block.
*/
length=GetPSDSize(&psd_info,image);
if (length == 8)
{
length=ReadBlobMSBLong(image);
length=ReadBlobMSBLong(image);
}
offset=TellBlob(image);
skip_layers=MagickFalse;
if ((image_info->number_scenes == 1) && (image_info->scene == 0) &&
(has_merged_image != MagickFalse))
{
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" read composite only");
skip_layers=MagickTrue;
}
if (length == 0)
{
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image has no layers");
}
else
{
if (ReadPSDLayers(image,image_info,&psd_info,skip_layers,exception) !=
MagickTrue)
{
(void) CloseBlob(image);
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Skip the rest of the layer and mask information.
*/
SeekBlob(image,offset+length,SEEK_SET);
}
/*
If we are only "pinging" the image, then we're done - so return.
*/
if (image_info->ping != MagickFalse)
{
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
/*
Read the precombined layer, present for PSD < 4 compatibility.
*/
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" reading the precombined layer");
if ((has_merged_image != MagickFalse) || (GetImageListLength(image) == 1))
has_merged_image=(MagickBooleanType) ReadPSDMergedImage(image_info,image,
&psd_info,exception);
if ((has_merged_image == MagickFalse) && (GetImageListLength(image) == 1) &&
(length != 0))
{
SeekBlob(image,offset,SEEK_SET);
status=ReadPSDLayers(image,image_info,&psd_info,MagickFalse,exception);
if (status != MagickTrue)
{
(void) CloseBlob(image);
image=DestroyImageList(image);
return((Image *) NULL);
}
}
if ((has_merged_image == MagickFalse) && (GetImageListLength(image) > 1))
{
Image
*merged;
SetImageAlphaChannel(image,TransparentAlphaChannel,exception);
image->background_color.alpha=TransparentAlpha;
image->background_color.alpha_trait=BlendPixelTrait;
merged=MergeImageLayers(image,FlattenLayer,exception);
ReplaceImageInList(&image,merged);
}
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e g i s t e r P S D I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% RegisterPSDImage() adds properties for the PSD 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 RegisterPSDImage method is:
%
% size_t RegisterPSDImage(void)
%
*/
ModuleExport size_t RegisterPSDImage(void)
{
MagickInfo
*entry;
entry=AcquireMagickInfo("PSD","PSB","Adobe Large Document Format");
entry->decoder=(DecodeImageHandler *) ReadPSDImage;
entry->encoder=(EncodeImageHandler *) WritePSDImage;
entry->magick=(IsImageFormatHandler *) IsPSD;
entry->flags|=CoderSeekableStreamFlag;
(void) RegisterMagickInfo(entry);
entry=AcquireMagickInfo("PSD","PSD","Adobe Photoshop bitmap");
entry->decoder=(DecodeImageHandler *) ReadPSDImage;
entry->encoder=(EncodeImageHandler *) WritePSDImage;
entry->magick=(IsImageFormatHandler *) IsPSD;
entry->flags|=CoderSeekableStreamFlag;
(void) RegisterMagickInfo(entry);
return(MagickImageCoderSignature);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% U n r e g i s t e r P S D I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% UnregisterPSDImage() removes format registrations made by the
% PSD module from the list of supported formats.
%
% The format of the UnregisterPSDImage method is:
%
% UnregisterPSDImage(void)
%
*/
ModuleExport void UnregisterPSDImage(void)
{
(void) UnregisterMagickInfo("PSB");
(void) UnregisterMagickInfo("PSD");
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% W r i t e P S D I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% WritePSDImage() writes an image in the Adobe Photoshop encoded image format.
%
% The format of the WritePSDImage method is:
%
% MagickBooleanType WritePSDImage(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 inline ssize_t SetPSDOffset(const PSDInfo *psd_info,Image *image,
const size_t offset)
{
if (psd_info->version == 1)
return(WriteBlobMSBShort(image,(unsigned short) offset));
return(WriteBlobMSBLong(image,(unsigned short) offset));
}
static inline ssize_t SetPSDSize(const PSDInfo *psd_info,Image *image,
const MagickSizeType size)
{
if (psd_info->version == 1)
return(WriteBlobMSBLong(image,(unsigned int) size));
return(WriteBlobMSBLongLong(image,size));
}
static size_t PSDPackbitsEncodeImage(Image *image,const size_t length,
const unsigned char *pixels,unsigned char *compact_pixels,
ExceptionInfo *exception)
{
int
count;
register ssize_t
i,
j;
register unsigned char
*q;
unsigned char
*packbits;
/*
Compress pixels with Packbits encoding.
*/
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(pixels != (unsigned char *) NULL);
packbits=(unsigned char *) AcquireQuantumMemory(128UL,sizeof(*packbits));
if (packbits == (unsigned char *) NULL)
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
q=compact_pixels;
for (i=(ssize_t) length; i != 0; )
{
switch (i)
{
case 1:
{
i--;
*q++=(unsigned char) 0;
*q++=(*pixels);
break;
}
case 2:
{
i-=2;
*q++=(unsigned char) 1;
*q++=(*pixels);
*q++=pixels[1];
break;
}
case 3:
{
i-=3;
if ((*pixels == *(pixels+1)) && (*(pixels+1) == *(pixels+2)))
{
*q++=(unsigned char) ((256-3)+1);
*q++=(*pixels);
break;
}
*q++=(unsigned char) 2;
*q++=(*pixels);
*q++=pixels[1];
*q++=pixels[2];
break;
}
default:
{
if ((*pixels == *(pixels+1)) && (*(pixels+1) == *(pixels+2)))
{
/*
Packed run.
*/
count=3;
while (((ssize_t) count < i) && (*pixels == *(pixels+count)))
{
count++;
if (count >= 127)
break;
}
i-=count;
*q++=(unsigned char) ((256-count)+1);
*q++=(*pixels);
pixels+=count;
break;
}
/*
Literal run.
*/
count=0;
while ((*(pixels+count) != *(pixels+count+1)) ||
(*(pixels+count+1) != *(pixels+count+2)))
{
packbits[count+1]=pixels[count];
count++;
if (((ssize_t) count >= (i-3)) || (count >= 127))
break;
}
i-=count;
*packbits=(unsigned char) (count-1);
for (j=0; j <= (ssize_t) count; j++)
*q++=packbits[j];
pixels+=count;
break;
}
}
}
*q++=(unsigned char) 128; /* EOD marker */
packbits=(unsigned char *) RelinquishMagickMemory(packbits);
return((size_t) (q-compact_pixels));
}
static void WritePackbitsLength(const PSDInfo *psd_info,
const ImageInfo *image_info,Image *image,Image *next_image,
unsigned char *compact_pixels,const QuantumType quantum_type,
ExceptionInfo *exception)
{
QuantumInfo
*quantum_info;
register const Quantum
*p;
size_t
length,
packet_size;
ssize_t
y;
unsigned char
*pixels;
if (next_image->depth > 8)
next_image->depth=16;
packet_size=next_image->depth > 8UL ? 2UL : 1UL;
(void) packet_size;
quantum_info=AcquireQuantumInfo(image_info,image);
pixels=(unsigned char *) GetQuantumPixels(quantum_info);
for (y=0; y < (ssize_t) next_image->rows; y++)
{
p=GetVirtualPixels(next_image,0,y,next_image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
length=ExportQuantumPixels(next_image,(CacheView *) NULL,quantum_info,
quantum_type,pixels,exception);
length=PSDPackbitsEncodeImage(image,length,pixels,compact_pixels,
exception);
(void) SetPSDOffset(psd_info,image,length);
}
quantum_info=DestroyQuantumInfo(quantum_info);
}
static void WriteOneChannel(const PSDInfo *psd_info,const ImageInfo *image_info,
Image *image,Image *next_image,unsigned char *compact_pixels,
const QuantumType quantum_type,const MagickBooleanType compression_flag,
ExceptionInfo *exception)
{
int
y;
MagickBooleanType
monochrome;
QuantumInfo
*quantum_info;
register const Quantum
*p;
register ssize_t
i;
size_t
length,
packet_size;
unsigned char
*pixels;
(void) psd_info;
if ((compression_flag != MagickFalse) &&
(next_image->compression != RLECompression))
(void) WriteBlobMSBShort(image,0);
if (next_image->depth > 8)
next_image->depth=16;
monochrome=IsImageMonochrome(image) && (image->depth == 1) ?
MagickTrue : MagickFalse;
packet_size=next_image->depth > 8UL ? 2UL : 1UL;
(void) packet_size;
quantum_info=AcquireQuantumInfo(image_info,image);
pixels=(unsigned char *) GetQuantumPixels(quantum_info);
for (y=0; y < (ssize_t) next_image->rows; y++)
{
p=GetVirtualPixels(next_image,0,y,next_image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
length=ExportQuantumPixels(next_image,(CacheView *) NULL,quantum_info,
quantum_type,pixels,exception);
if (monochrome != MagickFalse)
for (i=0; i < (ssize_t) length; i++)
pixels[i]=(~pixels[i]);
if (next_image->compression != RLECompression)
(void) WriteBlob(image,length,pixels);
else
{
length=PSDPackbitsEncodeImage(image,length,pixels,compact_pixels,
exception);
(void) WriteBlob(image,length,compact_pixels);
}
}
quantum_info=DestroyQuantumInfo(quantum_info);
}
static MagickBooleanType WriteImageChannels(const PSDInfo *psd_info,
const ImageInfo *image_info,Image *image,Image *next_image,
const MagickBooleanType separate,ExceptionInfo *exception)
{
size_t
channels,
packet_size;
unsigned char
*compact_pixels;
/*
Write uncompressed pixels as separate planes.
*/
channels=1;
packet_size=next_image->depth > 8UL ? 2UL : 1UL;
compact_pixels=(unsigned char *) NULL;
if (next_image->compression == RLECompression)
{
compact_pixels=(unsigned char *) AcquireQuantumMemory((2*channels*
next_image->columns)+1,packet_size*sizeof(*compact_pixels));
if (compact_pixels == (unsigned char *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
}
if (IsImageGray(next_image) != MagickFalse)
{
if (next_image->compression == RLECompression)
{
/*
Packbits compression.
*/
(void) WriteBlobMSBShort(image,1);
WritePackbitsLength(psd_info,image_info,image,next_image,
compact_pixels,GrayQuantum,exception);
if (next_image->alpha_trait != UndefinedPixelTrait)
WritePackbitsLength(psd_info,image_info,image,next_image,
compact_pixels,AlphaQuantum,exception);
}
WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels,
GrayQuantum,MagickTrue,exception);
if (next_image->alpha_trait != UndefinedPixelTrait)
WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels,
AlphaQuantum,separate,exception);
(void) SetImageProgress(image,SaveImagesTag,0,1);
}
else
if (next_image->storage_class == PseudoClass)
{
if (next_image->compression == RLECompression)
{
/*
Packbits compression.
*/
(void) WriteBlobMSBShort(image,1);
WritePackbitsLength(psd_info,image_info,image,next_image,
compact_pixels,IndexQuantum,exception);
if (next_image->alpha_trait != UndefinedPixelTrait)
WritePackbitsLength(psd_info,image_info,image,next_image,
compact_pixels,AlphaQuantum,exception);
}
WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels,
IndexQuantum,MagickTrue,exception);
if (next_image->alpha_trait != UndefinedPixelTrait)
WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels,
AlphaQuantum,separate,exception);
(void) SetImageProgress(image,SaveImagesTag,0,1);
}
else
{
if (next_image->colorspace == CMYKColorspace)
(void) NegateCMYK(next_image,exception);
if (next_image->compression == RLECompression)
{
/*
Packbits compression.
*/
(void) WriteBlobMSBShort(image,1);
WritePackbitsLength(psd_info,image_info,image,next_image,
compact_pixels,RedQuantum,exception);
WritePackbitsLength(psd_info,image_info,image,next_image,
compact_pixels,GreenQuantum,exception);
WritePackbitsLength(psd_info,image_info,image,next_image,
compact_pixels,BlueQuantum,exception);
if (next_image->colorspace == CMYKColorspace)
WritePackbitsLength(psd_info,image_info,image,next_image,
compact_pixels,BlackQuantum,exception);
if (next_image->alpha_trait != UndefinedPixelTrait)
WritePackbitsLength(psd_info,image_info,image,next_image,
compact_pixels,AlphaQuantum,exception);
}
(void) SetImageProgress(image,SaveImagesTag,0,6);
WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels,
RedQuantum,MagickTrue,exception);
(void) SetImageProgress(image,SaveImagesTag,1,6);
WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels,
GreenQuantum,separate,exception);
(void) SetImageProgress(image,SaveImagesTag,2,6);
WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels,
BlueQuantum,separate,exception);
(void) SetImageProgress(image,SaveImagesTag,3,6);
if (next_image->colorspace == CMYKColorspace)
WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels,
BlackQuantum,separate,exception);
(void) SetImageProgress(image,SaveImagesTag,4,6);
if (next_image->alpha_trait != UndefinedPixelTrait)
WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels,
AlphaQuantum,separate,exception);
(void) SetImageProgress(image,SaveImagesTag,5,6);
if (next_image->colorspace == CMYKColorspace)
(void) NegateCMYK(next_image,exception);
}
if (next_image->compression == RLECompression)
compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels);
return(MagickTrue);
}
static void WritePascalString(Image* inImage,const char *inString,int inPad)
{
size_t
length;
register ssize_t
i;
/*
Max length is 255.
*/
length=(strlen(inString) > 255UL ) ? 255UL : strlen(inString);
if (length == 0)
(void) WriteBlobByte(inImage,0);
else
{
(void) WriteBlobByte(inImage,(unsigned char) length);
(void) WriteBlob(inImage, length, (const unsigned char *) inString);
}
length++;
if ((length % inPad) == 0)
return;
for (i=0; i < (ssize_t) (inPad-(length % inPad)); i++)
(void) WriteBlobByte(inImage,0);
}
static void WriteResolutionResourceBlock(Image *image)
{
double
x_resolution,
y_resolution;
unsigned short
units;
if (image->units == PixelsPerCentimeterResolution)
{
x_resolution=2.54*65536.0*image->resolution.x+0.5;
y_resolution=2.54*65536.0*image->resolution.y+0.5;
units=2;
}
else
{
x_resolution=65536.0*image->resolution.x+0.5;
y_resolution=65536.0*image->resolution.y+0.5;
units=1;
}
(void) WriteBlob(image,4,(const unsigned char *) "8BIM");
(void) WriteBlobMSBShort(image,0x03ED);
(void) WriteBlobMSBShort(image,0);
(void) WriteBlobMSBLong(image,16); /* resource size */
(void) WriteBlobMSBLong(image,(unsigned int) (x_resolution+0.5));
(void) WriteBlobMSBShort(image,units); /* horizontal resolution unit */
(void) WriteBlobMSBShort(image,units); /* width unit */
(void) WriteBlobMSBLong(image,(unsigned int) (y_resolution+0.5));
(void) WriteBlobMSBShort(image,units); /* vertical resolution unit */
(void) WriteBlobMSBShort(image,units); /* height unit */
}
static void RemoveICCProfileFromResourceBlock(StringInfo *bim_profile)
{
register const unsigned char
*p;
size_t
length;
unsigned char
*datum;
unsigned int
count,
long_sans;
unsigned short
id,
short_sans;
length=GetStringInfoLength(bim_profile);
if (length < 16)
return;
datum=GetStringInfoDatum(bim_profile);
for (p=datum; (p >= datum) && (p < (datum+length-16)); )
{
register unsigned char
*q;
q=(unsigned char *) p;
if (LocaleNCompare((const char *) p,"8BIM",4) != 0)
break;
p=PushLongPixel(MSBEndian,p,&long_sans);
p=PushShortPixel(MSBEndian,p,&id);
p=PushShortPixel(MSBEndian,p,&short_sans);
p=PushLongPixel(MSBEndian,p,&count);
if (id == 0x0000040f)
{
(void) CopyMagickMemory(q,q+PSDQuantum(count)+12,length-
(PSDQuantum(count)+12)-(q-datum));
SetStringInfoLength(bim_profile,length-(PSDQuantum(count)+12));
break;
}
p+=count;
if ((count & 0x01) != 0)
p++;
}
}
static void RemoveResolutionFromResourceBlock(StringInfo *bim_profile)
{
register const unsigned char
*p;
size_t
length;
unsigned char
*datum;
unsigned int
count,
long_sans;
unsigned short
id,
short_sans;
length=GetStringInfoLength(bim_profile);
if (length < 16)
return;
datum=GetStringInfoDatum(bim_profile);
for (p=datum; (p >= datum) && (p < (datum+length-16)); )
{
register unsigned char
*q;
q=(unsigned char *) p;
if (LocaleNCompare((const char *) p,"8BIM",4) != 0)
break;
p=PushLongPixel(MSBEndian,p,&long_sans);
p=PushShortPixel(MSBEndian,p,&id);
p=PushShortPixel(MSBEndian,p,&short_sans);
p=PushLongPixel(MSBEndian,p,&count);
if ((id == 0x000003ed) && (PSDQuantum(count) < (ssize_t) (length-12)))
{
(void) CopyMagickMemory(q,q+PSDQuantum(count)+12,length-
(PSDQuantum(count)+12)-(q-datum));
SetStringInfoLength(bim_profile,length-(PSDQuantum(count)+12));
break;
}
p+=count;
if ((count & 0x01) != 0)
p++;
}
}
static MagickBooleanType WritePSDImage(const ImageInfo *image_info,Image *image,
ExceptionInfo *exception)
{
const char
*property;
const StringInfo
*icc_profile;
Image
*base_image,
*next_image;
MagickBooleanType
status;
PSDInfo
psd_info;
register ssize_t
i;
size_t
channel_size,
channelLength,
layer_count,
layer_info_size,
length,
num_channels,
packet_size,
rounded_layer_info_size;
StringInfo
*bim_profile;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception);
if (status == MagickFalse)
return(status);
packet_size=(size_t) (image->depth > 8 ? 6 : 3);
if (image->alpha_trait != UndefinedPixelTrait)
packet_size+=image->depth > 8 ? 2 : 1;
psd_info.version=1;
if ((LocaleCompare(image_info->magick,"PSB") == 0) ||
(image->columns > 30000) || (image->rows > 30000))
psd_info.version=2;
(void) WriteBlob(image,4,(const unsigned char *) "8BPS");
(void) WriteBlobMSBShort(image,psd_info.version); /* version */
for (i=1; i <= 6; i++)
(void) WriteBlobByte(image, 0); /* 6 bytes of reserved */
if (SetImageGray(image,exception) != MagickFalse)
num_channels=(image->alpha_trait != UndefinedPixelTrait ? 2UL : 1UL);
else
if ((image_info->type != TrueColorType) && (image_info->type !=
TrueColorAlphaType) && (image->storage_class == PseudoClass))
num_channels=(image->alpha_trait != UndefinedPixelTrait ? 2UL : 1UL);
else
{
if (image->storage_class == PseudoClass)
(void) SetImageStorageClass(image,DirectClass,exception);
if (image->colorspace != CMYKColorspace)
num_channels=(image->alpha_trait != UndefinedPixelTrait ? 4UL : 3UL);
else
num_channels=(image->alpha_trait != UndefinedPixelTrait ? 5UL : 4UL);
}
(void) WriteBlobMSBShort(image,(unsigned short) num_channels);
(void) WriteBlobMSBLong(image,(unsigned int) image->rows);
(void) WriteBlobMSBLong(image,(unsigned int) image->columns);
if (IsImageGray(image) != MagickFalse)
{
MagickBooleanType
monochrome;
/*
Write depth & mode.
*/
monochrome=IsImageMonochrome(image) && (image->depth == 1) ?
MagickTrue : MagickFalse;
(void) WriteBlobMSBShort(image,(unsigned short)
(monochrome != MagickFalse ? 1 : image->depth > 8 ? 16 : 8));
(void) WriteBlobMSBShort(image,(unsigned short)
(monochrome != MagickFalse ? BitmapMode : GrayscaleMode));
}
else
{
(void) WriteBlobMSBShort(image,(unsigned short) (image->storage_class ==
PseudoClass ? 8 : image->depth > 8 ? 16 : 8));
if (((image_info->colorspace != UndefinedColorspace) ||
(image->colorspace != CMYKColorspace)) &&
(image_info->colorspace != CMYKColorspace))
{
(void) TransformImageColorspace(image,sRGBColorspace,exception);
(void) WriteBlobMSBShort(image,(unsigned short)
(image->storage_class == PseudoClass ? IndexedMode : RGBMode));
}
else
{
if (image->colorspace != CMYKColorspace)
(void) TransformImageColorspace(image,CMYKColorspace,exception);
(void) WriteBlobMSBShort(image,CMYKMode);
}
}
if ((IsImageGray(image) != MagickFalse) ||
(image->storage_class == DirectClass) || (image->colors > 256))
(void) WriteBlobMSBLong(image,0);
else
{
/*
Write PSD raster colormap.
*/
(void) WriteBlobMSBLong(image,768);
for (i=0; i < (ssize_t) image->colors; i++)
(void) WriteBlobByte(image,ScaleQuantumToChar(image->colormap[i].red));
for ( ; i < 256; i++)
(void) WriteBlobByte(image,0);
for (i=0; i < (ssize_t) image->colors; i++)
(void) WriteBlobByte(image,ScaleQuantumToChar(
image->colormap[i].green));
for ( ; i < 256; i++)
(void) WriteBlobByte(image,0);
for (i=0; i < (ssize_t) image->colors; i++)
(void) WriteBlobByte(image,ScaleQuantumToChar(image->colormap[i].blue));
for ( ; i < 256; i++)
(void) WriteBlobByte(image,0);
}
/*
Image resource block.
*/
length=28; /* 0x03EB */
bim_profile=(StringInfo *) GetImageProfile(image,"8bim");
icc_profile=GetImageProfile(image,"icc");
if (bim_profile != (StringInfo *) NULL)
{
bim_profile=CloneStringInfo(bim_profile);
if (icc_profile != (StringInfo *) NULL)
RemoveICCProfileFromResourceBlock(bim_profile);
RemoveResolutionFromResourceBlock(bim_profile);
length+=PSDQuantum(GetStringInfoLength(bim_profile));
}
if (icc_profile != (const StringInfo *) NULL)
length+=PSDQuantum(GetStringInfoLength(icc_profile))+12;
(void) WriteBlobMSBLong(image,(unsigned int) length);
WriteResolutionResourceBlock(image);
if (bim_profile != (StringInfo *) NULL)
{
(void) WriteBlob(image,GetStringInfoLength(bim_profile),
GetStringInfoDatum(bim_profile));
bim_profile=DestroyStringInfo(bim_profile);
}
if (icc_profile != (StringInfo *) NULL)
{
(void) WriteBlob(image,4,(const unsigned char *) "8BIM");
(void) WriteBlobMSBShort(image,0x0000040F);
(void) WriteBlobMSBShort(image,0);
(void) WriteBlobMSBLong(image,(unsigned int) GetStringInfoLength(
icc_profile));
(void) WriteBlob(image,GetStringInfoLength(icc_profile),
GetStringInfoDatum(icc_profile));
if ((MagickOffsetType) GetStringInfoLength(icc_profile) !=
PSDQuantum(GetStringInfoLength(icc_profile)))
(void) WriteBlobByte(image,0);
}
layer_count=0;
layer_info_size=2;
base_image=GetNextImageInList(image);
if ((image->alpha_trait != UndefinedPixelTrait) && (base_image == (Image *) NULL))
base_image=image;
next_image=base_image;
while ( next_image != NULL )
{
packet_size=next_image->depth > 8 ? 2UL : 1UL;
if (IsImageGray(next_image) != MagickFalse)
num_channels=next_image->alpha_trait != UndefinedPixelTrait ? 2UL : 1UL;
else
if (next_image->storage_class == PseudoClass)
num_channels=next_image->alpha_trait != UndefinedPixelTrait ? 2UL : 1UL;
else
if (next_image->colorspace != CMYKColorspace)
num_channels=next_image->alpha_trait != UndefinedPixelTrait ? 4UL : 3UL;
else
num_channels=next_image->alpha_trait != UndefinedPixelTrait ? 5UL : 4UL;
channelLength=(size_t) (next_image->columns*next_image->rows*packet_size+2);
layer_info_size+=(size_t) (4*4+2+num_channels*6+(psd_info.version == 1 ? 8 :
16)+4*1+4+num_channels*channelLength);
property=(const char *) GetImageProperty(next_image,"label",exception);
if (property == (const char *) NULL)
layer_info_size+=16;
else
{
size_t
layer_length;
layer_length=strlen(property);
layer_info_size+=8+layer_length+(4-(layer_length % 4));
}
layer_count++;
next_image=GetNextImageInList(next_image);
}
if (layer_count == 0)
(void) SetPSDSize(&psd_info,image,0);
else
{
CompressionType
compression;
(void) SetPSDSize(&psd_info,image,layer_info_size+
(psd_info.version == 1 ? 8 : 16));
if ((layer_info_size/2) != ((layer_info_size+1)/2))
rounded_layer_info_size=layer_info_size+1;
else
rounded_layer_info_size=layer_info_size;
(void) SetPSDSize(&psd_info,image,rounded_layer_info_size);
if (image->alpha_trait != UndefinedPixelTrait)
(void) WriteBlobMSBShort(image,-(unsigned short) layer_count);
else
(void) WriteBlobMSBShort(image,(unsigned short) layer_count);
layer_count=1;
compression=base_image->compression;
for (next_image=base_image; next_image != NULL; )
{
next_image->compression=NoCompression;
(void) WriteBlobMSBLong(image,(unsigned int) next_image->page.y);
(void) WriteBlobMSBLong(image,(unsigned int) next_image->page.x);
(void) WriteBlobMSBLong(image,(unsigned int) (next_image->page.y+
next_image->rows));
(void) WriteBlobMSBLong(image,(unsigned int) (next_image->page.x+
next_image->columns));
packet_size=next_image->depth > 8 ? 2UL : 1UL;
channel_size=(unsigned int) ((packet_size*next_image->rows*
next_image->columns)+2);
if ((IsImageGray(next_image) != MagickFalse) ||
(next_image->storage_class == PseudoClass))
{
(void) WriteBlobMSBShort(image,(unsigned short)
(next_image->alpha_trait != UndefinedPixelTrait ? 2 : 1));
(void) WriteBlobMSBShort(image,0);
(void) SetPSDSize(&psd_info,image,channel_size);
if (next_image->alpha_trait != UndefinedPixelTrait)
{
(void) WriteBlobMSBShort(image,(unsigned short) -1);
(void) SetPSDSize(&psd_info,image,channel_size);
}
}
else
if (next_image->colorspace != CMYKColorspace)
{
(void) WriteBlobMSBShort(image,(unsigned short)
(next_image->alpha_trait != UndefinedPixelTrait ? 4 : 3));
(void) WriteBlobMSBShort(image,0);
(void) SetPSDSize(&psd_info,image,channel_size);
(void) WriteBlobMSBShort(image,1);
(void) SetPSDSize(&psd_info,image,channel_size);
(void) WriteBlobMSBShort(image,2);
(void) SetPSDSize(&psd_info,image,channel_size);
if (next_image->alpha_trait != UndefinedPixelTrait)
{
(void) WriteBlobMSBShort(image,(unsigned short) -1);
(void) SetPSDSize(&psd_info,image,channel_size);
}
}
else
{
(void) WriteBlobMSBShort(image,(unsigned short)
(next_image->alpha_trait ? 5 : 4));
(void) WriteBlobMSBShort(image,0);
(void) SetPSDSize(&psd_info,image,channel_size);
(void) WriteBlobMSBShort(image,1);
(void) SetPSDSize(&psd_info,image,channel_size);
(void) WriteBlobMSBShort(image,2);
(void) SetPSDSize(&psd_info,image,channel_size);
(void) WriteBlobMSBShort(image,3);
(void) SetPSDSize(&psd_info,image,channel_size);
if (next_image->alpha_trait)
{
(void) WriteBlobMSBShort(image,(unsigned short) -1);
(void) SetPSDSize(&psd_info,image,channel_size);
}
}
(void) WriteBlob(image,4,(const unsigned char *) "8BIM");
(void) WriteBlob(image,4,(const unsigned char *)
CompositeOperatorToPSDBlendMode(next_image->compose));
(void) WriteBlobByte(image,255); /* layer opacity */
(void) WriteBlobByte(image,0);
(void) WriteBlobByte(image,next_image->compose==NoCompositeOp ?
1 << 0x02 : 1); /* layer properties - visible, etc. */
(void) WriteBlobByte(image,0);
property=(const char *) GetImageProperty(next_image,"label",exception);
if (property == (const char *) NULL)
{
char
layer_name[MagickPathExtent];
(void) WriteBlobMSBLong(image,16);
(void) WriteBlobMSBLong(image,0);
(void) WriteBlobMSBLong(image,0);
(void) FormatLocaleString(layer_name,MagickPathExtent,"L%04ld",(long)
layer_count++);
WritePascalString(image,layer_name,4);
}
else
{
size_t
label_length;
label_length=strlen(property);
(void) WriteBlobMSBLong(image,(unsigned int) (label_length+(4-
(label_length % 4))+8));
(void) WriteBlobMSBLong(image,0);
(void) WriteBlobMSBLong(image,0);
WritePascalString(image,property,4);
}
next_image=GetNextImageInList(next_image);
}
/*
Now the image data!
*/
next_image=base_image;
while (next_image != NULL)
{
status=WriteImageChannels(&psd_info,image_info,image,next_image,
MagickTrue,exception);
next_image=GetNextImageInList(next_image);
}
(void) WriteBlobMSBLong(image,0); /* user mask data */
base_image->compression=compression;
}
/*
Write composite image.
*/
if (status != MagickFalse)
status=WriteImageChannels(&psd_info,image_info,image,image,MagickFalse,
exception);
(void) CloseBlob(image);
return(status);
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_5294_0 |
crossvul-cpp_data_good_351_9 | /*
* card-oberthur.c: Support for Oberthur smart cards
* CosmopolIC v5;
*
* Copyright (C) 2001, 2002 Juha Yrjölä <juha.yrjola@iki.fi>
* Copyright (C) 2009 Viktor Tarasov <viktor.tarasov@opentrust.com>,
* OpenTrust <www.opentrust.com>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.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
*
* best view with tabstop=4
*/
#if HAVE_CONFIG_H
#include "config.h"
#endif
#ifdef ENABLE_OPENSSL /* empty file without openssl */
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <openssl/sha.h>
#include <openssl/evp.h>
#include <openssl/rsa.h>
#include <openssl/opensslv.h>
#include "internal.h"
#include "cardctl.h"
#include "pkcs15.h"
#include "gp.h"
#define OBERTHUR_PIN_LOCAL 0x80
#define OBERTHUR_PIN_REFERENCE_USER 0x81
#define OBERTHUR_PIN_REFERENCE_ONETIME 0x82
#define OBERTHUR_PIN_REFERENCE_SO 0x04
#define OBERTHUR_PIN_REFERENCE_PUK 0x84
/* keep OpenSSL 0.9.6 users happy ;-) */
#if OPENSSL_VERSION_NUMBER < 0x00907000L
#define DES_cblock des_cblock
#define DES_key_schedule des_key_schedule
#define DES_set_key_unchecked(a,b) des_set_key_unchecked(a,*b)
#define DES_ecb_encrypt(a,b,c,d) des_ecb_encrypt(a,b,*c,d)
#endif
static struct sc_atr_table oberthur_atrs[] = {
{ "3B:7D:18:00:00:00:31:80:71:8E:64:77:E3:01:00:82:90:00", NULL,
"Oberthur 64k v4/2.1.1", SC_CARD_TYPE_OBERTHUR_64K, 0, NULL },
{ "3B:7D:18:00:00:00:31:80:71:8E:64:77:E3:02:00:82:90:00", NULL,
"Oberthur 64k v4/2.1.1", SC_CARD_TYPE_OBERTHUR_64K, 0, NULL },
{ "3B:7D:11:00:00:00:31:80:71:8E:64:77:E3:01:00:82:90:00", NULL,
"Oberthur 64k v5", SC_CARD_TYPE_OBERTHUR_64K, 0, NULL },
{ "3B:7D:11:00:00:00:31:80:71:8E:64:77:E3:02:00:82:90:00", NULL,
"Oberthur 64k v5/2.2.0", SC_CARD_TYPE_OBERTHUR_64K, 0, NULL },
{ "3B:7B:18:00:00:00:31:C0:64:77:E3:03:00:82:90:00", NULL,
"Oberthur 64k CosmopolIC v5.2/2.2", SC_CARD_TYPE_OBERTHUR_64K, 0, NULL },
{ "3B:FB:11:00:00:81:31:FE:45:00:31:C0:64:77:E9:10:00:00:90:00:6A", NULL,
"OCS ID-One Cosmo Card", SC_CARD_TYPE_OBERTHUR_64K, 0, NULL },
{ NULL, NULL, NULL, 0, 0, NULL }
};
struct auth_senv {
unsigned int algorithm;
int key_file_id;
size_t key_size;
};
struct auth_private_data {
unsigned char aid[SC_MAX_AID_SIZE];
int aid_len;
struct sc_pin_cmd_pin pin_info;
struct auth_senv senv;
long int sn;
};
struct auth_update_component_info {
enum SC_CARDCTL_OBERTHUR_KEY_TYPE type;
unsigned int component;
unsigned char *data;
unsigned int len;
};
static const unsigned char *aidAuthentIC_V5 =
(const unsigned char *)"\xA0\x00\x00\x00\x77\x01\x03\x03\x00\x00\x00\xF1\x00\x00\x00\x02";
static const int lenAidAuthentIC_V5 = 16;
static const char *nameAidAuthentIC_V5 = "AuthentIC v5";
#define OBERTHUR_AUTH_TYPE_PIN 1
#define OBERTHUR_AUTH_TYPE_PUK 2
#define OBERTHUR_AUTH_MAX_LENGTH_PIN 64
#define OBERTHUR_AUTH_MAX_LENGTH_PUK 16
#define SC_OBERTHUR_MAX_ATTR_SIZE 8
#define PUBKEY_512_ASN1_SIZE 0x4A
#define PUBKEY_1024_ASN1_SIZE 0x8C
#define PUBKEY_2048_ASN1_SIZE 0x10E
static unsigned char rsa_der[PUBKEY_2048_ASN1_SIZE];
static int rsa_der_len = 0;
static struct sc_file *auth_current_ef = NULL, *auth_current_df = NULL;
static struct sc_card_operations auth_ops;
static struct sc_card_operations *iso_ops;
static struct sc_card_driver auth_drv = {
"Oberthur AuthentIC.v2/CosmopolIC.v4",
"oberthur",
&auth_ops,
NULL, 0, NULL
};
static int auth_get_pin_reference (struct sc_card *card,
int type, int reference, int cmd, int *out_ref);
static int auth_read_component(struct sc_card *card,
enum SC_CARDCTL_OBERTHUR_KEY_TYPE type, int num,
unsigned char *out, size_t outlen);
static int auth_pin_is_verified(struct sc_card *card, int pin_reference,
int *tries_left);
static int auth_pin_verify(struct sc_card *card, unsigned int type,
struct sc_pin_cmd_data *data, int *tries_left);
static int auth_pin_reset(struct sc_card *card, unsigned int type,
struct sc_pin_cmd_data *data, int *tries_left);
static int auth_create_reference_data (struct sc_card *card,
struct sc_cardctl_oberthur_createpin_info *args);
static int auth_get_serialnr(struct sc_card *card, struct sc_serial_number *serial);
static int auth_select_file(struct sc_card *card, const struct sc_path *in_path,
struct sc_file **file_out);
static int acl_to_ac_byte(struct sc_card *card, const struct sc_acl_entry *e);
static int
auth_finish(struct sc_card *card)
{
free(card->drv_data);
return SC_SUCCESS;
}
static int
auth_select_aid(struct sc_card *card)
{
struct sc_apdu apdu;
unsigned char apdu_resp[SC_MAX_APDU_BUFFER_SIZE];
struct auth_private_data *data = (struct auth_private_data *) card->drv_data;
int rv, ii;
struct sc_path tmp_path;
/* Select Card Manager (to deselect previously selected application) */
rv = gp_select_card_manager(card);
LOG_TEST_RET(card->ctx, rv, "APDU transmit failed");
/* Get smart card serial number */
sc_format_apdu(card, &apdu, SC_APDU_CASE_2_SHORT, 0xCA, 0x9F, 0x7F);
apdu.cla = 0x80;
apdu.le = 0x2D;
apdu.resplen = 0x30;
apdu.resp = apdu_resp;
rv = sc_transmit_apdu(card, &apdu);
LOG_TEST_RET(card->ctx, rv, "APDU transmit failed");
card->serialnr.len = 4;
memcpy(card->serialnr.value, apdu.resp+15, 4);
for (ii=0, data->sn = 0; ii < 4; ii++)
data->sn += (long int)(*(apdu.resp + 15 + ii)) << (3-ii)*8;
sc_log(card->ctx, "serial number %li/0x%lX", data->sn, data->sn);
memset(&tmp_path, 0, sizeof(struct sc_path));
tmp_path.type = SC_PATH_TYPE_DF_NAME;
memcpy(tmp_path.value, aidAuthentIC_V5, lenAidAuthentIC_V5);
tmp_path.len = lenAidAuthentIC_V5;
rv = iso_ops->select_file(card, &tmp_path, NULL);
LOG_TEST_RET(card->ctx, rv, "select parent failed");
sc_format_path("3F00", &tmp_path);
rv = iso_ops->select_file(card, &tmp_path, &auth_current_df);
LOG_TEST_RET(card->ctx, rv, "select parent failed");
sc_format_path("3F00", &card->cache.current_path);
sc_file_dup(&auth_current_ef, auth_current_df);
memcpy(data->aid, aidAuthentIC_V5, lenAidAuthentIC_V5);
data->aid_len = lenAidAuthentIC_V5;
card->name = nameAidAuthentIC_V5;
LOG_FUNC_RETURN(card->ctx, rv);
}
static int
auth_match_card(struct sc_card *card)
{
if (_sc_match_atr(card, oberthur_atrs, &card->type) < 0)
return 0;
else
return 1;
}
static int
auth_init(struct sc_card *card)
{
struct auth_private_data *data;
struct sc_path path;
unsigned long flags;
int rv = 0;
data = calloc(1, sizeof(struct auth_private_data));
if (!data)
LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY);
card->cla = 0x00;
card->drv_data = data;
card->caps |= SC_CARD_CAP_RNG;
card->caps |= SC_CARD_CAP_USE_FCI_AC;
if (auth_select_aid(card)) {
sc_log(card->ctx, "Failed to initialize %s", card->name);
LOG_TEST_RET(card->ctx, SC_ERROR_INVALID_CARD, "Failed to initialize");
}
flags = SC_ALGORITHM_RSA_PAD_PKCS1 | SC_ALGORITHM_RSA_PAD_ISO9796;
flags |= SC_ALGORITHM_RSA_HASH_NONE;
flags |= SC_ALGORITHM_ONBOARD_KEY_GEN;
_sc_card_add_rsa_alg(card, 512, flags, 0);
_sc_card_add_rsa_alg(card, 1024, flags, 0);
_sc_card_add_rsa_alg(card, 2048, flags, 0);
sc_format_path("3F00", &path);
rv = auth_select_file(card, &path, NULL);
LOG_FUNC_RETURN(card->ctx, rv);
}
static void
add_acl_entry(struct sc_card *card, struct sc_file *file, unsigned int op,
unsigned char acl_byte)
{
if ((acl_byte & 0xE0) == 0x60) {
sc_log(card->ctx, "called; op 0x%X; SC_AC_PRO; ref 0x%X", op, acl_byte);
sc_file_add_acl_entry(file, op, SC_AC_PRO, acl_byte);
return;
}
switch (acl_byte) {
case 0x00:
sc_file_add_acl_entry(file, op, SC_AC_NONE, SC_AC_KEY_REF_NONE);
break;
/* User and OneTime PINs are locals */
case 0x21:
case 0x22:
sc_file_add_acl_entry(file, op, SC_AC_CHV, (acl_byte & 0x0F) | OBERTHUR_PIN_LOCAL);
break;
/* Local SOPIN is only for the unblocking. */
case 0x24:
case 0x25:
if (op == SC_AC_OP_PIN_RESET)
sc_file_add_acl_entry(file, op, SC_AC_CHV, 0x84);
else
sc_file_add_acl_entry(file, op, SC_AC_CHV, 0x04);
break;
case 0xFF:
sc_file_add_acl_entry(file, op, SC_AC_NEVER, SC_AC_KEY_REF_NONE);
break;
default:
sc_file_add_acl_entry(file, op, SC_AC_UNKNOWN, SC_AC_KEY_REF_NONE);
break;
}
}
static int
tlv_get(const unsigned char *msg, int len, unsigned char tag,
unsigned char *ret, int *ret_len)
{
int cur = 0;
while (cur < len) {
if (*(msg+cur)==tag) {
int ii, ln = *(msg+cur+1);
if (ln > *ret_len)
return SC_ERROR_WRONG_LENGTH;
for (ii=0; ii<ln; ii++)
*(ret + ii) = *(msg+cur+2+ii);
*ret_len = ln;
return SC_SUCCESS;
}
cur += 2 + *(msg+cur+1);
}
return SC_ERROR_INCORRECT_PARAMETERS;
}
static int
auth_process_fci(struct sc_card *card, struct sc_file *file,
const unsigned char *buf, size_t buflen)
{
unsigned char type, attr[SC_OBERTHUR_MAX_ATTR_SIZE];
int attr_len = sizeof(attr);
LOG_FUNC_CALLED(card->ctx);
attr_len = sizeof(attr);
if (tlv_get(buf, buflen, 0x82, attr, &attr_len))
LOG_FUNC_RETURN(card->ctx, SC_ERROR_UNKNOWN_DATA_RECEIVED);
type = attr[0];
attr_len = sizeof(attr);
if (tlv_get(buf, buflen, 0x83, attr, &attr_len))
LOG_FUNC_RETURN(card->ctx, SC_ERROR_UNKNOWN_DATA_RECEIVED);
file->id = attr[0]*0x100 + attr[1];
attr_len = sizeof(attr);
if (tlv_get(buf, buflen, type==0x01 ? 0x80 : 0x85, attr, &attr_len))
LOG_FUNC_RETURN(card->ctx, SC_ERROR_UNKNOWN_DATA_RECEIVED);
if (attr_len<2 && type != 0x04)
LOG_FUNC_RETURN(card->ctx, SC_ERROR_UNKNOWN_DATA_RECEIVED);
switch (type) {
case 0x01:
file->type = SC_FILE_TYPE_WORKING_EF;
file->ef_structure = SC_FILE_EF_TRANSPARENT;
file->size = attr[0]*0x100 + attr[1];
break;
case 0x04:
file->type = SC_FILE_TYPE_WORKING_EF;
file->ef_structure = SC_FILE_EF_LINEAR_VARIABLE;
file->size = attr[0];
attr_len = sizeof(attr);
if (tlv_get(buf, buflen, 0x82, attr, &attr_len))
LOG_FUNC_RETURN(card->ctx, SC_ERROR_UNKNOWN_DATA_RECEIVED);
if (attr_len!=5)
LOG_FUNC_RETURN(card->ctx, SC_ERROR_UNKNOWN_DATA_RECEIVED);
file->record_length = attr[2]*0x100+attr[3];
file->record_count = attr[4];
break;
case 0x11:
file->type = SC_FILE_TYPE_INTERNAL_EF;
file->ef_structure = SC_CARDCTL_OBERTHUR_KEY_DES;
file->size = attr[0]*0x100 + attr[1];
file->size /= 8;
break;
case 0x12:
file->type = SC_FILE_TYPE_INTERNAL_EF;
file->ef_structure = SC_CARDCTL_OBERTHUR_KEY_RSA_PUBLIC;
file->size = attr[0]*0x100 + attr[1];
if (file->size==512)
file->size = PUBKEY_512_ASN1_SIZE;
else if (file->size==1024)
file->size = PUBKEY_1024_ASN1_SIZE;
else if (file->size==2048)
file->size = PUBKEY_2048_ASN1_SIZE;
else {
sc_log(card->ctx,
"Not supported public key size: %"SC_FORMAT_LEN_SIZE_T"u",
file->size);
LOG_FUNC_RETURN(card->ctx, SC_ERROR_UNKNOWN_DATA_RECEIVED);
}
break;
case 0x14:
file->type = SC_FILE_TYPE_INTERNAL_EF;
file->ef_structure = SC_CARDCTL_OBERTHUR_KEY_RSA_CRT;
file->size = attr[0]*0x100 + attr[1];
break;
case 0x38:
file->type = SC_FILE_TYPE_DF;
file->size = attr[0];
if (SC_SUCCESS != sc_file_set_type_attr(file,attr,attr_len))
LOG_FUNC_RETURN(card->ctx, SC_ERROR_UNKNOWN_DATA_RECEIVED);
break;
default:
LOG_FUNC_RETURN(card->ctx, SC_ERROR_UNKNOWN_DATA_RECEIVED);
}
attr_len = sizeof(attr);
if (tlv_get(buf, buflen, 0x86, attr, &attr_len))
LOG_FUNC_RETURN(card->ctx, SC_ERROR_UNKNOWN_DATA_RECEIVED);
if (attr_len<8)
LOG_FUNC_RETURN(card->ctx, SC_ERROR_UNKNOWN_DATA_RECEIVED);
if (file->type == SC_FILE_TYPE_DF) {
add_acl_entry(card, file, SC_AC_OP_CREATE, attr[0]);
add_acl_entry(card, file, SC_AC_OP_CRYPTO, attr[1]);
add_acl_entry(card, file, SC_AC_OP_LIST_FILES, attr[2]);
add_acl_entry(card, file, SC_AC_OP_DELETE, attr[3]);
add_acl_entry(card, file, SC_AC_OP_PIN_DEFINE, attr[4]);
add_acl_entry(card, file, SC_AC_OP_PIN_CHANGE, attr[5]);
add_acl_entry(card, file, SC_AC_OP_PIN_RESET, attr[6]);
sc_log(card->ctx, "SC_FILE_TYPE_DF:CRYPTO %X", attr[1]);
}
else if (file->type == SC_FILE_TYPE_INTERNAL_EF) { /* EF */
switch (file->ef_structure) {
case SC_CARDCTL_OBERTHUR_KEY_DES:
add_acl_entry(card, file, SC_AC_OP_UPDATE, attr[0]);
add_acl_entry(card, file, SC_AC_OP_PSO_DECRYPT, attr[1]);
add_acl_entry(card, file, SC_AC_OP_PSO_ENCRYPT, attr[2]);
add_acl_entry(card, file, SC_AC_OP_PSO_COMPUTE_CHECKSUM, attr[3]);
add_acl_entry(card, file, SC_AC_OP_PSO_VERIFY_CHECKSUM, attr[4]);
add_acl_entry(card, file, SC_AC_OP_INTERNAL_AUTHENTICATE, attr[5]);
add_acl_entry(card, file, SC_AC_OP_EXTERNAL_AUTHENTICATE, attr[6]);
break;
case SC_CARDCTL_OBERTHUR_KEY_RSA_PUBLIC:
add_acl_entry(card, file, SC_AC_OP_UPDATE, attr[0]);
add_acl_entry(card, file, SC_AC_OP_PSO_ENCRYPT, attr[2]);
add_acl_entry(card, file, SC_AC_OP_PSO_VERIFY_SIGNATURE, attr[4]);
add_acl_entry(card, file, SC_AC_OP_EXTERNAL_AUTHENTICATE, attr[6]);
break;
case SC_CARDCTL_OBERTHUR_KEY_RSA_CRT:
add_acl_entry(card, file, SC_AC_OP_UPDATE, attr[0]);
add_acl_entry(card, file, SC_AC_OP_PSO_DECRYPT, attr[1]);
add_acl_entry(card, file, SC_AC_OP_PSO_COMPUTE_SIGNATURE, attr[3]);
add_acl_entry(card, file, SC_AC_OP_INTERNAL_AUTHENTICATE, attr[5]);
break;
}
}
else {
switch (file->ef_structure) {
case SC_FILE_EF_TRANSPARENT:
add_acl_entry(card, file, SC_AC_OP_WRITE, attr[0]);
add_acl_entry(card, file, SC_AC_OP_UPDATE, attr[1]);
add_acl_entry(card, file, SC_AC_OP_READ, attr[2]);
add_acl_entry(card, file, SC_AC_OP_ERASE, attr[3]);
break;
case SC_FILE_EF_LINEAR_VARIABLE:
add_acl_entry(card, file, SC_AC_OP_WRITE, attr[0]);
add_acl_entry(card, file, SC_AC_OP_UPDATE, attr[1]);
add_acl_entry(card, file, SC_AC_OP_READ, attr[2]);
add_acl_entry(card, file, SC_AC_OP_ERASE, attr[3]);
break;
}
}
file->status = SC_FILE_STATUS_ACTIVATED;
file->magic = SC_FILE_MAGIC;
LOG_FUNC_RETURN(card->ctx, SC_SUCCESS);
}
static int
auth_select_file(struct sc_card *card, const struct sc_path *in_path,
struct sc_file **file_out)
{
struct sc_path path;
struct sc_file *tmp_file = NULL;
size_t offs, ii;
int rv;
LOG_FUNC_CALLED(card->ctx);
assert(card != NULL && in_path != NULL);
memcpy(&path, in_path, sizeof(struct sc_path));
if (!auth_current_df)
return SC_ERROR_OBJECT_NOT_FOUND;
sc_log(card->ctx, "in_path; type=%d, path=%s, out %p",
in_path->type, sc_print_path(in_path), file_out);
sc_log(card->ctx, "current path; type=%d, path=%s",
auth_current_df->path.type, sc_print_path(&auth_current_df->path));
if (auth_current_ef)
sc_log(card->ctx, "current file; type=%d, path=%s",
auth_current_ef->path.type, sc_print_path(&auth_current_ef->path));
if (path.type == SC_PATH_TYPE_PARENT || path.type == SC_PATH_TYPE_FILE_ID) {
sc_file_free(auth_current_ef);
auth_current_ef = NULL;
rv = iso_ops->select_file(card, &path, &tmp_file);
LOG_TEST_RET(card->ctx, rv, "select file failed");
if (!tmp_file)
return SC_ERROR_OBJECT_NOT_FOUND;
if (path.type == SC_PATH_TYPE_PARENT) {
memcpy(&tmp_file->path, &auth_current_df->path, sizeof(struct sc_path));
if (tmp_file->path.len > 2)
tmp_file->path.len -= 2;
sc_file_free(auth_current_df);
sc_file_dup(&auth_current_df, tmp_file);
}
else {
if (tmp_file->type == SC_FILE_TYPE_DF) {
sc_concatenate_path(&tmp_file->path, &auth_current_df->path, &path);
sc_file_free(auth_current_df);
sc_file_dup(&auth_current_df, tmp_file);
}
else {
sc_file_free(auth_current_ef);
sc_file_dup(&auth_current_ef, tmp_file);
sc_concatenate_path(&auth_current_ef->path, &auth_current_df->path, &path);
}
}
if (file_out)
sc_file_dup(file_out, tmp_file);
sc_file_free(tmp_file);
}
else if (path.type == SC_PATH_TYPE_DF_NAME) {
rv = iso_ops->select_file(card, &path, NULL);
if (rv) {
sc_file_free(auth_current_ef);
auth_current_ef = NULL;
}
LOG_TEST_RET(card->ctx, rv, "select file failed");
}
else {
for (offs = 0; offs < path.len && offs < auth_current_df->path.len; offs += 2)
if (path.value[offs] != auth_current_df->path.value[offs] ||
path.value[offs + 1] != auth_current_df->path.value[offs + 1])
break;
sc_log(card->ctx, "offs %"SC_FORMAT_LEN_SIZE_T"u", offs);
if (offs && offs < auth_current_df->path.len) {
size_t deep = auth_current_df->path.len - offs;
sc_log(card->ctx, "deep %"SC_FORMAT_LEN_SIZE_T"u",
deep);
for (ii=0; ii<deep; ii+=2) {
struct sc_path tmp_path;
memcpy(&tmp_path, &auth_current_df->path, sizeof(struct sc_path));
tmp_path.type = SC_PATH_TYPE_PARENT;
rv = auth_select_file (card, &tmp_path, file_out);
LOG_TEST_RET(card->ctx, rv, "select file failed");
}
}
if (path.len - offs > 0) {
struct sc_path tmp_path;
memset(&tmp_path, 0, sizeof(struct sc_path));
tmp_path.type = SC_PATH_TYPE_FILE_ID;
tmp_path.len = 2;
for (ii=0; ii < path.len - offs; ii+=2) {
memcpy(tmp_path.value, path.value + offs + ii, 2);
rv = auth_select_file(card, &tmp_path, file_out);
LOG_TEST_RET(card->ctx, rv, "select file failed");
}
}
else if (path.len - offs == 0 && file_out) {
if (sc_compare_path(&path, &auth_current_df->path))
sc_file_dup(file_out, auth_current_df);
else if (auth_current_ef)
sc_file_dup(file_out, auth_current_ef);
else
LOG_TEST_RET(card->ctx, SC_ERROR_INTERNAL, "No current EF");
}
}
LOG_FUNC_RETURN(card->ctx, 0);
}
static int
auth_list_files(struct sc_card *card, unsigned char *buf, size_t buflen)
{
struct sc_apdu apdu;
unsigned char rbuf[SC_MAX_APDU_BUFFER_SIZE];
int rv;
LOG_FUNC_CALLED(card->ctx);
sc_format_apdu(card, &apdu, SC_APDU_CASE_2_SHORT, 0x34, 0, 0);
apdu.cla = 0x80;
apdu.le = 0x40;
apdu.resplen = sizeof(rbuf);
apdu.resp = rbuf;
rv = sc_transmit_apdu(card, &apdu);
LOG_TEST_RET(card->ctx, rv, "APDU transmit failed");
rv = sc_check_sw(card, apdu.sw1, apdu.sw2);
LOG_TEST_RET(card->ctx, rv, "Card returned error");
if (apdu.resplen == 0x100 && rbuf[0]==0 && rbuf[1]==0)
LOG_FUNC_RETURN(card->ctx, 0);
buflen = buflen < apdu.resplen ? buflen : apdu.resplen;
memcpy(buf, rbuf, buflen);
LOG_FUNC_RETURN(card->ctx, buflen);
}
static int
auth_delete_file(struct sc_card *card, const struct sc_path *path)
{
struct sc_apdu apdu;
unsigned char sbuf[2];
int rv;
char pbuf[SC_MAX_PATH_STRING_SIZE];
LOG_FUNC_CALLED(card->ctx);
rv = sc_path_print(pbuf, sizeof(pbuf), path);
if (rv != SC_SUCCESS)
pbuf[0] = '\0';
sc_log(card->ctx, "path; type=%d, path=%s", path->type, pbuf);
if (path->len < 2) {
sc_log(card->ctx, "Invalid path length");
LOG_FUNC_RETURN(card->ctx, SC_ERROR_INVALID_ARGUMENTS);
}
if (path->len > 2) {
struct sc_path parent = *path;
parent.len -= 2;
parent.type = SC_PATH_TYPE_PATH;
rv = auth_select_file(card, &parent, NULL);
LOG_TEST_RET(card->ctx, rv, "select parent failed ");
}
sbuf[0] = path->value[path->len - 2];
sbuf[1] = path->value[path->len - 1];
if (memcmp(sbuf,"\x00\x00",2)==0 || (memcmp(sbuf,"\xFF\xFF",2)==0) ||
memcmp(sbuf,"\x3F\xFF",2)==0)
LOG_FUNC_RETURN(card->ctx, SC_ERROR_INCORRECT_PARAMETERS);
sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0xE4, 0x02, 0x00);
apdu.lc = 2;
apdu.datalen = 2;
apdu.data = sbuf;
rv = sc_transmit_apdu(card, &apdu);
LOG_TEST_RET(card->ctx, rv, "APDU transmit failed");
if (apdu.sw1==0x6A && apdu.sw2==0x82) {
/* Clean up tDF contents.*/
struct sc_path tmp_path;
int ii, len;
unsigned char lbuf[SC_MAX_APDU_BUFFER_SIZE];
memset(&tmp_path, 0, sizeof(struct sc_path));
tmp_path.type = SC_PATH_TYPE_FILE_ID;
memcpy(tmp_path.value, sbuf, 2);
tmp_path.len = 2;
rv = auth_select_file(card, &tmp_path, NULL);
LOG_TEST_RET(card->ctx, rv, "select DF failed");
len = auth_list_files(card, lbuf, sizeof(lbuf));
LOG_TEST_RET(card->ctx, len, "list DF failed");
for (ii=0; ii<len/2; ii++) {
struct sc_path tmp_path_x;
memset(&tmp_path_x, 0, sizeof(struct sc_path));
tmp_path_x.type = SC_PATH_TYPE_FILE_ID;
tmp_path_x.value[0] = *(lbuf + ii*2);
tmp_path_x.value[1] = *(lbuf + ii*2 + 1);
tmp_path_x.len = 2;
rv = auth_delete_file(card, &tmp_path_x);
LOG_TEST_RET(card->ctx, rv, "delete failed");
}
tmp_path.type = SC_PATH_TYPE_PARENT;
rv = auth_select_file(card, &tmp_path, NULL);
LOG_TEST_RET(card->ctx, rv, "select parent failed");
apdu.p1 = 1;
rv = sc_transmit_apdu(card, &apdu);
}
LOG_TEST_RET(card->ctx, rv, "APDU transmit failed");
rv = sc_check_sw(card, apdu.sw1, apdu.sw2);
LOG_FUNC_RETURN(card->ctx, rv);
}
static int
acl_to_ac_byte(struct sc_card *card, const struct sc_acl_entry *e)
{
unsigned key_ref;
if (e == NULL)
return SC_ERROR_OBJECT_NOT_FOUND;
key_ref = e->key_ref & ~OBERTHUR_PIN_LOCAL;
switch (e->method) {
case SC_AC_NONE:
LOG_FUNC_RETURN(card->ctx, 0);
case SC_AC_CHV:
if (key_ref > 0 && key_ref < 6)
LOG_FUNC_RETURN(card->ctx, (0x20 | key_ref));
else
LOG_FUNC_RETURN(card->ctx, SC_ERROR_INCORRECT_PARAMETERS);
case SC_AC_PRO:
if (((key_ref & 0xE0) != 0x60) || ((key_ref & 0x18) == 0))
LOG_FUNC_RETURN(card->ctx, SC_ERROR_INCORRECT_PARAMETERS);
else
LOG_FUNC_RETURN(card->ctx, key_ref);
case SC_AC_NEVER:
return 0xff;
}
LOG_FUNC_RETURN(card->ctx, SC_ERROR_INCORRECT_PARAMETERS);
}
static int
encode_file_structure_V5(struct sc_card *card, const struct sc_file *file,
unsigned char *buf, size_t *buflen)
{
size_t ii;
int rv=0, size;
unsigned char *p = buf;
unsigned char ops[8] = {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF};
LOG_FUNC_CALLED(card->ctx);
sc_log(card->ctx,
"id %04X; size %"SC_FORMAT_LEN_SIZE_T"u; type 0x%X/0x%X",
file->id, file->size, file->type, file->ef_structure);
if (*buflen < 0x18)
LOG_FUNC_RETURN(card->ctx, SC_ERROR_INCORRECT_PARAMETERS);
p[0] = 0x62, p[1] = 0x16;
p[2] = 0x82, p[3] = 0x02;
rv = 0;
if (file->type == SC_FILE_TYPE_DF) {
p[4] = 0x38;
p[5] = 0x00;
}
else if (file->type == SC_FILE_TYPE_WORKING_EF) {
switch (file->ef_structure) {
case SC_FILE_EF_TRANSPARENT:
p[4] = 0x01;
p[5] = 0x01;
break;
case SC_FILE_EF_LINEAR_VARIABLE:
p[4] = 0x04;
p[5] = 0x01;
break;
default:
rv = SC_ERROR_INVALID_ARGUMENTS;
break;
}
}
else if (file->type == SC_FILE_TYPE_INTERNAL_EF) {
switch (file->ef_structure) {
case SC_CARDCTL_OBERTHUR_KEY_DES:
p[4] = 0x11;
p[5] = 0x00;
break;
case SC_CARDCTL_OBERTHUR_KEY_RSA_PUBLIC:
p[4] = 0x12;
p[5] = 0x00;
break;
case SC_CARDCTL_OBERTHUR_KEY_RSA_CRT:
p[4] = 0x14;
p[5] = 0x00;
break;
default:
rv = -1;
break;
}
}
else
rv = SC_ERROR_INVALID_ARGUMENTS;
if (rv) {
sc_log(card->ctx, "Invalid EF structure 0x%X/0x%X", file->type, file->ef_structure);
LOG_FUNC_RETURN(card->ctx, SC_ERROR_INCORRECT_PARAMETERS);
}
p[6] = 0x83;
p[7] = 0x02;
p[8] = file->id >> 8;
p[9] = file->id & 0xFF;
p[10] = 0x85;
p[11] = 0x02;
size = file->size;
if (file->type == SC_FILE_TYPE_DF) {
size &= 0xFF;
}
else if (file->type == SC_FILE_TYPE_INTERNAL_EF &&
file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_RSA_PUBLIC) {
sc_log(card->ctx, "ef %s","SC_FILE_EF_RSA_PUBLIC");
if (file->size == PUBKEY_512_ASN1_SIZE || file->size == 512)
size = 512;
else if (file->size == PUBKEY_1024_ASN1_SIZE || file->size == 1024)
size = 1024;
else if (file->size == PUBKEY_2048_ASN1_SIZE || file->size == 2048)
size = 2048;
else {
sc_log(card->ctx,
"incorrect RSA size %"SC_FORMAT_LEN_SIZE_T"X",
file->size);
LOG_FUNC_RETURN(card->ctx, SC_ERROR_INCORRECT_PARAMETERS);
}
}
else if (file->type == SC_FILE_TYPE_INTERNAL_EF &&
file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_DES) {
if (file->size == 8 || file->size == 64)
size = 64;
else if (file->size == 16 || file->size == 128)
size = 128;
else if (file->size == 24 || file->size == 192)
size = 192;
else {
sc_log(card->ctx,
"incorrect DES size %"SC_FORMAT_LEN_SIZE_T"u",
file->size);
LOG_FUNC_RETURN(card->ctx, SC_ERROR_INCORRECT_PARAMETERS);
}
}
p[12] = (size >> 8) & 0xFF;
p[13] = size & 0xFF;
p[14] = 0x86;
p[15] = 0x08;
if (file->type == SC_FILE_TYPE_DF) {
ops[0] = SC_AC_OP_CREATE;
ops[1] = SC_AC_OP_CRYPTO;
ops[2] = SC_AC_OP_LIST_FILES;
ops[3] = SC_AC_OP_DELETE;
ops[4] = SC_AC_OP_PIN_DEFINE;
ops[5] = SC_AC_OP_PIN_CHANGE;
ops[6] = SC_AC_OP_PIN_RESET;
}
else if (file->type == SC_FILE_TYPE_WORKING_EF) {
if (file->ef_structure == SC_FILE_EF_TRANSPARENT) {
sc_log(card->ctx, "SC_FILE_EF_TRANSPARENT");
ops[0] = SC_AC_OP_WRITE;
ops[1] = SC_AC_OP_UPDATE;
ops[2] = SC_AC_OP_READ;
ops[3] = SC_AC_OP_ERASE;
}
else if (file->ef_structure == SC_FILE_EF_LINEAR_VARIABLE) {
sc_log(card->ctx, "SC_FILE_EF_LINEAR_VARIABLE");
ops[0] = SC_AC_OP_WRITE;
ops[1] = SC_AC_OP_UPDATE;
ops[2] = SC_AC_OP_READ;
ops[3] = SC_AC_OP_ERASE;
}
}
else if (file->type == SC_FILE_TYPE_INTERNAL_EF) {
if (file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_DES) {
sc_log(card->ctx, "EF_DES");
ops[0] = SC_AC_OP_UPDATE;
ops[1] = SC_AC_OP_PSO_DECRYPT;
ops[2] = SC_AC_OP_PSO_ENCRYPT;
ops[3] = SC_AC_OP_PSO_COMPUTE_CHECKSUM;
ops[4] = SC_AC_OP_PSO_VERIFY_CHECKSUM;
ops[5] = SC_AC_OP_INTERNAL_AUTHENTICATE;
ops[6] = SC_AC_OP_EXTERNAL_AUTHENTICATE;
}
else if (file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_RSA_PUBLIC) {
sc_log(card->ctx, "EF_RSA_PUBLIC");
ops[0] = SC_AC_OP_UPDATE;
ops[2] = SC_AC_OP_PSO_ENCRYPT;
ops[4] = SC_AC_OP_PSO_VERIFY_SIGNATURE;
ops[6] = SC_AC_OP_EXTERNAL_AUTHENTICATE;
}
else if (file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_RSA_CRT) {
sc_log(card->ctx, "EF_RSA_PRIVATE");
ops[0] = SC_AC_OP_UPDATE;
ops[1] = SC_AC_OP_PSO_DECRYPT;
ops[3] = SC_AC_OP_PSO_COMPUTE_SIGNATURE;
ops[5] = SC_AC_OP_INTERNAL_AUTHENTICATE;
}
}
for (ii = 0; ii < sizeof(ops); ii++) {
const struct sc_acl_entry *entry;
p[16+ii] = 0xFF;
if (ops[ii]==0xFF)
continue;
entry = sc_file_get_acl_entry(file, ops[ii]);
rv = acl_to_ac_byte(card,entry);
LOG_TEST_RET(card->ctx, rv, "Invalid ACL");
p[16+ii] = rv;
}
*buflen = 0x18;
LOG_FUNC_RETURN(card->ctx, SC_SUCCESS);
}
static int
auth_create_file(struct sc_card *card, struct sc_file *file)
{
struct sc_apdu apdu;
struct sc_path path;
int rv, rec_nr;
unsigned char sbuf[0x18];
size_t sendlen = sizeof(sbuf);
char pbuf[SC_MAX_PATH_STRING_SIZE];
LOG_FUNC_CALLED(card->ctx);
rv = sc_path_print(pbuf, sizeof(pbuf), &file->path);
if (rv != SC_SUCCESS)
pbuf[0] = '\0';
sc_log(card->ctx, " create path=%s", pbuf);
sc_log(card->ctx,
"id %04X; size %"SC_FORMAT_LEN_SIZE_T"u; type 0x%X; ef 0x%X",
file->id, file->size, file->type, file->ef_structure);
if (file->id==0x0000 || file->id==0xFFFF || file->id==0x3FFF)
LOG_FUNC_RETURN(card->ctx, SC_ERROR_INVALID_ARGUMENTS);
rv = sc_path_print(pbuf, sizeof(pbuf), &card->cache.current_path);
if (rv != SC_SUCCESS)
pbuf[0] = '\0';
if (file->path.len) {
memcpy(&path, &file->path, sizeof(path));
if (path.len>2)
path.len -= 2;
if (auth_select_file(card, &path, NULL)) {
sc_log(card->ctx, "Cannot select parent DF.");
LOG_FUNC_RETURN(card->ctx, SC_ERROR_INVALID_ARGUMENTS);
}
}
rv = encode_file_structure_V5(card, file, sbuf, &sendlen);
LOG_TEST_RET(card->ctx, rv, "File structure encoding failed");
if (file->type != SC_FILE_TYPE_DF && file->ef_structure != SC_FILE_EF_TRANSPARENT)
rec_nr = file->record_count;
else
rec_nr = 0;
sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0xE0, 0x00, rec_nr);
apdu.data = sbuf;
apdu.datalen = sendlen;
apdu.lc = sendlen;
rv = sc_transmit_apdu(card, &apdu);
LOG_TEST_RET(card->ctx, rv, "APDU transmit failed");
rv = sc_check_sw(card, apdu.sw1, apdu.sw2);
LOG_TEST_RET(card->ctx, rv, "Card returned error");
/* select created DF. */
if (file->type == SC_FILE_TYPE_DF) {
struct sc_path tmp_path;
struct sc_file *df_file = NULL;
memset(&tmp_path, 0, sizeof(struct sc_path));
tmp_path.type = SC_PATH_TYPE_FILE_ID;
tmp_path.value[0] = file->id >> 8;
tmp_path.value[1] = file->id & 0xFF;
tmp_path.len = 2;
rv = auth_select_file(card, &tmp_path, &df_file);
sc_log(card->ctx, "rv %i", rv);
}
sc_file_free(auth_current_ef);
sc_file_dup(&auth_current_ef, file);
LOG_FUNC_RETURN(card->ctx, rv);
}
static int
auth_set_security_env(struct sc_card *card,
const struct sc_security_env *env, int se_num)
{
struct auth_senv *auth_senv = &((struct auth_private_data *) card->drv_data)->senv;
struct sc_apdu apdu;
long unsigned pads = env->algorithm_flags & SC_ALGORITHM_RSA_PADS;
long unsigned supported_pads = SC_ALGORITHM_RSA_PAD_PKCS1 | SC_ALGORITHM_RSA_PAD_ISO9796;
int rv;
unsigned char rsa_sbuf[3] = {
0x80, 0x01, 0xFF
};
unsigned char des_sbuf[13] = {
0x80, 0x01, 0x01,
0x87, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
};
LOG_FUNC_CALLED(card->ctx);
sc_log(card->ctx,
"op %i; path %s; key_ref 0x%X; algos 0x%X; flags 0x%lX",
env->operation, sc_print_path(&env->file_ref), env->key_ref[0],
env->algorithm_flags, env->flags);
memset(auth_senv, 0, sizeof(struct auth_senv));
if (!(env->flags & SC_SEC_ENV_FILE_REF_PRESENT))
LOG_TEST_RET(card->ctx, SC_ERROR_INTERNAL, "Key file is not selected.");
switch (env->algorithm) {
case SC_ALGORITHM_DES:
case SC_ALGORITHM_3DES:
sc_log(card->ctx,
"algo SC_ALGORITHM_xDES: ref %X, flags %lX",
env->algorithm_ref, env->flags);
if (env->operation == SC_SEC_OPERATION_DECIPHER) {
sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x22, 0x41, 0xB8);
apdu.lc = 3;
apdu.data = des_sbuf;
apdu.datalen = 3;
}
else {
sc_log(card->ctx, "Invalid crypto operation: %X", env->operation);
LOG_TEST_RET(card->ctx, SC_ERROR_NOT_SUPPORTED, "Invalid crypto operation");
}
break;
case SC_ALGORITHM_RSA:
sc_log(card->ctx, "algo SC_ALGORITHM_RSA");
if (env->algorithm_flags & SC_ALGORITHM_RSA_HASHES) {
LOG_TEST_RET(card->ctx, SC_ERROR_NOT_SUPPORTED, "No support for hashes.");
}
if (pads & (~supported_pads)) {
sc_log(card->ctx, "No support for PAD %lX", pads);
LOG_TEST_RET(card->ctx, SC_ERROR_NOT_SUPPORTED, "No padding support.");
}
if (env->operation == SC_SEC_OPERATION_SIGN) {
rsa_sbuf[2] = 0x11;
sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x22, 0x41, 0xB6);
apdu.lc = sizeof(rsa_sbuf);
apdu.datalen = sizeof(rsa_sbuf);
apdu.data = rsa_sbuf;
}
else if (env->operation == SC_SEC_OPERATION_DECIPHER) {
rsa_sbuf[2] = 0x11;
sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x22, 0x41, 0xB8);
apdu.lc = sizeof(rsa_sbuf);
apdu.datalen = sizeof(rsa_sbuf);
apdu.data = rsa_sbuf;
}
else {
sc_log(card->ctx, "Invalid crypto operation: %X", env->operation);
LOG_FUNC_RETURN(card->ctx, SC_ERROR_NOT_SUPPORTED);
}
break;
default:
LOG_TEST_RET(card->ctx, SC_ERROR_NOT_SUPPORTED, "Invalid crypto algorithm supplied");
}
rv = sc_transmit_apdu(card, &apdu);
LOG_TEST_RET(card->ctx, rv, "APDU transmit failed");
rv = sc_check_sw(card, apdu.sw1, apdu.sw2);
LOG_TEST_RET(card->ctx, rv, "Card returned error");
auth_senv->algorithm = env->algorithm;
LOG_FUNC_RETURN(card->ctx, rv);
}
static int
auth_restore_security_env(struct sc_card *card, int se_num)
{
return SC_SUCCESS;
}
static int
auth_compute_signature(struct sc_card *card, const unsigned char *in, size_t ilen,
unsigned char * out, size_t olen)
{
struct sc_apdu apdu;
unsigned char resp[SC_MAX_APDU_BUFFER_SIZE];
int rv;
if (!card || !in || !out) {
return SC_ERROR_INVALID_ARGUMENTS;
}
else if (ilen > 96) {
sc_log(card->ctx,
"Illegal input length %"SC_FORMAT_LEN_SIZE_T"u",
ilen);
LOG_TEST_RET(card->ctx, SC_ERROR_INVALID_ARGUMENTS, "Illegal input length");
}
LOG_FUNC_CALLED(card->ctx);
sc_log(card->ctx,
"inlen %"SC_FORMAT_LEN_SIZE_T"u, outlen %"SC_FORMAT_LEN_SIZE_T"u",
ilen, olen);
sc_format_apdu(card, &apdu, SC_APDU_CASE_4_SHORT, 0x2A, 0x9E, 0x9A);
apdu.datalen = ilen;
apdu.data = in;
apdu.lc = ilen;
apdu.le = olen > 256 ? 256 : olen;
apdu.resp = resp;
apdu.resplen = olen;
rv = sc_transmit_apdu(card, &apdu);
LOG_TEST_RET(card->ctx, rv, "APDU transmit failed");
rv = sc_check_sw(card, apdu.sw1, apdu.sw2);
LOG_TEST_RET(card->ctx, rv, "Compute signature failed");
if (apdu.resplen > olen) {
sc_log(card->ctx,
"Compute signature failed: invalid response length %"SC_FORMAT_LEN_SIZE_T"u",
apdu.resplen);
LOG_FUNC_RETURN(card->ctx, SC_ERROR_CARD_CMD_FAILED);
}
memcpy(out, apdu.resp, apdu.resplen);
LOG_FUNC_RETURN(card->ctx, apdu.resplen);
}
static int
auth_decipher(struct sc_card *card, const unsigned char *in, size_t inlen,
unsigned char *out, size_t outlen)
{
struct sc_apdu apdu;
unsigned char resp[SC_MAX_APDU_BUFFER_SIZE];
int rv, _inlen = inlen;
LOG_FUNC_CALLED(card->ctx);
sc_log(card->ctx,
"crgram_len %"SC_FORMAT_LEN_SIZE_T"u; outlen %"SC_FORMAT_LEN_SIZE_T"u",
inlen, outlen);
if (!out || !outlen || inlen > SC_MAX_APDU_BUFFER_SIZE)
LOG_FUNC_RETURN(card->ctx, SC_ERROR_INVALID_ARGUMENTS);
sc_format_apdu(card, &apdu, SC_APDU_CASE_4_SHORT, 0x2A, 0x80, 0x86);
sc_log(card->ctx, "algorithm SC_ALGORITHM_RSA");
if (inlen % 64) {
rv = SC_ERROR_INVALID_ARGUMENTS;
goto done;
}
_inlen = inlen;
if (_inlen == 256) {
apdu.cla |= 0x10;
apdu.data = in;
apdu.datalen = 8;
apdu.resp = resp;
apdu.resplen = SC_MAX_APDU_BUFFER_SIZE;
apdu.lc = 8;
apdu.le = 256;
rv = sc_transmit_apdu(card, &apdu);
sc_log(card->ctx, "rv %i", rv);
LOG_TEST_RET(card->ctx, rv, "APDU transmit failed");
rv = sc_check_sw(card, apdu.sw1, apdu.sw2);
LOG_TEST_RET(card->ctx, rv, "Card returned error");
_inlen -= 8;
in += 8;
apdu.cla &= ~0x10;
}
apdu.data = in;
apdu.datalen = _inlen;
apdu.resp = resp;
apdu.resplen = SC_MAX_APDU_BUFFER_SIZE;
apdu.lc = _inlen;
apdu.le = _inlen;
rv = sc_transmit_apdu(card, &apdu);
sc_log(card->ctx, "rv %i", rv);
LOG_TEST_RET(card->ctx, rv, "APDU transmit failed");
rv = sc_check_sw(card, apdu.sw1, apdu.sw2);
sc_log(card->ctx, "rv %i", rv);
LOG_TEST_RET(card->ctx, rv, "Card returned error");
if (outlen > apdu.resplen)
outlen = apdu.resplen;
memcpy(out, apdu.resp, outlen);
rv = outlen;
done:
LOG_FUNC_RETURN(card->ctx, rv);
}
/* Return the default AAK for this type of card */
static int
auth_get_default_key(struct sc_card *card, struct sc_cardctl_default_key *data)
{
LOG_FUNC_RETURN(card->ctx, SC_ERROR_NO_DEFAULT_KEY);
}
static int
auth_encode_exponent(unsigned long exponent, unsigned char *buff, size_t buff_len)
{
int shift;
size_t ii;
for (shift=0; exponent >> (shift+8); shift += 8)
;
for (ii = 0; ii<buff_len && shift>=0 ; ii++, shift-=8)
*(buff + ii) = (exponent >> shift) & 0xFF;
if (ii==buff_len)
return 0;
else
return ii;
}
/* Generate key on-card */
static int
auth_generate_key(struct sc_card *card, int use_sm,
struct sc_cardctl_oberthur_genkey_info *data)
{
struct sc_apdu apdu;
unsigned char sbuf[SC_MAX_APDU_BUFFER_SIZE];
struct sc_path tmp_path;
int rv = 0;
LOG_FUNC_CALLED(card->ctx);
if (data->key_bits < 512 || data->key_bits > 2048 ||
(data->key_bits%0x20)!=0) {
LOG_TEST_RET(card->ctx, SC_ERROR_INVALID_ARGUMENTS, "Illegal key length");
}
sbuf[0] = (data->id_pub >> 8) & 0xFF;
sbuf[1] = data->id_pub & 0xFF;
sbuf[2] = (data->id_prv >> 8) & 0xFF;
sbuf[3] = data->id_prv & 0xFF;
if (data->exponent != 0x10001) {
rv = auth_encode_exponent(data->exponent, &sbuf[5],SC_MAX_APDU_BUFFER_SIZE-6);
LOG_TEST_RET(card->ctx, rv, "Cannot encode exponent");
sbuf[4] = rv;
rv++;
}
sc_format_apdu(card, &apdu, SC_APDU_CASE_4_SHORT, 0x46, 0x00, 0x00);
apdu.resp = calloc(1, data->key_bits/8+8);
if (!apdu.resp)
LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY);
apdu.resplen = data->key_bits/8+8;
apdu.lc = rv + 4;
apdu.le = data->key_bits/8;
apdu.data = sbuf;
apdu.datalen = rv + 4;
rv = sc_transmit_apdu(card, &apdu);
LOG_TEST_RET(card->ctx, rv, "APDU transmit failed");
rv = sc_check_sw(card, apdu.sw1, apdu.sw2);
LOG_TEST_RET(card->ctx, rv, "Card returned error");
memset(&tmp_path, 0, sizeof(struct sc_path));
tmp_path.type = SC_PATH_TYPE_FILE_ID;
tmp_path.len = 2;
memcpy(tmp_path.value, sbuf, 2);
rv = auth_select_file(card, &tmp_path, NULL);
LOG_TEST_RET(card->ctx, rv, "cannot select public key");
rv = auth_read_component(card, SC_CARDCTL_OBERTHUR_KEY_RSA_PUBLIC,
1, apdu.resp, data->key_bits/8);
LOG_TEST_RET(card->ctx, rv, "auth_read_component() returned error");
apdu.resplen = rv;
if (data->pubkey) {
if (data->pubkey_len < apdu.resplen)
LOG_FUNC_RETURN(card->ctx, SC_ERROR_INVALID_ARGUMENTS);
memcpy(data->pubkey,apdu.resp,apdu.resplen);
}
data->pubkey_len = apdu.resplen;
free(apdu.resp);
sc_log(card->ctx, "resulted public key len %"SC_FORMAT_LEN_SIZE_T"u",
apdu.resplen);
LOG_FUNC_RETURN(card->ctx, SC_SUCCESS);
}
static int
auth_update_component(struct sc_card *card, struct auth_update_component_info *args)
{
struct sc_apdu apdu;
unsigned char sbuf[SC_MAX_APDU_BUFFER_SIZE + 0x10];
unsigned char ins, p1, p2;
int rv, len;
LOG_FUNC_CALLED(card->ctx);
if (args->len > sizeof(sbuf) || args->len > 0x100)
LOG_FUNC_RETURN(card->ctx, SC_ERROR_INVALID_ARGUMENTS);
sc_log(card->ctx, "nn %i; len %i", args->component, args->len);
ins = 0xD8;
p1 = args->component;
p2 = 0x04;
len = 0;
sbuf[len++] = args->type;
sbuf[len++] = args->len;
memcpy(sbuf + len, args->data, args->len);
len += args->len;
if (args->type == SC_CARDCTL_OBERTHUR_KEY_DES) {
int outl;
const unsigned char in[8] = {0,0,0,0,0,0,0,0};
unsigned char out[8];
EVP_CIPHER_CTX * ctx = NULL;
if (args->len!=8 && args->len!=24)
LOG_FUNC_RETURN(card->ctx, SC_ERROR_INVALID_ARGUMENTS);
ctx = EVP_CIPHER_CTX_new();
if (ctx == NULL)
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL,SC_ERROR_OUT_OF_MEMORY);
p2 = 0;
if (args->len == 24)
EVP_EncryptInit_ex(ctx, EVP_des_ede(), NULL, args->data, NULL);
else
EVP_EncryptInit_ex(ctx, EVP_des_ecb(), NULL, args->data, NULL);
rv = EVP_EncryptUpdate(ctx, out, &outl, in, 8);
EVP_CIPHER_CTX_free(ctx);
if (rv == 0) {
sc_log(card->ctx, "OpenSSL encryption error.");
LOG_FUNC_RETURN(card->ctx, SC_ERROR_INTERNAL);
}
sbuf[len++] = 0x03;
memcpy(sbuf + len, out, 3);
len += 3;
}
else {
sbuf[len++] = 0;
}
sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, ins, p1, p2);
apdu.cla |= 0x80;
apdu.data = sbuf;
apdu.datalen = len;
apdu.lc = len;
if (args->len == 0x100) {
sbuf[0] = args->type;
sbuf[1] = 0x20;
memcpy(sbuf + 2, args->data, 0x20);
sbuf[0x22] = 0;
apdu.cla |= 0x10;
apdu.data = sbuf;
apdu.datalen = 0x23;
apdu.lc = 0x23;
rv = sc_transmit_apdu(card, &apdu);
apdu.cla &= ~0x10;
LOG_TEST_RET(card->ctx, rv, "APDU transmit failed");
sbuf[0] = args->type;
sbuf[1] = 0xE0;
memcpy(sbuf + 2, args->data + 0x20, 0xE0);
sbuf[0xE2] = 0;
apdu.data = sbuf;
apdu.datalen = 0xE3;
apdu.lc = 0xE3;
}
rv = sc_transmit_apdu(card, &apdu);
sc_mem_clear(sbuf, sizeof(sbuf));
LOG_TEST_RET(card->ctx, rv, "APDU transmit failed");
rv = sc_check_sw(card, apdu.sw1, apdu.sw2);
LOG_FUNC_RETURN(card->ctx, rv);
}
static int
auth_update_key(struct sc_card *card, struct sc_cardctl_oberthur_updatekey_info *info)
{
int rv, ii;
LOG_FUNC_CALLED(card->ctx);
if (info->data_len != sizeof(void *) || !info->data)
LOG_FUNC_RETURN(card->ctx, SC_ERROR_INVALID_ARGUMENTS);
if (info->type == SC_CARDCTL_OBERTHUR_KEY_RSA_CRT) {
struct sc_pkcs15_prkey_rsa *rsa = (struct sc_pkcs15_prkey_rsa *)info->data;
struct sc_pkcs15_bignum bn[5];
sc_log(card->ctx, "Import RSA CRT");
bn[0] = rsa->p;
bn[1] = rsa->q;
bn[2] = rsa->iqmp;
bn[3] = rsa->dmp1;
bn[4] = rsa->dmq1;
for (ii=0;ii<5;ii++) {
struct auth_update_component_info args;
memset(&args, 0, sizeof(args));
args.type = SC_CARDCTL_OBERTHUR_KEY_RSA_CRT;
args.component = ii+1;
args.data = bn[ii].data;
args.len = bn[ii].len;
rv = auth_update_component(card, &args);
LOG_TEST_RET(card->ctx, rv, "Update RSA component failed");
}
}
else if (info->type == SC_CARDCTL_OBERTHUR_KEY_DES) {
rv = SC_ERROR_NOT_SUPPORTED;
}
else {
rv = SC_ERROR_INVALID_DATA;
}
LOG_FUNC_RETURN(card->ctx, rv);
}
static int
auth_card_ctl(struct sc_card *card, unsigned long cmd, void *ptr)
{
switch (cmd) {
case SC_CARDCTL_GET_DEFAULT_KEY:
return auth_get_default_key(card,
(struct sc_cardctl_default_key *) ptr);
case SC_CARDCTL_OBERTHUR_GENERATE_KEY:
return auth_generate_key(card, 0,
(struct sc_cardctl_oberthur_genkey_info *) ptr);
case SC_CARDCTL_OBERTHUR_UPDATE_KEY:
return auth_update_key(card,
(struct sc_cardctl_oberthur_updatekey_info *) ptr);
case SC_CARDCTL_OBERTHUR_CREATE_PIN:
return auth_create_reference_data(card,
(struct sc_cardctl_oberthur_createpin_info *) ptr);
case SC_CARDCTL_GET_SERIALNR:
return auth_get_serialnr(card, (struct sc_serial_number *)ptr);
case SC_CARDCTL_LIFECYCLE_GET:
case SC_CARDCTL_LIFECYCLE_SET:
return SC_ERROR_NOT_SUPPORTED;
default:
LOG_FUNC_RETURN(card->ctx, SC_ERROR_NOT_SUPPORTED);
}
}
static int
auth_read_component(struct sc_card *card, enum SC_CARDCTL_OBERTHUR_KEY_TYPE type,
int num, unsigned char *out, size_t outlen)
{
struct sc_apdu apdu;
int rv;
unsigned char resp[256];
LOG_FUNC_CALLED(card->ctx);
sc_log(card->ctx, "num %i, outlen %"SC_FORMAT_LEN_SIZE_T"u, type %i",
num, outlen, type);
if (!outlen || type!=SC_CARDCTL_OBERTHUR_KEY_RSA_PUBLIC)
LOG_FUNC_RETURN(card->ctx, SC_ERROR_INCORRECT_PARAMETERS);
sc_format_apdu(card, &apdu, SC_APDU_CASE_2_SHORT, 0xB4, num, 0x00);
apdu.cla |= 0x80;
apdu.le = outlen;
apdu.resp = resp;
apdu.resplen = sizeof(resp);
rv = sc_transmit_apdu(card, &apdu);
LOG_TEST_RET(card->ctx, rv, "APDU transmit failed");
rv = sc_check_sw(card, apdu.sw1, apdu.sw2);
LOG_TEST_RET(card->ctx, rv, "Card returned error");
if (outlen < apdu.resplen)
LOG_FUNC_RETURN(card->ctx, SC_ERROR_WRONG_LENGTH);
memcpy(out, apdu.resp, apdu.resplen);
LOG_FUNC_RETURN(card->ctx, apdu.resplen);
}
static int
auth_get_pin_reference (struct sc_card *card, int type, int reference, int cmd, int *out_ref)
{
if (!out_ref)
LOG_FUNC_RETURN(card->ctx, SC_ERROR_INVALID_ARGUMENTS);
switch (type) {
case SC_AC_CHV:
if (reference != 1 && reference != 2 && reference != 4)
LOG_FUNC_RETURN(card->ctx, SC_ERROR_INVALID_PIN_REFERENCE);
*out_ref = reference;
if (reference == 1 || reference == 4)
if (cmd == SC_PIN_CMD_VERIFY)
*out_ref |= 0x80;
break;
default:
LOG_FUNC_RETURN(card->ctx, SC_ERROR_INVALID_ARGUMENTS);
}
LOG_FUNC_RETURN(card->ctx, SC_SUCCESS);
}
static void
auth_init_pin_info(struct sc_card *card, struct sc_pin_cmd_pin *pin,
unsigned int type)
{
pin->offset = 0;
pin->pad_char = 0xFF;
pin->encoding = SC_PIN_ENCODING_ASCII;
if (type == OBERTHUR_AUTH_TYPE_PIN) {
pin->max_length = OBERTHUR_AUTH_MAX_LENGTH_PIN;
pin->pad_length = OBERTHUR_AUTH_MAX_LENGTH_PIN;
}
else {
pin->max_length = OBERTHUR_AUTH_MAX_LENGTH_PUK;
pin->pad_length = OBERTHUR_AUTH_MAX_LENGTH_PUK;
}
}
static int
auth_pin_verify_pinpad(struct sc_card *card, int pin_reference, int *tries_left)
{
struct sc_card_driver *iso_drv = sc_get_iso7816_driver();
struct sc_pin_cmd_data pin_cmd;
struct sc_apdu apdu;
unsigned char ffs1[0x100];
int rv;
LOG_FUNC_CALLED(card->ctx);
memset(ffs1, 0xFF, sizeof(ffs1));
memset(&pin_cmd, 0, sizeof(pin_cmd));
rv = auth_pin_is_verified(card, pin_reference, tries_left);
sc_log(card->ctx, "auth_pin_is_verified returned rv %i", rv);
/* Return SUCCESS without verifying if
* PIN has been already verified and PIN pad has to be used. */
if (!rv)
LOG_FUNC_RETURN(card->ctx, rv);
pin_cmd.flags |= SC_PIN_CMD_NEED_PADDING;
/* For Oberthur card, PIN command data length has to be 0x40.
* In PCSC10 v2.06 the upper limit of pin.max_length is 8.
*
* The standard sc_build_pin() throws an error when 'pin.len > pin.max_length' .
* So, let's build our own APDU.
*/
sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x20, 0x00, pin_reference);
apdu.lc = OBERTHUR_AUTH_MAX_LENGTH_PIN;
apdu.datalen = OBERTHUR_AUTH_MAX_LENGTH_PIN;
apdu.data = ffs1;
pin_cmd.apdu = &apdu;
pin_cmd.pin_type = SC_AC_CHV;
pin_cmd.cmd = SC_PIN_CMD_VERIFY;
pin_cmd.flags |= SC_PIN_CMD_USE_PINPAD;
pin_cmd.pin_reference = pin_reference;
if (pin_cmd.pin1.min_length < 4)
pin_cmd.pin1.min_length = 4;
pin_cmd.pin1.max_length = 8;
pin_cmd.pin1.encoding = SC_PIN_ENCODING_ASCII;
pin_cmd.pin1.offset = 5;
pin_cmd.pin1.data = ffs1;
pin_cmd.pin1.len = OBERTHUR_AUTH_MAX_LENGTH_PIN;
pin_cmd.pin1.pad_length = OBERTHUR_AUTH_MAX_LENGTH_PIN;
rv = iso_drv->ops->pin_cmd(card, &pin_cmd, tries_left);
LOG_TEST_RET(card->ctx, rv, "PIN CMD 'VERIFY' with pinpad failed");
LOG_FUNC_RETURN(card->ctx, rv);
}
static int
auth_pin_verify(struct sc_card *card, unsigned int type,
struct sc_pin_cmd_data *data, int *tries_left)
{
struct sc_card_driver *iso_drv = sc_get_iso7816_driver();
int rv;
LOG_FUNC_CALLED(card->ctx);
if (type != SC_AC_CHV)
LOG_TEST_RET(card->ctx, SC_ERROR_NOT_SUPPORTED, "PIN type other then SC_AC_CHV is not supported");
data->flags |= SC_PIN_CMD_NEED_PADDING;
auth_init_pin_info(card, &data->pin1, OBERTHUR_AUTH_TYPE_PIN);
/* User PIN is always local. */
if (data->pin_reference == OBERTHUR_PIN_REFERENCE_USER
|| data->pin_reference == OBERTHUR_PIN_REFERENCE_ONETIME)
data->pin_reference |= OBERTHUR_PIN_LOCAL;
rv = auth_pin_is_verified(card, data->pin_reference, tries_left);
sc_log(card->ctx, "auth_pin_is_verified returned rv %i", rv);
/* Return if only PIN status has been asked. */
if (data->pin1.data && !data->pin1.len)
LOG_FUNC_RETURN(card->ctx, rv);
/* Return SUCCESS without verifying if
* PIN has been already verified and PIN pad has to be used. */
if (!rv && !data->pin1.data && !data->pin1.len)
LOG_FUNC_RETURN(card->ctx, rv);
if (!data->pin1.data && !data->pin1.len)
rv = auth_pin_verify_pinpad(card, data->pin_reference, tries_left);
else
rv = iso_drv->ops->pin_cmd(card, data, tries_left);
LOG_FUNC_RETURN(card->ctx, rv);
}
static int
auth_pin_is_verified(struct sc_card *card, int pin_reference, int *tries_left)
{
struct sc_apdu apdu;
int rv;
sc_format_apdu(card, &apdu, SC_APDU_CASE_1, 0x20, 0, pin_reference);
rv = sc_transmit_apdu(card, &apdu);
LOG_TEST_RET(card->ctx, rv, "APDU transmit failed");
if (tries_left && apdu.sw1 == 0x63 && (apdu.sw2 & 0xF0) == 0xC0)
*tries_left = apdu.sw2 & 0x0F;
/* Replace 'no tries left' with 'auth method blocked' */
if (apdu.sw1 == 0x63 && apdu.sw2 == 0xC0) {
apdu.sw1 = 0x69;
apdu.sw2 = 0x83;
}
rv = sc_check_sw(card, apdu.sw1, apdu.sw2);
return rv;
}
static int
auth_pin_change_pinpad(struct sc_card *card, struct sc_pin_cmd_data *data,
int *tries_left)
{
struct sc_card_driver *iso_drv = sc_get_iso7816_driver();
struct sc_pin_cmd_data pin_cmd;
struct sc_apdu apdu;
unsigned char ffs1[0x100];
unsigned char ffs2[0x100];
int rv, pin_reference;
LOG_FUNC_CALLED(card->ctx);
pin_reference = data->pin_reference & ~OBERTHUR_PIN_LOCAL;
memset(ffs1, 0xFF, sizeof(ffs1));
memset(ffs2, 0xFF, sizeof(ffs2));
memset(&pin_cmd, 0, sizeof(pin_cmd));
if (data->pin1.len > OBERTHUR_AUTH_MAX_LENGTH_PIN)
LOG_TEST_RET(card->ctx, SC_ERROR_INVALID_ARGUMENTS, "'PIN CHANGE' failed");
if (data->pin1.data && data->pin1.len)
memcpy(ffs1, data->pin1.data, data->pin1.len);
pin_cmd.flags |= SC_PIN_CMD_NEED_PADDING;
sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x24, 0x00, pin_reference);
apdu.lc = OBERTHUR_AUTH_MAX_LENGTH_PIN * 2;
apdu.datalen = OBERTHUR_AUTH_MAX_LENGTH_PIN * 2;
apdu.data = ffs1;
pin_cmd.apdu = &apdu;
pin_cmd.pin_type = SC_AC_CHV;
pin_cmd.cmd = SC_PIN_CMD_CHANGE;
pin_cmd.flags |= SC_PIN_CMD_USE_PINPAD;
pin_cmd.pin_reference = pin_reference;
if (pin_cmd.pin1.min_length < 4)
pin_cmd.pin1.min_length = 4;
pin_cmd.pin1.max_length = 8;
pin_cmd.pin1.encoding = SC_PIN_ENCODING_ASCII;
pin_cmd.pin1.offset = 5 + OBERTHUR_AUTH_MAX_LENGTH_PIN;
pin_cmd.pin1.data = ffs1;
pin_cmd.pin1.len = OBERTHUR_AUTH_MAX_LENGTH_PIN;
pin_cmd.pin1.pad_length = 0;
memcpy(&pin_cmd.pin2, &pin_cmd.pin1, sizeof(pin_cmd.pin2));
pin_cmd.pin1.offset = 5;
pin_cmd.pin2.data = ffs2;
rv = iso_drv->ops->pin_cmd(card, &pin_cmd, tries_left);
LOG_TEST_RET(card->ctx, rv, "PIN CMD 'VERIFY' with pinpad failed");
LOG_FUNC_RETURN(card->ctx, rv);
}
static int
auth_pin_change(struct sc_card *card, unsigned int type,
struct sc_pin_cmd_data *data, int *tries_left)
{
struct sc_card_driver *iso_drv = sc_get_iso7816_driver();
int rv = SC_ERROR_INTERNAL;
LOG_FUNC_CALLED(card->ctx);
if (data->pin1.len && data->pin2.len) {
/* Direct unblock style */
data->flags |= SC_PIN_CMD_NEED_PADDING;
data->flags &= ~SC_PIN_CMD_USE_PINPAD;
data->apdu = NULL;
data->pin_reference &= ~OBERTHUR_PIN_LOCAL;
auth_init_pin_info(card, &data->pin1, OBERTHUR_AUTH_TYPE_PIN);
auth_init_pin_info(card, &data->pin2, OBERTHUR_AUTH_TYPE_PIN);
rv = iso_drv->ops->pin_cmd(card, data, tries_left);
LOG_TEST_RET(card->ctx, rv, "CMD 'PIN CHANGE' failed");
}
else if (!data->pin1.len && !data->pin2.len) {
/* Oberthur unblock style with PIN pad. */
rv = auth_pin_change_pinpad(card, data, tries_left);
LOG_TEST_RET(card->ctx, rv, "'PIN CHANGE' failed: SOPIN verify with pinpad failed");
}
else {
LOG_TEST_RET(card->ctx, SC_ERROR_INVALID_ARGUMENTS, "'PIN CHANGE' failed");
}
LOG_FUNC_RETURN(card->ctx, rv);
}
static int
auth_pin_reset_oberthur_style(struct sc_card *card, unsigned int type,
struct sc_pin_cmd_data *data, int *tries_left)
{
struct sc_card_driver *iso_drv = sc_get_iso7816_driver();
struct sc_pin_cmd_data pin_cmd;
struct sc_path tmp_path;
struct sc_file *tmp_file = NULL;
struct sc_apdu apdu;
unsigned char puk[OBERTHUR_AUTH_MAX_LENGTH_PUK];
unsigned char ffs1[0x100];
int rv, rvv, local_pin_reference;
LOG_FUNC_CALLED(card->ctx);
local_pin_reference = data->pin_reference & ~OBERTHUR_PIN_LOCAL;
if (data->pin_reference != OBERTHUR_PIN_REFERENCE_USER)
LOG_TEST_RET(card->ctx, SC_ERROR_INVALID_ARGUMENTS, "Oberthur style 'PIN RESET' failed: invalid PIN reference");
memset(&pin_cmd, 0, sizeof(pin_cmd));
memset(&tmp_path, 0, sizeof(struct sc_path));
pin_cmd.pin_type = SC_AC_CHV;
pin_cmd.cmd = SC_PIN_CMD_VERIFY;
pin_cmd.pin_reference = OBERTHUR_PIN_REFERENCE_PUK;
memcpy(&pin_cmd.pin1, &data->pin1, sizeof(pin_cmd.pin1));
rv = auth_pin_verify(card, SC_AC_CHV, &pin_cmd, tries_left);
LOG_TEST_RET(card->ctx, rv, "Oberthur style 'PIN RESET' failed: SOPIN verify error");
sc_format_path("2000", &tmp_path);
tmp_path.type = SC_PATH_TYPE_FILE_ID;
rv = iso_ops->select_file(card, &tmp_path, &tmp_file);
LOG_TEST_RET(card->ctx, rv, "select PUK file");
if (!tmp_file || tmp_file->size < OBERTHUR_AUTH_MAX_LENGTH_PUK)
LOG_TEST_RET(card->ctx, SC_ERROR_FILE_TOO_SMALL, "Oberthur style 'PIN RESET' failed");
rv = iso_ops->read_binary(card, 0, puk, OBERTHUR_AUTH_MAX_LENGTH_PUK, 0);
LOG_TEST_RET(card->ctx, rv, "read PUK file error");
if (rv != OBERTHUR_AUTH_MAX_LENGTH_PUK)
LOG_TEST_RET(card->ctx, SC_ERROR_INVALID_DATA, "Oberthur style 'PIN RESET' failed");
memset(ffs1, 0xFF, sizeof(ffs1));
memcpy(ffs1, puk, rv);
memset(&pin_cmd, 0, sizeof(pin_cmd));
pin_cmd.pin_type = SC_AC_CHV;
pin_cmd.cmd = SC_PIN_CMD_UNBLOCK;
pin_cmd.pin_reference = local_pin_reference;
auth_init_pin_info(card, &pin_cmd.pin1, OBERTHUR_AUTH_TYPE_PUK);
pin_cmd.pin1.data = ffs1;
pin_cmd.pin1.len = OBERTHUR_AUTH_MAX_LENGTH_PUK;
if (data->pin2.data) {
memcpy(&pin_cmd.pin2, &data->pin2, sizeof(pin_cmd.pin2));
rv = auth_pin_reset(card, SC_AC_CHV, &pin_cmd, tries_left);
LOG_FUNC_RETURN(card->ctx, rv);
}
sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x2C, 0x00, local_pin_reference);
apdu.lc = OBERTHUR_AUTH_MAX_LENGTH_PIN + OBERTHUR_AUTH_MAX_LENGTH_PUK;
apdu.datalen = OBERTHUR_AUTH_MAX_LENGTH_PIN + OBERTHUR_AUTH_MAX_LENGTH_PUK;
apdu.data = ffs1;
pin_cmd.apdu = &apdu;
pin_cmd.flags |= SC_PIN_CMD_USE_PINPAD | SC_PIN_CMD_IMPLICIT_CHANGE;
pin_cmd.pin1.min_length = 4;
pin_cmd.pin1.max_length = 8;
pin_cmd.pin1.encoding = SC_PIN_ENCODING_ASCII;
pin_cmd.pin1.offset = 5;
pin_cmd.pin2.data = &ffs1[OBERTHUR_AUTH_MAX_LENGTH_PUK];
pin_cmd.pin2.len = OBERTHUR_AUTH_MAX_LENGTH_PIN;
pin_cmd.pin2.offset = 5 + OBERTHUR_AUTH_MAX_LENGTH_PUK;
pin_cmd.pin2.min_length = 4;
pin_cmd.pin2.max_length = 8;
pin_cmd.pin2.encoding = SC_PIN_ENCODING_ASCII;
rvv = iso_drv->ops->pin_cmd(card, &pin_cmd, tries_left);
if (rvv)
sc_log(card->ctx,
"%s: PIN CMD 'VERIFY' with pinpad failed",
sc_strerror(rvv));
if (auth_current_ef)
rv = iso_ops->select_file(card, &auth_current_ef->path, &auth_current_ef);
if (rv > 0)
rv = 0;
LOG_FUNC_RETURN(card->ctx, rv ? rv: rvv);
}
static int
auth_pin_reset(struct sc_card *card, unsigned int type,
struct sc_pin_cmd_data *data, int *tries_left)
{
int rv;
LOG_FUNC_CALLED(card->ctx);
/* Oberthur unblock style: PUK value is a SOPIN */
rv = auth_pin_reset_oberthur_style(card, SC_AC_CHV, data, tries_left);
LOG_TEST_RET(card->ctx, rv, "Oberthur style 'PIN RESET' failed");
LOG_FUNC_RETURN(card->ctx, rv);
}
static int
auth_pin_cmd(struct sc_card *card, struct sc_pin_cmd_data *data, int *tries_left)
{
int rv = SC_ERROR_INTERNAL;
LOG_FUNC_CALLED(card->ctx);
if (data->pin_type != SC_AC_CHV)
LOG_TEST_RET(card->ctx, SC_ERROR_NOT_SUPPORTED, "auth_pin_cmd() unsupported PIN type");
sc_log(card->ctx, "PIN CMD:%i; reference:%i; pin1:%p/%i, pin2:%p/%i", data->cmd,
data->pin_reference, data->pin1.data, data->pin1.len,
data->pin2.data, data->pin2.len);
switch (data->cmd) {
case SC_PIN_CMD_VERIFY:
rv = auth_pin_verify(card, SC_AC_CHV, data, tries_left);
LOG_TEST_RET(card->ctx, rv, "CMD 'PIN VERIFY' failed");
break;
case SC_PIN_CMD_CHANGE:
rv = auth_pin_change(card, SC_AC_CHV, data, tries_left);
LOG_TEST_RET(card->ctx, rv, "CMD 'PIN VERIFY' failed");
break;
case SC_PIN_CMD_UNBLOCK:
rv = auth_pin_reset(card, SC_AC_CHV, data, tries_left);
LOG_TEST_RET(card->ctx, rv, "CMD 'PIN VERIFY' failed");
break;
default:
LOG_TEST_RET(card->ctx, SC_ERROR_NOT_SUPPORTED, "Unsupported PIN operation");
}
LOG_FUNC_RETURN(card->ctx, rv);
}
static int
auth_create_reference_data (struct sc_card *card,
struct sc_cardctl_oberthur_createpin_info *args)
{
struct sc_apdu apdu;
struct sc_pin_cmd_pin pin_info, puk_info;
int rv, len;
unsigned char sbuf[SC_MAX_APDU_BUFFER_SIZE];
LOG_FUNC_CALLED(card->ctx);
sc_log(card->ctx, "PIN reference %i", args->ref);
if (args->type != SC_AC_CHV)
LOG_TEST_RET(card->ctx, SC_ERROR_NOT_SUPPORTED, "Unsupported PIN type");
if (args->pin_tries < 1 || !args->pin || !args->pin_len)
LOG_TEST_RET(card->ctx, SC_ERROR_INVALID_ARGUMENTS, "Invalid PIN options");
if (args->ref != OBERTHUR_PIN_REFERENCE_USER && args->ref != OBERTHUR_PIN_REFERENCE_PUK)
LOG_TEST_RET(card->ctx, SC_ERROR_INVALID_PIN_REFERENCE, "Invalid PIN reference");
auth_init_pin_info(card, &puk_info, OBERTHUR_AUTH_TYPE_PUK);
auth_init_pin_info(card, &pin_info, OBERTHUR_AUTH_TYPE_PIN);
if (args->puk && args->puk_len && (args->puk_len%puk_info.pad_length))
LOG_TEST_RET(card->ctx, SC_ERROR_INVALID_ARGUMENTS, "Invalid PUK options");
len = 0;
sc_log(card->ctx, "len %i", len);
sbuf[len++] = args->pin_tries;
sbuf[len++] = pin_info.pad_length;
sc_log(card->ctx, "len %i", len);
memset(sbuf + len, pin_info.pad_char, pin_info.pad_length);
memcpy(sbuf + len, args->pin, args->pin_len);
len += pin_info.pad_length;
sc_log(card->ctx, "len %i", len);
if (args->puk && args->puk_len) {
sbuf[len++] = args->puk_tries;
sbuf[len++] = args->puk_len / puk_info.pad_length;
sc_log(card->ctx, "len %i", len);
memcpy(sbuf + len, args->puk, args->puk_len);
len += args->puk_len;
}
sc_log(card->ctx, "len %i", len);
sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x24, 1, args->ref & ~OBERTHUR_PIN_LOCAL);
apdu.data = sbuf;
apdu.datalen = len;
apdu.lc = len;
rv = sc_transmit_apdu(card, &apdu);
sc_mem_clear(sbuf, sizeof(sbuf));
LOG_TEST_RET(card->ctx, rv, "APDU transmit failed");
rv = sc_check_sw(card, apdu.sw1, apdu.sw2);
LOG_FUNC_RETURN(card->ctx, rv);
}
static int
auth_logout(struct sc_card *card)
{
struct sc_apdu apdu;
int ii, rv = 0, pin_ref;
int reset_flag = 0x20;
for (ii=0; ii < 4; ii++) {
rv = auth_get_pin_reference (card, SC_AC_CHV, ii+1, SC_PIN_CMD_UNBLOCK, &pin_ref);
LOG_TEST_RET(card->ctx, rv, "Cannot get PIN reference");
sc_format_apdu(card, &apdu, SC_APDU_CASE_1, 0x2E, 0x00, 0x00);
apdu.cla = 0x80;
apdu.p2 = pin_ref | reset_flag;
rv = sc_transmit_apdu(card, &apdu);
LOG_TEST_RET(card->ctx, rv, "APDU transmit failed");
}
LOG_FUNC_RETURN(card->ctx, rv);
}
static int
write_publickey (struct sc_card *card, unsigned int offset,
const unsigned char *buf, size_t count)
{
struct auth_update_component_info args;
struct sc_pkcs15_pubkey_rsa key;
int ii, rv;
size_t len = 0, der_size = 0;
LOG_FUNC_CALLED(card->ctx);
sc_log_hex(card->ctx, "write_publickey", buf, count);
if (1+offset > sizeof(rsa_der))
LOG_TEST_RET(card->ctx, SC_ERROR_INVALID_ARGUMENTS, "Invalid offset value");
len = offset+count > sizeof(rsa_der) ? sizeof(rsa_der) - offset : count;
memcpy(rsa_der + offset, buf, len);
rsa_der_len = offset + len;
if (rsa_der[0]==0x30) {
if (rsa_der[1] & 0x80)
for (ii=0; ii < (rsa_der[1]&0x0F); ii++)
der_size = der_size*0x100 + rsa_der[2+ii];
else
der_size = rsa_der[1];
}
sc_log(card->ctx, "der_size %"SC_FORMAT_LEN_SIZE_T"u", der_size);
if (offset + len < der_size + 2)
LOG_FUNC_RETURN(card->ctx, len);
rv = sc_pkcs15_decode_pubkey_rsa(card->ctx, &key, rsa_der, rsa_der_len);
rsa_der_len = 0;
memset(rsa_der, 0, sizeof(rsa_der));
LOG_TEST_RET(card->ctx, rv, "cannot decode public key");
memset(&args, 0, sizeof(args));
args.type = SC_CARDCTL_OBERTHUR_KEY_RSA_PUBLIC;
args.component = 1;
args.data = key.modulus.data;
args.len = key.modulus.len;
rv = auth_update_component(card, &args);
LOG_TEST_RET(card->ctx, rv, "Update component failed");
memset(&args, 0, sizeof(args));
args.type = SC_CARDCTL_OBERTHUR_KEY_RSA_PUBLIC;
args.component = 2;
args.data = key.exponent.data;
args.len = key.exponent.len;
rv = auth_update_component(card, &args);
LOG_TEST_RET(card->ctx, rv, "Update component failed");
LOG_FUNC_RETURN(card->ctx, len);
}
static int
auth_update_binary(struct sc_card *card, unsigned int offset,
const unsigned char *buf, size_t count, unsigned long flags)
{
int rv = 0;
LOG_FUNC_CALLED(card->ctx);
sc_log(card->ctx, "offset %i; count %"SC_FORMAT_LEN_SIZE_T"u", offset,
count);
sc_log(card->ctx, "last selected : magic %X; ef %X",
auth_current_ef->magic, auth_current_ef->ef_structure);
if (offset & ~0x7FFF)
LOG_TEST_RET(card->ctx, SC_ERROR_INVALID_ARGUMENTS, "Invalid file offset");
if (auth_current_ef->magic==SC_FILE_MAGIC &&
auth_current_ef->ef_structure == SC_CARDCTL_OBERTHUR_KEY_RSA_PUBLIC) {
rv = write_publickey(card, offset, buf, count);
}
else if (auth_current_ef->magic==SC_FILE_MAGIC &&
auth_current_ef->ef_structure == SC_CARDCTL_OBERTHUR_KEY_DES) {
struct auth_update_component_info args;
memset(&args, 0, sizeof(args));
args.type = SC_CARDCTL_OBERTHUR_KEY_DES;
args.data = (unsigned char *)buf;
args.len = count;
rv = auth_update_component(card, &args);
}
else {
rv = iso_ops->update_binary(card, offset, buf, count, 0);
}
LOG_FUNC_RETURN(card->ctx, rv);
}
static int
auth_read_binary(struct sc_card *card, unsigned int offset,
unsigned char *buf, size_t count, unsigned long flags)
{
int rv;
struct sc_pkcs15_bignum bn[2];
unsigned char *out = NULL;
bn[0].data = NULL;
bn[1].data = NULL;
LOG_FUNC_CALLED(card->ctx);
if (!auth_current_ef)
LOG_TEST_RET(card->ctx, SC_ERROR_INVALID_ARGUMENTS, "Invalid auth_current_ef");
sc_log(card->ctx,
"offset %i; size %"SC_FORMAT_LEN_SIZE_T"u; flags 0x%lX",
offset, count, flags);
sc_log(card->ctx,"last selected : magic %X; ef %X",
auth_current_ef->magic, auth_current_ef->ef_structure);
if (offset & ~0x7FFF)
LOG_TEST_RET(card->ctx, SC_ERROR_INVALID_ARGUMENTS, "Invalid file offset");
if (auth_current_ef->magic==SC_FILE_MAGIC &&
auth_current_ef->ef_structure == SC_CARDCTL_OBERTHUR_KEY_RSA_PUBLIC) {
int jj;
unsigned char resp[256];
size_t resp_len, out_len;
struct sc_pkcs15_pubkey_rsa key;
resp_len = sizeof(resp);
rv = auth_read_component(card, SC_CARDCTL_OBERTHUR_KEY_RSA_PUBLIC,
2, resp, resp_len);
LOG_TEST_RET(card->ctx, rv, "read component failed");
for (jj=0; jj<rv && *(resp+jj)==0; jj++)
;
bn[0].data = calloc(1, rv - jj);
if (!bn[0].data) {
rv = SC_ERROR_OUT_OF_MEMORY;
goto err;
}
bn[0].len = rv - jj;
memcpy(bn[0].data, resp + jj, rv - jj);
rv = auth_read_component(card, SC_CARDCTL_OBERTHUR_KEY_RSA_PUBLIC,
1, resp, resp_len);
LOG_TEST_GOTO_ERR(card->ctx, rv, "Cannot read RSA public key component");
bn[1].data = calloc(1, rv);
if (!bn[1].data) {
rv = SC_ERROR_OUT_OF_MEMORY;
goto err;
}
bn[1].len = rv;
memcpy(bn[1].data, resp, rv);
key.exponent = bn[0];
key.modulus = bn[1];
if (sc_pkcs15_encode_pubkey_rsa(card->ctx, &key, &out, &out_len)) {
rv = SC_ERROR_INVALID_ASN1_OBJECT;
LOG_TEST_GOTO_ERR(card->ctx, rv, "cannot encode RSA public key");
}
else {
rv = out_len - offset > count ? count : out_len - offset;
memcpy(buf, out + offset, rv);
sc_log_hex(card->ctx, "write_publickey", buf, rv);
}
}
else {
rv = iso_ops->read_binary(card, offset, buf, count, 0);
}
err:
free(bn[0].data);
free(bn[1].data);
free(out);
LOG_FUNC_RETURN(card->ctx, rv);
}
static int
auth_read_record(struct sc_card *card, unsigned int nr_rec,
unsigned char *buf, size_t count, unsigned long flags)
{
struct sc_apdu apdu;
int rv = 0;
unsigned char recvbuf[SC_MAX_APDU_BUFFER_SIZE];
sc_log(card->ctx,
"auth_read_record(): nr_rec %i; count %"SC_FORMAT_LEN_SIZE_T"u",
nr_rec, count);
sc_format_apdu(card, &apdu, SC_APDU_CASE_2_SHORT, 0xB2, nr_rec, 0);
apdu.p2 = (flags & SC_RECORD_EF_ID_MASK) << 3;
if (flags & SC_RECORD_BY_REC_NR)
apdu.p2 |= 0x04;
apdu.le = count;
apdu.resplen = count;
apdu.resp = recvbuf;
rv = sc_transmit_apdu(card, &apdu);
LOG_TEST_RET(card->ctx, rv, "APDU transmit failed");
if (apdu.resplen == 0)
LOG_FUNC_RETURN(card->ctx, sc_check_sw(card, apdu.sw1, apdu.sw2));
memcpy(buf, recvbuf, apdu.resplen);
rv = sc_check_sw(card, apdu.sw1, apdu.sw2);
LOG_TEST_RET(card->ctx, rv, "Card returned error");
LOG_FUNC_RETURN(card->ctx, apdu.resplen);
}
static int
auth_delete_record(struct sc_card *card, unsigned int nr_rec)
{
struct sc_apdu apdu;
int rv = 0;
LOG_FUNC_CALLED(card->ctx);
sc_log(card->ctx, "auth_delete_record(): nr_rec %i", nr_rec);
sc_format_apdu(card, &apdu, SC_APDU_CASE_1, 0x32, nr_rec, 0x04);
apdu.cla = 0x80;
rv = sc_transmit_apdu(card, &apdu);
LOG_TEST_RET(card->ctx, rv, "APDU transmit failed");
rv = sc_check_sw(card, apdu.sw1, apdu.sw2);
LOG_FUNC_RETURN(card->ctx, rv);
}
static int
auth_get_serialnr(struct sc_card *card, struct sc_serial_number *serial)
{
if (!serial)
LOG_FUNC_RETURN(card->ctx, SC_ERROR_INVALID_ARGUMENTS);
if (card->serialnr.len==0)
LOG_FUNC_RETURN(card->ctx, SC_ERROR_INTERNAL);
memcpy(serial, &card->serialnr, sizeof(*serial));
LOG_FUNC_RETURN(card->ctx, SC_SUCCESS);
}
static const struct sc_card_error
auth_warnings[] = {
{ 0x6282, SC_SUCCESS,
"ignore warning 'End of file or record reached before reading Ne bytes'" },
{0, 0, NULL},
};
static int
auth_check_sw(struct sc_card *card, unsigned int sw1, unsigned int sw2)
{
int ii;
for (ii=0; auth_warnings[ii].SWs; ii++) {
if (auth_warnings[ii].SWs == ((sw1 << 8) | sw2)) {
sc_log(card->ctx, "%s", auth_warnings[ii].errorstr);
return auth_warnings[ii].errorno;
}
}
return iso_ops->check_sw(card, sw1, sw2);
}
static struct sc_card_driver *
sc_get_driver(void)
{
if (iso_ops == NULL)
iso_ops = sc_get_iso7816_driver()->ops;
auth_ops = *iso_ops;
auth_ops.match_card = auth_match_card;
auth_ops.init = auth_init;
auth_ops.finish = auth_finish;
auth_ops.select_file = auth_select_file;
auth_ops.list_files = auth_list_files;
auth_ops.delete_file = auth_delete_file;
auth_ops.create_file = auth_create_file;
auth_ops.read_binary = auth_read_binary;
auth_ops.update_binary = auth_update_binary;
auth_ops.read_record = auth_read_record;
auth_ops.delete_record = auth_delete_record;
auth_ops.card_ctl = auth_card_ctl;
auth_ops.set_security_env = auth_set_security_env;
auth_ops.restore_security_env = auth_restore_security_env;
auth_ops.compute_signature = auth_compute_signature;
auth_ops.decipher = auth_decipher;
auth_ops.process_fci = auth_process_fci;
auth_ops.pin_cmd = auth_pin_cmd;
auth_ops.logout = auth_logout;
auth_ops.check_sw = auth_check_sw;
return &auth_drv;
}
struct sc_card_driver *
sc_get_oberthur_driver(void)
{
return sc_get_driver();
}
#endif /* ENABLE_OPENSSL */
| ./CrossVul/dataset_final_sorted/CWE-125/c/good_351_9 |
crossvul-cpp_data_good_4039_1 | /*
* rdppm.c
*
* This file was part of the Independent JPEG Group's software:
* Copyright (C) 1991-1997, Thomas G. Lane.
* Modified 2009 by Bill Allombert, Guido Vollbeding.
* libjpeg-turbo Modifications:
* Copyright (C) 2015-2017, 2020, D. R. Commander.
* For conditions of distribution and use, see the accompanying README.ijg
* file.
*
* This file contains routines to read input images in PPM/PGM format.
* The extended 2-byte-per-sample raw PPM/PGM formats are supported.
* The PBMPLUS library is NOT required to compile this software
* (but it is highly useful as a set of PPM image manipulation programs).
*
* These routines may need modification for non-Unix environments or
* specialized applications. As they stand, they assume input from
* an ordinary stdio stream. They further assume that reading begins
* at the start of the file; start_input may need work if the
* user interface has already read some data (e.g., to determine that
* the file is indeed PPM format).
*/
#include "cmyk.h"
#include "cdjpeg.h" /* Common decls for cjpeg/djpeg applications */
#ifdef PPM_SUPPORTED
/* Portions of this code are based on the PBMPLUS library, which is:
**
** Copyright (C) 1988 by Jef Poskanzer.
**
** 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. This software is provided "as is" without express or
** implied warranty.
*/
/* Macros to deal with unsigned chars as efficiently as compiler allows */
#ifdef HAVE_UNSIGNED_CHAR
typedef unsigned char U_CHAR;
#define UCH(x) ((int)(x))
#else /* !HAVE_UNSIGNED_CHAR */
#ifdef __CHAR_UNSIGNED__
typedef char U_CHAR;
#define UCH(x) ((int)(x))
#else
typedef char U_CHAR;
#define UCH(x) ((int)(x) & 0xFF)
#endif
#endif /* HAVE_UNSIGNED_CHAR */
#define ReadOK(file, buffer, len) \
(JFREAD(file, buffer, len) == ((size_t)(len)))
static int alpha_index[JPEG_NUMCS] = {
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 3, 3, 0, 0, -1
};
/* Private version of data source object */
typedef struct {
struct cjpeg_source_struct pub; /* public fields */
/* Usually these two pointers point to the same place: */
U_CHAR *iobuffer; /* fread's I/O buffer */
JSAMPROW pixrow; /* compressor input buffer */
size_t buffer_width; /* width of I/O buffer */
JSAMPLE *rescale; /* => maxval-remapping array, or NULL */
unsigned int maxval;
} ppm_source_struct;
typedef ppm_source_struct *ppm_source_ptr;
LOCAL(int)
pbm_getc(FILE *infile)
/* Read next char, skipping over any comments */
/* A comment/newline sequence is returned as a newline */
{
register int ch;
ch = getc(infile);
if (ch == '#') {
do {
ch = getc(infile);
} while (ch != '\n' && ch != EOF);
}
return ch;
}
LOCAL(unsigned int)
read_pbm_integer(j_compress_ptr cinfo, FILE *infile, unsigned int maxval)
/* Read an unsigned decimal integer from the PPM file */
/* Swallows one trailing character after the integer */
/* Note that on a 16-bit-int machine, only values up to 64k can be read. */
/* This should not be a problem in practice. */
{
register int ch;
register unsigned int val;
/* Skip any leading whitespace */
do {
ch = pbm_getc(infile);
if (ch == EOF)
ERREXIT(cinfo, JERR_INPUT_EOF);
} while (ch == ' ' || ch == '\t' || ch == '\n' || ch == '\r');
if (ch < '0' || ch > '9')
ERREXIT(cinfo, JERR_PPM_NONNUMERIC);
val = ch - '0';
while ((ch = pbm_getc(infile)) >= '0' && ch <= '9') {
val *= 10;
val += ch - '0';
}
if (val > maxval)
ERREXIT(cinfo, JERR_PPM_OUTOFRANGE);
return val;
}
/*
* Read one row of pixels.
*
* We provide several different versions depending on input file format.
* In all cases, input is scaled to the size of JSAMPLE.
*
* A really fast path is provided for reading byte/sample raw files with
* maxval = MAXJSAMPLE, which is the normal case for 8-bit data.
*/
METHODDEF(JDIMENSION)
get_text_gray_row(j_compress_ptr cinfo, cjpeg_source_ptr sinfo)
/* This version is for reading text-format PGM files with any maxval */
{
ppm_source_ptr source = (ppm_source_ptr)sinfo;
FILE *infile = source->pub.input_file;
register JSAMPROW ptr;
register JSAMPLE *rescale = source->rescale;
JDIMENSION col;
unsigned int maxval = source->maxval;
ptr = source->pub.buffer[0];
for (col = cinfo->image_width; col > 0; col--) {
*ptr++ = rescale[read_pbm_integer(cinfo, infile, maxval)];
}
return 1;
}
#define GRAY_RGB_READ_LOOP(read_op, alpha_set_op) { \
for (col = cinfo->image_width; col > 0; col--) { \
ptr[rindex] = ptr[gindex] = ptr[bindex] = read_op; \
alpha_set_op \
ptr += ps; \
} \
}
METHODDEF(JDIMENSION)
get_text_gray_rgb_row(j_compress_ptr cinfo, cjpeg_source_ptr sinfo)
/* This version is for reading text-format PGM files with any maxval and
converting to extended RGB */
{
ppm_source_ptr source = (ppm_source_ptr)sinfo;
FILE *infile = source->pub.input_file;
register JSAMPROW ptr;
register JSAMPLE *rescale = source->rescale;
JDIMENSION col;
unsigned int maxval = source->maxval;
register int rindex = rgb_red[cinfo->in_color_space];
register int gindex = rgb_green[cinfo->in_color_space];
register int bindex = rgb_blue[cinfo->in_color_space];
register int aindex = alpha_index[cinfo->in_color_space];
register int ps = rgb_pixelsize[cinfo->in_color_space];
ptr = source->pub.buffer[0];
if (maxval == MAXJSAMPLE) {
if (aindex >= 0)
GRAY_RGB_READ_LOOP(read_pbm_integer(cinfo, infile, maxval),
ptr[aindex] = 0xFF;)
else
GRAY_RGB_READ_LOOP(read_pbm_integer(cinfo, infile, maxval),)
} else {
if (aindex >= 0)
GRAY_RGB_READ_LOOP(rescale[read_pbm_integer(cinfo, infile, maxval)],
ptr[aindex] = 0xFF;)
else
GRAY_RGB_READ_LOOP(rescale[read_pbm_integer(cinfo, infile, maxval)],)
}
return 1;
}
METHODDEF(JDIMENSION)
get_text_gray_cmyk_row(j_compress_ptr cinfo, cjpeg_source_ptr sinfo)
/* This version is for reading text-format PGM files with any maxval and
converting to CMYK */
{
ppm_source_ptr source = (ppm_source_ptr)sinfo;
FILE *infile = source->pub.input_file;
register JSAMPROW ptr;
register JSAMPLE *rescale = source->rescale;
JDIMENSION col;
unsigned int maxval = source->maxval;
ptr = source->pub.buffer[0];
if (maxval == MAXJSAMPLE) {
for (col = cinfo->image_width; col > 0; col--) {
JSAMPLE gray = read_pbm_integer(cinfo, infile, maxval);
rgb_to_cmyk(gray, gray, gray, ptr, ptr + 1, ptr + 2, ptr + 3);
ptr += 4;
}
} else {
for (col = cinfo->image_width; col > 0; col--) {
JSAMPLE gray = rescale[read_pbm_integer(cinfo, infile, maxval)];
rgb_to_cmyk(gray, gray, gray, ptr, ptr + 1, ptr + 2, ptr + 3);
ptr += 4;
}
}
return 1;
}
#define RGB_READ_LOOP(read_op, alpha_set_op) { \
for (col = cinfo->image_width; col > 0; col--) { \
ptr[rindex] = read_op; \
ptr[gindex] = read_op; \
ptr[bindex] = read_op; \
alpha_set_op \
ptr += ps; \
} \
}
METHODDEF(JDIMENSION)
get_text_rgb_row(j_compress_ptr cinfo, cjpeg_source_ptr sinfo)
/* This version is for reading text-format PPM files with any maxval */
{
ppm_source_ptr source = (ppm_source_ptr)sinfo;
FILE *infile = source->pub.input_file;
register JSAMPROW ptr;
register JSAMPLE *rescale = source->rescale;
JDIMENSION col;
unsigned int maxval = source->maxval;
register int rindex = rgb_red[cinfo->in_color_space];
register int gindex = rgb_green[cinfo->in_color_space];
register int bindex = rgb_blue[cinfo->in_color_space];
register int aindex = alpha_index[cinfo->in_color_space];
register int ps = rgb_pixelsize[cinfo->in_color_space];
ptr = source->pub.buffer[0];
if (maxval == MAXJSAMPLE) {
if (aindex >= 0)
RGB_READ_LOOP(read_pbm_integer(cinfo, infile, maxval),
ptr[aindex] = 0xFF;)
else
RGB_READ_LOOP(read_pbm_integer(cinfo, infile, maxval),)
} else {
if (aindex >= 0)
RGB_READ_LOOP(rescale[read_pbm_integer(cinfo, infile, maxval)],
ptr[aindex] = 0xFF;)
else
RGB_READ_LOOP(rescale[read_pbm_integer(cinfo, infile, maxval)],)
}
return 1;
}
METHODDEF(JDIMENSION)
get_text_rgb_cmyk_row(j_compress_ptr cinfo, cjpeg_source_ptr sinfo)
/* This version is for reading text-format PPM files with any maxval and
converting to CMYK */
{
ppm_source_ptr source = (ppm_source_ptr)sinfo;
FILE *infile = source->pub.input_file;
register JSAMPROW ptr;
register JSAMPLE *rescale = source->rescale;
JDIMENSION col;
unsigned int maxval = source->maxval;
ptr = source->pub.buffer[0];
if (maxval == MAXJSAMPLE) {
for (col = cinfo->image_width; col > 0; col--) {
JSAMPLE r = read_pbm_integer(cinfo, infile, maxval);
JSAMPLE g = read_pbm_integer(cinfo, infile, maxval);
JSAMPLE b = read_pbm_integer(cinfo, infile, maxval);
rgb_to_cmyk(r, g, b, ptr, ptr + 1, ptr + 2, ptr + 3);
ptr += 4;
}
} else {
for (col = cinfo->image_width; col > 0; col--) {
JSAMPLE r = rescale[read_pbm_integer(cinfo, infile, maxval)];
JSAMPLE g = rescale[read_pbm_integer(cinfo, infile, maxval)];
JSAMPLE b = rescale[read_pbm_integer(cinfo, infile, maxval)];
rgb_to_cmyk(r, g, b, ptr, ptr + 1, ptr + 2, ptr + 3);
ptr += 4;
}
}
return 1;
}
METHODDEF(JDIMENSION)
get_scaled_gray_row(j_compress_ptr cinfo, cjpeg_source_ptr sinfo)
/* This version is for reading raw-byte-format PGM files with any maxval */
{
ppm_source_ptr source = (ppm_source_ptr)sinfo;
register JSAMPROW ptr;
register U_CHAR *bufferptr;
register JSAMPLE *rescale = source->rescale;
JDIMENSION col;
if (!ReadOK(source->pub.input_file, source->iobuffer, source->buffer_width))
ERREXIT(cinfo, JERR_INPUT_EOF);
ptr = source->pub.buffer[0];
bufferptr = source->iobuffer;
for (col = cinfo->image_width; col > 0; col--) {
*ptr++ = rescale[UCH(*bufferptr++)];
}
return 1;
}
METHODDEF(JDIMENSION)
get_gray_rgb_row(j_compress_ptr cinfo, cjpeg_source_ptr sinfo)
/* This version is for reading raw-byte-format PGM files with any maxval
and converting to extended RGB */
{
ppm_source_ptr source = (ppm_source_ptr)sinfo;
register JSAMPROW ptr;
register U_CHAR *bufferptr;
register JSAMPLE *rescale = source->rescale;
JDIMENSION col;
unsigned int maxval = source->maxval;
register int rindex = rgb_red[cinfo->in_color_space];
register int gindex = rgb_green[cinfo->in_color_space];
register int bindex = rgb_blue[cinfo->in_color_space];
register int aindex = alpha_index[cinfo->in_color_space];
register int ps = rgb_pixelsize[cinfo->in_color_space];
if (!ReadOK(source->pub.input_file, source->iobuffer, source->buffer_width))
ERREXIT(cinfo, JERR_INPUT_EOF);
ptr = source->pub.buffer[0];
bufferptr = source->iobuffer;
if (maxval == MAXJSAMPLE) {
if (aindex >= 0)
GRAY_RGB_READ_LOOP(*bufferptr++, ptr[aindex] = 0xFF;)
else
GRAY_RGB_READ_LOOP(*bufferptr++,)
} else {
if (aindex >= 0)
GRAY_RGB_READ_LOOP(rescale[UCH(*bufferptr++)], ptr[aindex] = 0xFF;)
else
GRAY_RGB_READ_LOOP(rescale[UCH(*bufferptr++)],)
}
return 1;
}
METHODDEF(JDIMENSION)
get_gray_cmyk_row(j_compress_ptr cinfo, cjpeg_source_ptr sinfo)
/* This version is for reading raw-byte-format PGM files with any maxval
and converting to CMYK */
{
ppm_source_ptr source = (ppm_source_ptr)sinfo;
register JSAMPROW ptr;
register U_CHAR *bufferptr;
register JSAMPLE *rescale = source->rescale;
JDIMENSION col;
unsigned int maxval = source->maxval;
if (!ReadOK(source->pub.input_file, source->iobuffer, source->buffer_width))
ERREXIT(cinfo, JERR_INPUT_EOF);
ptr = source->pub.buffer[0];
bufferptr = source->iobuffer;
if (maxval == MAXJSAMPLE) {
for (col = cinfo->image_width; col > 0; col--) {
JSAMPLE gray = *bufferptr++;
rgb_to_cmyk(gray, gray, gray, ptr, ptr + 1, ptr + 2, ptr + 3);
ptr += 4;
}
} else {
for (col = cinfo->image_width; col > 0; col--) {
JSAMPLE gray = rescale[UCH(*bufferptr++)];
rgb_to_cmyk(gray, gray, gray, ptr, ptr + 1, ptr + 2, ptr + 3);
ptr += 4;
}
}
return 1;
}
METHODDEF(JDIMENSION)
get_rgb_row(j_compress_ptr cinfo, cjpeg_source_ptr sinfo)
/* This version is for reading raw-byte-format PPM files with any maxval */
{
ppm_source_ptr source = (ppm_source_ptr)sinfo;
register JSAMPROW ptr;
register U_CHAR *bufferptr;
register JSAMPLE *rescale = source->rescale;
JDIMENSION col;
unsigned int maxval = source->maxval;
register int rindex = rgb_red[cinfo->in_color_space];
register int gindex = rgb_green[cinfo->in_color_space];
register int bindex = rgb_blue[cinfo->in_color_space];
register int aindex = alpha_index[cinfo->in_color_space];
register int ps = rgb_pixelsize[cinfo->in_color_space];
if (!ReadOK(source->pub.input_file, source->iobuffer, source->buffer_width))
ERREXIT(cinfo, JERR_INPUT_EOF);
ptr = source->pub.buffer[0];
bufferptr = source->iobuffer;
if (maxval == MAXJSAMPLE) {
if (aindex >= 0)
RGB_READ_LOOP(*bufferptr++, ptr[aindex] = 0xFF;)
else
RGB_READ_LOOP(*bufferptr++,)
} else {
if (aindex >= 0)
RGB_READ_LOOP(rescale[UCH(*bufferptr++)], ptr[aindex] = 0xFF;)
else
RGB_READ_LOOP(rescale[UCH(*bufferptr++)],)
}
return 1;
}
METHODDEF(JDIMENSION)
get_rgb_cmyk_row(j_compress_ptr cinfo, cjpeg_source_ptr sinfo)
/* This version is for reading raw-byte-format PPM files with any maxval and
converting to CMYK */
{
ppm_source_ptr source = (ppm_source_ptr)sinfo;
register JSAMPROW ptr;
register U_CHAR *bufferptr;
register JSAMPLE *rescale = source->rescale;
JDIMENSION col;
unsigned int maxval = source->maxval;
if (!ReadOK(source->pub.input_file, source->iobuffer, source->buffer_width))
ERREXIT(cinfo, JERR_INPUT_EOF);
ptr = source->pub.buffer[0];
bufferptr = source->iobuffer;
if (maxval == MAXJSAMPLE) {
for (col = cinfo->image_width; col > 0; col--) {
JSAMPLE r = *bufferptr++;
JSAMPLE g = *bufferptr++;
JSAMPLE b = *bufferptr++;
rgb_to_cmyk(r, g, b, ptr, ptr + 1, ptr + 2, ptr + 3);
ptr += 4;
}
} else {
for (col = cinfo->image_width; col > 0; col--) {
JSAMPLE r = rescale[UCH(*bufferptr++)];
JSAMPLE g = rescale[UCH(*bufferptr++)];
JSAMPLE b = rescale[UCH(*bufferptr++)];
rgb_to_cmyk(r, g, b, ptr, ptr + 1, ptr + 2, ptr + 3);
ptr += 4;
}
}
return 1;
}
METHODDEF(JDIMENSION)
get_raw_row(j_compress_ptr cinfo, cjpeg_source_ptr sinfo)
/* This version is for reading raw-byte-format files with maxval = MAXJSAMPLE.
* In this case we just read right into the JSAMPLE buffer!
* Note that same code works for PPM and PGM files.
*/
{
ppm_source_ptr source = (ppm_source_ptr)sinfo;
if (!ReadOK(source->pub.input_file, source->iobuffer, source->buffer_width))
ERREXIT(cinfo, JERR_INPUT_EOF);
return 1;
}
METHODDEF(JDIMENSION)
get_word_gray_row(j_compress_ptr cinfo, cjpeg_source_ptr sinfo)
/* This version is for reading raw-word-format PGM files with any maxval */
{
ppm_source_ptr source = (ppm_source_ptr)sinfo;
register JSAMPROW ptr;
register U_CHAR *bufferptr;
register JSAMPLE *rescale = source->rescale;
JDIMENSION col;
unsigned int maxval = source->maxval;
if (!ReadOK(source->pub.input_file, source->iobuffer, source->buffer_width))
ERREXIT(cinfo, JERR_INPUT_EOF);
ptr = source->pub.buffer[0];
bufferptr = source->iobuffer;
for (col = cinfo->image_width; col > 0; col--) {
register unsigned int temp;
temp = UCH(*bufferptr++) << 8;
temp |= UCH(*bufferptr++);
if (temp > maxval)
ERREXIT(cinfo, JERR_PPM_OUTOFRANGE);
*ptr++ = rescale[temp];
}
return 1;
}
METHODDEF(JDIMENSION)
get_word_rgb_row(j_compress_ptr cinfo, cjpeg_source_ptr sinfo)
/* This version is for reading raw-word-format PPM files with any maxval */
{
ppm_source_ptr source = (ppm_source_ptr)sinfo;
register JSAMPROW ptr;
register U_CHAR *bufferptr;
register JSAMPLE *rescale = source->rescale;
JDIMENSION col;
unsigned int maxval = source->maxval;
if (!ReadOK(source->pub.input_file, source->iobuffer, source->buffer_width))
ERREXIT(cinfo, JERR_INPUT_EOF);
ptr = source->pub.buffer[0];
bufferptr = source->iobuffer;
for (col = cinfo->image_width; col > 0; col--) {
register unsigned int temp;
temp = UCH(*bufferptr++) << 8;
temp |= UCH(*bufferptr++);
if (temp > maxval)
ERREXIT(cinfo, JERR_PPM_OUTOFRANGE);
*ptr++ = rescale[temp];
temp = UCH(*bufferptr++) << 8;
temp |= UCH(*bufferptr++);
if (temp > maxval)
ERREXIT(cinfo, JERR_PPM_OUTOFRANGE);
*ptr++ = rescale[temp];
temp = UCH(*bufferptr++) << 8;
temp |= UCH(*bufferptr++);
if (temp > maxval)
ERREXIT(cinfo, JERR_PPM_OUTOFRANGE);
*ptr++ = rescale[temp];
}
return 1;
}
/*
* Read the file header; return image size and component count.
*/
METHODDEF(void)
start_input_ppm(j_compress_ptr cinfo, cjpeg_source_ptr sinfo)
{
ppm_source_ptr source = (ppm_source_ptr)sinfo;
int c;
unsigned int w, h, maxval;
boolean need_iobuffer, use_raw_buffer, need_rescale;
if (getc(source->pub.input_file) != 'P')
ERREXIT(cinfo, JERR_PPM_NOT);
c = getc(source->pub.input_file); /* subformat discriminator character */
/* detect unsupported variants (ie, PBM) before trying to read header */
switch (c) {
case '2': /* it's a text-format PGM file */
case '3': /* it's a text-format PPM file */
case '5': /* it's a raw-format PGM file */
case '6': /* it's a raw-format PPM file */
break;
default:
ERREXIT(cinfo, JERR_PPM_NOT);
break;
}
/* fetch the remaining header info */
w = read_pbm_integer(cinfo, source->pub.input_file, 65535);
h = read_pbm_integer(cinfo, source->pub.input_file, 65535);
maxval = read_pbm_integer(cinfo, source->pub.input_file, 65535);
if (w <= 0 || h <= 0 || maxval <= 0) /* error check */
ERREXIT(cinfo, JERR_PPM_NOT);
cinfo->data_precision = BITS_IN_JSAMPLE; /* we always rescale data to this */
cinfo->image_width = (JDIMENSION)w;
cinfo->image_height = (JDIMENSION)h;
source->maxval = maxval;
/* initialize flags to most common settings */
need_iobuffer = TRUE; /* do we need an I/O buffer? */
use_raw_buffer = FALSE; /* do we map input buffer onto I/O buffer? */
need_rescale = TRUE; /* do we need a rescale array? */
switch (c) {
case '2': /* it's a text-format PGM file */
if (cinfo->in_color_space == JCS_UNKNOWN)
cinfo->in_color_space = JCS_GRAYSCALE;
TRACEMS2(cinfo, 1, JTRC_PGM_TEXT, w, h);
if (cinfo->in_color_space == JCS_GRAYSCALE)
source->pub.get_pixel_rows = get_text_gray_row;
else if (IsExtRGB(cinfo->in_color_space))
source->pub.get_pixel_rows = get_text_gray_rgb_row;
else if (cinfo->in_color_space == JCS_CMYK)
source->pub.get_pixel_rows = get_text_gray_cmyk_row;
else
ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
need_iobuffer = FALSE;
break;
case '3': /* it's a text-format PPM file */
if (cinfo->in_color_space == JCS_UNKNOWN)
cinfo->in_color_space = JCS_EXT_RGB;
TRACEMS2(cinfo, 1, JTRC_PPM_TEXT, w, h);
if (IsExtRGB(cinfo->in_color_space))
source->pub.get_pixel_rows = get_text_rgb_row;
else if (cinfo->in_color_space == JCS_CMYK)
source->pub.get_pixel_rows = get_text_rgb_cmyk_row;
else
ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
need_iobuffer = FALSE;
break;
case '5': /* it's a raw-format PGM file */
if (cinfo->in_color_space == JCS_UNKNOWN)
cinfo->in_color_space = JCS_GRAYSCALE;
TRACEMS2(cinfo, 1, JTRC_PGM, w, h);
if (maxval > 255) {
source->pub.get_pixel_rows = get_word_gray_row;
} else if (maxval == MAXJSAMPLE && sizeof(JSAMPLE) == sizeof(U_CHAR) &&
cinfo->in_color_space == JCS_GRAYSCALE) {
source->pub.get_pixel_rows = get_raw_row;
use_raw_buffer = TRUE;
need_rescale = FALSE;
} else {
if (cinfo->in_color_space == JCS_GRAYSCALE)
source->pub.get_pixel_rows = get_scaled_gray_row;
else if (IsExtRGB(cinfo->in_color_space))
source->pub.get_pixel_rows = get_gray_rgb_row;
else if (cinfo->in_color_space == JCS_CMYK)
source->pub.get_pixel_rows = get_gray_cmyk_row;
else
ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
}
break;
case '6': /* it's a raw-format PPM file */
if (cinfo->in_color_space == JCS_UNKNOWN)
cinfo->in_color_space = JCS_EXT_RGB;
TRACEMS2(cinfo, 1, JTRC_PPM, w, h);
if (maxval > 255) {
source->pub.get_pixel_rows = get_word_rgb_row;
} else if (maxval == MAXJSAMPLE && sizeof(JSAMPLE) == sizeof(U_CHAR) &&
(cinfo->in_color_space == JCS_EXT_RGB
#if RGB_RED == 0 && RGB_GREEN == 1 && RGB_BLUE == 2 && RGB_PIXELSIZE == 3
|| cinfo->in_color_space == JCS_RGB
#endif
)) {
source->pub.get_pixel_rows = get_raw_row;
use_raw_buffer = TRUE;
need_rescale = FALSE;
} else {
if (IsExtRGB(cinfo->in_color_space))
source->pub.get_pixel_rows = get_rgb_row;
else if (cinfo->in_color_space == JCS_CMYK)
source->pub.get_pixel_rows = get_rgb_cmyk_row;
else
ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
}
break;
}
if (IsExtRGB(cinfo->in_color_space))
cinfo->input_components = rgb_pixelsize[cinfo->in_color_space];
else if (cinfo->in_color_space == JCS_GRAYSCALE)
cinfo->input_components = 1;
else if (cinfo->in_color_space == JCS_CMYK)
cinfo->input_components = 4;
/* Allocate space for I/O buffer: 1 or 3 bytes or words/pixel. */
if (need_iobuffer) {
if (c == '6')
source->buffer_width = (size_t)w * 3 *
((maxval <= 255) ? sizeof(U_CHAR) : (2 * sizeof(U_CHAR)));
else
source->buffer_width = (size_t)w *
((maxval <= 255) ? sizeof(U_CHAR) : (2 * sizeof(U_CHAR)));
source->iobuffer = (U_CHAR *)
(*cinfo->mem->alloc_small) ((j_common_ptr)cinfo, JPOOL_IMAGE,
source->buffer_width);
}
/* Create compressor input buffer. */
if (use_raw_buffer) {
/* For unscaled raw-input case, we can just map it onto the I/O buffer. */
/* Synthesize a JSAMPARRAY pointer structure */
source->pixrow = (JSAMPROW)source->iobuffer;
source->pub.buffer = &source->pixrow;
source->pub.buffer_height = 1;
} else {
/* Need to translate anyway, so make a separate sample buffer. */
source->pub.buffer = (*cinfo->mem->alloc_sarray)
((j_common_ptr)cinfo, JPOOL_IMAGE,
(JDIMENSION)w * cinfo->input_components, (JDIMENSION)1);
source->pub.buffer_height = 1;
}
/* Compute the rescaling array if required. */
if (need_rescale) {
long val, half_maxval;
/* On 16-bit-int machines we have to be careful of maxval = 65535 */
source->rescale = (JSAMPLE *)
(*cinfo->mem->alloc_small) ((j_common_ptr)cinfo, JPOOL_IMAGE,
(size_t)(((long)MAX(maxval, 255) + 1L) *
sizeof(JSAMPLE)));
half_maxval = maxval / 2;
for (val = 0; val <= (long)maxval; val++) {
/* The multiplication here must be done in 32 bits to avoid overflow */
source->rescale[val] = (JSAMPLE)((val * MAXJSAMPLE + half_maxval) /
maxval);
}
}
}
/*
* Finish up at the end of the file.
*/
METHODDEF(void)
finish_input_ppm(j_compress_ptr cinfo, cjpeg_source_ptr sinfo)
{
/* no work */
}
/*
* The module selection routine for PPM format input.
*/
GLOBAL(cjpeg_source_ptr)
jinit_read_ppm(j_compress_ptr cinfo)
{
ppm_source_ptr source;
/* Create module interface object */
source = (ppm_source_ptr)
(*cinfo->mem->alloc_small) ((j_common_ptr)cinfo, JPOOL_IMAGE,
sizeof(ppm_source_struct));
/* Fill in method ptrs, except get_pixel_rows which start_input sets */
source->pub.start_input = start_input_ppm;
source->pub.finish_input = finish_input_ppm;
return (cjpeg_source_ptr)source;
}
#endif /* PPM_SUPPORTED */
| ./CrossVul/dataset_final_sorted/CWE-125/c/good_4039_1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.